diff --git a/.github/workflows/performance-contracts.yml b/.github/workflows/performance-contracts.yml index e8132e2aa79..2c453310526 100644 --- a/.github/workflows/performance-contracts.yml +++ b/.github/workflows/performance-contracts.yml @@ -29,7 +29,6 @@ on: - 'src/main/codex-usage/scanner-incremental-append.test.ts' - 'src/main/usage/jsonl-file-reader.test.ts' - 'src/main/usage/jsonl-file-snapshot.test.ts' - - 'src/renderer/src/lib/pane-manager/pane-terminal-output-scheduler-queue-retention.test.ts' - 'src/main/claude-usage/scanner-incremental-append.test.ts' - 'src/main/claude-usage/store-checkpoint-persistence.test.ts' diff --git a/config/ast-grep/rule-tests/__snapshots__/claude-chat-entrypoint-callers-snapshot.yml b/config/ast-grep/rule-tests/__snapshots__/claude-chat-entrypoint-callers-snapshot.yml new file mode 100644 index 00000000000..6bd5f856dd1 --- /dev/null +++ b/config/ast-grep/rule-tests/__snapshots__/claude-chat-entrypoint-callers-snapshot.yml @@ -0,0 +1,14 @@ +id: claude-chat-entrypoint-callers +snapshots: + "import { withOrcaClaudeChatEntrypoint as stamp } from './claude-chat-entrypoint'": + labels: + - source: withOrcaClaudeChatEntrypoint + style: primary + start: 9 + end: 37 + 'withOrcaClaudeChatEntrypoint(env, platform)': + labels: + - source: withOrcaClaudeChatEntrypoint + style: primary + start: 0 + end: 28 diff --git a/config/ast-grep/rule-tests/__snapshots__/claude-chat-entrypoint-owner-snapshot.yml b/config/ast-grep/rule-tests/__snapshots__/claude-chat-entrypoint-owner-snapshot.yml new file mode 100644 index 00000000000..05f177c95df --- /dev/null +++ b/config/ast-grep/rule-tests/__snapshots__/claude-chat-entrypoint-owner-snapshot.yml @@ -0,0 +1,20 @@ +id: claude-chat-entrypoint-owner +snapshots: + "const env = { CLAUDE_CODE_ENTRYPOINT: 'orca' }": + labels: + - source: CLAUDE_CODE_ENTRYPOINT + style: primary + start: 14 + end: 36 + const identity = 'sdk-cli': + labels: + - source: sdk-cli + style: primary + start: 18 + end: 25 + "env['claude_code_entrypoint'] = 'other'": + labels: + - source: claude_code_entrypoint + style: primary + start: 5 + end: 27 diff --git a/config/ast-grep/rule-tests/__snapshots__/claude-entrypoint-key-owner-snapshot.yml b/config/ast-grep/rule-tests/__snapshots__/claude-entrypoint-key-owner-snapshot.yml new file mode 100644 index 00000000000..ea2790098fb --- /dev/null +++ b/config/ast-grep/rule-tests/__snapshots__/claude-entrypoint-key-owner-snapshot.yml @@ -0,0 +1,14 @@ +id: claude-entrypoint-key-owner +snapshots: + "env[CLAUDE_ENTRYPOINT_ENV] = 'orca'": + labels: + - source: CLAUDE_ENTRYPOINT_ENV + style: primary + start: 4 + end: 25 + "import { CLAUDE_ENTRYPOINT_ENV as key } from './claude-chat-entrypoint'": + labels: + - source: CLAUDE_ENTRYPOINT_ENV + style: primary + start: 9 + end: 30 diff --git a/config/ast-grep/rule-tests/claude-chat-entrypoint-callers-test.yml b/config/ast-grep/rule-tests/claude-chat-entrypoint-callers-test.yml new file mode 100644 index 00000000000..cca0fcf607c --- /dev/null +++ b/config/ast-grep/rule-tests/claude-chat-entrypoint-callers-test.yml @@ -0,0 +1,6 @@ +id: claude-chat-entrypoint-callers +valid: + - 'stripInheritedClaudeSessionEnv(env)' +invalid: + - 'withOrcaClaudeChatEntrypoint(env, platform)' + - "import { withOrcaClaudeChatEntrypoint as stamp } from './claude-chat-entrypoint'" diff --git a/config/ast-grep/rule-tests/claude-chat-entrypoint-owner-test.yml b/config/ast-grep/rule-tests/claude-chat-entrypoint-owner-test.yml new file mode 100644 index 00000000000..87a75f4a143 --- /dev/null +++ b/config/ast-grep/rule-tests/claude-chat-entrypoint-owner-test.yml @@ -0,0 +1,8 @@ +id: claude-chat-entrypoint-owner +valid: + - 'const env = withOrcaClaudeChatEntrypoint(configured, platform)' + - "const binary = 'orca'" +invalid: + - "const env = { CLAUDE_CODE_ENTRYPOINT: 'orca' }" + - "env['claude_code_entrypoint'] = 'other'" + - "const identity = 'sdk-cli'" diff --git a/config/ast-grep/rule-tests/claude-entrypoint-key-owner-test.yml b/config/ast-grep/rule-tests/claude-entrypoint-key-owner-test.yml new file mode 100644 index 00000000000..c63b8b38063 --- /dev/null +++ b/config/ast-grep/rule-tests/claude-entrypoint-key-owner-test.yml @@ -0,0 +1,6 @@ +id: claude-entrypoint-key-owner +valid: + - "const binary = 'orca'" +invalid: + - "env[CLAUDE_ENTRYPOINT_ENV] = 'orca'" + - "import { CLAUDE_ENTRYPOINT_ENV as key } from './claude-chat-entrypoint'" diff --git a/config/ast-grep/rules/claude-chat-entrypoint.yml b/config/ast-grep/rules/claude-chat-entrypoint.yml new file mode 100644 index 00000000000..cb56d1fa679 --- /dev/null +++ b/config/ast-grep/rules/claude-chat-entrypoint.yml @@ -0,0 +1,117 @@ +id: claude-chat-entrypoint-owner +language: typescript +severity: error +message: Keep the Claude identity literal in claude-chat-entrypoint.ts. +files: ['src/**'] +ignores: + - '**/*.test.*' + - '**/*.test-fixtures.*' + - '**/__fixtures__/**' + - 'src/shared/agent-launch/startup/claude-chat-entrypoint.ts' +rule: + all: + - any: + - kind: string_fragment + - kind: property_identifier + - kind: identifier + - regex: '(?i)^(CLAUDE_CODE_ENTRYPOINT|sdk-cli)$' +--- +id: claude-chat-entrypoint-owner-tsx +language: tsx +severity: error +message: Keep the Claude identity literal in claude-chat-entrypoint.ts. +files: ['src/**'] +ignores: + - '**/*.test.*' + - '**/*.test-fixtures.*' + - '**/__fixtures__/**' + - 'src/shared/agent-launch/startup/claude-chat-entrypoint.ts' +rule: + all: + - any: + - kind: string_fragment + - kind: property_identifier + - kind: identifier + - regex: '(?i)^(CLAUDE_CODE_ENTRYPOINT|sdk-cli)$' +--- +id: claude-chat-entrypoint-callers +language: typescript +severity: error +message: Only structured native chat and its own probes may apply the chat identity. +files: ['src/**'] +ignores: + - '**/*.test.*' + - '**/*.test-fixtures.*' + - '**/__fixtures__/**' + - 'src/shared/agent-launch/startup/claude-chat-entrypoint.ts' + - 'src/main/claude/claude-stream-json-connection.ts' + - 'src/main/claude/claude-agent-sdk-process-spawn.ts' + - 'src/main/claude/structured/launch/claude-structured-child-env.ts' + - 'src/main/claude/claude-model-catalog-probe.ts' +rule: + all: + - any: + - kind: string_fragment + - kind: property_identifier + - kind: identifier + - regex: '^withOrcaClaudeChatEntrypoint$' +--- +id: claude-chat-entrypoint-callers-tsx +language: tsx +severity: error +message: Only structured native chat and its own probes may apply the chat identity. +files: ['src/**'] +ignores: + - '**/*.test.*' + - '**/*.test-fixtures.*' + - '**/__fixtures__/**' + - 'src/shared/agent-launch/startup/claude-chat-entrypoint.ts' + - 'src/main/claude/claude-stream-json-connection.ts' + - 'src/main/claude/claude-agent-sdk-process-spawn.ts' + - 'src/main/claude/structured/launch/claude-structured-child-env.ts' + - 'src/main/claude/claude-model-catalog-probe.ts' +rule: + all: + - any: + - kind: string_fragment + - kind: property_identifier + - kind: identifier + - regex: '^withOrcaClaudeChatEntrypoint$' +--- +id: claude-entrypoint-key-owner +language: typescript +severity: error +message: Only the chat identity owner and inherited-session isolation may access this key directly. +files: ['src/**'] +ignores: + - '**/*.test.*' + - '**/*.test-fixtures.*' + - '**/__fixtures__/**' + - 'src/shared/agent-launch/startup/claude-chat-entrypoint.ts' + - 'src/shared/agent-launch/startup/claude-parent-session-env.ts' +rule: + all: + - any: + - kind: string_fragment + - kind: property_identifier + - kind: identifier + - regex: '^CLAUDE_ENTRYPOINT_ENV$' +--- +id: claude-entrypoint-key-owner-tsx +language: tsx +severity: error +message: Only the chat identity owner and inherited-session isolation may access this key directly. +files: ['src/**'] +ignores: + - '**/*.test.*' + - '**/*.test-fixtures.*' + - '**/__fixtures__/**' + - 'src/shared/agent-launch/startup/claude-chat-entrypoint.ts' + - 'src/shared/agent-launch/startup/claude-parent-session-env.ts' +rule: + all: + - any: + - kind: string_fragment + - kind: property_identifier + - kind: identifier + - regex: '^CLAUDE_ENTRYPOINT_ENV$' diff --git a/config/flaky-test-pattern-baseline.txt b/config/flaky-test-pattern-baseline.txt index 1a8f5fe612f..8f09cf85492 100644 --- a/config/flaky-test-pattern-baseline.txt +++ b/config/flaky-test-pattern-baseline.txt @@ -30,7 +30,6 @@ 3 test-no-in-test-import-actual:src/renderer/src/components/terminal-pane/snapshots/remote-snapshot-alt-screen-host-chain.test.ts 1 test-no-in-test-import-actual:src/renderer/src/hooks/useIpcEvents-agent-status-pane-teardown.test.ts 1 test-no-in-test-import-actual:src/renderer/src/hooks/useIpcEvents-agent-status-snapshot-hydration.test.ts -1 test-no-in-test-import-actual:src/renderer/src/lib/agent-session/launch/new-tab/agent-launch-caller-routing.test.ts 1 test-no-polling-loop:src/main/browser/cookies/browser-cookie-import-concurrency.test.ts 1 test-no-polling-loop:src/main/claude/claude-stop-ack-race.test.ts 1 test-no-polling-loop:src/main/claude/claude-stream-json-connection.test.ts @@ -635,7 +634,7 @@ 1 test-no-wall-clock:src/renderer/src/components/native-chat/session/structured/delivery/NativeChatMessageList.unsent-message.test.tsx 3 test-no-wall-clock:src/renderer/src/components/native-chat/surfaces/integration/NativeChatMessageList.test.tsx 2 test-no-wall-clock:src/renderer/src/components/native-chat/tools/tasks/NativeChatStructuredSessionStatus.test.tsx -3 test-no-wall-clock:src/renderer/src/components/sidebar/workspace-card/review/use-workspace-reference-details.test.tsx +1 test-no-wall-clock:src/renderer/src/components/sidebar/workspace-card/review/use-workspace-reference-details.test.tsx 1 test-no-wall-clock:src/renderer/src/components/sidebar/worktree-list/listing/WorktreeList.lineage-agent-expansion-coupling.test.tsx 2 test-no-wall-clock:src/renderer/src/components/task-page/jira/task-page-jira-cache-selectors.test.ts 2 test-no-wall-clock:src/renderer/src/components/terminal-pane/pty-connection/emulation/fish-color-scheme-child-stdin.node-pty.test.ts @@ -645,7 +644,6 @@ 1 test-no-wall-clock:src/renderer/src/components/worktree-jump/WorktreeJumpPalette.recent-tabs.behavior.test.tsx 4 test-no-wall-clock:src/renderer/src/components/worktree-jump/WorktreeJumpPalette.recent-tabs.test.tsx 2 test-no-wall-clock:src/renderer/src/hooks/ipc-events/agent-status-terminal-title-tab-write.test.ts -1 test-no-wall-clock:src/renderer/src/hooks/useIpcEvents-agent-status-hook-titles.test.ts 1 test-no-wall-clock:src/renderer/src/lib/paired-runtime-closed-tab-resume.test.ts 2 test-no-wall-clock:src/renderer/src/lib/use-tab-agent-observed-signal-dispatch.test.tsx 2 test-no-wall-clock:src/renderer/src/lib/wake-sleeping-agents-live-unmounted-pane.test.ts diff --git a/config/main-sync-fs-baseline.txt b/config/main-sync-fs-baseline.txt index 67ac9d1f775..36b07604a3e 100644 --- a/config/main-sync-fs-baseline.txt +++ b/config/main-sync-fs-baseline.txt @@ -551,7 +551,6 @@ 2 src/main/worker-threads/forked-child-entry-path.ts 4 src/main/workspace-hooks/hooks.ts 10 src/main/workspace-hooks/issue-command-file.ts -4 src/main/workspace-hooks/worktree-runner-script.ts 1 src/main/workspaces/catalog/folder-repo-git-conversion.ts 2 src/main/workspaces/catalog/folder-upgrade-worktree-path.ts 3 src/main/workspaces/execution-host/project-runtime-git-router.ts diff --git a/config/react-compiler-bailout-baseline.txt b/config/react-compiler-bailout-baseline.txt index a6e8fdf9418..12aa339d614 100644 --- a/config/react-compiler-bailout-baseline.txt +++ b/config/react-compiler-bailout-baseline.txt @@ -707,7 +707,7 @@ 6 src/renderer/src/hooks/useVirtualizedScrollAnchor.ts 1 src/renderer/src/lib/agent-session/launch/inventory/host-chat-program-acquisition.ts 1 src/renderer/src/lib/files/search/quick-open-file-history.ts -2 src/renderer/src/lib/worker-auto-close.ts +2 src/renderer/src/runtime/agent-orchestration/worker-auto-close.ts 1 src/renderer/src/runtime/native-chat/naming/structured-chat-name-observation.ts 1 src/renderer/src/store/plugins/appearance/plugin-icon-themes.ts 5 src/renderer/src/store/retained-views/app-state-view.ts diff --git a/config/recurring-timer-baseline.txt b/config/recurring-timer-baseline.txt index e48d5c80d66..6e17989d975 100644 --- a/config/recurring-timer-baseline.txt +++ b/config/recurring-timer-baseline.txt @@ -85,9 +85,9 @@ 1 src/renderer/src/components/terminal-pane/render-health/terminal-render-desync-sentinel.ts 1 src/renderer/src/hooks/use-now.ts 1 src/renderer/src/lib/agent-session/hibernation/agent-hibernation-coordinator.ts -1 src/renderer/src/lib/crash-diagnostics.ts -1 src/renderer/src/lib/window-visibility-interval.ts -1 src/renderer/src/lib/worker-auto-close.ts +1 src/renderer/src/diagnostics/crash-reporting/crash-diagnostics.ts +1 src/renderer/src/lib/window-activity/window-visibility-interval.ts +1 src/renderer/src/runtime/agent-orchestration/worker-auto-close.ts 1 src/renderer/src/runtime/hosts/wsl/wsl-refused-read-watch.ts 1 src/shared/remote-runtime/control/remote-runtime-shared-control-app-heartbeat.ts 1 src/shared/remote-runtime/remote-runtime-socket-liveness.ts diff --git a/config/reliability-gates.jsonc b/config/reliability-gates.jsonc index 211712f364c..90b27e1136b 100644 --- a/config/reliability-gates.jsonc +++ b/config/reliability-gates.jsonc @@ -1089,7 +1089,7 @@ "id": "settings.terminal-section-lifetime", "title": "Terminal settings search preserves matching section state", "maturity": "experimental", - "protection": "partial", + "protection": "none", "owner": "terminal-runtime", "layer": "renderer-unit", "surfaces": [ @@ -1099,66 +1099,43 @@ ], "platforms": ["macos", "linux", "windows"], "providers": ["local", "daemon", "ssh", "wsl", "remote-runtime"], - "coveredPlatforms": ["macos"], + "coveredPlatforms": [], "coveredProviders": [], - "coverageNotes": "Actual TerminalPane, ManageSessionsSection, health listener and scrollback form with mocked store/provider and display/action boundaries. Unix/Windows and Mac-client/Windows-host flags simulated; no physical provider, process-stop or native input coverage.", + "coverageNotes": "Module-layout wave1 retires the terminal-section lifetime owning suite and its complete dated receipt. The remaining TCC attribution notice suite does not establish the search-lifetime invariant. No current protection, replacement coverage, native/provider execution or fresh evidence is claimed. Historical scope before retirement: Actual TerminalPane, ManageSessionsSection, health listener and scrollback form with mocked store/provider and display/action boundaries. Unix/Windows and Mac-client/Windows-host flags simulated; no physical provider, process-stop or native input coverage.", "motivatingLinks": [ "https://github.com/stablyai/orca/blob/main/src/renderer/src/components/settings/terminal/TerminalPane.tsx" ], "invariant": "A matching settings section retains its state when preceding sections are filtered away; a section removed from search releases its owner and refreshes when shown again. A retained section still refreshes when another surface invalidates the session inventory. Diagnostic inventory never becomes authority for process death.", - "oracle": "Across 15 matched search edits the matched section keeps the same DOM node and the inventory/health read counts do not grow, instead of six reads each. A foreign inventory invalidation still reads once on the retained section and not after unmount. A draft and pending target survive matched search; actual hide/reopen reloads, explicit Refresh still reads, and hidden/unmounted health listeners do not fire.", - "commands": [ - "ORCA_BACKGROUND_LAUNCH=1 pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/settings/terminal/TerminalPane.section-lifetime.test.tsx src/renderer/src/components/settings/developer-permissions/TerminalTccAttributionNotice.test.tsx" - ], - "testFiles": [ - "src/renderer/src/components/settings/terminal/TerminalPane.section-lifetime.test.tsx", - "src/renderer/src/components/settings/developer-permissions/TerminalTccAttributionNotice.test.tsx" - ], - "assertionRefs": [ - { - "file": "src/renderer/src/components/settings/terminal/TerminalPane.section-lifetime.test.tsx", - "assertions": [ - "refreshes a retained section when another surface invalidates the inventory", - "refreshes explicitly, reloads genuinely hidden sections, and removes focus listeners", - "preserves an uncommitted scrollback draft while its section remains visible", - "retains a pending action target only while its section remains visible" - ] - } - ], - "evidenceRuns": [ - { - "date": "2026-09-26", - "runner": "local", - "platform": "macos", - "command": "ORCA_BACKGROUND_LAUNCH=1 pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/settings/TerminalPane.section-lifetime.test.tsx src/renderer/src/components/settings/TerminalTccAttributionNotice.test.tsx", - "currentCommand": "ORCA_BACKGROUND_LAUNCH=1 pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/settings/terminal/TerminalPane.section-lifetime.test.tsx src/renderer/src/components/settings/developer-permissions/TerminalTccAttributionNotice.test.tsx", - "result": "passed", - "durationSeconds": 1.48, - "summary": "12 tests/2 suites pass after the shared SettingsSectionStack adoption and the inventory-invalidation subscription. Read-count oracles restated as node identity plus non-growing read counts; original main fails all three simulated platform cases, the draft, the pending target and the foreign-invalidation refresh." - } - ], + "oracle": "Target oracle, currently unprotected after whole-suite retirement: Across 15 matched search edits the matched section keeps the same DOM node and the inventory/health read counts do not grow, instead of six reads each. A foreign inventory invalidation still reads once on the retained section and not after unmount. A draft and pending target survive matched search; actual hide/reopen reloads, explicit Refresh still reads, and hidden/unmounted health listeners do not fire.", + "commands": [], + "testFiles": [], + "assertionRefs": [], + "evidenceRuns": [], "runtimeBudget": { "p95Seconds": 10, "scope": "Focused renderer-unit suites, p95 not established." }, "flakeHistory": { "status": "not-started", - "evidence": "Author and independent local evidence only; no CI soak." + "evidence": "No current search-lifetime suite or soak evidence remains. Historical statement before retirement: Author and independent local evidence only; no CI soak." }, "redGreenEvidence": { - "status": "complete", - "evidence": "Original new suite fails all three simulated platform read-count cases, draft and pending target; one cleanup/refresh control passes. Candidate6pass. Independent scratch5pass/original4fail1control." + "status": "missing", + "evidence": "The owning search-lifetime suite was retired whole. Its historical red/green result does not validate the remaining unrelated TCC attribution notice suite." }, "performanceBudget": { "required": true, - "evidence": "Actual child inventory and health reads 6 to 1 across 15 matched search edits. Fixed small section filter/map now lives in the shared SettingsSectionStack; no new polling, cache or subprocess. One added in-renderer invalidation listener replaces the incidental search-driven refresh, so a retained section stays as fresh as the signal every other inventory reader already uses. No packaged CPU/frame/heap claim." + "evidence": "Historical budget account only; no current selector or fresh performance measurement: Actual child inventory and health reads 6 to 1 across 15 matched search edits. Fixed small section filter/map now lives in the shared SettingsSectionStack; no new polling, cache or subprocess. One added in-renderer invalidation listener replaces the incidental search-driven refresh, so a retained section stays as fresh as the signal every other inventory reader already uses. No packaged CPU/frame/heap claim." }, "knownGaps": [ "CI soak pending.", "No physical local/daemon/SSH/WSL/remote-runtime provider, native Linux/Windows or process-stop behavior exercised; routing, PTY ownership, commands and wire formats unchanged.", "Matched searches keep the loaded snapshot until existing Refresh, completed mutation, a foreign inventory invalidation or genuine hide/reopen; health also refreshes on focus/revision.", "Pending action target and drafts remain while their parent section matches, including individual controls hidden inside a retained section.", - "No packaged app latency, heap, real focus or pending destructive-mutation completion evidence. Hidden Electron component visual proof is separate from the gate." + "No packaged app latency, heap, real focus or pending destructive-mutation completion evidence. Hidden Electron component visual proof is separate from the gate.", + "Module-layout wave1 intentionally retires complete prohibited owning registrations in src/renderer/src/components/settings/terminal/TerminalPane.section-lifetime.test.tsx. Lost alarms: refreshes a retained section when another surface invalidates the inventory; refreshes explicitly, reloads genuinely hidden sections, and removes focus listeners; preserves an uncommitted scrollback draft while its section remains visible; retains a pending action target only while its section remains visible. No equivalent replacement coverage or pass for a reduced selector is claimed. All unrelated selectors and historical receipts retain their original scope.", + "Module-layout wave1 retires this complete historical receipt because its explicit current selector was reduced. It does not validate the reduced suite. Original receipt verbatim:\n{\n \"date\": \"2026-09-26\",\n \"runner\": \"local\",\n \"platform\": \"macos\",\n \"command\": \"ORCA_BACKGROUND_LAUNCH=1 pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/settings/TerminalPane.section-lifetime.test.tsx src/renderer/src/components/settings/TerminalTccAttributionNotice.test.tsx\",\n \"currentCommand\": \"ORCA_BACKGROUND_LAUNCH=1 pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/settings/terminal/TerminalPane.section-lifetime.test.tsx src/renderer/src/components/settings/developer-permissions/TerminalTccAttributionNotice.test.tsx\",\n \"result\": \"passed\",\n \"durationSeconds\": 1.48,\n \"summary\": \"12 tests/2 suites pass after the shared SettingsSectionStack adoption and the inventory-invalidation subscription. Read-count oracles restated as node identity plus non-growing read counts; original main fails all three simulated platform cases, the draft, the pending target and the foreign-invalidation refresh.\"\n }", + "Module-layout wave1 historical red/green statement before owning-suite retirement, retained verbatim without current validation credit: {\"status\":\"complete\",\"evidence\":\"Original new suite fails all three simulated platform read-count cases, draft and pending target; one cleanup/refresh control passes. Candidate6pass. Independent scratch5pass/original4fail1control.\"}" ], "promotionCriteria": [ "Retain count, real draft, pending target and cleanup oracles; obtain stable CI history and relevant full-app/provider evidence before promotion." @@ -5858,14 +5835,12 @@ "invariant": "Append-only external file growth changes only Monaco's model suffix, retaining the viewport, selection, Find state, and renderer liveness above the append point; read-only live tails do not create undo history, while editable external updates remain undoable and arbitrary rewrites continue to replace the model content.", "oracle": "Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit1709 retires changed-source assertion and execution scope without equivalent replacement coverage. Existing unchanged-selector receipts remain scoped to their original sources. Historical prior-source oracle: Focused tests assert one post-mount content owner and actual lifecycle remount ordering across retained path models. Real-Monaco tests cover undo behavior for read-only live tails versus editable files. Standalone Node timing and private undo-retention budgets at 9 and 50 MiB were retired by audit1677 and provide no current alarm. The Electron scenario compares legacy setValue with watcher appends, checking visible ranges, selection, Find state, scroll offset, non-undoability, renderer survival and memory budgets. Mock-only edit-shape assertions were retired during test-value audit.", "commands": [ - "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/editor/EditorContent.monaco-lifecycle.test.tsx", "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/editor/monaco-content-sync.undo-history.test.ts", "node --expose-gc ./node_modules/vitest/vitest.mjs bench --pool=threads", "pnpm run test:e2e -- tests/e2e/agent-session-log-tail-stability.spec.ts --workers=1" ], "testFiles": [ "src/renderer/src/components/editor/monaco-content-sync.undo-history.test.ts", - "src/renderer/src/components/editor/EditorContent.monaco-lifecycle.test.tsx", "tests/e2e/agent-session-log-tail-stability.spec.ts" ], "assertionRefs": [ @@ -5875,12 +5850,6 @@ "a real Monaco read-only live-tail append leaves canUndo false while an ordinary external update remains undoable" ] }, - { - "file": "src/renderer/src/components/editor/EditorContent.monaco-lifecycle.test.tsx", - "assertions": [ - "a same-pane path switch unmounts the prior outer Monaco before real mount reconciliation refreshes the stale target; the prior retained model content and undo sentinel remain untouched" - ] - }, { "file": "tests/e2e/agent-session-log-tail-stability.spec.ts", "assertions": [ @@ -5931,7 +5900,8 @@ "Audit1677 removes low-value test projections, mock wiring, private-state assertions, inventories and duplicate examples without equivalent replacement coverage. Per-source reviews record retained public behavior and refusal boundaries with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded.", "No live Windows or Linux View Log evidence yet.", "Historical retired benchmark receipt (not active evidence): {\"date\":\"2026-07-12\",\"runner\":\"local\",\"platform\":\"macos\",\"command\":\"node --expose-gc ./node_modules/vitest/vitest.mjs bench src/renderer/src/components/editor/monaco-content-sync.bench.ts --pool=threads\",\"result\":\"passed\",\"durationSeconds\":75,\"summary\":\"Forced-GC, settled, alternating fresh-model Monaco p95: 9 MiB append 4.02-5.51ms versus replacement 81.42-83.76ms; 50 MiB append 22.72-26.60ms versus replacement 445.11-449.21ms.\"}", - "Historical retired benchmark receipt (not active evidence): {\"date\":\"2026-07-13\",\"runner\":\"local\",\"platform\":\"macos\",\"command\":\"node --expose-gc ./node_modules/vitest/vitest.mjs bench src/renderer/src/components/editor/monaco-content-sync.undo-retention.bench.ts --pool=threads\",\"result\":\"passed\",\"durationSeconds\":5,\"summary\":\"The undoable 50 MiB control retained 104,858,630 undo-service bytes and 104,857,790 ArrayBuffer bytes; the read-only live-tail arm retained zero of both and remained non-undoable.\"}" + "Historical retired benchmark receipt (not active evidence): {\"date\":\"2026-07-13\",\"runner\":\"local\",\"platform\":\"macos\",\"command\":\"node --expose-gc ./node_modules/vitest/vitest.mjs bench src/renderer/src/components/editor/monaco-content-sync.undo-retention.bench.ts --pool=threads\",\"result\":\"passed\",\"durationSeconds\":5,\"summary\":\"The undoable 50 MiB control retained 104,858,630 undo-service bytes and 104,857,790 ArrayBuffer bytes; the read-only live-tail arm retained zero of both and remained non-undoable.\"}", + "Module-layout wave1 intentionally retires complete prohibited owning registrations in src/renderer/src/components/editor/EditorContent.monaco-lifecycle.test.tsx. Lost alarms: unmounts the prior path before reconciling a stale retained target model; keeps the diff editor mounted when a save updates the modified content; still remounts the diff editor for an explicit reload request. No equivalent replacement coverage or pass for a reduced selector is claimed. All unrelated selectors and historical receipts retain their original scope." ], "demotionRule": "Quarantine the Electron scenario if it flakes without a product or harness bug; demote if viewport/Find drift, renderer loss, or Electron memory retention exceeds the registered budgets." }, @@ -7196,7 +7166,7 @@ "commands": [ "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/lib/agent-session/resume/resume-sleeping-agent-session.test.ts", "pnpm exec vitest run --config config/vitest.config.ts tests/e2e/completed-worker-retirement-resume.unit.test.ts --reporter=verbose", - "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/lib/agent-session/resume/resume-sleeping-agent-session.test.ts src/main/providers/local-pty/local-pty-provider-spawn-session.test.ts src/main/daemon/terminal-host/testing/terminal-host.test.ts src/main/daemon/providers/adapter/testing/daemon-pty-adapter.test.ts src/main/ipc/pty/pty-pane-reservation-settlement.test.ts src/main/runtime/construction/orca-runtime.test.ts src/renderer/src/lib/pane-manager/pane-fit.test.ts src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-hidden-replay.test.ts src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport-host-session-launch.test.ts", + "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/lib/agent-session/resume/resume-sleeping-agent-session.test.ts src/main/providers/local-pty/local-pty-provider-spawn-session.test.ts src/main/daemon/terminal-host/testing/terminal-host.test.ts src/main/daemon/providers/adapter/testing/daemon-pty-adapter.test.ts src/main/ipc/pty/pty-pane-reservation-settlement.test.ts src/main/runtime/construction/orca-runtime.test.ts src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-hidden-replay.test.ts src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport-host-session-launch.test.ts", "pnpm exec electron-vite build --mode e2e && SKIP_BUILD=1 pnpm exec playwright test tests/e2e/live-background-terminal-mount-authority.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1", "pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/agent-session/lifecycle/structured-agent-cli-writers.test.ts src/main/runtime/rpc/methods/structured-sessions/creation/structured-agent-session-adoption-replay.test.ts src/main/providers/agent-foreground-process-git-bash.win32.test.ts" ], @@ -7208,7 +7178,6 @@ "src/main/daemon/providers/adapter/testing/daemon-pty-adapter.test.ts", "src/main/ipc/pty/pty-pane-reservation-settlement.test.ts", "src/main/runtime/construction/orca-runtime.test.ts", - "src/renderer/src/lib/pane-manager/pane-fit.test.ts", "src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-hidden-replay.test.ts", "src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport-host-session-launch.test.ts", "tests/e2e/live-background-terminal-mount-authority.spec.ts", @@ -7241,12 +7210,6 @@ "hibernated stable panes with cleared live PTY bindings are skipped" ] }, - { - "file": "src/renderer/src/lib/pane-manager/pane-fit.test.ts", - "assertions": [ - "withheld hidden-window animation frames exhaust the bounded fit retry and release its continuation" - ] - }, { "file": "src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-hidden-replay.test.ts", "assertions": [ @@ -7332,7 +7295,8 @@ "Audit2056 (sources2054/2055): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime.test.ts: ordinary registration cleanup removes only await import('./orca-runtime-tests/mobile-session-tabs-part-14.spec'). src/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-03.spec.ts: arms the stale-title timer for a seeded working title; arms the Command Code scrape from the noted spawn command; prefers the tracked title over a stale renderer lastTitle in the hydration seed; writes recent output into the current runtime output map; uses a later title handler replacement with the runtime receiver; calls the current injected listener with the runtime receiver; keeps optional reconciliation lazy after its callback is removed. src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-14.spec.ts: lists them, so a paired client can mirror a migrated editor; closes one by retiring it from the host session; keeps an unsaved draft unless the close is forced; shares aggregate work but leaves a replacement pending promise alone; lets a targeted refresh finish while an aggregate refresh waits; refuses a close when the store lacks %s before the guard; keeps a later missing %s on the original caught failure path. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed.", "Audit2061 (sources2059/2060): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime.test.ts: ordinary registration cleanup removes only await import('./orca-runtime-tests/mobile-session-tabs-headless-chat-rebuild.spec'); await import('./orca-runtime-tests/mobile-session-tabs-cold-serve-hydrate.spec'); await import('./orca-runtime-tests/worktree-removal-execution-host.spec'); await import('./orca-runtime-tests/terminal-spawn-dispatch.spec'). src/main/runtime/orca-runtime-tests/headless-snapshots-part-02.spec.ts: replaces a cwd parsed before late WSL context with the provider cwd; keeps a live WSL cwd that arrives during late-context snapshot recovery; infers local reconstructed WSL context from a WSL UNC worktree; clears stale terminal file URI hostnames after empty-host OSC7 cwd updates; serializes SSH headless OSC7 cwd as POSIX when the desktop runtime is on Windows; keeps Windows SSH OSC7 cwd as a drive path when the desktop runtime is POSIX; serializes Windows SSH headless OSC7 cwd as a drive path on POSIX desktops; infers restored SSH connection identity from app-scoped PTY ids. src/main/runtime/orca-runtime-tests/mobile-session-tabs-headless-chat-rebuild.spec.ts: survives the rebuild that closing a saved editor tab forces; keeps its place in the tab order when the host lists the workspace again; lists tabs to phones in the order desktop clients draw after a rebuild; keeps the place a window gave a chat across a graph resend before the chat is restored. src/main/runtime/orca-runtime-tests/mobile-session-tabs-cold-serve-hydrate.spec.ts: lists every persisted terminal of a windowless host after a cold restart; lists every persisted terminal in the all-worktrees inventory after a cold restart; lists persisted editor tabs beside the terminals after a cold restart; restores a persisted split group layout on the cold rebuild; restores the saved active group of a split even when it is not the first group; falls back to the active tab group when the saved active group was not restored; keeps the headless group active when there is no persisted split; keeps phone and CLI creates in the group they joined across a cold restart. src/main/runtime/orca-runtime-tests/worktree-removal-failed-retry.spec.ts: lists the leftover with its error, though Git no longer does; takes the normal delete once Git registers a checkout at the path again; joins a retry another client started while this Delete listed Git; shows the failed row with its error, not the scan cached before the delete. src/main/runtime/orca-runtime-tests/worktree-removal-execution-host.spec.ts: refuses an SSH row whose host is unreachable instead of deleting here; refuses a runtime row with no nested SSH target rather than deleting locally; refuses a runtime row that also names a nested SSH target; retains runtime purge dispatch in a recovery job; uses the runtime helper override before resuming an interrupted removal; uses the runtime helper override before retrying a failed removal; captures the watcher callback and retains its job-host receiver; reads the current runtime removal queue. src/main/runtime/orca-runtime-tests/terminal-spawn-dispatch.spec.ts: reports the spawn request before it leaves for the pty controller; reports it even when the spawn itself then fails; does not report it when the create fails before any spawn request; captures the admission method before reading the incarnation; captures the record method before evaluating its state object; skips database payload serialization when no database exists; skips a throwing database payload when no database exists; keeps the database method and receiver captured before its payload; captures the canonical map method before a binding getter changes it; completes the captured replacement fence without another map lookup. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed.", "Module layout policy correction: retire the remaining program-status-osc.spec.ts event-projection case (production/mock-derived pane-key oracle) and sign-in timeout case (real setTimeout wait with Date-only fake clocks). The runtime test registrar no longer imports that file. No replacement coverage or fresh execution is claimed for these losses; historical receipts retain their original source scope.", - "Module layout policy correction: retire the two remaining worktree-ps-agent-row-dismissal.spec.ts registrations. The remint/dismissal/exit case computed expected snapshotVersion increments from a production snapshot and used real-clock vi.waitFor; the legacy OSC case derived its expected paneKey from the production layout-owner switch. The runtime registrar no longer imports this file. These public projection scenarios have no replacement coverage or fresh execution claimed; all historical receipts and earlier loss notes retain their original source scope." + "Module layout policy correction: retire the two remaining worktree-ps-agent-row-dismissal.spec.ts registrations. The remint/dismissal/exit case computed expected snapshotVersion increments from a production snapshot and used real-clock vi.waitFor; the legacy OSC case derived its expected paneKey from the production layout-owner switch. The runtime registrar no longer imports this file. These public projection scenarios have no replacement coverage or fresh execution claimed; all historical receipts and earlier loss notes retain their original source scope.", + "Module-layout wave1 intentionally retires complete prohibited owning registrations in src/renderer/src/lib/pane-manager/pane-fit.test.ts. Lost alarms: runs the continuation when the reveal fit arrives on a different pane object; does not let a stale handle cancel its deferred replacement; resolves failure when hidden-window animation frames are withheld. No equivalent replacement coverage or pass for a reduced selector is claimed. All unrelated selectors and historical receipts retain their original scope." ], "demotionRule": "Demote or quarantine if failures are non-actionable or if a duplicate resume escape occurs outside the modeled matrix." }, @@ -7370,8 +7334,8 @@ "invariant": "For every claim-capable execution route, one provider-session identity has at most one live PTY owner and one canonical host surface across concurrent clients, retries, reconnects, and stale publications. For paired structured fresh and resume requests, the authenticated owning runtime creates in background without a renderer window; activate=true focuses the exact requested leaf only on the requesting viewer, while activate=false changes no viewer focus. A live orphan may be adopted only when the controller proves its exact handle and incarnation, its worktree and host owner match, no competing visual owner exists, and a host topology CAS wins. A viewer may classify completion only from successful host/provider inspection or explicit lifecycle evidence; transport, handle, or provider unavailability remains unknown and breaks any consecutive-idle proof. A physical exit retires that exact incarnation durably so stale client state and host restart cannot recreate it. Mixed-version routes select the unchanged legacy request before any authority side effect or execution-owner-local filesystem access.", "oracle": "Audit2694 source-only review: Remove14 authored/14 expanded cases in the renderer completion wrapper family, including the complete bell/query-reply/stale-input factory, without replacement. Retain29 authored/34 expanded cases with unchanged callback bodies. Three removals are the existing pending2203 overlap and must be adopted/count-reconciled once; eleven are fresh removals. No current-source runtime or gate execution is supplied by this packet; dated evidence retains its original source scope and does not validate the reduced factory bytes. No equivalent replacement, physical provider, mixed-version, mobile, rendered UI, cross-platform, soak or measured-performance result is claimed. The existing command and testFiles selector retain tests/pty-connection-completion-and-notification.test.ts; no wrapper-specific assertionRef is removed. Historical selector results do not validate its changed reachable factories. Historical prior account (preserved verbatim): Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2090 (sources2088/2089): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2086 (sources2082/2083): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2076 (sources2073/2074): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime-tests/terminal-handles-part-02.spec.ts: recovers a moved SSH pane through the tab it now sits in, not the one its lease froze; reports a plain expired orphan; does not report a pane whose only recent lease was superseded; does not report a pane whose only recent lease had its relay id recycled; picks the eligible orphan over a superseded predecessor that matches first; collects the same tabs the per-tab reader reports, in one sweep of the leases; reports no candidate when no lease names any of the worktree tabs. src/main/runtime/orca-runtime-tests/runtime-availability.spec.ts: starts unavailable with no authoritative window; reports the configured Windows terminal shell on status; reports floating workspace availability from settings on status; polls floating tabs with targeted PTY liveness and no repo/provider inventory; hydrates persisted tabs when the store cannot report repos; advertises browser screencast only when a renderer window is available; routes mobile Codex reset consumption through the account mutation coordinator; maps a definite pre-provider rejection into an authoritative current snapshot. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Frozen current literal-import graph reaches these changed test bytes; unresolved local and computed edges remain debt, and current reachability is not historical execution or equivalent replacement evidence. Historical prior account (preserved verbatim): Audit2003: Delete the complete pure orphan-topology suite and its file membership; preserve the other selectors from its combined command after archiving the original command string. Lost alarms are synthetic current-layout preservation, one-anchor grafting and ambiguous-anchor appending examples. Do not transfer their ownership/topology scope to sibling suites. Preserve all5 independent historical receipts exactly. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, physical provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1983: Delete the mocked agent-session suite and its prospective selector and aliases. Retire all3 whole dated changed-selector receipts, preserving their original raw objects in historical gaps without transferring counts or durations. Preserve5 unrelated receipts. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1931 (sources1928/1929): Partial agent-operation service suite retains only concurrent retry joining with changed-fingerprint conflict. Retire its complete three-title assertion object: old-owner legacy fallback before side effects, nested SSH Pi transcript refusal and completed/ambiguous physical-commit replay fences are no longer backed. Other probe/launch option/ledger/failure/remote-inventory examples disappear as detailed below. No actual provider spawn, live SSH or physical commit proof is retained by this source. Preserve meaningful remaining selectors/assertions and unchanged dated receipts within their original scope. Reduced selectors have no fresh gate execution evidence in this metadata packet. No equivalent replacement, physical watcher/PTY/provider, live SSH/remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): Audit1911: The complete provider PTY-inspection mock suite is removed: missing-provider rejection, stale-PTY renderer unverifiable mapping, preserved supplied renderer failures, and supplied transport-loss mapping alarms are intentionally lost. No actual terminal teardown, daemon error or remote transport was exercised. Only the deleted explicit source tokens, testFile and whole assertionRef are removed. Meaningful remaining source selectors/assertions and unaffected dated receipts retain their original scope. No equivalent replacement, fresh reduced-gate, native/platform/provider, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): Retained exact unchanged-source receipts remain the only current execution evidence. Reduced selectors have no fresh execution result. Historical pre-audit oracle account for changed sources: Existing exact unchanged-selector receipts remain the only current execution evidence. Changed source selectors have no fresh execution result. Historical prior-source oracle account: The retained unchanged-source receipts are the only current execution evidence; reduced-source assertions await validation. Historical oracle account (not a current claim for changed sources): The retained unchanged-source receipts are the only current execution evidence; reduced-source assertions await validation. Historical oracle account (not a current claim for changed sources): Race independent clients and repeated operation IDs, then assert one physical spawn and one canonical PTY/surface; inject exit-before-reply, provider disconnect, conflicting claim scope, old daemon/relay capabilities, reused handles, stale incarnations, owner mismatch, and topology revision conflict; assert safe adoption or explicit failure without a second spawn or wrong-process attachment. Run fresh/resume with activate true/false against an isolated headed desktop host and a separate paired client, then against isolated headless serve: assert host presentation stays background, only the requesting viewer focuses the exact leaf, inactive calls preserve client/DOM focus, a same-version publication replay cannot lose focus intent, and sibling-first split publication cannot consume exact-leaf intent. Restore legacy split panes and groups beside a newer host-owned tab, preserving exact predecessor/new/successor order, output, input, resize, titles, tab/leaf identity, active group, and multi-client convergence. For completion, drive a known running agent through outer transport loss, authoritative provider rejection, reconnect, explicit stop, real exit status, and successful hook completion; assert unavailable evidence never dispatches completion and two fresh authoritative idle samples are required after the gap. After exact exit, assert terminal and tab listings omit the surface, a stale publication cannot restore it, restart cannot resurrect it, exact tokened fixture PIDs are dead, and unrelated tabs/processes survive until scoped cleanup.", "commands": [ - "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/runtime/web-session-tabs-sync/inventory/web-runtime-session.test.ts src/renderer/src/runtime/web-session-tabs-sync/navigation/web-session-tabs-sync-focus-intent.test.ts", - "pnpm exec vitest run --config config/vitest.config.ts src/shared/claimed-agent-pty-owner.test.ts src/main/daemon/providers/adapter/testing/daemon-pty-adapter.test.ts src/main/runtime/session-construction/agent-session/orca-runtime-agent-session-operation.test.ts src/main/runtime/session-construction/agent-session/remote-agent-session-host-authority.integration.test.ts src/main/runtime/terminal/surface/orca-runtime-terminal-retirement.test.ts src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport-host-session-launch.test.ts src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport-create-handoff.test.ts src/renderer/src/runtime/web-session-tabs-sync/inventory/web-runtime-session.test.ts", + "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/runtime/web-session-tabs-sync/navigation/web-session-tabs-sync-focus-intent.test.ts", + "pnpm exec vitest run --config config/vitest.config.ts src/shared/claimed-agent-pty-owner.test.ts src/main/daemon/providers/adapter/testing/daemon-pty-adapter.test.ts src/main/runtime/session-construction/agent-session/orca-runtime-agent-session-operation.test.ts src/main/runtime/session-construction/agent-session/remote-agent-session-host-authority.integration.test.ts src/main/runtime/terminal/surface/orca-runtime-terminal-retirement.test.ts src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport-host-session-launch.test.ts src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport-create-handoff.test.ts", "pnpm exec vitest run --config config/vitest.config.ts tests/e2e/remote-terminal-tab-retirement.unit.test.ts", "pnpm run build:cli && pnpm run build:electron-vite && node config/scripts/diagnostics/remote-agent-authority/remote-agent-session-authority-repro.mjs", "node --check config/scripts/development/remote-session-cleanup/remote-agent-session-process-cleanup.mjs && node config/scripts/diagnostics/remote-agent-authority/remote-agent-session-authority-repro.mjs", @@ -7400,7 +7364,6 @@ "src/main/runtime/terminal/surface/orca-runtime-terminal-retirement.test.ts", "src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport-host-session-launch.test.ts", "src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport-create-handoff.test.ts", - "src/renderer/src/runtime/web-session-tabs-sync/inventory/web-runtime-session.test.ts", "tests/e2e/remote-agent-session-focus-authority.spec.ts", "config/scripts/diagnostics/remote-agent-authority/remote-agent-session-authority-repro.mjs", "config/scripts/development/remote-session-cleanup/remote-agent-session-process-cleanup.mjs", @@ -7482,10 +7445,6 @@ "same-epoch stale publications cannot resurrect the retired surface after reconnect" ] }, - { - "file": "src/renderer/src/runtime/web-session-tabs-sync/inventory/web-runtime-session.test.ts", - "assertions": ["confirms only the exact handoff after its post-create list completes"] - }, { "file": "src/renderer/src/runtime/web-session-tabs-sync/navigation/web-session-tabs-sync-focus-intent.test.ts", "assertions": [ @@ -7631,7 +7590,8 @@ "Audit2061 (sources2059/2060): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime.test.ts: ordinary registration cleanup removes only await import('./orca-runtime-tests/mobile-session-tabs-headless-chat-rebuild.spec'); await import('./orca-runtime-tests/mobile-session-tabs-cold-serve-hydrate.spec'); await import('./orca-runtime-tests/worktree-removal-execution-host.spec'); await import('./orca-runtime-tests/terminal-spawn-dispatch.spec'). src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-completion-and-notification.test.ts: ordinary registration cleanup removes only import { registerPtyConnectionSshHookStatusAuthorityTests } from '../host-ownership/pty-connection-ssh-hook-status-authority.spec'; registerPtyConnectionSshHookStatusAuthorityTests(). src/main/runtime/orca-runtime-tests/headless-snapshots-part-02.spec.ts: replaces a cwd parsed before late WSL context with the provider cwd; keeps a live WSL cwd that arrives during late-context snapshot recovery; infers local reconstructed WSL context from a WSL UNC worktree; clears stale terminal file URI hostnames after empty-host OSC7 cwd updates; serializes SSH headless OSC7 cwd as POSIX when the desktop runtime is on Windows; keeps Windows SSH OSC7 cwd as a drive path when the desktop runtime is POSIX; serializes Windows SSH headless OSC7 cwd as a drive path on POSIX desktops; infers restored SSH connection identity from app-scoped PTY ids. src/main/runtime/orca-runtime-tests/mobile-session-tabs-headless-chat-rebuild.spec.ts: survives the rebuild that closing a saved editor tab forces; keeps its place in the tab order when the host lists the workspace again; lists tabs to phones in the order desktop clients draw after a rebuild; keeps the place a window gave a chat across a graph resend before the chat is restored. src/main/runtime/orca-runtime-tests/mobile-session-tabs-cold-serve-hydrate.spec.ts: lists every persisted terminal of a windowless host after a cold restart; lists every persisted terminal in the all-worktrees inventory after a cold restart; lists persisted editor tabs beside the terminals after a cold restart; restores a persisted split group layout on the cold rebuild; restores the saved active group of a split even when it is not the first group; falls back to the active tab group when the saved active group was not restored; keeps the headless group active when there is no persisted split; keeps phone and CLI creates in the group they joined across a cold restart. src/main/runtime/orca-runtime-tests/worktree-removal-failed-retry.spec.ts: lists the leftover with its error, though Git no longer does; takes the normal delete once Git registers a checkout at the path again; joins a retry another client started while this Delete listed Git; shows the failed row with its error, not the scan cached before the delete. src/main/runtime/orca-runtime-tests/worktree-removal-execution-host.spec.ts: refuses an SSH row whose host is unreachable instead of deleting here; refuses a runtime row with no nested SSH target rather than deleting locally; refuses a runtime row that also names a nested SSH target; retains runtime purge dispatch in a recovery job; uses the runtime helper override before resuming an interrupted removal; uses the runtime helper override before retrying a failed removal; captures the watcher callback and retains its job-host receiver; reads the current runtime removal queue. src/main/runtime/orca-runtime-tests/terminal-spawn-dispatch.spec.ts: reports the spawn request before it leaves for the pty controller; reports it even when the spawn itself then fails; does not report it when the create fails before any spawn request; captures the admission method before reading the incarnation; captures the record method before evaluating its state object; skips database payload serialization when no database exists; skips a throwing database payload when no database exists; keeps the database method and receiver captured before its payload; captures the canonical map method before a binding getter changes it; completes the captured replacement fence without another map lookup. src/renderer/src/components/terminal-pane/pty-connection/host-ownership/pty-connection-ssh-hook-status-authority.spec.ts: leaves SSH IPC OSC 9999 status ownership in the main runtime. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed.", "Module layout policy correction: retire the remaining program-status-osc.spec.ts event-projection case (production/mock-derived pane-key oracle) and sign-in timeout case (real setTimeout wait with Date-only fake clocks). The runtime test registrar no longer imports that file. No replacement coverage or fresh execution is claimed for these losses; historical receipts retain their original source scope.", "Module layout policy correction: retire the two remaining worktree-ps-agent-row-dismissal.spec.ts registrations. The remint/dismissal/exit case computed expected snapshotVersion increments from a production snapshot and used real-clock vi.waitFor; the legacy OSC case derived its expected paneKey from the production layout-owner switch. The runtime registrar no longer imports this file. These public projection scenarios have no replacement coverage or fresh execution claimed; all historical receipts and earlier loss notes retain their original source scope.", - "Audit2709 removes src/renderer/src/runtime/web-session-tabs-sync/inventory/remote-runtime-session-tabs-inflight.test.ts: intentionally retire waiting out an older inventory and sharing a fresh post-operation request among concurrent callers. No equivalent replacement or fresh execution is claimed. Dated receipts remain historical evidence for their unchanged selectors only; they do not validate the reduced commands or full current gate. Original prospective command before removal: pnpm exec vitest run --config config/vitest.config.ts src/shared/claimed-agent-pty-owner.test.ts src/main/daemon/providers/adapter/testing/daemon-pty-adapter.test.ts src/main/runtime/session-construction/agent-session/orca-runtime-agent-session-operation.test.ts src/main/runtime/session-construction/agent-session/remote-agent-session-host-authority.integration.test.ts src/main/runtime/terminal/surface/orca-runtime-terminal-retirement.test.ts src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport-host-session-launch.test.ts src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport-create-handoff.test.ts src/renderer/src/runtime/web-session-tabs-sync/inventory/remote-runtime-session-tabs-inflight.test.ts src/renderer/src/runtime/web-session-tabs-sync/inventory/web-runtime-session.test.ts" + "Audit2709 removes src/renderer/src/runtime/web-session-tabs-sync/inventory/remote-runtime-session-tabs-inflight.test.ts: intentionally retire waiting out an older inventory and sharing a fresh post-operation request among concurrent callers. No equivalent replacement or fresh execution is claimed. Dated receipts remain historical evidence for their unchanged selectors only; they do not validate the reduced commands or full current gate. Original prospective command before removal: pnpm exec vitest run --config config/vitest.config.ts src/shared/claimed-agent-pty-owner.test.ts src/main/daemon/providers/adapter/testing/daemon-pty-adapter.test.ts src/main/runtime/session-construction/agent-session/orca-runtime-agent-session-operation.test.ts src/main/runtime/session-construction/agent-session/remote-agent-session-host-authority.integration.test.ts src/main/runtime/terminal/surface/orca-runtime-terminal-retirement.test.ts src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport-host-session-launch.test.ts src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport-create-handoff.test.ts src/renderer/src/runtime/web-session-tabs-sync/inventory/remote-runtime-session-tabs-inflight.test.ts src/renderer/src/runtime/web-session-tabs-sync/inventory/web-runtime-session.test.ts", + "Module-layout wave1 intentionally retires complete prohibited owning registrations in src/renderer/src/runtime/web-session-tabs-sync/inventory/web-runtime-session.test.ts. Lost alarms: confirms only the exact handoff after its post-create list completes. No equivalent replacement coverage or pass for a reduced selector is claimed. All unrelated selectors and historical receipts retain their original scope." ], "demotionRule": "Keep experimental or demote if the focused gate flakes without a product or harness bug, if a retry can physically spawn twice, if a stale exit/publication can replace or resurrect a terminal, or if mixed-version fallback occurs after an authority side effect." }, @@ -9157,36 +9117,34 @@ "providers": ["local", "daemon", "ssh", "wsl", "remote-runtime"], "coveredPlatforms": ["macos"], "coveredProviders": [], - "coverageNotes": "Renderer unit coverage proves replay-guard lost-completion and certified-wedge events carry correlatable tab, worktree, durable leaf, pane, and redacted PTY identity without exposing path-bearing values. Full provider lifecycle attribution and diagnostics-bundle artifact proof remain gaps.", + "coverageNotes": "Retained renderer unit cases exercise guard release after a silent stalled parse and hardcoded breadcrumb event/pane identity with a fake terminal and mocked recorder. The identity-rich hashing/redaction registration was retired whole. No hashed tab/worktree/leaf identity, path-redaction, diagnostics-bundle export, live provider or packaged runtime coverage is claimed.", "motivatingLinks": [ "https://github.com/stablyai/orca/pull/6800", "https://github.com/stablyai/orca/issues/6773" ], "invariant": "Terminal lifecycle anomalies around reattach, restore, replay wedges, provider ownership, stale liveness, and fallback routing must leave compact, deduped, privacy-safe breadcrumbs in crash diagnostics so future reports can be attributed from evidence. Replay anomalies must distinguish pane managers and PTYs without recording path-bearing worktree or session identities.", - "oracle": "Drop a replay write completion while allowing its FIFO probe to parse, then require the lost-completion breadcrumb to include pane ID, stable hashes for tab/worktree/leaf identity, and a path-redacted PTY ID. Existing wedge tests require both lost-completion and certified-dead paths to record their distinct event names. Full pane transition traces and diagnostics-bundle artifact proof remain follow-ups.", + "oracle": "Simulate replay and probe completions that never arrive, advance fake timers through both quiet windows, and require the real replay guard to transition from engaged to released while the mocked recorder receives terminal_replay_guard_wedged_release with paneId 1. This does not establish correlation hashing, path redaction or diagnostics-bundle export.", "commands": [ - "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/snapshots/replay-guard.test.ts" + "ORCA_BACKGROUND_LAUNCH=1 pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/snapshots/replay-guard.test.ts --maxWorkers=2" ], "testFiles": ["src/renderer/src/components/terminal-pane/snapshots/replay-guard.test.ts"], "assertionRefs": [ { "file": "src/renderer/src/components/terminal-pane/snapshots/replay-guard.test.ts", "assertions": [ - "records correlatable replay identity without exposing worktree or PTY paths", "releases after the probe itself never parses (wedged pipeline) and reports it" ] } ], "evidenceRuns": [ { - "date": "2026-07-29", + "date": "2026-11-10", "runner": "local", "platform": "macos", - "command": "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/replay-guard.test.ts", "result": "passed", - "durationSeconds": 0.201, - "summary": "The focused file passed 29 tests; replay anomaly breadcrumbs preserved event classification while adding hashed tab/worktree/leaf correlation and a path-redacted PTY identity.", - "currentCommand": "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/snapshots/replay-guard.test.ts" + "command": "ORCA_BACKGROUND_LAUNCH=1 pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/snapshots/replay-guard.test.ts --maxWorkers=2", + "durationSeconds": 1.52, + "summary": "Retained replay-guard suite passed 19 cases on the module-layout wave1 candidate. The named breadcrumb case preserves real replay guard release and the hardcoded wedged event/pane1 with a fake terminal and mocked recorder. No identity-hash/redaction, live provider, diagnostics-bundle, fresh red/green, performance or CI-soak claim." } ], "runtimeBudget": { @@ -9195,11 +9153,11 @@ }, "flakeHistory": { "status": "unknown", - "evidence": "The replay-guard unit slice passed locally once; no CI soak history yet." + "evidence": "Retained selector has no CI soak history; fresh focused execution is recorded separately." }, "redGreenEvidence": { - "status": "partial", - "evidence": "Tests fail if replay anomalies stop recording their event name, omit pane/terminal correlation, or expose the fixture's path-bearing worktree and PTY prefixes. Needs diagnostics-bundle artifact proof and full transition-trace evidence before promotion." + "status": "missing", + "evidence": "No fresh revert/fault control was run for the retained selector. Historical richer-oracle statement before retirement is preserved in knownGaps and is not current reduced-selector evidence." }, "performanceBudget": { "required": true, @@ -9214,7 +9172,10 @@ "The replay identity schema has not yet been exercised in a live Electron/provider failure.", "Current coverage records anomaly breadcrumbs only, not a full pane lifecycle state-machine trace.", "Current coverage does not prove crash/diagnostics bundle export includes the breadcrumb.", - "Current coverage does not assert forbidden transitions across live Electron/provider flows." + "Current coverage does not assert forbidden transitions across live Electron/provider flows.", + "Module-layout wave1 intentionally retires complete prohibited owning registrations in src/renderer/src/components/terminal-pane/snapshots/replay-guard.test.ts. Lost alarms: a wedged release hands the terminal to pane recovery; a healthy parse completion never notifies pane recovery; HOLDS the guard while a slow replay is still parsing — a probe is queued, never a blind release; records correlatable replay identity without exposing worktree or PTY paths; holds past the probe deadline while sibling completions prove the parser alive; settles guards on a disposed xterm without certifying a wedge. No equivalent replacement coverage or pass for a reduced selector is claimed. All unrelated selectors and historical receipts retain their original scope.", + "Module-layout wave1 retires this complete historical receipt because its explicit current selector was reduced. It does not validate the reduced suite. Original receipt verbatim:\n{\n \"date\": \"2026-07-29\",\n \"runner\": \"local\",\n \"platform\": \"macos\",\n \"command\": \"pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/replay-guard.test.ts\",\n \"result\": \"passed\",\n \"durationSeconds\": 0.201,\n \"summary\": \"The focused file passed 29 tests; replay anomaly breadcrumbs preserved event classification while adding hashed tab/worktree/leaf correlation and a path-redacted PTY identity.\",\n \"currentCommand\": \"pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/snapshots/replay-guard.test.ts\"\n }", + "Module-layout wave1 historical richer-oracle metadata before identity-registration retirement, retained verbatim without current validation credit: {\"coverageNotes\":\"Renderer unit coverage proves replay-guard lost-completion and certified-wedge events carry correlatable tab, worktree, durable leaf, pane, and redacted PTY identity without exposing path-bearing values. Full provider lifecycle attribution and diagnostics-bundle artifact proof remain gaps.\",\"oracle\":\"Drop a replay write completion while allowing its FIFO probe to parse, then require the lost-completion breadcrumb to include pane ID, stable hashes for tab/worktree/leaf identity, and a path-redacted PTY ID. Existing wedge tests require both lost-completion and certified-dead paths to record their distinct event names. Full pane transition traces and diagnostics-bundle artifact proof remain follow-ups.\",\"redGreenEvidence\":{\"status\":\"partial\",\"evidence\":\"Tests fail if replay anomalies stop recording their event name, omit pane/terminal correlation, or expose the fixture's path-bearing worktree and PTY prefixes. Needs diagnostics-bundle artifact proof and full transition-trace evidence before promotion.\"}}" ], "demotionRule": "Cannot promote if diagnostics are console-only, unbounded, or missing from support artifacts." }, @@ -9663,8 +9624,7 @@ "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/paired-reconnect-multi-pane-materialization.test.ts src/renderer/src/runtime/web-session-tabs-sync/agent-status/paired-reconnect-sidebar-agent-count.test.ts --reporter=dot", "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/lib/resolved-worktree-execution-host.test.ts src/renderer/src/components/terminal/background-terminal-worktree-mount.test.ts src/renderer/src/components/terminal-pane/mounting/queued-pane-startup.test.ts src/renderer/src/components/terminal-pane/parking/one-shot-park-replay.test.ts src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-spawn-and-startup.test.ts src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport-host-surface-replacement.test.ts src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport-stream-reconnect.test.ts src/renderer/src/store/terminals/terminal-pty-identity-replacement.test.ts", "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/pty-transport/ipc/pty-transport-detach-attach-handoff.test.ts", - "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport-attach-subscription.test.ts --reporter=dot", - "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport-attach-subscription.test.ts src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport-host-surface-replacement.test.ts src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport-stream-reconnect.test.ts src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport-expired-pane-recovery.test.ts src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport-create-outcome-recovery.test.ts src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport-create-handoff.test.ts src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/recovery/remote-runtime-pty-recovery-state.test.ts src/shared/remote-runtime/remote-runtime-socket-liveness.test.ts src/shared/remote-runtime/control/remote-runtime-shared-control-connection.test.ts src/shared/remote-runtime/control/remote-runtime-shared-control-socket-generation.test.ts src/shared/remote-runtime/remote-runtime-client-error-classification.test.ts src/main/runtime/rpc/remote-runtime-server-heartbeat.test.ts src/main/runtime/terminal/launch/orca-runtime-terminal-create-idempotency.test.ts", + "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport-host-surface-replacement.test.ts src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport-stream-reconnect.test.ts src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport-expired-pane-recovery.test.ts src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport-create-outcome-recovery.test.ts src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport-create-handoff.test.ts src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/recovery/remote-runtime-pty-recovery-state.test.ts src/shared/remote-runtime/remote-runtime-socket-liveness.test.ts src/shared/remote-runtime/control/remote-runtime-shared-control-connection.test.ts src/shared/remote-runtime/control/remote-runtime-shared-control-socket-generation.test.ts src/shared/remote-runtime/remote-runtime-client-error-classification.test.ts src/main/runtime/rpc/remote-runtime-server-heartbeat.test.ts src/main/runtime/terminal/launch/orca-runtime-terminal-create-idempotency.test.ts", "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/store/slices/ui/workspace-navigation-history-hydration.test.ts src/renderer/src/store/repos/repos-ssh-host-reconciliation.test.ts src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-spawn-and-startup.test.ts --reporter=dot", "pnpm exec vitest run --config config/vitest.config.ts src/main/ipc/ssh/ssh.test.ts src/main/ipc/worktrees-ssh-repo-owner-resolution.test.ts src/main/ssh/connection/ssh-connection-manager.test.ts src/main/ssh/connection/ssh-connection.test.ts src/preload/ssh-authority-forwarding.test.ts src/renderer/src/runtime/rpc/subscriptions/runtime-client-events.test.ts src/renderer/src/runtime/hosts/ssh/runtime-environment-ssh-state.test.ts src/shared/ssh-retained-payload-admission.test.ts --reporter=dot", "pnpm exec electron-vite build --mode e2e", @@ -9680,7 +9640,6 @@ "src/renderer/src/components/terminal-pane/parking/one-shot-park-replay.test.ts", "src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-spawn-and-startup.test.ts", "src/renderer/src/components/terminal-pane/pty-transport/ipc/pty-transport-detach-attach-handoff.test.ts", - "src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport-attach-subscription.test.ts", "src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport-host-surface-replacement.test.ts", "src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport-stream-reconnect.test.ts", "src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport-expired-pane-recovery.test.ts", @@ -9728,15 +9687,6 @@ "replacement polling and each in-flight request share a 15-second deadline, then accepted snapshots own recovery without input re-arming polling" ] }, - { - "file": "src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport-attach-subscription.test.ts", - "assertions": [ - "cold restored-terminal subscription failure retries and resumes snapshot, output, and input without a fatal error", - "a canonical close before subscription readiness opens exactly one replacement stream without surfacing a fatal error", - "cached terminal pixels remain disconnected until authoritative replay completes", - "authoritative current-stream replay clears every distinct error surfaced by that transport" - ] - }, { "file": "src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport-stream-reconnect.test.ts", "assertions": [ @@ -9927,7 +9877,8 @@ "Audit2195 removes the low-value startup admission boolean and host deferral predicate inventories from background-terminal-worktree-mount.test.ts. The reduced source retains concrete targeted mount, prune and reveal ownership transitions, not those oracle assertions. Existing selectors remain unexecuted here; no equivalent replacement or new runtime/provider/platform/budget result is claimed. Original retired assertion object verbatim:\n{\n \"file\": \"src/renderer/src/components/terminal/background-terminal-worktree-mount.test.ts\",\n \"assertions\": [\n \"startup waits for hydration before mounting terminal panes while degraded mode remains interactive\",\n \"only an explicit local execution host can defer cold activation\",\n \"SSH, remote-runtime, and unresolved owners remain eager\"\n ]\n }", "Audit2709 removes src/renderer/src/runtime/web-session-tabs-sync/inventory/remote-runtime-session-tabs-inflight.test.ts: intentionally retire waiting out an older inventory and sharing a fresh post-operation request among concurrent callers. No equivalent replacement or fresh execution is claimed. Dated receipts remain historical evidence for their unchanged selectors only; they do not validate the reduced commands or full current gate. Original prospective command before removal: pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/lib/resolved-worktree-execution-host.test.ts src/renderer/src/components/terminal/background-terminal-worktree-mount.test.ts src/renderer/src/components/terminal-pane/mounting/queued-pane-startup.test.ts src/renderer/src/components/terminal-pane/parking/one-shot-park-replay.test.ts src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-spawn-and-startup.test.ts src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport-host-surface-replacement.test.ts src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport-stream-reconnect.test.ts src/renderer/src/runtime/web-session-tabs-sync/inventory/remote-runtime-session-tabs-inflight.test.ts src/renderer/src/store/terminals/terminal-pty-identity-replacement.test.ts", "Audit3086: retire the destroyed fresh-session fallback settlement/non-destructive reattach alias and its direct selector; retain the detach/attach selector and assertion unchanged. The retained admission cases cover adopt-before-data and explicitly buffered-death admission without a new spawn, without replacing fallback retirement. July 28 evidence was already archived by audit3077; no duplicate retirement or new execution is claimed.", - "Audit3096: remove the deleted reconnect-banner selector and its two UI aliases. The reduced recovery-state selector retains only the deadline cancelling pending backoff and explicit retry owning a new epoch alias; healthy-replacement stale-schedule and independent caller-cutoff cancellation aliases retire. Other retained state cases cover reentrant retry, owner settlement and same-epoch parked revival, without replacing those removed alarms. Prior admission-selector retirement, archived July 28 receipt, unrelated selectors/claims/receipts and old gaps remain unchanged; no fresh execution is claimed." + "Audit3096: remove the deleted reconnect-banner selector and its two UI aliases. The reduced recovery-state selector retains only the deadline cancelling pending backoff and explicit retry owning a new epoch alias; healthy-replacement stale-schedule and independent caller-cutoff cancellation aliases retire. Other retained state cases cover reentrant retry, owner settlement and same-epoch parked revival, without replacing those removed alarms. Prior admission-selector retirement, archived July 28 receipt, unrelated selectors/claims/receipts and old gaps remain unchanged; no fresh execution is claimed.", + "Module-layout wave1 intentionally retires complete prohibited owning registrations in src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport-attach-subscription.test.ts. Lost alarms: attaches to an existing remote runtime terminal handle; reports a rejected multiplex write through the pane recovery callback; does not report a rejected write from a superseded multiplex stream; does not report attachment health until the authoritative PTY snapshot arrives; drops its side-effect gauge from the census on %s; recovers when the first restored-terminal subscription attempt is offline; recovers when the runtime closes before a restored subscription becomes ready; surfaces a fatal error during subscription setup exactly once; reports viewer disconnect as an unverifiable remote exit; clears every retained transport error when the current stream becomes healthy. No equivalent replacement coverage or pass for a reduced selector is claimed. All unrelated selectors and historical receipts retain their original scope." ], "demotionRule": "Cannot promote if provider failure can close panes or if the oracle is screenshot-only." }, diff --git a/config/scripts/ci/sharding/ci-shard-timings.json b/config/scripts/ci/sharding/ci-shard-timings.json index 3b6e0e6bf81..9ed17e62079 100644 --- a/config/scripts/ci/sharding/ci-shard-timings.json +++ b/config/scripts/ci/sharding/ci-shard-timings.json @@ -4622,11 +4622,9 @@ "src/preload/usage-provider-api.test.ts": 46, "src/renderer/src/app-shell/app-command-handlers-tab-rename.test.ts": 1786, "src/renderer/src/app-shell/shutdown-checkpoint-persist.test.ts": 65, - "src/renderer/src/app-shell/shutdown-checkpoint-restart-lifecycle.test.ts": 210, "src/renderer/src/app-shell/startup-window-parity.test.ts": 2306, "src/renderer/src/app-shell/use-profile-state-save-delay-notice.sonner.test.tsx": 355, "src/renderer/src/app-shell/use-profile-state-save-delay-notice.test.tsx": 293, - "src/renderer/src/app-shell/use-visible-hosted-review-refresh.test.tsx": 572, "src/renderer/src/app-shell/visible-review-reporting.test.ts": 1872, "src/renderer/src/app-shell/workspace-view-cross-client-sync.test.tsx": 1170, "src/renderer/src/app-shell/worktree-creation-chat-handoff.test.tsx": 2824, @@ -4711,7 +4709,6 @@ "src/renderer/src/components/automations/runs/use-automation-runs-dashboard.test.tsx": 854, "src/renderer/src/components/automations/use-selected-automation-run-history.test.tsx": 2104, "src/renderer/src/components/browser-favicon.test.tsx": 333, - "src/renderer/src/components/browser-pane/ClientHostedBrowserPagePane.dead-guest.test.tsx": 6219, "src/renderer/src/components/browser-pane/ClientHostedBrowserPagePane.drag-focus.test.tsx": 5826, "src/renderer/src/components/browser-pane/ClientHostedBrowserPagePane.failure-remount.test.tsx": 3085, "src/renderer/src/components/browser-pane/ClientHostedBrowserPagePane.markup.test.tsx": 4575, @@ -4808,7 +4805,6 @@ "src/renderer/src/components/dashboard-popout/preview-terminal-box-fit-lifecycle.test.ts": 192, "src/renderer/src/components/dashboard-popout/preview-terminal-ime-bridge-kitty-bytes.test.ts": 479, "src/renderer/src/components/dashboard-popout/remote-runtime-terminal-preview-api.test.ts": 81, - "src/renderer/src/components/dashboard-popout/use-agent-dashboard-telemetry.test.ts": 2108, "src/renderer/src/components/dashboard-popout/useDashboardSnapshot.test.tsx": 432, "src/renderer/src/components/dashboard/AgentDashboardDrawer.focus.test.tsx": 2567, "src/renderer/src/components/dashboard/AgentDashboardDrawer.test.tsx": 1981, @@ -4830,14 +4826,11 @@ "src/renderer/src/components/diff-comments/diff-comment-popover-outside-click.test.tsx": 1889, "src/renderer/src/components/diff-comments/useDiffCommentDecorator.lifecycle.test.tsx": 2669, "src/renderer/src/components/diff-comments/useDiffCommentDecorator.range-selection.test.tsx": 1782, - "src/renderer/src/components/editor/check-details/panel/CheckRunDetailsPanel.captured-failure.test.tsx": 2412, "src/renderer/src/components/editor/check-details/panel/CheckRunDetailsPanel.copy.test.tsx": 3108, - "src/renderer/src/components/editor/check-details/panel/CheckRunDetailsPanel.log-outcomes.test.tsx": 3230, "src/renderer/src/components/editor/DiagramViewerModal.test.tsx": 2539, "src/renderer/src/components/editor/diff/sections/DiffSectionBody.word-wrap-lifecycle.test.tsx": 3036, "src/renderer/src/components/editor/diff/monaco-view/DiffViewer.word-wrap-lifecycle.test.tsx": 2499, "src/renderer/src/components/editor/EditorConflictReviewSurface.live-record.test.tsx": 1193, - "src/renderer/src/components/editor/EditorContent.monaco-lifecycle.test.tsx": 3162, "src/renderer/src/components/editor/EditorEditFileSurface.monaco-containment.test.tsx": 2666, "src/renderer/src/components/editor/EditorFileLoadErrorView.test.tsx": 660, "src/renderer/src/components/editor/EditorFileLocationMenuItems.test.tsx": 846, @@ -4849,17 +4842,13 @@ "src/renderer/src/components/editor/notebook/document/IpynbRendering.test.tsx": 2143, "src/renderer/src/components/editor/markdown-preview/surface/MarkdownPreview.link-routing.interaction.test.tsx": 1127, "src/renderer/src/components/editor/MediaViewer.test.tsx": 308, - "src/renderer/src/components/editor/MermaidViewer.test.tsx": 3079, - "src/renderer/src/components/editor/MonacoEditor.owner-view-state.test.tsx": 7073, "src/renderer/src/components/editor/PdfFind.test.tsx": 581, "src/renderer/src/components/editor/PluginBytesCustomEditorSurface.test.tsx": 641, "src/renderer/src/components/editor/PluginEditorNeedsDesktopNotice.test.tsx": 2107, "src/renderer/src/components/editor/PluginFileTypeSuggestion.test.tsx": 2062, "src/renderer/src/components/editor/rich-markdown/instance/RichMarkdownEditor.focus-leave.test.tsx": 4927, - "src/renderer/src/components/editor/rich-markdown/instance/RichMarkdownErrorBoundary.lazy-chunk.test.tsx": 367, "src/renderer/src/components/editor/ai-vault-session-log-content.test.tsx": 1899, "src/renderer/src/components/editor/check-details/actions/check-annotation-path.test.ts": 53, - "src/renderer/src/components/editor/check-details/reading/check-details-reading-viewport.test.ts": 259, "src/renderer/src/components/editor/model-lifetime/retention/closed-editor-model-lifetime.test.ts": 7921, "src/renderer/src/components/editor/model-lifetime/retention/closed-editor-model-shell.test.tsx": 4492, "src/renderer/src/components/editor/model-lifetime/retention/closed-editor-tab-disposal.test.ts": 121, @@ -4963,7 +4952,6 @@ "src/renderer/src/components/editor/monaco-programmatic-sync.test.ts": 46, "src/renderer/src/components/editor/pdf-orca-media-range-transport.test.ts": 282, "src/renderer/src/components/editor/pdf-view-position.test.ts": 74, - "src/renderer/src/components/editor/pdf-viewer-failed-load-recovery.test.tsx": 2363, "src/renderer/src/components/editor/pdf-viewer-zoom-ownership.test.tsx": 789, "src/renderer/src/components/editor/plugin-custom-editor-host.test.ts": 480, "src/renderer/src/components/editor/rich-markdown/raw-source/raw-markdown-html-line-break.test.ts": 2188, @@ -5034,7 +5022,6 @@ "src/renderer/src/components/editor/use-monaco-editor-mount.cursor-owner.test.tsx": 1332, "src/renderer/src/components/editor/use-monaco-editor-mount.stale-cache.test.tsx": 877, "src/renderer/src/components/editor/use-monaco-reveal-scheduler.test.tsx": 273, - "src/renderer/src/components/editor/use-pdf-viewer-find-shortcut.test.tsx": 907, "src/renderer/src/components/editor/use-preserve-section-during-external-edit.test.tsx": 268, "src/renderer/src/components/editor/rich-markdown/tables/use-rich-markdown-table-context-menu.test.tsx": 2238, "src/renderer/src/components/editor/external-changes/useEditorPanelExternalContentEvents.test.tsx": 2018, @@ -5042,7 +5029,6 @@ "src/renderer/src/components/editor/useEditorPanelHostUnresolvedContentState.test.tsx": 1952, "src/renderer/src/components/editor/notebook/kernel/useIpynbCellExecution.test.tsx": 695, "src/renderer/src/components/editor/notebook/document/useIpynbDocumentEditing.test.tsx": 2192, - "src/renderer/src/components/editor/notebook/document/useIpynbScrollRestoration.test.tsx": 323, "src/renderer/src/components/editor/rich-markdown/links/useLinkBubble.test.tsx": 493, "src/renderer/src/components/editor/rich-markdown/images/useLocalImagePick.test.tsx": 1319, "src/renderer/src/components/editor/document-images/useLocalImageSrc.test.ts": 736, @@ -5066,11 +5052,7 @@ "src/renderer/src/components/emulator-pane/emulator-screen-stream-content.test.tsx": 408, "src/renderer/src/components/emulator-pane/use-emulator-pane-session.test.tsx": 1968, "src/renderer/src/components/emulator-pane/use-mobile-emulator-tab-intro-actions.test.tsx": 1828, - "src/renderer/src/components/error-boundaries/RecoverableRenderErrorBoundary.lazy-chunk.test.tsx": 451, - "src/renderer/src/components/error-boundaries/RecoverableRenderErrorBoundary.never-landed-reload.test.tsx": 449, - "src/renderer/src/components/feature-tips/ChatUiHereCornerCard.test.tsx": 2798, "src/renderer/src/components/feature-tips/ChatUiHereFeatureTipVisual.test.tsx": 1093, - "src/renderer/src/components/feature-tips/ChatUiHereTip.test.tsx": 6788, "src/renderer/src/components/feature-tips/feature-tip-modal-state.test.ts": 244, "src/renderer/src/components/feature-wall/FeatureWallSetupWorkflowActions.test.tsx": 2028, "src/renderer/src/components/feature-wall/FullDiskAccessSetupPrompt.test.ts": 466, @@ -5215,7 +5197,6 @@ "src/renderer/src/components/native-chat/attachments/intake/native-chat-composer-drop-scope.test.tsx": 1409, "src/renderer/src/components/native-chat/attachments/intake/native-chat-composer-ime-file-drop.test.tsx": 1326, "src/renderer/src/components/native-chat/drafts/native-chat-composer-prompt-recall.test.tsx": 1724, - "src/renderer/src/components/native-chat/composer/focus/native-chat-composer-reveal-focus.test.tsx": 526, "src/renderer/src/components/native-chat/attachments/intake/native-chat-composer-workspace-file-drop.test.tsx": 1166, "src/renderer/src/components/native-chat/drafts/native-chat-draft-retention.test.ts": 1415, "src/renderer/src/components/native-chat/attachments/intake/native-chat-external-attachments-destination.test.tsx": 951, @@ -5279,7 +5260,6 @@ "src/renderer/src/components/native-chat/conversation/projection/use-native-chat-context-clear-floor.test.tsx": 271, "src/renderer/src/components/native-chat/pane/actions/use-native-chat-context-menu.targets.test.tsx": 3071, "src/renderer/src/components/native-chat/attachments/intake/use-native-chat-external-attachments.test.tsx": 797, - "src/renderer/src/components/native-chat/viewport/find/use-native-chat-find.test.tsx": 1458, "src/renderer/src/components/native-chat/session/status/use-native-chat-hook-status.test.ts": 1927, "src/renderer/src/components/native-chat/host-access/use-native-chat-host-outage.test.tsx": 2131, "src/renderer/src/components/native-chat/drafts/use-native-chat-launch-draft-adoption.test.tsx": 319, @@ -5328,7 +5308,6 @@ "src/renderer/src/components/new-workspace/use-recent-project-ids.test.ts": 1730, "src/renderer/src/components/new-workspace/use-smart-workspace-name-field-foundation.source.test.tsx": 2290, "src/renderer/src/components/new-workspace/work-item-source-selection.test.ts": 1736, - "src/renderer/src/components/onboarding/OnboardingInlineCommandTerminal.command-finished.test.tsx": 681, "src/renderer/src/components/onboarding/OnboardingLanguageLoading.test.tsx": 2167, "src/renderer/src/components/onboarding/onboarding-feature-setup.test.ts": 76, "src/renderer/src/components/pet/pet-blob-cache.test.ts": 64, @@ -5392,7 +5371,6 @@ "src/renderer/src/components/right-sidebar/ai-vault/scanning/ai-vault-panel-session-list-request.test.tsx": 3044, "src/renderer/src/components/right-sidebar/ai-vault/search/ai-vault-search-session.test.ts": 201, "src/renderer/src/components/right-sidebar/ai-vault/accounts/ai-vault-session-account-render.test.tsx": 2885, - "src/renderer/src/components/right-sidebar/ai-vault/scanning/ai-vault-session-conditional-refresh-hook.test.tsx": 2370, "src/renderer/src/components/right-sidebar/ai-vault/session-list/ai-vault-session-filters.test.ts": 105, "src/renderer/src/components/right-sidebar/ai-vault/scope/ai-vault-session-projects.test.ts": 117, "src/renderer/src/components/right-sidebar/ai-vault/scanning/ai-vault-session-refresh.test.ts": 2034, @@ -5408,7 +5386,6 @@ "src/renderer/src/components/right-sidebar/checks-panel/gitlab-review-client.test.ts": 321, "src/renderer/src/components/right-sidebar/checks-panel/comments/review-comment-markdown.test.tsx": 2171, "src/renderer/src/components/right-sidebar/checks-panel/refresh/use-checks-panel-manual-refresh-recovery.test.tsx": 2909, - "src/renderer/src/components/right-sidebar/checks-panel/refresh/use-checks-panel-polling.test.tsx": 2189, "src/renderer/src/lib/repository-refresh/coalesced-poll-runner.test.ts": 61, "src/renderer/src/components/right-sidebar/file-explorer/mutations/file-explorer-delete-undo-precondition.test.tsx": 2023, "src/renderer/src/components/right-sidebar/file-explorer/tree/file-explorer-dir-pages.test.ts": 1767, @@ -5430,7 +5407,6 @@ "src/renderer/src/components/right-sidebar/plugin-panels/health/plugin-panel-watchdog.test.ts": 116, "src/renderer/src/components/right-sidebar/checks-panel/comments/pr-comments-ai-launch-ack.test.ts": 118, "src/renderer/src/components/right-sidebar/checks-panel/comments/pr-comments-list-selection.test.tsx": 3290, - "src/renderer/src/components/right-sidebar/right-sidebar-titlebar-drag-regions.render.test.tsx": 1044, "src/renderer/src/components/right-sidebar/source-control/ai/runSourceControlAgentActionStart.test.ts": 1917, "src/renderer/src/components/right-sidebar/source-control/review/source-control-create-pr-intent-flow.test.ts": 71, "src/renderer/src/components/right-sidebar/source-control/review/source-control-manual-review-url.test.ts": 77, @@ -5475,7 +5451,6 @@ "src/renderer/src/components/settings/browser/BrowserSitePermissionsSetting.test.tsx": 739, "src/renderer/src/components/settings/browser/BrowserUserAgentSetting.test.tsx": 2325, "src/renderer/src/components/settings/chat/ChatNamingSetting.test.tsx": 2454, - "src/renderer/src/components/settings/chat/ChatPermissionSetting.test.tsx": 834, "src/renderer/src/components/settings/chat/ChatSettingsSection.test.tsx": 2718, "src/renderer/src/lib/skills/runtime/skill-runtime-command.test.ts": 1670, "src/renderer/src/components/settings/virtual-machines/recipes/EphemeralVmsPane.test.tsx": 1025, @@ -5488,7 +5463,6 @@ "src/renderer/src/components/settings/advanced/network/NodeDistMirrorDialog.test.tsx": 2412, "src/renderer/src/components/plugins/list/PluginsSettingsSection.lifecycle.test.tsx": 5402, "src/renderer/src/components/settings/runtime-environments/pairing/RuntimePairingGeneratorForm.test.tsx": 461, - "src/renderer/src/components/settings/session-history/SessionHistorySettingsPane.test.tsx": 1474, "src/renderer/src/components/settings/appearance/fonts/FontAutocomplete.test.tsx": 1202, "src/renderer/src/components/settings/form-controls/SettingsFormControls.segmented-control.test.tsx": 730, "src/renderer/src/components/settings/shortcuts/ShortcutFilterRail.test.ts": 273, @@ -5503,7 +5477,6 @@ "src/renderer/src/components/settings/TerminalAppearanceSection.ghostty.test.ts": 549, "src/renderer/src/components/settings/terminal/appearance/TerminalContrastSetting.test.tsx": 798, "src/renderer/src/components/settings/terminal/session-management/TerminalLimitSetting.test.tsx": 1015, - "src/renderer/src/components/settings/terminal/TerminalPane.section-lifetime.test.tsx": 1237, "src/renderer/src/components/settings/developer-permissions/TerminalTccAttributionNotice.test.tsx": 401, "src/renderer/src/components/settings/voice/VoiceMicrophoneSetting.test.tsx": 957, "src/renderer/src/components/settings/voice/VoicePane.test.tsx": 1042, @@ -5538,7 +5511,6 @@ "src/renderer/src/components/session-search/use-session-search-status.test.tsx": 477, "src/renderer/src/components/settings/accounts/usage/use-zcode-plan-credentials.test.tsx": 880, "src/renderer/src/components/setup-guide/SetupGuideModal.mount-gating.test.tsx": 2348, - "src/renderer/src/components/shared/MacFolderAccessFixDialog.test.tsx": 1356, "src/renderer/src/components/shared/kill-all-terminal-surfaces.test.ts": 1925, "src/renderer/src/components/shared/useDaemonActions.test.tsx": 332, "src/renderer/src/components/sidebar/host-admission/ssh/AddRemoteHostDialog.config-picker.test.tsx": 1178, @@ -5560,7 +5532,6 @@ "src/renderer/src/components/sidebar/SeveredTerminalDaemonBanner.test.tsx": 574, "src/renderer/src/components/sidebar/Sidebar.test.tsx": 833, "src/renderer/src/components/sidebar/SidebarAgentsList.test.tsx": 2985, - "src/renderer/src/components/sidebar/sidebar-feedback/SidebarFeedbackDialog.test.tsx": 2529, "src/renderer/src/components/sidebar/StalledTerminalDaemonBanner.test.tsx": 320, "src/renderer/src/components/sidebar/workspace-board/viewport/WorkspaceKanbanLaneGrid.test.tsx": 360, "src/renderer/src/components/sidebar/workspace-card/surface/WorktreeCard.single-reference-details.test.tsx": 2032, @@ -5663,7 +5634,6 @@ "src/renderer/src/components/stats/usage-daily-chart.test.tsx": 333, "src/renderer/src/components/stats/usage-overview-model.test.ts": 364, "src/renderer/src/components/status-bar/ClaudeSwitcherMenu.owner-lifetime.test.tsx": 2317, - "src/renderer/src/components/status-bar/PortsStatusSegment.render-stability.test.tsx": 2161, "src/renderer/src/components/status-bar/SshStatusSegment.large-host-list.test.tsx": 1838, "src/renderer/src/components/status-bar/StatusBarUsageChangeNotices.test.tsx": 785, @@ -5685,7 +5655,6 @@ "src/renderer/src/components/status-bar/use-resource-pty-actions.test.tsx": 879, "src/renderer/src/components/status-bar/use-resource-usage-derived-model.test.tsx": 742, "src/renderer/src/components/tab-bar/CopyTabIdMenuItem.test.tsx": 428, - "src/renderer/src/components/tab-bar/NativeChatNamingFailure.test.tsx": 1062, "src/renderer/src/components/tab-bar/TabBarCreateEntry.search.test.tsx": 3224, "src/renderer/src/components/tab-bar/TabBarItemRow.test.tsx": 2116, "src/renderer/src/components/tab-bar/TabBarQuickCommandItem.test.tsx": 384, @@ -5808,7 +5777,6 @@ "src/renderer/src/components/terminal-pane/layout/close/pending-pane-close-confirmation.test.ts": 4695, "src/renderer/src/components/terminal-pane/layout/close/pending-runtime-pane-close.test.ts": 3487, "src/renderer/src/components/terminal-pane/layout/close/pending-split-close.test.ts": 4680, - "tests/e2e/terminal-agent-pane-launch.unit.test.ts": 8045, "src/renderer/src/components/terminal-pane/snapshots/pty-buffer-serializer.test.ts": 53, "src/renderer/src/components/terminal-pane/pty-connection/agent-identity/pty-connection-command-finished-late-done.test.ts": 10940, "src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-completion-and-notification.test.ts": 18380, @@ -5856,7 +5824,6 @@ "src/renderer/src/components/terminal-pane/pty-connection/host-ownership/unserved-ssh-pane-bridge.test.ts": 70, "src/renderer/src/components/terminal-pane/pty-transport/delivery/pty-dispatcher-delivery-resync.test.ts": 85, "src/renderer/src/components/terminal-pane/pty-transport/delivery/pty-dispatcher-pi-routing.test.ts": 1362, - "src/renderer/src/components/terminal-pane/pty-transport/delivery/pty-dispatcher-push-reattach.test.ts": 108, "src/renderer/src/components/terminal-pane/pty-transport/input/pty-input-write-queue.test.ts": 787, "src/renderer/src/components/terminal-pane/pty-transport/delivery/pty-model-restore-channel.test.ts": 44, "src/renderer/src/components/terminal-pane/pty-transport/output/pty-output-processor-program-activity.test.ts": 160, @@ -5893,7 +5860,6 @@ "src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-query-reply-immediate.test.ts": 1556, "src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/recovery/remote-runtime-pty-recovery-state.test.ts": 85, "src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport-activation-inventory-fallback.test.ts": 1311, - "src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport-attach-subscription.test.ts": 2346, "src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport-create-handoff.test.ts": 14353, "src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport-create-outcome-recovery.test.ts": 2041, "src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport-empty-initial-snapshot.test.ts": 1491, @@ -5994,10 +5960,8 @@ "src/renderer/src/components/terminal-pane/layout/reconciliation/terminal-pane-frame-reconciliation.test.ts": 903, "src/renderer/src/components/terminal-pane/host-state/terminal-pane-host-state-memo.test.ts": 4534, "src/renderer/src/components/terminal-pane/mounting/terminal-pane-mount-bootstrap.test.ts": 1723, - "src/renderer/src/components/terminal-pane/render-health/recovery/terminal-pane-recovery-unsettled-fallback.test.ts": 831, "src/renderer/src/components/terminal-pane/render-health/recovery/terminal-pane-recovery.test.ts": 949, "src/renderer/src/components/terminal-pane/layout/split/terminal-pane-split-request-routing.test.ts": 2015, - "src/renderer/src/components/terminal-pane/pty-transport/recovery/terminal-pane-surface-ownership.test.ts": 426, "src/renderer/src/components/terminal-pane/layout/detach/terminal-pane-tab-detach-main-commit.test.ts": 2090, "src/renderer/src/components/terminal-pane/layout/detach/terminal-pane-tab-detach-main-move.test.ts": 2147, "src/renderer/src/components/terminal-pane/parking/verdict/terminal-park-verdict-flip-telemetry.test.ts": 123, @@ -6187,7 +6151,6 @@ "src/renderer/src/hooks/useImmediateMutation.test.ts": 618, "src/renderer/src/hooks/skills/discovery/useInstalledAgentSkills.react.test.tsx": 2093, "src/renderer/src/hooks/useIpcEvents-agent-status-connection-attribution.test.ts": 5510, - "src/renderer/src/hooks/useIpcEvents-agent-status-hook-titles.test.ts": 5621, "src/renderer/src/hooks/useIpcEvents-agent-status-pane-teardown.test.ts": 5268, "src/renderer/src/hooks/useIpcEvents-agent-status-queue-ordering.test.ts": 3680, "src/renderer/src/hooks/useIpcEvents-agent-status-snapshot-hydration.test.ts": 7403, @@ -6204,7 +6167,6 @@ "src/renderer/src/hooks/useIpcEvents-runtime-environment-selectors.test.ts": 530, "src/renderer/src/hooks/useIpcEvents-session-tab-close-request.test.ts": 2252, "src/renderer/src/hooks/useIssueMetadata.test.tsx": 344, - "src/renderer/src/hooks/useMacTccAttributionSeveredNotice.test.tsx": 2358, "src/renderer/src/hooks/useMetadataListRequest.test.tsx": 266, "src/renderer/src/hooks/useModalReturnFocus.test.tsx": 1938, "src/renderer/src/hooks/clipboard/primary-selection/usePrimarySelectionPaste.terminal-native-paste.test.tsx": 388, @@ -6240,8 +6202,6 @@ "src/renderer/src/lib/agent-session/hibernation/agent-hibernation-pane-age.test.ts": 41, "src/renderer/src/lib/agent-session/hibernation/agent-hibernation-planner.test.ts": 341, "src/renderer/src/lib/agent-session/hibernation/agent-hibernation-runtime-liveness-race.test.ts": 1914, - "src/renderer/src/lib/agent-session/launch/new-tab/agent-launch-caller-prompt-transport.test.ts": 1326, - "src/renderer/src/lib/agent-session/launch/new-tab/agent-launch-caller-routing.test.ts": 1266, "src/renderer/src/lib/agent-session/launch/pane/agent-launch-pane-verdict-application.test.ts": 1869, "src/renderer/src/lib/agent-session/launch/routing/agent-launch-route-input.test.ts": 1659, "src/renderer/src/lib/agent-session/launch/routing/agent-launch-route-registered-agents.test.ts": 1749, @@ -6312,7 +6272,6 @@ "src/renderer/src/lib/source-control/review/comments/comment-body-submit-state.test.ts": 55, "src/renderer/src/lib/composer-submit-cancellation.test.ts": 41, "src/renderer/src/lib/workspace/ownership/connection-context.test.ts": 1817, - "src/renderer/src/lib/crash-diagnostics.test.ts": 176, "src/renderer/src/lib/create-untitled-markdown.test.ts": 566, "src/renderer/src/lib/desktop-created-server-tabs.test.ts": 1933, "src/renderer/src/lib/workspace/ownership/direct-ssh-target-scope.test.ts": 48, @@ -6324,8 +6283,7 @@ "src/renderer/src/runtime/repo-hooks/ensure-hooks-confirmed.test.ts": 799, "src/renderer/src/lib/simulator/tabs/ensure-simulator-tab-behavior.test.ts": 3601, "src/renderer/src/runtime/hosts/platform/execution-host-facts.test.ts": 1796, - "src/renderer/src/lib/feature-education-telemetry.test.ts": 52, - "src/renderer/src/lib/feedback-image-attachments.test.ts": 557, + "src/renderer/src/components/sidebar/sidebar-feedback/feedback-image-attachments.test.ts": 557, "src/renderer/src/lib/files/search/file-search-selection.test.ts": 51, "src/renderer/src/lib/finished-agent-resume-resurrection.test.ts": 1872, "src/renderer/src/components/terminal-pane/parking/retention/foreground-terminal-tabs.test.ts": 55, @@ -6351,10 +6309,7 @@ "src/renderer/src/lib/workspace/creation/work-item/launch-work-item-direct-accepted.test.tsx": 2754, "src/renderer/src/lib/workspace/creation/work-item/launch-work-item-direct-defaults.test.ts": 1594, "src/renderer/src/lib/workspace/creation/work-item/launch-work-item-direct-setup.test.tsx": 3435, - "src/renderer/src/lib/lazy-chunk-recovery-reload.test.ts": 246, - "src/renderer/src/lib/lazy-with-retry.never-landed-reload.test.ts": 194, - "src/renderer/src/lib/lazy-with-retry.preload.test.tsx": 208, - "src/renderer/src/lib/lazy-with-retry.test.ts": 282, + "src/renderer/src/app-shell/startup/lazy-with-retry.never-landed-reload.test.ts": 194, "src/renderer/src/lib/work-items/linear/linear-board-drag-payload.test.ts": 58, "src/renderer/src/lib/work-items/linear/linear-issue-workspace-attachment.test.ts": 99, "src/renderer/src/lib/link-source-local-open-owner.test.ts": 433, @@ -6384,7 +6339,6 @@ "src/renderer/src/lib/pane-manager/pane-cursor-blink-suspension.test.ts": 429, "src/renderer/src/lib/pane-manager/pane-drag-window-blur.test.ts": 618, "src/renderer/src/lib/pane-manager/pane-fit-resize-observer.test.ts": 94, - "src/renderer/src/lib/pane-manager/pane-fit.test.ts": 166, "src/renderer/src/lib/pane-manager/pane-inline-image-recovery.test.ts": 61, "src/renderer/src/lib/pane-manager/pane-inline-images.test.ts": 74, "src/renderer/src/lib/pane-manager/pane-layout-geometry-apply.test.ts": 897, @@ -6394,11 +6348,6 @@ "src/renderer/src/lib/pane-manager/pane-terminal-foreground-render-settle.test.ts": 43, "src/renderer/src/lib/pane-manager/pane-terminal-mouse-wheel.test.ts": 88, "src/renderer/src/lib/pane-manager/pane-terminal-output-queue-chunks.test.ts": 44, - "src/renderer/src/lib/pane-manager/pane-terminal-output-scheduler-ack-credit.test.ts": 173, - "src/renderer/src/lib/pane-manager/pane-terminal-output-scheduler-disposed-writes.test.ts": 121, - "src/renderer/src/lib/pane-manager/pane-terminal-output-scheduler-queue-retention.test.ts": 301, - "src/renderer/src/lib/pane-manager/pane-terminal-output-scheduler-synchronized-frames.test.ts": 213, - "src/renderer/src/lib/pane-manager/pane-terminal-output-scheduler.test.ts": 236, "src/renderer/src/lib/pane-manager/pane-tree-equalization-parity.test.ts": 182, "src/renderer/src/lib/pane-manager/pane-tree-equalization-scaling.test.ts": 239, "src/renderer/src/lib/pane-manager/pane-tree-match-moves.test.ts": 662, @@ -6415,7 +6364,6 @@ "src/renderer/src/lib/pane-manager/terminal-indic-cluster-ranges.test.ts": 50, "src/renderer/src/lib/pane-manager/terminal-kitty-file-reader.test.ts": 83, "src/renderer/src/lib/pane-manager/terminal-ligatures-addon.test.ts": 59, - "src/renderer/src/lib/pane-manager/terminal-link-provider-guard.test.ts": 48, "src/renderer/src/lib/pane-manager/terminal-linkifier-hover-reset-on-write.test.ts": 59, "src/renderer/src/lib/pane-manager/terminal-mouse-encoding-tracker.test.ts": 95, "src/renderer/src/lib/pane-manager/terminal-mouse-report-finite-coordinates.test.ts": 272, @@ -6433,7 +6381,6 @@ "src/renderer/src/lib/pane-manager/xterm-instance-disposed.test.ts": 57, "src/renderer/src/lib/pane-manager/xterm-parse-barrier.test.ts": 154, "src/renderer/src/lib/pane-manager/xterm-user-scrolling-contract.test.ts": 1266, - "src/renderer/src/lib/pane-manager/xterm-write-callback-guard.test.ts": 53, "src/renderer/src/components/terminal-pane/session-restore/spawn-deferral/pane-spawn-deferral-drain.test.ts": 61, "src/renderer/src/components/terminal-pane/mounting/parked-terminal-host-hydration.test.ts": 274, "src/renderer/src/lib/text-input/paste/paste-payload-metadata.test.ts": 53, @@ -6448,15 +6395,10 @@ "src/renderer/src/lib/workspace/creation/project-clone-url-prefill.test.ts": 61, "src/renderer/src/lib/workspace/creation/project-host-workspace-target.jira-mapping.test.ts": 76, "src/renderer/src/lib/workspace/creation/project-host-workspace-target.test.ts": 92, - "src/renderer/src/lib/react-commit-cascade-observer.react185.test.tsx": 285, - "src/renderer/src/lib/react-commit-cascade-observer.test.ts": 189, - "src/renderer/src/lib/react-commit-cascade-telemetry.test.ts": 159, - "src/renderer/src/lib/react-error-boundary-reporting.test.ts": 55, "src/renderer/src/lib/editor/file-operations/remap-open-editor-tabs-for-path-change.test.ts": 2178, "src/renderer/src/lib/rename-user-named-tab-access.test.ts": 2804, "src/renderer/src/lib/renderer-agent-status-observation-ingress.test.ts": 81, - "src/renderer/src/lib/renderer-app-platform.test.ts": 197, - "src/renderer/src/lib/renderer-memory-profile.test.ts": 70, + "src/renderer/src/diagnostics/memory/renderer-memory-profile.test.ts": 70, "src/renderer/src/lib/repo-search.test.ts": 54, "src/renderer/src/lib/repo-slug-cache.test.ts": 52, "src/renderer/src/lib/repo-slug-index.test.ts": 2240, @@ -6479,7 +6421,6 @@ "src/renderer/src/lib/script-textarea-rows.test.ts": 93, "src/renderer/src/lib/session-write-subscriber-acknowledgment.test.ts": 1823, "src/renderer/src/lib/session-write-subscriber.test.ts": 1882, - "src/renderer/src/lib/shutdown-checkpoint-guard.test.ts": 209, "src/renderer/src/lib/sidebar-ended-creations.test.ts": 1889, "src/renderer/src/lib/sidebar-pending-layer.test.ts": 338, "src/renderer/src/lib/sidebar-shadow/workspace-activity-shadow.test.ts": 1728, @@ -6490,7 +6431,7 @@ "src/renderer/src/lib/simulator/tabs/simulator-tab-palette-activation.test.ts": 1903, "src/renderer/src/lib/source-control/remote/source-control-remote-error.test.ts": 340, "src/renderer/src/lib/ssh-config-passive-sync.test.ts": 1513, - "src/renderer/src/lib/state-collection-byte-estimate.test.ts": 86, + "src/renderer/src/diagnostics/memory/state-collection-byte-estimate.test.ts": 86, "src/renderer/src/lib/agent-session/launch/structured-agent-session-launch-draft.test.ts": 1042, "src/renderer/src/lib/agent-session/launch/structured-agent-session-launch-prerequisites.test.ts": 2427, "src/renderer/src/lib/agent-session/options/structured-agent-session-selection-lifetime.test.tsx": 2947, @@ -6515,8 +6456,6 @@ "src/renderer/src/lib/use-tab-agent-opencode-native-title.test.ts": 2093, "src/renderer/src/lib/use-tab-agent.test.ts": 1961, "src/renderer/src/lib/wake-sleeping-agents-live-unmounted-pane.test.ts": 2432, - "src/renderer/src/lib/window-visibility-interval.test.ts": 48, - "src/renderer/src/lib/window-visibility-timeout-poller.test.ts": 207, "src/renderer/src/runtime/hosts/capabilities/windows-terminal-capabilities-race.test.ts": 450, "src/renderer/src/lib/workspace/activation/workspace-activation-path-gate.test.ts": 2107, "src/renderer/src/lib/browser/workspace/workspace-browser-tab-open-placement.test.ts": 1996, @@ -6625,11 +6564,6 @@ "src/renderer/src/runtime/browser/creation/web-runtime-browser-creation-placement.test.ts": 1927, "src/renderer/src/runtime/browser/creation/web-runtime-browser-link-open.test.ts": 2217, "src/renderer/src/runtime/browser/creation/web-runtime-browser-link-session.test.ts": 1964, - "src/renderer/src/runtime/browser/creation/web-runtime-session-browser-create-split-placement.test.ts": 949, - "src/renderer/src/runtime/web-session-tabs-sync/closing/web-runtime-session-tab-activate-close.test.ts": 1426, - "src/renderer/src/runtime/hosted-terminals/actions/web-runtime-session-terminal-pane-delegation.test.ts": 1341, - "src/renderer/src/runtime/hosted-terminals/creation/web-runtime-session-terminal-workspace-routing.test.ts": 768, - "src/renderer/src/runtime/web-session-tabs-sync/inventory/web-runtime-session.test.ts": 743, "src/renderer/src/runtime/web-session-tabs-sync/closing/web-session-close-replay.test.ts": 1119, "src/renderer/src/runtime/web-session-tabs-sync/placement/web-session-open-files-batch-equivalence.test.ts": 1478, "src/renderer/src/runtime/web-session-tabs-sync/identity/web-session-restored-placeholder-identity.test.ts": 985, @@ -6638,7 +6572,6 @@ "src/renderer/src/runtime/web-session-tabs-sync/subscriptions/web-session-tabs-stream-end-resubscribe.test.tsx": 2282, "src/renderer/src/runtime/web-session-tabs-sync/agent-status/web-session-tabs-sync-agent-status.test.ts": 987, "src/renderer/src/runtime/web-session-tabs-sync/placement/web-session-tabs-sync-browser-tabs.test.ts": 925, - "src/renderer/src/runtime/web-session-tabs-sync/subscriptions/web-session-tabs-sync-completion-on-reveal.test.tsx": 2249, "src/renderer/src/runtime/web-session-tabs-sync/identity/web-session-tabs-sync-cross-runtime-worktree.test.ts": 964, "src/renderer/src/runtime/web-session-tabs-sync/placement/web-session-tabs-sync-editor-ownership.test.ts": 1902, "src/renderer/src/runtime/web-session-tabs-sync/placement/web-session-tabs-sync-editor-tabs.test.ts": 1073, @@ -6732,7 +6665,6 @@ "src/renderer/src/store/slices/browser/pages/browser-workspace-doc-location.test.ts": 2007, "src/renderer/src/store/slices/browser/browser.test.ts": 2001, "src/renderer/src/store/slices/worktrees/teardown/bulk-worktree-purge-terminal-maps-leak.test.ts": 1727, - "src/renderer/src/store/workspaces/creation/active-workspace-create-actions.test.ts": 1879, "src/renderer/src/store/terminals/codex-restart-notice-lifecycle.test.ts": 1685, "src/renderer/src/store/slices/tabs/content-tabs-from-main-frames.test.ts": 2025, "src/renderer/src/store/slices/tabs/content-tabs-paired-server-workspace.test.ts": 1923, @@ -8009,7 +7941,6 @@ "tests/e2e/terminal-binding-crash-hydration.unit.test.ts": 1769, "tests/e2e/terminal-foreground-confirmation.unit.test.ts": 644, "tests/e2e/terminal-perf-presentation.unit.test.ts": 60, - "tests/e2e/web-runtime-session-terminal-host-authority.unit.test.ts": 1061, "tests/e2e/worktree-status-warning.unit.test.ts": 2331, "tests/tools/branch-line-total-renderer.test.mjs": 1222, "tests/tools/omp-close-lifecycle.test.mjs": 403, diff --git a/config/scripts/test-runtime/sqlite-admission/vitest-node-runtime-files.mjs b/config/scripts/test-runtime/sqlite-admission/vitest-node-runtime-files.mjs index a095551ab09..d7542ed8616 100644 --- a/config/scripts/test-runtime/sqlite-admission/vitest-node-runtime-files.mjs +++ b/config/scripts/test-runtime/sqlite-admission/vitest-node-runtime-files.mjs @@ -27,8 +27,6 @@ const NODE_RUNTIME_INCLUDE = [ 'src/main/browser/extensions/native-messaging/browser-extension-native-host-process-backpressure.test.ts', 'src/main/daemon/providers/lifecycle/testing/daemon-init-provider-installation.test.ts', 'src/renderer/src/components/terminal-pane/pty-transport/input/pty-input-write-queue.test.ts', - 'src/renderer/src/lib/react-commit-cascade-observer.test.ts', - 'src/renderer/src/lib/react-commit-cascade-telemetry.test.ts', // Asserts payloads are collected; Bun's GC scans the stack conservatively and may keep one alive. 'src/shared/ws-inbound-message-queue.test.ts', 'src/renderer/src/lib/agent-session/history/title-sync/ai-vault-tab-title-sync-inputs.test.ts', diff --git a/config/tsconfig.node.json b/config/tsconfig.node.json index 5702c01cc47..f68039491a0 100644 --- a/config/tsconfig.node.json +++ b/config/tsconfig.node.json @@ -24,7 +24,6 @@ "../src/cli/runtime/runtime-pid-liveness.ts", "../src/renderer/src/store/slices/worktrees/create/worktree-create-payload.ts", "../src/renderer/src/runtime/repo-hooks/orca-hook-trust.ts", - "../src/renderer/src/lib/sha256.ts", "../src/renderer/src/components/native-chat/native-chat-resolution-receipt.ts", "../src/renderer/src/components/native-chat/structured-agent-question-projection.ts", "../src/renderer/src/components/native-chat/subagents/native-chat-subagent-delegation.ts", diff --git a/config/tsconfig.tc.web.json b/config/tsconfig.tc.web.json index d7542c5e628..a8d6f7c30cb 100644 --- a/config/tsconfig.tc.web.json +++ b/config/tsconfig.tc.web.json @@ -3,7 +3,6 @@ "exclude": [ "../src/renderer/src/lib/agent-session/launch/new-tab/launch-agent-in-new-tab-main-surface.test.ts", "../src/renderer/src/components/task-page/linear/task-page-linear-detail-query.test.tsx", - "../tests/e2e/terminal-agent-pane-launch.unit.test.ts", "../src/renderer/src/runtime/provider-accounts/observations/provider-account-observation.test-fixture.ts", "../src/shared/**/*.test.ts", "../src/shared/**/*.test.tsx", diff --git a/config/tsconfig.test.pane-launch.json b/config/tsconfig.test.pane-launch.json index 63896e6d839..0885af36f1d 100644 --- a/config/tsconfig.test.pane-launch.json +++ b/config/tsconfig.test.pane-launch.json @@ -5,7 +5,6 @@ "../src/main/runtime/orchestration/terminal-authority/structured-sessions/structured-chat-coordinator-mail.test.ts", "../src/main/runtime/rpc/methods/orchestration/orchestration-check-ambiguous-caller.test.ts", "../src/renderer/src/components/task-page/linear/task-page-linear-detail-query.test.tsx", - "../tests/e2e/terminal-agent-pane-launch.unit.test.ts", "../src/renderer/src/runtime/observed-provider-accounts.test.tsx", "../src/renderer/src/components/status-bar/ClaudeSwitcherMenu.observation.test.tsx", "../src/renderer/src/runtime/provider-accounts/observations/provider-account-observation.test-fixture.ts", diff --git a/config/tsconfig.web.json b/config/tsconfig.web.json index 02a420684d3..8b5c4e283c7 100644 --- a/config/tsconfig.web.json +++ b/config/tsconfig.web.json @@ -13,7 +13,6 @@ "exclude": [ "../src/renderer/src/lib/agent-session/launch/new-tab/launch-agent-in-new-tab-main-surface.test.ts", "../src/renderer/src/components/task-page/linear/task-page-linear-detail-query.test.tsx", - "../tests/e2e/terminal-agent-pane-launch.unit.test.ts", "../src/renderer/src/runtime/provider-accounts/observations/provider-account-observation.test-fixture.ts" ], "compilerOptions": { diff --git a/config/vitest.performance.config.ts b/config/vitest.performance.config.ts index ceb2d73b083..a068105564d 100644 --- a/config/vitest.performance.config.ts +++ b/config/vitest.performance.config.ts @@ -17,7 +17,6 @@ const contracts = [ 'src/main/codex-usage/scanner-incremental-append.test.ts', 'src/main/usage/jsonl-file-reader.test.ts', 'src/main/usage/jsonl-file-snapshot.test.ts', - 'src/renderer/src/lib/pane-manager/pane-terminal-output-scheduler-queue-retention.test.ts', 'config/scripts/static-analysis/oxlint-contracts/app-store-performance-plugin.test.mjs', 'config/scripts/static-analysis/oxlint-contracts/quadratic-buffer-concat-plugin.test.mjs', 'src/main/claude-usage/scanner-incremental-append.test.ts', diff --git a/config/workspace-record-read-baseline.txt b/config/workspace-record-read-baseline.txt index 5fc633ab0e3..c4307876cf2 100644 --- a/config/workspace-record-read-baseline.txt +++ b/config/workspace-record-read-baseline.txt @@ -8,7 +8,6 @@ 4 src/renderer/src/components/dashboard/build-dashboard-bucket-counts.ts # P5b-2 must clear: optional state fields; memo compare goes stale when absent 3 src/renderer/src/components/dashboard/dashboard-card-terminal-input.ts # P5b-2 must clear: optional state fields default to empty 1 src/renderer/src/components/dashboard/dashboard-snapshot-workspaces.ts # P5b-2 must clear: optional state field defaults to empty -1 src/renderer/src/components/dashboard/dashboard-worktree-launch-options.ts # P5b-2 must clear: optional state field defaults to empty 4 src/renderer/src/components/dashboard/useDashboardPopoutBridge.ts # P5b-2 must clear: change detection on optional fields never fires when absent 1 src/renderer/src/components/editor/markdown/documents/markdown-document-worktree-path-selector.ts # P5b-2 must clear: optional state field 2 src/renderer/src/components/right-sidebar/file-explorer/watching/useFileExplorerWatch.ts # P5b-2 must clear: optional state fields default to empty diff --git a/docs/assets/readme-downloads.svg b/docs/assets/readme-downloads.svg index f1d9f61f62f..25b9a04169b 100644 --- a/docs/assets/readme-downloads.svg +++ b/docs/assets/readme-downloads.svg @@ -1,5 +1,5 @@ - - downloads: 164m + + downloads: 168m @@ -15,7 +15,7 @@ downloads downloads - 164m - 164m + 168m + 168m diff --git a/mobile/src/agents/agent-list-row-text.ts b/mobile/src/agents/agent-list-row-text.ts index c3e9d8ef8b7..194a77e7616 100644 --- a/mobile/src/agents/agent-list-row-text.ts +++ b/mobile/src/agents/agent-list-row-text.ts @@ -21,7 +21,14 @@ function oneLine(text: string | null | undefined): string { return text?.replace(/\s+/g, ' ').trim() ?? '' } -function lastMessage(agent: RuntimeWorktreeAgentRow): string { +// A worktree agent row or a session tab's AgentStatusEntry, which leaves these optional. +type AgentPreviewSource = Pick & { + lastAssistantMessage?: string | null + toolName?: string | null + toolInput?: string | null +} + +function lastMessage(agent: AgentPreviewSource): string { const message = agent.lastAssistantMessage return message ? oneLine(withoutNativeChatVisualDirectiveLines(message)) : '' } @@ -31,7 +38,7 @@ function lastMessage(agent: RuntimeWorktreeAgentRow): string { * (`group` null) shows no tool, since the tool call is long over. */ export function agentListPreview( - agent: RuntimeWorktreeAgentRow, + agent: AgentPreviewSource, group: AgentStatusGroup | null, title: string ): string { diff --git a/mobile/src/components/SwipeRowActions.tsx b/mobile/src/components/SwipeRowActions.tsx index 704077f636d..b070de4ff38 100644 --- a/mobile/src/components/SwipeRowActions.tsx +++ b/mobile/src/components/SwipeRowActions.tsx @@ -84,6 +84,8 @@ export function SwipeRowActions({ }) // Web has no worklet plugin; mapper hooks need this explicit dependency list. const rowStyle = useAnimatedStyle(() => ({ transform: [{ translateX: offset.value }] }), [offset]) + // Hidden at rest, so the action can't show through a rounded group's antialiased corners. + const actionsStyle = useAnimatedStyle(() => ({ opacity: offset.value === 0 ? 0 : 1 }), [offset]) // A tap on an open row closes it rather than pressing the row. const guardPress = (onPress: () => void) => () => { // The click a drag release produces belongs to the drag, not to the row. @@ -124,8 +126,10 @@ export function SwipeRowActions({ } return ( - {leading ? renderAction(leading, 'leading') : null} - {trailing ? renderAction(trailing, 'trailing') : null} + + {leading ? renderAction(leading, 'leading') : null} + {trailing ? renderAction(trailing, 'trailing') : null} + {/* pan-y keeps the page scrolling vertically over the row on the web. */} {children(guardPress)} @@ -144,6 +148,7 @@ const styles = themedStyleSheet(() => ({ justifyContent: 'center', gap: 2 }, + actions: { position: 'absolute', top: 0, right: 0, bottom: 0, left: 0 }, leading: { left: 0 }, trailing: { right: 0 }, actionPressed: { opacity: feedback.pressedOpacity }, diff --git a/mobile/src/i18n/locales/de.json b/mobile/src/i18n/locales/de.json index 4ace38e5fa1..c8c64c2cf93 100644 --- a/mobile/src/i18n/locales/de.json +++ b/mobile/src/i18n/locales/de.json @@ -2454,8 +2454,7 @@ "tabStrip": { "checkingCapabilities": "Desktop-Funktionen werden geprüft – gleich erneut versuchen", "newTab": "Neuen Tab erstellen", - "quickCommandsUpdateRequired": "Desktop-Update für Schnellbefehle erforderlich", - "tabStatus": "{{title}}, {{status}}" + "quickCommandsUpdateRequired": "Desktop-Update für Schnellbefehle erforderlich" }, "terminalActionSheetActions": { "clearTerminal": "Terminal leeren", diff --git a/mobile/src/i18n/locales/en.json b/mobile/src/i18n/locales/en.json index dd1db03f89e..f14faed6778 100644 --- a/mobile/src/i18n/locales/en.json +++ b/mobile/src/i18n/locales/en.json @@ -2182,10 +2182,10 @@ "renameTerminal": "Rename Terminal", "renameTerminalFailed": "Couldn't rename the terminal. {{reason}}", "terminalName": "Terminal name", - "allowAutoClose": "Allow Auto-Close" + "allowAutoClose": "Allow Auto-Close", + "agents": "Agents" }, "tabStrip": { - "tabStatus": "{{title}}, {{status}}", "newTab": "New tab", "quickCommandsUpdateRequired": "Desktop update required for quick commands", "checkingCapabilities": "Checking desktop capabilities — try again in a moment" @@ -2887,8 +2887,6 @@ }, "presentation": { "loadingTabs": "Loading tabs", - "oneTab": "1 tab", - "tabCount": "{{tabCount}} tabs", "tapToRetry": "{{status}} — tap to retry" }, "documentReaders": { @@ -2926,6 +2924,29 @@ "skip": "Skip", "stop": "Stop", "yes": "Yes" + }, + "tabsSheet": { + "needsYou": "Needs you", + "working": "Working", + "everythingElse": "Everything else", + "open": "Open", + "closeTab": "Close {{title}}" + }, + "tabRows": { + "browser": "Browser", + "markdown": "Markdown note", + "file": "File", + "chat": "Chat", + "terminal": "Terminal" + }, + "tabBar": { + "oneTab": "1 tab", + "tabCount": "{{count}} tabs", + "anotherNeedsYou": "another tab needs you", + "actionsHint": "Shows actions for this tab", + "next": "Next tab", + "previous": "Previous tab", + "hint": "Shows all tabs" } }, "chat": { @@ -2967,7 +2988,12 @@ "skip": "Skip", "step": "Step {{step}}", "other": "Other…", - "answerPlaceholder": "Type your answer" + "answerPlaceholder": "Type your answer", + "optionPreview": "{{option}} preview", + "previewPosition": "{{current}} of {{total}}", + "chosen": "Chosen", + "chooseThis": "Choose this", + "viewPreview": "View" }, "permission": { "reason": "Reason: ", diff --git a/mobile/src/i18n/locales/es.json b/mobile/src/i18n/locales/es.json index f994d2c966b..78f372f2264 100644 --- a/mobile/src/i18n/locales/es.json +++ b/mobile/src/i18n/locales/es.json @@ -2524,8 +2524,7 @@ "tabStrip": { "checkingCapabilities": "Comprobando las funciones del escritorio. Inténtalo de nuevo en un momento.", "newTab": "Nueva pestaña", - "quickCommandsUpdateRequired": "Actualiza el escritorio para usar los comandos rápidos.", - "tabStatus": "{{title}}, {{status}}" + "quickCommandsUpdateRequired": "Actualiza el escritorio para usar los comandos rápidos." }, "terminalActionSheetActions": { "clearTerminal": "Limpiar terminal", diff --git a/mobile/src/i18n/locales/fr.json b/mobile/src/i18n/locales/fr.json index 966264702ec..20d2d3b5828 100644 --- a/mobile/src/i18n/locales/fr.json +++ b/mobile/src/i18n/locales/fr.json @@ -2524,8 +2524,7 @@ "tabStrip": { "checkingCapabilities": "Vérification des fonctionnalités de l'ordinateur — réessayez dans un instant", "newTab": "Nouvel onglet", - "quickCommandsUpdateRequired": "Mettez à jour Orca sur l'ordinateur pour utiliser les commandes rapides", - "tabStatus": "{{title}}, {{status}}" + "quickCommandsUpdateRequired": "Mettez à jour Orca sur l'ordinateur pour utiliser les commandes rapides" }, "terminalActionSheetActions": { "clearTerminal": "Effacer le terminal", diff --git a/mobile/src/i18n/locales/ja.json b/mobile/src/i18n/locales/ja.json index 39364412640..c6ee2e0fa4f 100644 --- a/mobile/src/i18n/locales/ja.json +++ b/mobile/src/i18n/locales/ja.json @@ -2450,8 +2450,7 @@ "tabStrip": { "checkingCapabilities": "デスクトップの対応機能を確認中です。少し待ってから再試行してください。", "newTab": "新規タブ", - "quickCommandsUpdateRequired": "クイックコマンドの利用にはデスクトップの更新が必要です。", - "tabStatus": "{{title}}、{{status}}" + "quickCommandsUpdateRequired": "クイックコマンドの利用にはデスクトップの更新が必要です。" }, "terminalActionSheetActions": { "clearTerminal": "ターミナルをクリア", diff --git a/mobile/src/i18n/locales/ko.json b/mobile/src/i18n/locales/ko.json index c8304776585..2b51f3ce5ae 100644 --- a/mobile/src/i18n/locales/ko.json +++ b/mobile/src/i18n/locales/ko.json @@ -2450,8 +2450,7 @@ "tabStrip": { "checkingCapabilities": "데스크톱에서 지원하는 기능을 확인 중입니다. 잠시 후 다시 시도하세요.", "newTab": "새 탭", - "quickCommandsUpdateRequired": "빠른 명령을 사용하려면 데스크톱 업데이트가 필요합니다.", - "tabStatus": "{{title}}, {{status}}" + "quickCommandsUpdateRequired": "빠른 명령을 사용하려면 데스크톱 업데이트가 필요합니다." }, "terminalActionSheetActions": { "clearTerminal": "터미널 지우기", diff --git a/mobile/src/i18n/locales/pt.json b/mobile/src/i18n/locales/pt.json index c065a24a76f..0d4a2150210 100644 --- a/mobile/src/i18n/locales/pt.json +++ b/mobile/src/i18n/locales/pt.json @@ -2524,8 +2524,7 @@ "tabStrip": { "checkingCapabilities": "Verificando os recursos do desktop — tente novamente em instantes", "newTab": "Nova aba", - "quickCommandsUpdateRequired": "Atualize o desktop para usar comandos rápidos", - "tabStatus": "{{title}}, {{status}}" + "quickCommandsUpdateRequired": "Atualize o desktop para usar comandos rápidos" }, "terminalActionSheetActions": { "clearTerminal": "Limpar Terminal", diff --git a/mobile/src/i18n/locales/ru.json b/mobile/src/i18n/locales/ru.json index 1333beff214..cec7d8ced57 100644 --- a/mobile/src/i18n/locales/ru.json +++ b/mobile/src/i18n/locales/ru.json @@ -2594,8 +2594,7 @@ "tabStrip": { "checkingCapabilities": "Проверяем возможности Orca на компьютере — повторите попытку чуть позже", "newTab": "Новая вкладка", - "quickCommandsUpdateRequired": "Для быстрых команд обновите Orca на компьютере", - "tabStatus": "{{title}}, {{status}}" + "quickCommandsUpdateRequired": "Для быстрых команд обновите Orca на компьютере" }, "terminalActionSheetActions": { "clearTerminal": "Очистить терминал", diff --git a/mobile/src/i18n/locales/tr.json b/mobile/src/i18n/locales/tr.json index 8c58ec1fe2e..81be23db055 100644 --- a/mobile/src/i18n/locales/tr.json +++ b/mobile/src/i18n/locales/tr.json @@ -2454,8 +2454,7 @@ "tabStrip": { "checkingCapabilities": "Masaüstü özellikleri kontrol ediliyor — birazdan tekrar deneyin", "newTab": "Yeni sekme", - "quickCommandsUpdateRequired": "Hızlı komutlar için masaüstü uygulaması güncellenmeli", - "tabStatus": "{{title}}, {{status}}" + "quickCommandsUpdateRequired": "Hızlı komutlar için masaüstü uygulaması güncellenmeli" }, "terminalActionSheetActions": { "clearTerminal": "Terminali Temizle", diff --git a/mobile/src/i18n/locales/zh-Hant.json b/mobile/src/i18n/locales/zh-Hant.json index 3e4a1c25efc..535fb5d378a 100644 --- a/mobile/src/i18n/locales/zh-Hant.json +++ b/mobile/src/i18n/locales/zh-Hant.json @@ -2450,8 +2450,7 @@ "tabStrip": { "checkingCapabilities": "正在檢查桌面版支援的功能,請稍後再試", "newTab": "新分頁", - "quickCommandsUpdateRequired": "需更新桌面版才能使用快速命令", - "tabStatus": "{{title}},{{status}}" + "quickCommandsUpdateRequired": "需更新桌面版才能使用快速命令" }, "terminalActionSheetActions": { "clearTerminal": "清除終端機", diff --git a/mobile/src/i18n/locales/zh.json b/mobile/src/i18n/locales/zh.json index 820e95b80a3..f845b0e146d 100644 --- a/mobile/src/i18n/locales/zh.json +++ b/mobile/src/i18n/locales/zh.json @@ -2450,8 +2450,7 @@ "tabStrip": { "checkingCapabilities": "正在检查桌面支持的功能,请稍后重试", "newTab": "新标签页", - "quickCommandsUpdateRequired": "使用快捷命令需更新桌面应用", - "tabStatus": "{{title}},{{status}}" + "quickCommandsUpdateRequired": "使用快捷命令需更新桌面应用" }, "terminalActionSheetActions": { "clearTerminal": "清空终端", diff --git a/mobile/src/session/MobileSessionHeader.tsx b/mobile/src/session/MobileSessionHeader.tsx index c7593258e42..9020e7d7486 100644 --- a/mobile/src/session/MobileSessionHeader.tsx +++ b/mobile/src/session/MobileSessionHeader.tsx @@ -6,7 +6,7 @@ import { NavBar, NavBarRefreshLine } from '../components/nav-bar/NavBar' import { useRefreshHint } from '../query/refresh-hint' import { NavBarButton } from '../components/nav-bar/NavBarButton' import { MobileSessionHeaderMoreMenu } from './MobileSessionHeaderMoreMenu' -import { MobileSessionTabStrip } from './tabs/MobileSessionTabStrip' +import { MobileSessionTabBar } from './tabs/MobileSessionTabBar' import { MobileSessionTitleBlock } from './MobileSessionTitleBlock' import type { SessionTitleCard } from './tabs/use-session-title-card' import { styles } from './mobile-session-styles' @@ -58,11 +58,11 @@ export function MobileSessionHeader({ // Why: a sideways phone is ~390pt tall, so the tabs share the top bar instead of taking a second row. const hasTabs = visibleTabs.length > 0 const tabsInTopBar = (layout.isLandscapePhone || sideRail) && hasTabs - // Bar buttons otherwise leave less than two readable tabs on a narrow header. + // Bar buttons otherwise leave the tab bar too narrow to read on a narrow header. const actionsCollapsed = tabsInTopBar && (headerWidth ?? layout.width) < 600 const sourceControlInBar = !isFloatingWorkspaceRoute && !actionsCollapsed const tabStrip = hasTabs ? ( - - { - setShowCreateTabDrawer(false) - void handleCreateTerminal() - } - }, - // Why: browser/markdown creation resolve a real worktree on the host - // (browser.tabCreate, files.createFile); the floating sentinel is - // terminal-only over RPC, so those options hide there. - ...(isFloatingWorkspaceRoute - ? [] - : [ - { - id: 'browser', - label: t('session.sheets.browser', 'Browser'), - icon: Globe, - closeBeforePress: true, - onPress: () => { - if (browserScreencastSupported !== true) { - showToast( - t( - 'session.sheets.browserUpdateRequired', - 'Desktop update required for mobile browser streaming' - ), - 1600 - ) - return - } - setShowCreateBrowserModal(true) - } - }, - ...(onPairedHost - ? [ - { - id: 'markdownNote', - label: t('session.sheets.markdownNote', 'Markdown Note'), - icon: FileText, - onPress: () => { - setShowCreateTabDrawer(false) - void handleCreateMarkdownNote() - } - } - ] - : []) - ]) - ]} + workspaceName={worktreeName} + agentOptions={createTabAgentOptions} + agentStatusRow={createTabAgentStatusRow} + // Why: browser/markdown creation resolve a real worktree on the host + // (browser.tabCreate, files.createFile); the floating sentinel is + // terminal-only over RPC, so those options hide there. + canCreateBrowser={!isFloatingWorkspaceRoute} + canCreateMarkdownNote={!isFloatingWorkspaceRoute && onPairedHost} onClose={() => setShowCreateTabDrawer(false)} + onCreateAgent={(agent) => void handleCreateTerminal(agent)} + onCreateTerminal={() => void handleCreateTerminal()} + onCreateBrowser={() => { + if (browserScreencastSupported !== true) { + showToast( + t( + 'session.sheets.browserUpdateRequired', + 'Desktop update required for mobile browser streaming' + ), + 1600 + ) + return + } + setShowCreateBrowserModal(true) + }} + onCreateMarkdownNote={() => void handleCreateMarkdownNote()} /> ({ color: colors.textSecondary, fontSize: typography.metaSize }, - tabBar: { - flexDirection: 'row', - alignItems: 'center', - borderTopWidth: 1, - borderTopColor: colors.borderSubtle - }, - // Cancels the top bar's vertical padding so tab borders run the bar's full height. - tabBarInTopBar: { - flex: 1, - minWidth: 0, - flexDirection: 'row', - alignItems: 'center', - alignSelf: 'stretch', - marginVertical: -spacing.xs, - marginLeft: spacing.md, - borderLeftWidth: 1, - borderLeftColor: colors.borderSubtle - }, - tabScrollFrame: { - flex: 1, - minWidth: 0, - flexDirection: 'row', - alignItems: 'center', - alignSelf: 'stretch' - }, - tabEdgeHint: { - position: 'absolute', - top: 0, - bottom: 0, - justifyContent: 'center', - paddingHorizontal: spacing.xs, - backgroundColor: colors.bgPanel - }, - tabEdgeHintLeft: { - left: 0, - borderRightWidth: 1, - borderRightColor: colors.borderSubtle - }, - tabEdgeHintRight: { - right: 0, - borderLeftWidth: 1, - borderLeftColor: colors.borderSubtle - }, - // Opaque like the chrome behind it: see the chat page scroll (#36553). - tabScroll: { - flex: 1, - maxHeight: 44, - backgroundColor: colors.bgPanel - }, - tabScrollInTopBar: { - alignSelf: 'stretch', - maxHeight: 44 - }, - tabContent: { - paddingLeft: spacing.md, - paddingRight: spacing.sm - }, - tabContentInTopBar: { - paddingLeft: 0 - }, - tab: { - minWidth: 44, - maxWidth: 128, - minHeight: 44, - alignItems: 'center', - justifyContent: 'center', - paddingHorizontal: spacing.sm, - paddingVertical: spacing.sm, - borderBottomWidth: 2, - borderBottomColor: 'transparent', - borderRightWidth: 1, - borderRightColor: colors.borderSubtle - }, - tabFirst: { - borderLeftWidth: 1, - borderLeftColor: colors.borderSubtle - }, - tabActive: { - borderBottomColor: colors.textSecondary, - backgroundColor: colors.bgRaised - }, - tabPressed: { - backgroundColor: colors.translucentFill - }, - tabLabelRow: { - maxWidth: '100%', - flexDirection: 'row', - alignItems: 'center', - gap: spacing.xs - }, - // Prevent web SVG shrink before the title ellipsizes. - tabIcon: { - flexShrink: 0 - }, - tabText: { - flexShrink: 1, - color: colors.textSecondary, - fontSize: 13 - }, - tabTextActive: { - color: colors.textPrimary - }, newTerminalButtonPressed: { backgroundColor: colors.bgRaised }, diff --git a/mobile/src/session/native-chat/input/MobileNativeChatAsk.previews.test.tsx b/mobile/src/session/native-chat/input/MobileNativeChatAsk.previews.test.tsx new file mode 100644 index 00000000000..6abc1652572 --- /dev/null +++ b/mobile/src/session/native-chat/input/MobileNativeChatAsk.previews.test.tsx @@ -0,0 +1,165 @@ +import { createElement, type ReactNode } from 'react' +import { act, create, type ReactTestInstance, type ReactTestRenderer } from 'react-test-renderer' +import { afterEach, expect, it, vi, type Mock } from 'vitest' +import type { AskPrompt } from '../../../../../src/shared/native-chat/input/native-chat-ask-types' +import { MobileNativeChatAsk } from './MobileNativeChatAsk' + +vi.mock('react-native', () => ({ + Keyboard: { dismiss: vi.fn() }, + Platform: { select: (options: { ios: unknown }) => options.ios }, + Pressable: 'Pressable', + ScrollView: 'ScrollView', + Text: 'Text', + View: 'View', + StyleSheet: { create: (styles: unknown) => styles, hairlineWidth: 1 } +})) +vi.mock('lucide-react-native', () => ({ Check: 'Check' })) +vi.mock('../../../components/composer-input/MessageBox', () => ({ MessageBox: 'MessageBox' })) +vi.mock('../transcript/MobileNativeChatQuestionText', () => ({ + MobileNativeChatQuestionText: 'QuestionText' +})) +vi.mock('./MobileNativeChatCardHeaderAction', () => ({ + MobileNativeChatCardHeaderAction: () => null +})) +vi.mock('../../../components/bottom-drawer/keyed-bottom-drawer', () => ({ + KeyedBottomDrawer: ({ + sheet, + children + }: { + sheet: number | null + children: (index: number) => ReactNode + }) => (sheet === null ? null : children(sheet)) +})) +vi.mock('../../../components/nav-bar/SheetHeader', () => ({ + SheetHeader: ({ onClose }: { onClose: () => void }) => + createElement('button', { accessibilityLabel: 'Close viewer', onPress: onClose }) +})) + +let renderer: ReactTestRenderer +const compactedPreview = `${'| panes |'.repeat(450)}…` +function prompt(multiSelect = false): AskPrompt { + return { + questions: [ + { + question: 'Which layout?', + header: 'Layout', + multiSelect, + options: [ + { label: 'First', preview: 'A\t|\n𠀀\t|' }, + { label: 'No preview' }, + { label: 'Last', preview: compactedPreview } + ] + } + ] + } +} +function buttons(): ReactTestInstance[] { + return renderer.root.findAll( + (node) => String(node.type) === 'Pressable' || String(node.type) === 'button' + ) +} +function button(label: string): ReactTestInstance { + return buttons().find((node) => node.props.accessibilityLabel === label)! +} +function row(index: number): ReactTestInstance { + return buttons().filter((node) => ['radio', 'checkbox'].includes(node.props.accessibilityRole))[ + index + ]! +} +function textAction(label: string): ReactTestInstance { + return buttons().find((node) => + node + .findAll((child) => String(child.type) === 'Text') + .some((text) => text.children.includes(label)) + )! +} +function press(node: ReactTestInstance): void { + act(() => node.props.onPress()) +} +type Answer = Parameters[0]['onAnswer'] +function mount(value: AskPrompt): Mock { + const onAnswer = vi.fn(async () => true) + act(() => { + renderer = create(createElement(MobileNativeChatAsk, { prompt: value, onAnswer })) + }) + return onAnswer +} + +afterEach(() => { + act(() => renderer?.unmount()) + vi.useRealTimers() +}) + +it('inspects every preview without choosing, and keeps the original option when choosing and submitting', async () => { + vi.useFakeTimers() + const onAnswer = mount(prompt()) + expect(button('First preview')).toBeDefined() + expect(button('Last preview')).toBeDefined() + expect(row(2).props.accessibilityState.checked).toBe(false) + press(button('First preview')) + expect(renderer.root.findByProps({ selectable: true }).props.children).toBe('A\t|\n𠀀\t|') + // Paging crosses the option with no preview; inspection does not change the answer. + press( + buttons().find( + (node) => node.props.accessibilityLabel === 'Last preview' && node.props.accessibilityState + )! + ) + expect( + renderer.root + .findAll((node) => String(node.type) === 'Text') + .some((node) => node.children.includes(compactedPreview)) + ).toBe(true) + press(button('Close viewer')) + act(() => { + vi.runAllTimers() + }) + expect(onAnswer).not.toHaveBeenCalled() + expect(row(2).props.accessibilityState.checked).toBe(false) + press(button('Last preview')) + press(button('Choose this')) + act(() => { + vi.runAllTimers() + }) + expect(row(2).props.accessibilityState.checked).toBe(true) + expect(onAnswer).not.toHaveBeenCalled() + press(button('Last preview')) + press(button('Chosen')) + press(row(2)) + expect(row(2).props.accessibilityState.checked).toBe(true) + await act(async () => textAction('Submit').props.onPress()) + expect(onAnswer).toHaveBeenCalledWith([{ indices: [2] }], expect.any(Function)) +}) + +it('preserves generic multi choices while inspecting and choosing, with row checkbox removal', async () => { + const onAnswer = mount(prompt(true)) + press(row(0)) + press(button('Last preview')) + press(button('Choose this')) + press(button('Last preview')) + press(button('Chosen')) + expect(row(0).props.accessibilityState.checked).toBe(true) + expect(row(2).props.accessibilityState.checked).toBe(true) + press(row(0)) + await act(async () => textAction('Submit').props.onPress()) + expect(onAnswer).toHaveBeenCalledWith([{ indices: [2] }], expect.any(Function)) +}) + +it('retains automatic answer for an ordinary question and disables the viewer choice while pending', async () => { + vi.useFakeTimers() + const plain = prompt() + plain.questions[0]!.options = [{ label: 'Plain' }] + const onAnswer = mount(plain) + press(row(0)) + await act(async () => { + vi.runAllTimers() + }) + expect(onAnswer).toHaveBeenCalledWith([{ indices: [0] }], expect.any(Function)) + act(() => renderer.unmount()) + act(() => { + renderer = create( + createElement(MobileNativeChatAsk, { prompt: prompt(), answerPending: true, onAnswer }) + ) + }) + press(button('Last preview')) + expect(button('Choose this').props.disabled).toBe(true) +}) diff --git a/mobile/src/session/native-chat/input/MobileNativeChatAsk.styles.ts b/mobile/src/session/native-chat/input/MobileNativeChatAsk.styles.ts new file mode 100644 index 00000000000..cc895c5404f --- /dev/null +++ b/mobile/src/session/native-chat/input/MobileNativeChatAsk.styles.ts @@ -0,0 +1,95 @@ +import { StyleSheet } from 'react-native' +import { colors, radii, spacing, typography } from '../../../theme/mobile-theme' +import { themedStyleSheet } from '../../../theme/themed-styles' + +export const mobileNativeChatAskStyles = themedStyleSheet(() => ({ + card: { + flexShrink: 1, + minHeight: 0, + backgroundColor: colors.bgPanel, + borderTopWidth: StyleSheet.hairlineWidth, + borderTopColor: colors.borderSubtle + }, + tabs: { + flexGrow: 0, + paddingTop: spacing.sm, + borderBottomWidth: StyleSheet.hairlineWidth, + borderBottomColor: colors.borderSubtle + }, + tabsContent: { + paddingHorizontal: spacing.sm, + gap: spacing.xs, + alignItems: 'center' + }, + tab: { + flexDirection: 'row', + alignItems: 'center', + gap: 4, + minHeight: 36, + paddingHorizontal: spacing.sm, + paddingVertical: spacing.xs, + borderBottomWidth: 2, + borderBottomColor: 'transparent' + }, + tabActive: { + borderBottomColor: colors.statusGreen + }, + tabText: { + color: colors.textSecondary, + fontSize: typography.metaSize, + fontWeight: '600' + }, + tabTextActive: { + color: colors.textPrimary + }, + scroll: { + paddingHorizontal: spacing.md + }, + questionRow: { flexDirection: 'row', alignItems: 'flex-start', gap: spacing.sm }, + questionText: { + flex: 1, + marginVertical: spacing.sm + }, + other: { + marginBottom: spacing.xs + }, + footer: { + flexDirection: 'row', + alignItems: 'center', + justifyContent: 'space-between', + padding: spacing.md, + gap: spacing.sm, + borderTopWidth: StyleSheet.hairlineWidth, + borderTopColor: colors.borderSubtle + }, + cancel: { + paddingVertical: spacing.sm, + paddingHorizontal: spacing.sm + }, + cancelText: { + color: colors.textSecondary, + fontSize: typography.bodySize, + fontWeight: '600' + }, + progress: { + color: colors.textMuted, + fontSize: typography.metaSize + }, + next: { + paddingVertical: spacing.sm, + paddingHorizontal: spacing.lg, + borderRadius: radii.control, + backgroundColor: colors.textPrimary + }, + nextSkip: { + backgroundColor: colors.bgRaised + }, + nextText: { + color: colors.bgBase, + fontSize: typography.bodySize, + fontWeight: '700' + }, + nextSkipText: { + color: colors.textMuted + } +})) diff --git a/mobile/src/session/native-chat/input/MobileNativeChatAsk.tsx b/mobile/src/session/native-chat/input/MobileNativeChatAsk.tsx index dc1d41efb78..3ec989ff1ee 100644 --- a/mobile/src/session/native-chat/input/MobileNativeChatAsk.tsx +++ b/mobile/src/session/native-chat/input/MobileNativeChatAsk.tsx @@ -1,5 +1,5 @@ import { useMemo, useRef, useState } from 'react' -import { Pressable, ScrollView, StyleSheet, Text, View } from 'react-native' +import { Keyboard, Pressable, ScrollView, Text, View } from 'react-native' import { Check } from 'lucide-react-native' import { nativeChatAnswerOperationEvidence, @@ -17,8 +17,7 @@ import { askTypedText, toggleAskOption } from '../../../../../src/shared/native-chat/input/native-chat-ask-card-rules' -import { colors, radii, spacing, typography, pressedStyle } from '../../../theme/mobile-theme' -import { themedStyleSheet } from '../../../theme/themed-styles' +import { colors, pressedStyle } from '../../../theme/mobile-theme' import { useMobileColorScheme } from '../../../theme/use-mobile-color-scheme' import type { Translate } from '../../../i18n/mobile-i18n' import { useMobileTranslation } from '../../../i18n/use-mobile-translation' @@ -27,6 +26,8 @@ import { MobileNativeChatCardHeaderAction } from './MobileNativeChatCardHeaderAc import { MobileNativeChatQuestionText } from '../transcript/MobileNativeChatQuestionText' import { useMobileNativeChatAskAutoAdvance } from './use-mobile-native-chat-ask-auto-advance' import { MobileNativeChatAskOptionRow } from './MobileNativeChatAskOptionRow' +import { MobileNativeChatOptionPreviewSheet } from './MobileNativeChatOptionPreviewSheet' +import { mobileNativeChatAskStyles as styles } from './MobileNativeChatAsk.styles' import { useMobileNativeChatReplyScroll } from './use-mobile-native-chat-reply-scroll' type Props = { @@ -66,9 +67,9 @@ export function MobileNativeChatAsk({ }: Props): React.JSX.Element { useMobileColorScheme() const t = useMobileTranslation() - const { scrollRef, inputRef, revealReply, scrollViewProps, revealContent } = - useMobileNativeChatReplyScroll() + const { scrollRef, inputRef, revealReply, onViewportLayout } = useMobileNativeChatReplyScroll() const [index, setIndex] = useState(0) + const [viewedOption, setViewedOption] = useState(null) const [selections, setSelections] = useState(() => prompt.questions.map(() => [])) const [otherText, setOtherText] = useState(() => prompt.questions.map((_, qi) => freeTextInputs?.[qi]?.initialValue ?? '') @@ -93,6 +94,7 @@ export function MobileNativeChatAsk({ const autoAdvance = useMobileNativeChatAskAutoAdvance(submitting) // Open each step at its question and end the last step's edit, so no typing lands out of view. const showStep = (next: (current: number) => number): void => { + setViewedOption(null) inputRef.current?.blur() scrollRef.current?.scrollTo({ y: 0, animated: false }) setIndex(next) @@ -105,17 +107,17 @@ export function MobileNativeChatAsk({ askAcceptsEmptyAnswer(prompt.questions[qi], freeTextInputs?.[qi]) // Delay single-select advance to show the choice; Other still needs text. - const toggle = (qi: number, optIndex: number, multi: boolean): void => { + const toggle = (qi: number, optIndex: number, multi: boolean, choosing = false): void => { // Block same-frame taps before disabled state renders. if (isLocalPending(operationRef.current) || answerPending) { return } const cur = selections[qi] ?? [] - // A pick reveals its preview, so a re-tap keeps it and the user confirms. + // Preview choices wait for Submit so inspecting alternatives never commits an answer. const keep = optIndex !== OTHER && askQuestionShowsPreviews(prompt.questions[qi]) const picked = !cur.includes(optIndex) const next = selections.map((s, i) => - i === qi ? toggleAskOption(cur, optIndex, multi, keep) : s + i === qi ? toggleAskOption(cur, optIndex, multi, keep || choosing) : s ) setSelections(next) autoAdvance.cancel() @@ -252,7 +254,12 @@ export function MobileNativeChatAsk({ ) : null} - + { + autoAdvance.cancel() + inputRef.current?.blur() + Keyboard.dismiss() + setViewedOption(optIndex) + }} selected={(selections[index] ?? []).includes(optIndex)} multi={q.multiSelect} disabled={submitting} @@ -333,98 +345,18 @@ export function MobileNativeChatAsk({ + setViewedOption(null)} + onChoose={(optionIndex) => { + setViewedOption(null) + toggle(index, optionIndex, q.multiSelect, true) + }} + /> ) } - -const styles = themedStyleSheet(() => ({ - card: { - flexShrink: 1, - minHeight: 0, - backgroundColor: colors.bgPanel, - borderTopWidth: StyleSheet.hairlineWidth, - borderTopColor: colors.borderSubtle - }, - tabs: { - flexGrow: 0, - paddingTop: spacing.sm, - borderBottomWidth: StyleSheet.hairlineWidth, - borderBottomColor: colors.borderSubtle - }, - tabsContent: { - paddingHorizontal: spacing.sm, - gap: spacing.xs, - alignItems: 'center' - }, - tab: { - flexDirection: 'row', - alignItems: 'center', - gap: 4, - minHeight: 36, - paddingHorizontal: spacing.sm, - paddingVertical: spacing.xs, - borderBottomWidth: 2, - borderBottomColor: 'transparent' - }, - tabActive: { - borderBottomColor: colors.statusGreen - }, - tabText: { - color: colors.textSecondary, - fontSize: typography.metaSize, - fontWeight: '600' - }, - tabTextActive: { - color: colors.textPrimary - }, - scroll: { - paddingHorizontal: spacing.md - }, - questionRow: { flexDirection: 'row', alignItems: 'flex-start', gap: spacing.sm }, - questionText: { - flex: 1, - marginVertical: spacing.sm - }, - other: { - marginBottom: spacing.xs - }, - footer: { - flexDirection: 'row', - alignItems: 'center', - justifyContent: 'space-between', - padding: spacing.md, - gap: spacing.sm, - borderTopWidth: StyleSheet.hairlineWidth, - borderTopColor: colors.borderSubtle - }, - cancel: { - paddingVertical: spacing.sm, - paddingHorizontal: spacing.sm - }, - cancelText: { - color: colors.textSecondary, - fontSize: typography.bodySize, - fontWeight: '600' - }, - progress: { - color: colors.textMuted, - fontSize: typography.metaSize - }, - next: { - paddingVertical: spacing.sm, - paddingHorizontal: spacing.lg, - borderRadius: radii.control, - backgroundColor: colors.textPrimary - }, - nextSkip: { - backgroundColor: colors.bgRaised - }, - nextText: { - color: colors.bgBase, - fontSize: typography.bodySize, - fontWeight: '700' - }, - nextSkipText: { - color: colors.textMuted - } -})) diff --git a/mobile/src/session/native-chat/input/MobileNativeChatAskOptionRow.tsx b/mobile/src/session/native-chat/input/MobileNativeChatAskOptionRow.tsx index 4a57a60103c..8734fd41ce0 100644 --- a/mobile/src/session/native-chat/input/MobileNativeChatAskOptionRow.tsx +++ b/mobile/src/session/native-chat/input/MobileNativeChatAskOptionRow.tsx @@ -1,5 +1,6 @@ -import { Pressable, ScrollView, Text, View, type LayoutChangeEvent } from 'react-native' +import { Pressable, Text, View } from 'react-native' import { Check } from 'lucide-react-native' +import { MobileNativeChatOptionThumbnail } from './MobileNativeChatOptionThumbnail' import { colors, concentricRadius, @@ -15,7 +16,7 @@ export function MobileNativeChatAskOptionRow({ label, description, preview, - onPreviewLayout, + onPreview, selected, multi, disabled, @@ -23,16 +24,16 @@ export function MobileNativeChatAskOptionRow({ }: { label: string description?: string - /** Shown under the row while it is selected, as the agent wrote it. */ + /** Read-only inspection is separate from choosing the option. */ preview?: string - /** The preview's edges in the card's scroll content; the row renders as its direct children. */ - onPreviewLayout?: (top: number, bottom: number) => void + onPreview?: () => void selected: boolean multi?: boolean disabled: boolean onPress: () => void }): React.JSX.Element { useMobileColorScheme() + const hasPreview = Boolean(preview && onPreview) const row = ( [ styles.option, selected && styles.optionSelected, + hasPreview && styles.optionWithPreview, pressed && pressedStyle ]} disabled={disabled} @@ -65,29 +67,15 @@ export function MobileNativeChatAskOptionRow({ ) - // One root shape whether or not the preview shows, so selecting never remounts the row. - return ( - <> + return hasPreview ? ( + {row} - {preview && selected ? ( - { - const { y, height } = event.nativeEvent.layout - onPreviewLayout?.(y, y + height) - }} - > - - {/* Mockups are drawn in columns, so they scroll sideways instead of wrapping at phone width. */} - - - {preview} - - - - - ) : null} - + + + + + ) : ( + row ) } @@ -137,18 +125,17 @@ const styles = themedStyleSheet(() => ({ color: colors.textSecondary, fontSize: typography.metaSize }, - preview: { - backgroundColor: colors.bgPanel, + optionCard: { borderWidth: 1, borderColor: colors.borderSubtle, borderRadius: concentricRadius(radii.surface, spacing.xs), - padding: spacing.sm, - marginBottom: spacing.xs, - maxHeight: 220 + backgroundColor: colors.bgRaised, + marginBottom: spacing.xs }, - previewText: { - color: colors.textPrimary, - fontFamily: typography.monoFamily, - fontSize: typography.metaSize + optionWithPreview: { borderWidth: 0, marginBottom: 0 }, + previewInset: { + marginLeft: 18 + spacing.sm * 2, + marginRight: spacing.sm, + marginBottom: spacing.sm } })) diff --git a/mobile/src/session/native-chat/input/MobileNativeChatOptionPreviewSheet.tsx b/mobile/src/session/native-chat/input/MobileNativeChatOptionPreviewSheet.tsx new file mode 100644 index 00000000000..3328570d533 --- /dev/null +++ b/mobile/src/session/native-chat/input/MobileNativeChatOptionPreviewSheet.tsx @@ -0,0 +1,129 @@ +import { useMemo } from 'react' +import { Pressable, ScrollView, Text, View } from 'react-native' +import type { AskQuestion } from '../../../../../src/shared/native-chat/input/native-chat-ask-types' +import { KeyedBottomDrawer } from '../../../components/bottom-drawer/keyed-bottom-drawer' +import { SheetHeader } from '../../../components/nav-bar/SheetHeader' +import { SheetPrimaryButton } from '../../../components/SheetPrimaryButton' +import { useMobileTranslation } from '../../../i18n/use-mobile-translation' +import { colors, radii, spacing, typography, pressedStyle } from '../../../theme/mobile-theme' +import { themedStyleSheet } from '../../../theme/themed-styles' +import { useMobileColorScheme } from '../../../theme/use-mobile-color-scheme' +import { optionPreviewFont } from './mobile-native-chat-option-preview' + +const sheetKey = () => 'option-preview' + +export function MobileNativeChatOptionPreviewSheet({ + options, + viewedIndex, + selected, + disabled, + onView, + onChoose, + onClose +}: { + options: AskQuestion['options'] + viewedIndex: number | null + selected: readonly number[] + disabled: boolean + onView: (index: number) => void + onChoose: (index: number) => void + onClose: () => void +}): React.JSX.Element { + useMobileColorScheme() + const t = useMobileTranslation() + const previews = useMemo( + () => options.flatMap((option, index) => (option.preview ? [{ option, index }] : [])), + [options] + ) + return ( + + {(index) => { + const option = options[index]! + return ( + <> + item.index === index) + 1, + total: previews.length + })} + onClose={onClose} + /> + + {previews.length > 1 ? ( + + {previews.map((item) => ( + onView(item.index)} + style={({ pressed }) => [styles.page, pressed && pressedStyle]} + > + + + ))} + + ) : null} + onChoose(index)} + /> + + ) + }} + + ) +} + +function ReadablePreview({ preview }: { preview: string }): React.JSX.Element { + useMobileColorScheme() + return ( + + + + {preview} + + + + ) +} + +const styles = themedStyleSheet(() => ({ + preview: { flex: 1, minHeight: 0, backgroundColor: colors.bgPanel }, + text: { + padding: spacing.md, + color: colors.textPrimary, + fontFamily: optionPreviewFont, + fontSize: typography.bodySize, + lineHeight: typography.bodySize * 1.5 + }, + pages: { flexGrow: 0, marginVertical: spacing.xs }, + pageContent: { flexGrow: 1, justifyContent: 'center' }, + page: { width: 44, height: 44, alignItems: 'center', justifyContent: 'center' }, + dot: { width: 6, height: 6, borderRadius: radii.pill, backgroundColor: colors.borderSubtle }, + currentDot: { backgroundColor: colors.textPrimary } +})) diff --git a/mobile/src/session/native-chat/input/MobileNativeChatOptionThumbnail.tsx b/mobile/src/session/native-chat/input/MobileNativeChatOptionThumbnail.tsx new file mode 100644 index 00000000000..1399a26db65 --- /dev/null +++ b/mobile/src/session/native-chat/input/MobileNativeChatOptionThumbnail.tsx @@ -0,0 +1,117 @@ +import { useState } from 'react' +import { Platform, Pressable, Text, View, type TextStyle } from 'react-native' +import { MobileEdgeFade } from '../../../components/MobileEdgeFade' +import { useMobileTranslation } from '../../../i18n/use-mobile-translation' +import { colors, radii, spacing, typography, pressedStyle } from '../../../theme/mobile-theme' +import { themedStyleSheet } from '../../../theme/themed-styles' +import { useMobileColorScheme } from '../../../theme/use-mobile-color-scheme' +import { optionPreviewFont } from './mobile-native-chat-option-preview' + +const MAX_HEIGHT = 96 - spacing.sm * 2 + +export function MobileNativeChatOptionThumbnail({ + label, + preview, + onPress +}: { + label: string + preview: string + onPress: () => void +}): React.JSX.Element { + return ( + + ) +} + +function MeasuredPreviewThumbnail({ + label, + preview, + onPress +}: { + label: string + preview: string + onPress: () => void +}): React.JSX.Element { + useMobileColorScheme() + const t = useMobileTranslation() + const [width, setWidth] = useState(0) + const [bounds, setBounds] = useState<{ width: number; height: number } | null>(null) + const scale = bounds && width > 0 ? Math.min(1, width / Math.max(1, bounds.width)) : 0 + const height = bounds && width > 0 ? Math.min(MAX_HEIGHT, bounds.height * scale) : MAX_HEIGHT + + return ( + [styles.thumbnail, pressed && pressedStyle]} + > + setWidth(event.nativeEvent.layout.width)} + style={[styles.image, { height }]} + accessibilityElementsHidden + importantForAccessibility="no-hide-descendants" + > + { + const { width, height } = event.nativeEvent.layout + setBounds((previous) => + previous?.width === width && previous.height === height ? previous : { width, height } + ) + }} + style={[styles.text, { transform: [{ scale }] }]} + > + {preview} + + {height >= MAX_HEIGHT ? : null} + + {t('chat.ask.viewPreview', 'View')} + + ) +} + +const styles = themedStyleSheet(() => ({ + thumbnail: { + minHeight: 44, + padding: spacing.sm, + borderWidth: 1, + borderColor: colors.borderSubtle, + borderRadius: radii.control, + backgroundColor: colors.bgPanel, + overflow: 'hidden' + }, + // Native rows measure absolute Text intrinsically; the web uses its explicit CSS width below. + image: { position: 'relative', flexDirection: 'row', overflow: 'hidden' }, + text: { + position: 'absolute', + ...(Platform.OS === 'web' + ? { + whiteSpace: 'pre' as const, + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: RN Web accepts intrinsic CSS widths; this branch never reaches native. + width: 'max-content' as TextStyle['width'] + } + : {}), + top: 0, + left: 0, + transformOrigin: 'top left', + fontFamily: optionPreviewFont, + fontSize: typography.metaSize, + lineHeight: typography.metaSize * 1.25, + color: colors.textPrimary, + includeFontPadding: false + }, + view: { + alignSelf: 'flex-end', + color: colors.textSecondary, + fontSize: typography.metaSize, + fontWeight: '600', + position: 'absolute', + right: spacing.xs, + bottom: spacing.xs, + paddingHorizontal: spacing.sm, + borderRadius: radii.pill, + backgroundColor: colors.bgRaised + } +})) diff --git a/mobile/src/session/native-chat/input/mobile-native-chat-option-preview.ts b/mobile/src/session/native-chat/input/mobile-native-chat-option-preview.ts new file mode 100644 index 00000000000..e39b7d52635 --- /dev/null +++ b/mobile/src/session/native-chat/input/mobile-native-chat-option-preview.ts @@ -0,0 +1,7 @@ +import { Platform } from 'react-native' +import { typography } from '../../../theme/mobile-theme' + +export const optionPreviewFont = Platform.select({ + ios: 'Menlo', + default: typography.monoFamily +}) diff --git a/mobile/src/session/native-chat/input/use-mobile-native-chat-reply-scroll.ts b/mobile/src/session/native-chat/input/use-mobile-native-chat-reply-scroll.ts index 9226a6f7f2f..fe9fd376050 100644 --- a/mobile/src/session/native-chat/input/use-mobile-native-chat-reply-scroll.ts +++ b/mobile/src/session/native-chat/input/use-mobile-native-chat-reply-scroll.ts @@ -1,18 +1,11 @@ import { useRef } from 'react' -import type { - LayoutChangeEvent, - NativeScrollEvent, - NativeSyntheticEvent, - ScrollView, - TextInput -} from 'react-native' +import type { LayoutChangeEvent, ScrollView, TextInput } from 'react-native' // Keep a focused reply in view when its card shrinks above the keyboard. export function useMobileNativeChatReplyScroll() { const scrollRef = useRef(null) const inputRef = useRef(null) const viewportHeight = useRef(0) - const scrollOffset = useRef(0) const revealReply = (): void => { if (inputRef.current?.isFocused()) { scrollRef.current?.scrollToEnd({ animated: false }) @@ -27,31 +20,5 @@ export function useMobileNativeChatReplyScroll() { revealReply() } } - const onScroll = (event: NativeSyntheticEvent): void => { - scrollOffset.current = event.nativeEvent.contentOffset.y - } - // Scroll just enough to show content that opened below the visible edge, never past its top. - const revealContent = (top: number, bottom: number): void => { - const hidden = bottom - (scrollOffset.current + viewportHeight.current) - if (viewportHeight.current > 0 && hidden > 0) { - scrollRef.current?.scrollTo({ - y: Math.min(scrollOffset.current + hidden, top), - animated: true - }) - } - } - const scrollViewProps = { - ref: scrollRef, - onLayout: onViewportLayout, - onScroll, - scrollEventThrottle: 16 - } - return { - scrollRef, - inputRef, - revealReply, - onViewportLayout, - scrollViewProps, - revealContent - } + return { scrollRef, inputRef, revealReply, onViewportLayout } } diff --git a/mobile/src/session/tabs/MobileNewTabSheet.tsx b/mobile/src/session/tabs/MobileNewTabSheet.tsx new file mode 100644 index 00000000000..0f7730ddd75 --- /dev/null +++ b/mobile/src/session/tabs/MobileNewTabSheet.tsx @@ -0,0 +1,183 @@ +import { useRef } from 'react' +import { Pressable, Text, View } from 'react-native' +import { FileText, Globe, SquareTerminal } from 'lucide-react-native' +import type { TuiAgent } from '../../../../src/shared/agent-launch/catalog/tui-agent' +import { ActionSheetContent, type ActionSheetAction } from '../../components/ActionSheetModal' +import { BottomDrawer } from '../../components/bottom-drawer/BottomDrawer' +import { + LIST_LEADING_INSET, + ListGroup, + ListRow, + SectionHeader +} from '../../components/list/ListGroup' +import { MobileAgentIcon } from '../../components/MobileAgentIcon' +import { SheetHeader } from '../../components/nav-bar/SheetHeader' +import { useMobileTranslation } from '../../i18n/use-mobile-translation' +import { colors, radii, spacing } from '../../theme/mobile-theme' +import { themedStyleSheet } from '../../theme/themed-styles' +import { useMobileColorScheme } from '../../theme/use-mobile-color-scheme' +import type { MobileNewTabAgentOption } from '../agent-launch/mobile-new-tab-agent-options' + +const AGENT_GRID_COLUMNS = 3 + +type Props = { + visible: boolean + workspaceName: string + agentOptions: readonly MobileNewTabAgentOption[] + /** Loading, none, other-server or error; shown instead of the agent grid. */ + agentStatusRow: ActionSheetAction | null + canCreateBrowser: boolean + canCreateMarkdownNote: boolean + onClose: () => void + onCreateAgent: (agent: TuiAgent) => void + onCreateTerminal: () => void + /** Runs after the sheet has gone, so it may open another modal. */ + onCreateBrowser: () => void + onCreateMarkdownNote: () => void +} + +export function MobileNewTabSheet({ + visible, + workspaceName, + agentOptions, + agentStatusRow, + canCreateBrowser, + canCreateMarkdownNote, + onClose, + onCreateAgent, + onCreateTerminal, + onCreateBrowser, + onCreateMarkdownNote +}: Props) { + useMobileColorScheme() + const t = useMobileTranslation() + // Wait for the iOS sheet window to unmount before presenting another native modal. + const afterCloseRef = useRef<(() => void) | null>(null) + const closeThen = (action: () => void) => { + afterCloseRef.current = action + onClose() + } + const closeAndRun = (action: () => void) => { + onClose() + action() + } + const showAgentGrid = agentStatusRow === null && agentOptions.length > 0 + // Short last rows keep empty slots so every tile stays a third of the row wide. + const agentRows: { options: MobileNewTabAgentOption[]; emptySlots: string[] }[] = [] + for (let start = 0; start < agentOptions.length; start += AGENT_GRID_COLUMNS) { + const options = agentOptions.slice(start, start + AGENT_GRID_COLUMNS) + const emptySlots: string[] = [] + for (let column = options.length; column < AGENT_GRID_COLUMNS; column += 1) { + emptySlots.push(`empty:${column}`) + } + agentRows.push({ options, emptySlots }) + } + const iconColor = colors.textSecondary + return ( + { + const run = afterCloseRef.current + afterCloseRef.current = null + run?.() + }} + dragContentToDismiss + > + + {showAgentGrid || agentStatusRow ? ( + + ) : null} + {agentStatusRow ? : null} + {showAgentGrid ? ( + + {agentRows.map((row) => ( + option.agent).join(':')} style={styles.gridRow}> + {row.options.map((option) => ( + closeAndRun(() => onCreateAgent(option.agent))} + accessibilityRole="button" + accessibilityLabel={option.label} + style={styles.tile} + > + {({ pressed }) => ( + <> + {pressed ? : null} + + + {option.label} + + + )} + + ))} + {row.emptySlots.map((slot) => ( + + ))} + + ))} + + ) : null} + + } + onPress={() => closeAndRun(onCreateTerminal)} + /> + {canCreateBrowser ? ( + } + navigates + onPress={() => closeThen(onCreateBrowser)} + /> + ) : null} + {canCreateMarkdownNote ? ( + } + onPress={() => closeAndRun(onCreateMarkdownNote)} + /> + ) : null} + + + ) +} + +const styles = themedStyleSheet(() => ({ + grid: { gap: spacing.sm }, + gridRow: { flexDirection: 'row', gap: spacing.sm }, + tile: { + flex: 1, + minWidth: 0, + height: 78, + borderRadius: radii.surface, + backgroundColor: colors.sheetGroup, + overflow: 'hidden', + alignItems: 'center', + justifyContent: 'center', + gap: spacing.sm, + paddingHorizontal: spacing.sm + }, + // Same wash as a pressed ListRow, laid over the tile so its own fill stays underneath. + tilePressed: { + position: 'absolute', + top: 0, + right: 0, + bottom: 0, + left: 0, + backgroundColor: colors.translucentFill + }, + tileLabel: { fontSize: 13.5, fontWeight: '600', color: colors.textPrimary, maxWidth: '100%' }, + // Padded like a tile: flex shares space after padding, so a bare spacer would widen its row's tiles. + tileSpacer: { flex: 1, paddingHorizontal: spacing.sm }, + actions: { marginTop: spacing.lg } +})) diff --git a/mobile/src/session/tabs/MobileSessionTabBar.tsx b/mobile/src/session/tabs/MobileSessionTabBar.tsx new file mode 100644 index 00000000000..a9aeb494c8e --- /dev/null +++ b/mobile/src/session/tabs/MobileSessionTabBar.tsx @@ -0,0 +1,361 @@ +import { useMemo, useRef, useState } from 'react' +import { Pressable, Text, View } from 'react-native' +import { Plus } from 'lucide-react-native' +import { Gesture, GestureDetector } from 'react-native-gesture-handler' +import Animated, { + Easing, + ReduceMotion, + useAnimatedStyle, + useSharedValue, + withSequence, + withTiming +} from 'react-native-reanimated' +import { triggerMediumImpact, triggerSelection } from '../../platform/haptics' +import { useMobileTranslation } from '../../i18n/use-mobile-translation' +import { AgentStateDot } from '../../components/AgentStateDot' +import { ArrivalFade } from '../../components/ArrivalFade' +import { useDrawerReducedMotion } from '../../components/bottom-drawer/bottom-drawer-constants' +import { SHEET_CURVE } from '../../components/sheet-motion-values' +import { useReducedMotionEnabled } from '../../platform/use-reduced-motion' +import { useKeyboardPersistingTaps } from '../../platform/keyboard-persisting-taps' +import { useNow } from '../../hooks/use-now' +import { agentStateLabel, type AgentDotState } from '../../worktree/agent-row-display' +import { colors, feedback, radii, spacing } from '../../theme/mobile-theme' +import { themedStyleSheet } from '../../theme/themed-styles' +import { useMobileColorScheme } from '../../theme/use-mobile-color-scheme' +import { buildMobileSessionTabRow, type MobileSessionTabRow } from './mobile-session-tab-rows' +import { MobileSessionTabMark } from './MobileSessionTabMark' +import { MobileSessionTabsSheet } from './MobileSessionTabsSheet' +import type { MobileSessionController } from '../use-mobile-session-controller' + +const SWIPE_SETTLE_MS = 250 +// A tab arriving from the side starts this far out, as a share of the tab cell's width. +const SWIPE_ENTRY_SHARE = 0.4 +const FLICK_VELOCITY = 600 +// With no tab on that side, the tab gives only this share of the drag. +const EDGE_RESISTANCE = 0.25 +const DRAG_CLICK_WINDOW_MS = 400 + +// A tab drawn before it had any agent state (from the phone's store) fades its dot in when one lands. +function TabBarDot({ tabId, state }: { tabId: string; state: AgentDotState | undefined }) { + const [startedEmpty] = useState({ tabId, empty: state === undefined }) + if (startedEmpty.tabId === tabId && startedEmpty.empty) { + return + } + return state && state !== 'idle' ? : null +} + +// Mounted with the bare tab, so the motion preference is read before the dot arrives. +function ArrivingTabBarDot({ state }: { state: AgentDotState | undefined }) { + const reducedMotion = useReducedMotionEnabled() + if (!state || state === 'idle') { + return null + } + return ( + + + + ) +} + +/** The tab you're in as one cell: tap for its actions, swipe for the next one; the count shows every tab, + adds one. */ +export function MobileSessionTabBar({ + controller, + inTopBar, + actionsCollapsed = false +}: { + controller: MobileSessionController + inTopBar: boolean + actionsCollapsed?: boolean +}) { + useMobileColorScheme() + const t = useMobileTranslation() + const { + activeSessionTabId, + connState, + createTabBusy, + handleOpenNewTab, + switchSessionTab, + openSessionTabActionSheetAfterKeyboardDismiss, + visibleTabs, + terminals + } = controller + // Why: the first tap must reach the bar with the keyboard open instead of only dismissing it (#5106). + const keepsKeyboard = useKeyboardPersistingTaps('handled') + const now = useNow(60_000) + const rows = useMemo( + () => visibleTabs.map((tab) => buildMobileSessionTabRow(tab, terminals, now)), + [visibleTabs, terminals, now] + ) + const activeIndex = rows.findIndex((row) => row.tab.id === activeSessionTabId) + const active: MobileSessionTabRow | undefined = rows[activeIndex] + const previous = activeIndex > 0 ? rows[activeIndex - 1] : undefined + const next = activeIndex !== -1 ? rows[activeIndex + 1] : undefined + const othersNeedYou = rows.some( + (row) => row.tab.id !== activeSessionTabId && row.group === 'needs-you' + ) + const [sheetOpen, setSheetOpen] = useState(false) + + const reducedMotion = useDrawerReducedMotion() + const offset = useSharedValue(0) + const width = useSharedValue(0) + // On the web, releasing a mouse drag also clicks the tab. + const dragEndedAtRef = useRef(0) + const settle = (to: number) => + withTiming( + to, + reducedMotion + ? { duration: 0, reduceMotion: ReduceMotion.Never } + : { duration: SWIPE_SETTLE_MS, easing: Easing.bezier(...SHEET_CURVE) } + ) + const step = (target: MobileSessionTabRow | undefined, direction: 1 | -1) => { + if (!target) { + offset.value = settle(0) + return + } + triggerSelection() + switchSessionTab(target.tab) + offset.value = withSequence( + withTiming(-direction * width.value * SWIPE_ENTRY_SHARE, { duration: 0 }), + settle(0) + ) + } + // Callbacks run on JS: the session page is a web document, and stepping switches React state. + const pan = Gesture.Pan() + .runOnJS(true) + .enabled(rows.length > 1) + .activeOffsetX([-12, 12]) + .failOffsetY([-10, 10]) + .onUpdate((event) => { + const target = event.translationX > 0 ? previous : next + offset.value = target ? event.translationX : event.translationX * EDGE_RESISTANCE + }) + .onEnd((event) => { + // oxlint-disable-next-line react/purity -- runs when the drag ends, never during render. + dragEndedAtRef.current = Date.now() + const direction = event.translationX > 0 ? 1 : -1 + const flicked = + Math.abs(event.velocityX) > FLICK_VELOCITY && Math.sign(event.velocityX) === direction + if (Math.abs(event.translationX) > width.value / 2 || flicked) { + step(direction === 1 ? previous : next, direction) + return + } + offset.value = settle(0) + }) + // Web has no worklet plugin; mapper hooks need this explicit dependency list. + const contentStyle = useAnimatedStyle( + () => ({ + transform: [{ translateX: offset.value }], + opacity: 1 - Math.min(Math.abs(offset.value) / Math.max(width.value, 1), 1) * 0.6 + }), + [offset, width] + ) + + const status = active?.dotState && active.dotState !== 'idle' ? active.dotState : undefined + const countLabel = + rows.length === 1 + ? t('session.tabBar.oneTab', '1 tab') + : t('session.tabBar.tabCount', '{{count}} tabs', { count: rows.length }) + const tabLabel = [active?.title, status ? agentStateLabel(status) : null] + .filter(Boolean) + .join(', ') + const countAccessibilityLabel = [ + countLabel, + othersNeedYou ? t('session.tabBar.anotherNeedsYou', 'another tab needs you') : null + ] + .filter(Boolean) + .join(', ') + const createDisabled = createTabBusy || connState !== 'connected' + const openTabActions = () => { + // The click a drag release produces on the web belongs to the drag. + if (!active || Date.now() - dragEndedAtRef.current < DRAG_CLICK_WINDOW_MS) { + return + } + openSessionTabActionSheetAfterKeyboardDismiss(active.tab) + } + + return ( + + {/* pan-y keeps vertical touches with the page on the web. */} + + { + width.value = event.nativeEvent.layout.width + }} + > + [styles.tabPress, pressed && styles.cellPressed]} + onPress={openTabActions} + onLongPress={() => { + triggerMediumImpact() + openTabActions() + }} + delayLongPress={400} + disabled={!active} + accessibilityRole="button" + accessibilityLabel={tabLabel || countLabel} + accessibilityHint={t('session.tabBar.actionsHint', 'Shows actions for this tab')} + accessibilityActions={[ + ...(next ? [{ name: 'nextTab', label: t('session.tabBar.next', 'Next tab') }] : []), + ...(previous + ? [{ name: 'previousTab', label: t('session.tabBar.previous', 'Previous tab') }] + : []) + ]} + onAccessibilityAction={(event) => { + const name = event.nativeEvent.actionName + if (name === 'nextTab') { + step(next, -1) + } else if (name === 'previousTab') { + step(previous, 1) + } + }} + > + {/* Only the contents slide, so the cell stays flush with the screen edge. */} + + {active ? ( + <> + + + + + + ) : null} + + {active?.title ?? countLabel} + + + + + + [ + styles.sideCell, + actionsCollapsed && !inTopBar && styles.lastCell, + pressed && styles.cellPressed + ]} + onPress={() => setSheetOpen(true)} + accessibilityRole="button" + accessibilityLabel={countAccessibilityLabel} + accessibilityHint={t('session.tabBar.hint', 'Shows all tabs')} + > + + {rows.length} + + {othersNeedYou ? : null} + + {/* A collapsed bar's + lives in the header's ⋯ menu. */} + {!actionsCollapsed ? ( + [ + styles.sideCell, + !inTopBar && styles.lastCell, + pressed && styles.cellPressed, + createDisabled && styles.cellDisabled + ]} + disabled={createDisabled} + onPress={handleOpenNewTab} + accessibilityRole="button" + accessibilityLabel={t('session.tabStrip.newTab', 'New tab')} + accessibilityState={{ disabled: createDisabled }} + > + + + ) : null} + setSheetOpen(false)} + /> + + ) +} + +const styles = themedStyleSheet(() => ({ + bar: { + height: 44, + flexDirection: 'row', + alignItems: 'stretch', + borderTopWidth: 1, + borderTopColor: colors.borderSubtle + }, + // Cancels the top bar's vertical padding so the cells run the bar's full height. + barInTopBar: { + flex: 1, + minWidth: 0, + flexDirection: 'row', + alignItems: 'stretch', + alignSelf: 'stretch', + marginVertical: -spacing.xs, + marginLeft: spacing.md, + borderLeftWidth: 1, + borderLeftColor: colors.borderSubtle + }, + // The open tab, drawn like the strip's active tab: raised, with a line under it. + tabCell: { + flex: 1, + minWidth: 0, + backgroundColor: colors.bgRaised, + borderBottomWidth: 2, + borderBottomColor: colors.textSecondary, + borderRightWidth: 1, + borderRightColor: colors.borderSubtle, + overflow: 'hidden' + }, + tabPress: { + flex: 1, + justifyContent: 'center', + paddingLeft: spacing.lg, + paddingRight: spacing.sm + }, + tabContent: { flexDirection: 'row', alignItems: 'center', gap: 6 }, + // Keeps web SVGs from shrinking before the title ellipsizes. + mark: { flexShrink: 0 }, + title: { + flexShrink: 1, + minWidth: 0, + fontSize: 14, + fontWeight: '600', + color: colors.textPrimary + }, + sideCell: { + width: 46, + alignItems: 'center', + justifyContent: 'center', + borderRightWidth: 1, + borderRightColor: colors.borderSubtle + }, + // At the screen edge; in the top bar the hairline stays to part the cells from the round buttons. + lastCell: { borderRightWidth: 0 }, + cellPressed: { backgroundColor: colors.translucentFill }, + cellDisabled: { opacity: feedback.disabledOpacity }, + countBox: { + minWidth: 19, + height: 19, + paddingHorizontal: 3, + borderRadius: 6, + borderWidth: 1.8, + borderColor: colors.textPrimary, + alignItems: 'center', + justifyContent: 'center' + }, + countText: { + fontSize: 11, + fontWeight: '700', + color: colors.textPrimary, + fontVariant: ['tabular-nums'] + }, + // Another tab needs you: a red dot on the count's corner, ringed in the bar's colour. + alert: { + position: 'absolute', + top: 8, + right: 9, + width: 9, + height: 9, + borderRadius: radii.pill, + backgroundColor: colors.statusRed, + borderWidth: 2, + borderColor: colors.bgPanel + } +})) diff --git a/mobile/src/session/tabs/MobileSessionTabMark.tsx b/mobile/src/session/tabs/MobileSessionTabMark.tsx new file mode 100644 index 00000000000..67a1d0b3895 --- /dev/null +++ b/mobile/src/session/tabs/MobileSessionTabMark.tsx @@ -0,0 +1,28 @@ +import { File, FileText, Globe, SquareTerminal } from 'lucide-react-native' +import { MobileAgentIcon } from '../../components/MobileAgentIcon' +import { colors } from '../../theme/mobile-theme' +import { useMobileColorScheme } from '../../theme/use-mobile-color-scheme' +import type { MobileSessionTabRow } from './mobile-session-tab-rows' + +/** The tab's agent icon, else an icon for what kind of tab it is. */ +export function MobileSessionTabMark({ + row, + size +}: { + row: Pick + size: number +}) { + useMobileColorScheme() + if (row.agentId) { + return + } + const Icon = + row.tab.type === 'browser' + ? Globe + : row.tab.type === 'markdown' + ? FileText + : row.tab.type === 'file' + ? File + : SquareTerminal + return +} diff --git a/mobile/src/session/tabs/MobileSessionTabStrip.tsx b/mobile/src/session/tabs/MobileSessionTabStrip.tsx deleted file mode 100644 index 6455c9bf6f8..00000000000 --- a/mobile/src/session/tabs/MobileSessionTabStrip.tsx +++ /dev/null @@ -1,327 +0,0 @@ -import { useCallback, useMemo, useRef, useState } from 'react' -import { View, Text, ScrollView, Pressable, StyleSheet } from 'react-native' -import { File, FileText, Globe, Plus, SquareTerminal } from 'lucide-react-native' -import { triggerMediumImpact } from '../../platform/haptics' -import { useMobileTranslation } from '../../i18n/use-mobile-translation' -import { MobileAgentIcon } from '../../components/MobileAgentIcon' -import { AgentStateDot } from '../../components/AgentStateDot' -import { ArrivalFade } from '../../components/ArrivalFade' -import { useReducedMotionEnabled } from '../../platform/use-reduced-motion' -import { useNow } from '../../hooks/use-now' -import { - agentDotState, - agentStateLabel, - type AgentDotState -} from '../../worktree/agent-row-display' -import { - getMobileTerminalTabHostAgentIdentity, - getMobileSessionTabTitle, - resolveMobileTerminalTabAgentId -} from '../../terminal/session/mobile-terminal-tab-agent' -import { colors, spacing } from '../../theme/mobile-theme' -import { useMobileColorScheme } from '../../theme/use-mobile-color-scheme' -import { NavBarButton } from '../../components/nav-bar/NavBarButton' -import { - resolveTabStripEdgeHint, - resolveTabStripHiddenTabs, - resolveTabStripTapOffset, - type TabStripHiddenTabs -} from './tab-strip-scroll' -import { styles } from '../mobile-session-styles' -import { useKeyboardPersistingTaps } from '../../platform/keyboard-persisting-taps' -import type { MobileSessionController } from '../use-mobile-session-controller' - -const DOUBLE_TAP_RENAME_MS = 300 - -// A tab drawn before it had any agent state (a strip from the phone's store) fades its dot in when one lands. -function SessionTabAgentDot({ state }: { state: AgentDotState | undefined }) { - const [startedEmpty] = useState(state === undefined) - if (startedEmpty) { - return - } - return state && state !== 'idle' ? : null -} - -// Mounted with the bare tab, so the motion preference is read before the dot arrives. -function ArrivingSessionTabAgentDot({ state }: { state: AgentDotState | undefined }) { - const reducedMotion = useReducedMotionEnabled() - if (!state || state === 'idle') { - return null - } - return ( - - - - ) -} - -export function MobileSessionTabStrip({ - controller, - inTopBar, - actionsCollapsed = false -}: { - controller: MobileSessionController - inTopBar: boolean - actionsCollapsed?: boolean -}) { - useMobileColorScheme() - const t = useMobileTranslation() - const { - activeSessionTabId, - activeSessionTabIdRef, - tabStripRef, - tabStripOffsetRef, - tabStripViewportWidthRef, - tabStripContentWidthRef, - tabLayoutsRef, - connState, - createTabBusy, - handleOpenNewTab, - scrollActiveTabIntoView, - holdTabStripReveal, - cancelHeldTabStripReveal, - switchSessionTab, - openSessionTabActionSheetAfterKeyboardDismiss, - setRenameTarget, - activeHandleRef, - visibleTabs, - terminals - } = controller - const tabBarKeepsKeyboard = useKeyboardPersistingTaps('handled') - const lastTabTapRef = useRef<{ id: string; at: number } | null>(null) - const now = useNow(60_000) - const tabStates = useMemo(() => { - const states = new Map() - for (const tab of visibleTabs) { - // Why: a status restored across a host restart is unconfirmed, so like desktop it shows no live state. - if (tab.type === 'terminal' && tab.agentStatus && !tab.agentStatus.restoredUnconfirmed) { - states.set(tab.id, agentDotState(tab.agentStatus, now)) - } else if (tab.type === 'agent-session' && tab.chatStatus) { - states.set(tab.id, agentDotState(tab.chatStatus, now)) - } - } - return states - }, [visibleTabs, now]) - const [hiddenTabs, setHiddenTabs] = useState({ left: [], right: [] }) - const refreshHiddenTabs = () => { - const next = resolveTabStripHiddenTabs({ - layouts: tabLayoutsRef.current, - viewportWidth: tabStripViewportWidthRef.current, - currentOffset: tabStripOffsetRef.current - }) - // Why: scroll fires every frame; re-render only when a tab crosses an edge. - setHiddenTabs((prev) => - prev.left.join('\n') === next.left.join('\n') && - prev.right.join('\n') === next.right.join('\n') - ? prev - : next - ) - } - const leftHint = resolveTabStripEdgeHint(hiddenTabs.left, tabStates) - const rightHint = resolveTabStripEdgeHint(hiddenTabs.right, tabStates) - const pressTab = useCallback( - (t: (typeof visibleTabs)[number]) => { - const at = Date.now() - const lastTap = lastTabTapRef.current - lastTabTapRef.current = { id: t.id, at } - if ( - lastTap?.id === t.id && - at - lastTap.at < DOUBLE_TAP_RENAME_MS && - t.type === 'terminal' && - typeof t.terminal === 'string' - ) { - lastTabTapRef.current = null - triggerMediumImpact() - setRenameTarget({ - handle: t.terminal, - title: t.title, - isActive: t.terminal === activeHandleRef.current - }) - // The first tap's held reveal still runs once the window closes. - return - } - cancelHeldTabStripReveal() - const nextOffset = resolveTabStripTapOffset({ - tabId: t.id, - tabs: visibleTabs, - layouts: tabLayoutsRef.current, - viewportWidth: tabStripViewportWidthRef.current, - contentWidth: tabStripContentWidthRef.current, - currentOffset: tabStripOffsetRef.current - }) - if (nextOffset !== tabStripOffsetRef.current) { - holdTabStripReveal(nextOffset, DOUBLE_TAP_RENAME_MS) - } - switchSessionTab(t) - }, - [ - activeHandleRef, - cancelHeldTabStripReveal, - holdTabStripReveal, - setRenameTarget, - switchSessionTab, - tabLayoutsRef, - tabStripContentWidthRef, - tabStripOffsetRef, - tabStripRef, - tabStripViewportWidthRef, - visibleTabs - ] - ) - const attachTabStrip = useCallback( - (view: ScrollView | null) => { - if (view) { - tabStripOffsetRef.current = 0 - tabStripViewportWidthRef.current = 0 - tabStripContentWidthRef.current = 0 - tabLayoutsRef.current.clear() - } - tabStripRef.current = view - }, - [ - tabStripRef, - tabStripOffsetRef, - tabStripViewportWidthRef, - tabStripContentWidthRef, - tabLayoutsRef - ] - ) - return ( - - {/* Why: tab taps must register on first press with the keyboard open instead of being eaten by dismissal (#5106). */} - - { - tabStripOffsetRef.current = e.nativeEvent.contentOffset.x - refreshHiddenTabs() - }} - onLayout={(e) => { - tabStripViewportWidthRef.current = e.nativeEvent.layout.width - scrollActiveTabIntoView(activeSessionTabIdRef.current, false) - refreshHiddenTabs() - }} - onContentSizeChange={(width) => { - tabStripContentWidthRef.current = width - scrollActiveTabIntoView(activeSessionTabIdRef.current, false) - refreshHiddenTabs() - }} - > - {visibleTabs.map((tab, index) => { - const tabState = tabStates.get(tab.id) - const hostAgentIdentity = getMobileTerminalTabHostAgentIdentity(tab, terminals) - const title = getMobileSessionTabTitle(tab, hostAgentIdentity) - return ( - [ - styles.tab, - index === 0 && !inTopBar && styles.tabFirst, - tab.id === activeSessionTabId && styles.tabActive, - pressed && styles.tabPressed - ]} - onLayout={(e) => { - const { x, width } = e.nativeEvent.layout - tabLayoutsRef.current.set(tab.id, { x, width }) - if (tab.id === activeSessionTabIdRef.current) { - scrollActiveTabIntoView(tab.id, false) - } - refreshHiddenTabs() - }} - onPress={() => pressTab(tab)} - accessibilityRole="tab" - accessibilityLabel={ - tabState && tabState !== 'idle' - ? t('session.tabStrip.tabStatus', '{{title}}, {{status}}', { - title, - status: agentStateLabel(tabState) - }) - : title - } - accessibilityState={{ selected: tab.id === activeSessionTabId }} - onLongPress={() => { - triggerMediumImpact() - openSessionTabActionSheetAfterKeyboardDismiss(tab) - }} - delayLongPress={400} - > - - - - {tab.type === 'browser' && ( - - )} - {tab.type === 'markdown' && ( - - )} - {tab.type === 'file' && ( - - )} - {tab.type === 'agent-session' && ( - - )} - {tab.type === 'terminal' && - (() => { - const agentId = resolveMobileTerminalTabAgentId(tab, hostAgentIdentity) - return agentId ? ( - - ) : ( - - ) - })()} - - - {title} - - - - ) - })} - - {leftHint ? ( - - - - ) : null} - {rightHint ? ( - - - - ) : null} - - {/* Terminal layout and Quick commands live in the header's ⋯ menu. */} - {!actionsCollapsed ? ( - - - - ) : null} - - ) -} - -// The right inset matches the nav bar's, so the + lines up with the ⋯ above it. -const newTabStyles = StyleSheet.create({ - slot: { - paddingLeft: spacing.sm, - paddingRight: spacing.md - } -}) diff --git a/mobile/src/session/tabs/MobileSessionTabsSheet.tsx b/mobile/src/session/tabs/MobileSessionTabsSheet.tsx new file mode 100644 index 00000000000..f8cd5cd1981 --- /dev/null +++ b/mobile/src/session/tabs/MobileSessionTabsSheet.tsx @@ -0,0 +1,220 @@ +import { Fragment, useRef, useState } from 'react' +import { Pressable, Text, View } from 'react-native' +import { Plus, X } from 'lucide-react-native' +import { BottomDrawer } from '../../components/bottom-drawer/BottomDrawer' +import { ListGroup, SectionHeader } from '../../components/list/ListGroup' +import { NavBarButton } from '../../components/nav-bar/NavBarButton' +import { SheetHeader } from '../../components/nav-bar/SheetHeader' +import { SwipeRowActions } from '../../components/SwipeRowActions' +import { AgentStateDot } from '../../components/AgentStateDot' +import { useMobileTranslation } from '../../i18n/use-mobile-translation' +import { useNow } from '../../hooks/use-now' +import { formatTimeAgo } from '../../worktree/agent-row-display' +import { colors, radii, spacing } from '../../theme/mobile-theme' +import { themedStyleSheet } from '../../theme/themed-styles' +import { useMobileColorScheme } from '../../theme/use-mobile-color-scheme' +import type { MobileSessionTabGroup, MobileSessionTabRow } from './mobile-session-tab-rows' +import { MobileSessionTabMark } from './MobileSessionTabMark' +import type { MobileSessionController } from '../use-mobile-session-controller' + +const TILE_SIZE = 34 +const TILE_DOT_RING = 2 +const GROUP_ORDER: readonly MobileSessionTabGroup[] = ['needs-you', 'working', 'other'] + +/** Every tab in the workspace, what needs you first; tap one to go there, swipe one to close it. */ +export function MobileSessionTabsSheet({ + controller, + rows, + visible, + onClose +}: { + controller: MobileSessionController + rows: readonly MobileSessionTabRow[] + visible: boolean + onClose: () => void +}) { + useMobileColorScheme() + const t = useMobileTranslation() + const now = useNow(60_000) + const { + activeSessionTabId, + worktreeName, + switchSessionTab, + handleCloseSessionTab, + handleOpenNewTab, + createTabBusy, + connState + } = controller + // Sections hold still while the sheet is open, so a row never moves under a finger. + const [frozenGroups, setFrozenGroups] = useState>() + if (visible && frozenGroups === undefined) { + setFrozenGroups(new Map(rows.map((row) => [row.tab.id, row.group]))) + } + const afterCloseRef = useRef<(() => void) | null>(null) + const sections = GROUP_ORDER.map((group) => ({ + group, + rows: rows.filter((row) => (frozenGroups?.get(row.tab.id) ?? row.group) === group) + })).filter((section) => section.rows.length > 0) + const sectionTitles: Record = { + 'needs-you': t('session.tabsSheet.needsYou', 'Needs you'), + working: t('session.tabsSheet.working', 'Working'), + other: t('session.tabsSheet.everythingElse', 'Everything else') + } + const title = + rows.length === 1 + ? t('session.tabBar.oneTab', '1 tab') + : t('session.tabBar.tabCount', '{{count}} tabs', { count: rows.length }) + + const renderRow = (row: MobileSessionTabRow) => { + const current = row.tab.id === activeSessionTabId + const badge = row.dotState && row.dotState !== 'idle' ? row.dotState : undefined + const time = current + ? t('session.tabsSheet.open', 'Open') + : row.timeAt !== null + ? formatTimeAgo(row.timeAt, now) + : '' + return ( + void handleCloseSessionTab(row.tab) + }} + > + {(guardPress) => ( + { + if (!current) { + switchSessionTab(row.tab) + } + onClose() + })} + > + {({ pressed }) => ( + <> + {current || pressed ? : null} + + + {badge ? ( + + + + ) : null} + + + + {row.title} + + + {row.detail} + + + {time ? ( + {time} + ) : null} + + )} + + )} + + ) + } + + return ( + { + setFrozenGroups(undefined) + const afterClose = afterCloseRef.current + afterCloseRef.current = null + afterClose?.() + }} + > + + + + { + // The new-tab sheet is its own drawer; open it once this one is gone. + afterCloseRef.current = handleOpenNewTab + onClose() + }} + /> + + + + {sections.map((section, index) => ( + + {sections.length > 1 ? ( + + ) : null} + + {section.rows.map(renderRow)} + + + ))} + + + ) +} + +const styles = themedStyleSheet(() => ({ + // Over the sheet header's empty trailing side, centred in its 52pt row. + newTab: { position: 'absolute', top: 8, right: spacing.xs }, + body: { paddingBottom: spacing.lg }, + // Opaque so a swipe's action stays hidden until the row slides off it. + row: { + minHeight: 60, + flexDirection: 'row', + alignItems: 'center', + gap: spacing.md, + paddingHorizontal: spacing.lg, + paddingVertical: spacing.sm, + backgroundColor: colors.sheetGroup + }, + // The tab you're in, or a pressed row, washed like a picked segment on a sheet group. + wash: { + position: 'absolute', + top: 0, + right: 0, + bottom: 0, + left: 0, + backgroundColor: colors.translucentFill + }, + tile: { + width: TILE_SIZE, + height: TILE_SIZE, + borderRadius: radii.tile, + backgroundColor: colors.translucentFill, + alignItems: 'center', + justifyContent: 'center' + }, + // The state dot on the tile's corner, ringed in the group's colour. + tileBadge: { + position: 'absolute', + top: -4, + right: -4, + padding: TILE_DOT_RING, + borderRadius: radii.pill, + backgroundColor: colors.sheetGroup + }, + text: { flex: 1, minWidth: 0, gap: 2 }, + title: { fontSize: 15, fontWeight: '600', color: colors.textPrimary }, + detail: { fontSize: 13, color: colors.textSecondary }, + time: { fontSize: 12, color: colors.textMuted, fontVariant: ['tabular-nums'] }, + timeCurrent: { fontWeight: '600', color: colors.accentBlue } +})) diff --git a/mobile/src/session/tabs/mobile-session-tab-rows.ts b/mobile/src/session/tabs/mobile-session-tab-rows.ts new file mode 100644 index 00000000000..1b2854512f6 --- /dev/null +++ b/mobile/src/session/tabs/mobile-session-tab-rows.ts @@ -0,0 +1,121 @@ +import { agentListPreview } from '../../agents/agent-list-row-text' +import { agentStatusGroup } from '../../agents/agent-list-rows' +import { translate } from '../../i18n/mobile-i18n' +import { + getMobileSessionTabTitle, + getMobileTerminalTabHostAgentIdentity, + resolveMobileTerminalTabAgentId +} from '../../terminal/session/mobile-terminal-tab-agent' +import { + agentDotState, + agentRowTimeAt, + agentStateLabel, + type AgentDotState +} from '../../worktree/agent-row-display' +import type { MobileSessionTab } from './mobile-session-tabs' + +export type MobileSessionTabGroup = 'needs-you' | 'working' | 'other' + +export type MobileSessionTabRow = { + tab: MobileSessionTab + title: string + /** The agent whose icon marks the tab; null draws the tab kind's icon. */ + agentId: string | null + dotState: AgentDotState | undefined + group: MobileSessionTabGroup + /** The second line: the state, then what the tab is doing or showing. */ + detail: string + timeAt: number | null +} + +export function mobileSessionTabDotState( + tab: MobileSessionTab, + now: number +): AgentDotState | undefined { + // Why: a status restored across a host restart is unconfirmed, so like desktop it shows no live state. + if (tab.type === 'terminal' && tab.agentStatus && !tab.agentStatus.restoredUnconfirmed) { + return agentDotState(tab.agentStatus, now) + } + if (tab.type === 'agent-session' && tab.chatStatus) { + return agentDotState(tab.chatStatus, now) + } + return undefined +} + +function tabGroup(state: AgentDotState | undefined): MobileSessionTabGroup { + if (!state) { + return 'other' + } + const group = agentStatusGroup(state) + return group === 'needs-you' || group === 'working' ? group : 'other' +} + +function tabContent( + tab: MobileSessionTab, + title: string, + dotState: AgentDotState | undefined +): string { + switch (tab.type) { + case 'terminal': { + const status = tab.agentStatus + if (!status || !dotState) { + return '' + } + return agentListPreview(status, agentStatusGroup(dotState), title) + } + case 'browser': + return tab.url === title ? '' : tab.url + case 'markdown': + case 'file': + return tab.relativePath === title ? '' : tab.relativePath + case 'agent-session': + return '' + } +} + +function tabKindLabel(tab: MobileSessionTab): string { + switch (tab.type) { + case 'browser': + return translate('session.tabRows.browser', 'Browser') + case 'markdown': + return translate('session.tabRows.markdown', 'Markdown note') + case 'file': + return translate('session.tabRows.file', 'File') + case 'agent-session': + return translate('session.tabRows.chat', 'Chat') + case 'terminal': + return translate('session.tabRows.terminal', 'Terminal') + } +} + +export function buildMobileSessionTabRow( + tab: MobileSessionTab, + terminals: readonly { handle: string; agentIdentity?: string }[], + now: number +): MobileSessionTabRow { + const hostAgentIdentity = getMobileTerminalTabHostAgentIdentity(tab, terminals) + const title = getMobileSessionTabTitle(tab, hostAgentIdentity) + const dotState = mobileSessionTabDotState(tab, now) + const stateWord = dotState && dotState !== 'idle' ? agentStateLabel(dotState) : '' + const content = tabContent(tab, title, dotState) + const timeAt = + tab.type === 'terminal' && tab.agentStatus && !tab.agentStatus.restoredUnconfirmed + ? agentRowTimeAt(tab.agentStatus) + : tab.type === 'agent-session' && tab.chatStatus + ? tab.chatStatus.updatedAt + : null + return { + tab, + title, + agentId: + tab.type === 'agent-session' + ? tab.agent + : tab.type === 'terminal' + ? resolveMobileTerminalTabAgentId(tab, hostAgentIdentity) + : null, + dotState, + group: tabGroup(dotState), + detail: [stateWord, content].filter(Boolean).join(' · ') || tabKindLabel(tab), + timeAt + } +} diff --git a/mobile/src/session/tabs/tab-strip-scroll.ts b/mobile/src/session/tabs/tab-strip-scroll.ts index 9b9dd9ce99b..e7d6c85e416 100644 --- a/mobile/src/session/tabs/tab-strip-scroll.ts +++ b/mobile/src/session/tabs/tab-strip-scroll.ts @@ -1,5 +1,3 @@ -import type { AgentDotState } from '../../worktree/agent-row-display' - export type TabStripScrollInput = { tabX: number tabWidth: number @@ -36,98 +34,3 @@ export function resolveTabStripScrollOffset({ return Math.min(Math.max(0, nextOffset), maxOffset) } - -type TabLayouts = ReadonlyMap - -export function resolveTabStripTapOffset(args: { - tabId: string - tabs: readonly { id: string }[] - layouts: TabLayouts - viewportWidth: number - contentWidth: number - currentOffset: number -}): number { - const { tabs, layouts, viewportWidth, contentWidth, currentOffset } = args - const index = tabs.findIndex((tab) => tab.id === args.tabId) - const selected = layouts.get(args.tabId) - if (index === -1 || !selected || viewportWidth <= 0) { - return currentOffset - } - const selectedOnly = resolveTabStripScrollOffset({ - tabX: selected.x, - tabWidth: selected.width, - viewportWidth, - contentWidth, - currentOffset - }) - if (selectedOnly === currentOffset) { - return currentOffset - } - const left = selected.x + selected.width / 2 < currentOffset + viewportWidth / 2 - const neighbor = tabs[index + (left ? -1 : 1)] - const layout = neighbor ? layouts.get(neighbor.id) : undefined - let start = selected.x - let end = selected.x + selected.width - if (layout) { - const gap = left ? selected.x - (layout.x + layout.width) : layout.x - end - // Keep the tapped tab whole while revealing as much of its neighbor as fits within both margins. - const peek = Math.min(layout.width, Math.max(0, viewportWidth - 24 - selected.width - gap)) - if (left) { - start -= gap + peek - } else { - end += gap + peek - } - } - return resolveTabStripScrollOffset({ - tabX: start, - tabWidth: end - start, - viewportWidth, - contentWidth, - currentOffset - }) -} - -export type TabStripHiddenTabs = { left: readonly string[]; right: readonly string[] } - -export function resolveTabStripHiddenTabs(args: { - layouts: TabLayouts - viewportWidth: number - currentOffset: number -}): TabStripHiddenTabs { - const left: string[] = [] - const right: string[] = [] - if (args.viewportWidth > 0) { - for (const [tabId, layout] of args.layouts) { - const center = layout.x + layout.width / 2 - if (center < args.currentOffset) { - left.push(tabId) - } else if (center > args.currentOffset + args.viewportWidth) { - right.push(tabId) - } - } - } - return { left, right } -} - -// Lower ranks win when several hidden tabs share an edge; other states get no edge hint. -const EDGE_HINT_RANK: Partial> = { - blocked: 0, - waiting: 0, - working: 1, - monitoring: 1 -} - -export function resolveTabStripEdgeHint( - tabIds: readonly string[], - tabStates: ReadonlyMap -): AgentDotState | null { - let hint: AgentDotState | null = null - for (const tabId of tabIds) { - const state = tabStates.get(tabId) - const rank = state ? EDGE_HINT_RANK[state] : undefined - if (state && rank !== undefined && (hint === null || rank < (EDGE_HINT_RANK[hint] ?? 0))) { - hint = state - } - } - return hint -} diff --git a/mobile/src/session/use-mobile-session-foundation.ts b/mobile/src/session/use-mobile-session-foundation.ts index 6ecb5ae9870..cdc21bbabb0 100644 --- a/mobile/src/session/use-mobile-session-foundation.ts +++ b/mobile/src/session/use-mobile-session-foundation.ts @@ -52,6 +52,7 @@ export function useMobileSessionFoundation() { name: worktreeName, path: worktreePath, hostId: worktreeHostId, + branch: worktreeBranch, resolution: worktreeResolution } = useLiveWorktreeName({ client, @@ -115,6 +116,7 @@ export function useMobileSessionFoundation() { worktreeName, worktreePath, worktreeHostId, + worktreeBranch, worktreeResolution, isWideLayout, activePanel, diff --git a/mobile/src/session/use-mobile-session-panel-route-actions.tsx b/mobile/src/session/use-mobile-session-panel-route-actions.tsx index 6cd74e382eb..c4ae529e4a8 100644 --- a/mobile/src/session/use-mobile-session-panel-route-actions.tsx +++ b/mobile/src/session/use-mobile-session-panel-route-actions.tsx @@ -7,7 +7,7 @@ import { shouldShowSessionHeaderChecksAction, panelRouteDescriptor } from './session-panel-host' -import { MobileAgentIcon } from '../components/MobileAgentIcon' +import type { ActionSheetAction } from '../components/ActionSheetModal' import { useMobileTranslation } from '../i18n/use-mobile-translation' import { useWorkspaceExecutionHost, @@ -49,127 +49,81 @@ export function useMobileSessionPanelRouteActions(scope: MobileSessionPresentati quickCommandsSupported, showToast } = scope - const otherRuntimeAgentRow = { - id: 'otherServerAgents', - label: t('session.usePanelRouteActions.otherServerAgents', 'Agents on Another Server'), - hint: t('session.usePanelRouteActions.pairServerHint', 'Pair that server directly'), - icon: Bot, - disabled: true, - onPress: () => {} - } - const createTabAgentActions = + const agentStatusRow = (errorHint: string): ActionSheetAction | null => createTabAgentLoadState === 'loading' - ? [ - { - id: 'detectingAgents', - label: t('session.usePanelRouteActions.detectingAgents', 'Detecting Agents'), - icon: Bot, - disabled: true, - loading: true, - onPress: () => {} - } - ] + ? { + id: 'detectingAgents', + label: t('session.usePanelRouteActions.detectingAgents', 'Detecting Agents'), + icon: Bot, + disabled: true, + loading: true, + onPress: () => {} + } : createTabAgentOptions.length > 0 - ? createTabAgentOptions.map((option) => ({ - id: `agent:${option.agent}`, - label: option.label, - renderIcon: () => , - onPress: () => { - setShowCreateTabDrawer(false) - void handleCreateTerminal(option.agent) - } - })) + ? null : createTabAgentLoadState === 'loaded' - ? [ - { - id: 'noEnabledAgents', - label: t('session.usePanelRouteActions.noEnabledAgents', 'No Enabled Agents'), + ? { + id: 'noEnabledAgents', + label: t('session.usePanelRouteActions.noEnabledAgents', 'No Enabled Agents'), + icon: Bot, + disabled: true, + onPress: () => {} + } + : createTabAgentLoadState === 'other-runtime' + ? { + id: 'otherServerAgents', + label: t( + 'session.usePanelRouteActions.otherServerAgents', + 'Agents on Another Server' + ), + hint: t('session.usePanelRouteActions.pairServerHint', 'Pair that server directly'), icon: Bot, disabled: true, onPress: () => {} } - ] - : createTabAgentLoadState === 'other-runtime' - ? [otherRuntimeAgentRow] : createTabAgentLoadState === 'error' - ? [ - { - id: 'presetsUnavailable', - label: t( - 'session.usePanelRouteActions.presetsUnavailable', - 'Agent Presets Unavailable' - ), - hint: t( - 'session.usePanelRouteActions.checkHostHint', - 'Check the host connection' - ), - icon: Bot, - disabled: true, - onPress: () => {} - } - ] - : [] - const sendDiffNotesAgentActions = - pendingDiffNotesDelivery === null - ? [] - : createTabAgentLoadState === 'loading' - ? [ - { - id: 'detectingAgents', - label: t('session.usePanelRouteActions.detectingAgents', 'Detecting Agents'), - icon: Bot, - disabled: true, - loading: true, - onPress: () => {} - } - ] - : createTabAgentOptions.length > 0 - ? createTabAgentOptions.map((option) => ({ - id: `agent:${option.agent}`, - label: option.label, - hint: t('session.usePanelRouteActions.newSessionHint', 'New agent session'), - icon: Bot, - onPress: () => { - const delivery = pendingDiffNotesDelivery - setPendingDiffNotesDelivery(null) - if (!delivery) { - return - } - void sendDiffNotesToNewAgent(delivery, async () => { - await handleCreateTerminal(option.agent, { - initialPrompt: delivery.prompt, - onPromptSent: () => void clearDeliveredDiffComments(delivery.comments) - }) - }) - } - })) - : createTabAgentLoadState === 'loaded' - ? [ - { - id: 'noEnabledAgents', - label: t('session.usePanelRouteActions.noEnabledAgents', 'No Enabled Agents'), + ? { + id: 'presetsUnavailable', + label: t( + 'session.usePanelRouteActions.presetsUnavailable', + 'Agent Presets Unavailable' + ), + hint: errorHint, icon: Bot, disabled: true, onPress: () => {} } - ] - : createTabAgentLoadState === 'other-runtime' - ? [otherRuntimeAgentRow] - : createTabAgentLoadState === 'error' - ? [ - { - id: 'presetsUnavailable', - label: t( - 'session.usePanelRouteActions.presetsUnavailable', - 'Agent Presets Unavailable' - ), - hint: t('session.usePanelRouteActions.copyNotesHint', 'Copy notes instead'), - icon: Bot, - disabled: true, - onPress: () => {} - } - ] - : [] + : null + const createTabAgentStatusRow = agentStatusRow( + t('session.usePanelRouteActions.checkHostHint', 'Check the host connection') + ) + const sendDiffNotesStatusRow = agentStatusRow( + t('session.usePanelRouteActions.copyNotesHint', 'Copy notes instead') + ) + const sendDiffNotesAgentActions: ActionSheetAction[] = + pendingDiffNotesDelivery === null + ? [] + : sendDiffNotesStatusRow + ? [sendDiffNotesStatusRow] + : createTabAgentOptions.map((option) => ({ + id: `agent:${option.agent}`, + label: option.label, + hint: t('session.usePanelRouteActions.newSessionHint', 'New agent session'), + icon: Bot, + onPress: () => { + const delivery = pendingDiffNotesDelivery + setPendingDiffNotesDelivery(null) + if (!delivery) { + return + } + void sendDiffNotesToNewAgent(delivery, async () => { + await handleCreateTerminal(option.agent, { + initialPrompt: delivery.prompt, + onPromptSent: () => void clearDeliveredDiffComments(delivery.comments) + }) + }) + } + })) const handleSessionContentRowLayout = useCallback((event: LayoutChangeEvent) => { const width = Math.round(event.nativeEvent.layout.width) @@ -235,7 +189,7 @@ export function useMobileSessionPanelRouteActions(scope: MobileSessionPresentati ) } return { - createTabAgentActions, + createTabAgentStatusRow, sendDiffNotesAgentActions, handleSessionContentRowLayout, handlePanelTap, diff --git a/mobile/src/session/use-mobile-session-presentation.ts b/mobile/src/session/use-mobile-session-presentation.ts index 374e1db46e8..8f4b3c23331 100644 --- a/mobile/src/session/use-mobile-session-presentation.ts +++ b/mobile/src/session/use-mobile-session-presentation.ts @@ -76,11 +76,8 @@ export function useMobileSessionPresentation(scope: MobileSessionBulkCloseModel) presentedConnState === 'connected' ? showLoadingState && visibleTabs.length === 0 ? t('session.presentation.loadingTabs', 'Loading tabs') - : visibleTabs.length === 1 - ? t('session.presentation.oneTab', '1 tab') - : t('session.presentation.tabCount', '{{tabCount}} tabs', { - tabCount: visibleTabs.length - }) + : // The tab count lives in the tab bar, so the header names the branch instead. + (scope.worktreeBranch ?? MOBILE_SESSION_STATUS_LABELS.connected) : showConnectionRetry ? t('session.presentation.tapToRetry', '{{status}} — tap to retry', { status: verdictDisplayLabel(connectionVerdict) diff --git a/mobile/src/session/use-mobile-session-screen-state.ts b/mobile/src/session/use-mobile-session-screen-state.ts index bde653c4045..45fd4a9d886 100644 --- a/mobile/src/session/use-mobile-session-screen-state.ts +++ b/mobile/src/session/use-mobile-session-screen-state.ts @@ -1,7 +1,7 @@ import { useState, useRef, useMemo } from 'react' import { useTerminalSplitLayout } from '../terminal/session/use-terminal-split-layout' import { createLiveInputCapture } from '../terminal/session/live-input-capture' -import { Animated, type ScrollView } from 'react-native' +import { Animated } from 'react-native' import type { MobileTerminalLinkOpenMode } from '../storage/preferences' import type { TerminalKeyboardAvoidanceMetrics } from '../terminal/terminal-webview-contract' import { @@ -46,11 +46,6 @@ export function useMobileSessionScreenState(scope: MobileSessionFoundationModel) const activeSessionTabIdRef = useRef(null) // Preserve an explicit phone tab pick while a host snapshot is transiently incomplete. const selectedSessionTabIdRef = useRef(null) - const tabStripRef = useRef(null) - const tabStripOffsetRef = useRef(0) - const tabStripViewportWidthRef = useRef(0) - const tabStripContentWidthRef = useRef(0) - const tabLayoutsRef = useRef>(new Map()) const [markdownDocs, setMarkdownDocs] = useState>(new Map()) const markdownDocsRef = useRef>(new Map()) const [fileDocs, setFileDocs] = useState>(new Map()) @@ -134,11 +129,6 @@ export function useMobileSessionScreenState(scope: MobileSessionFoundationModel) setActiveSessionTabId, activeSessionTabIdRef, selectedSessionTabIdRef, - tabStripRef, - tabStripOffsetRef, - tabStripViewportWidthRef, - tabStripContentWidthRef, - tabLayoutsRef, markdownDocs, setMarkdownDocs, markdownDocsRef, diff --git a/mobile/src/terminal/session/use-mobile-session-keyboard-state.ts b/mobile/src/terminal/session/use-mobile-session-keyboard-state.ts index ec532d01bf5..785f282bb4f 100644 --- a/mobile/src/terminal/session/use-mobile-session-keyboard-state.ts +++ b/mobile/src/terminal/session/use-mobile-session-keyboard-state.ts @@ -1,10 +1,9 @@ -import { useEffect, useCallback, useRef } from 'react' +import { useEffect, useCallback } from 'react' import { currentSoftKeyboardHeight, subscribeSoftKeyboard } from '../../platform/keyboard-occlusion' import { useTerminalViewportRefit } from '../terminal-viewport-refit' import { removeCustomKey, type CustomKey } from '../terminal-custom-keys' import { useWorkspaceExecutionHost } from '../../navigation/workspace-execution-host' import { writeLastVisitedWorktree } from '../../worktree/last-visited-worktree-by-host' -import { resolveTabStripScrollOffset } from '../../session/tabs/tab-strip-scroll' import type { MobileSessionLifecycleModel } from '../../session/use-mobile-session-lifecycle' export type MobileSessionKeyboardScope = Pick< @@ -12,7 +11,6 @@ export type MobileSessionKeyboardScope = Pick< | 'activeHandleRef' | 'visibleTerminalHandlesRef' | 'terminalPaneViewportsRef' - | 'activeSessionTabId' | 'clientRef' | 'connState' | 'deviceTokenRef' @@ -22,11 +20,6 @@ export type MobileSessionKeyboardScope = Pick< | 'setShowCustomKeyModal' | 'showNativeChatRef' | 'subscribeToTerminal' - | 'tabLayoutsRef' - | 'tabStripContentWidthRef' - | 'tabStripOffsetRef' - | 'tabStripRef' - | 'tabStripViewportWidthRef' | 'terminalFrameRef' | 'terminalRefs' | 'terminals' @@ -45,12 +38,6 @@ export function useMobileSessionKeyboardState(scope: MobileSessionKeyboardScope) connState, terminals, terminalTextScale, - activeSessionTabId, - tabStripRef, - tabStripOffsetRef, - tabStripViewportWidthRef, - tabStripContentWidthRef, - tabLayoutsRef, setCustomKeys, setShowCustomKeyModal, deviceTokenRef, @@ -98,55 +85,6 @@ export function useMobileSessionKeyboardState(scope: MobileSessionKeyboardScope) ) }, [notifyKeyboardVisibility]) - const heldTabStripRevealRef = useRef | null>(null) - const cancelHeldTabStripReveal = useCallback(() => { - if (heldTabStripRevealRef.current) { - clearTimeout(heldTabStripRevealRef.current) - heldTabStripRevealRef.current = null - } - }, []) - useEffect(() => cancelHeldTabStripReveal, [cancelHeldTabStripReveal]) - // Hold strip movement through double-tap detection so its second tap reaches the same tab. - const holdTabStripReveal = useCallback( - (offset: number, delayMs: number) => { - cancelHeldTabStripReveal() - heldTabStripRevealRef.current = setTimeout(() => { - heldTabStripRevealRef.current = null - if (offset !== tabStripOffsetRef.current) { - tabStripOffsetRef.current = offset - tabStripRef.current?.scrollTo({ x: offset, animated: true }) - } - }, delayMs) - }, - [cancelHeldTabStripReveal] - ) - - const scrollActiveTabIntoView = useCallback((tabId: string | null, animated: boolean) => { - if (!tabId || heldTabStripRevealRef.current) { - return - } - const layout = tabLayoutsRef.current.get(tabId) - if (!layout) { - return - } - const nextOffset = resolveTabStripScrollOffset({ - tabX: layout.x, - tabWidth: layout.width, - viewportWidth: tabStripViewportWidthRef.current, - contentWidth: tabStripContentWidthRef.current, - currentOffset: tabStripOffsetRef.current - }) - if (nextOffset !== tabStripOffsetRef.current) { - tabStripOffsetRef.current = nextOffset - tabStripRef.current?.scrollTo({ x: nextOffset, animated }) - } - }, []) - - useEffect(() => { - const id = requestAnimationFrame(() => scrollActiveTabIntoView(activeSessionTabId, true)) - return () => cancelAnimationFrame(id) - }, [activeSessionTabId, scrollActiveTabIntoView]) - const executionHost = useWorkspaceExecutionHost() useEffect(() => { if (hostId && worktreeId) { @@ -171,9 +109,6 @@ export function useMobileSessionKeyboardState(scope: MobileSessionKeyboardScope) notifyTerminalFrameWidth, notifyKeyboardVisibility, notifyTerminalCellBoxChange, - scrollActiveTabIntoView, - holdTabStripReveal, - cancelHeldTabStripReveal, handleDeleteCustomKey, handleManageShortcuts } diff --git a/mobile/src/worktree/agent-row-display.ts b/mobile/src/worktree/agent-row-display.ts index 5969f45afc0..5fc384ec91d 100644 --- a/mobile/src/worktree/agent-row-display.ts +++ b/mobile/src/worktree/agent-row-display.ts @@ -88,7 +88,7 @@ export function agentDisplayLabel(row: RuntimeWorktreeAgentRow, now: number): st // Mirror desktop lastEnteredDoneAt: date main-agent failures independently while subagents remain active. export function agentRowTimeAt( - row: Pick + row: AgentRowVerdictSource & Pick ): number { if (row.state !== 'done' && row.mainAgent && agentVerdictDisplayMark(row) === 'failed') { return row.mainAgent.stateStartedAt diff --git a/mobile/src/worktree/session-worktree-record-reply-schema.ts b/mobile/src/worktree/session-worktree-record-reply-schema.ts index c5b807e093c..6ac8c10d1b8 100644 --- a/mobile/src/worktree/session-worktree-record-reply-schema.ts +++ b/mobile/src/worktree/session-worktree-record-reply-schema.ts @@ -14,6 +14,7 @@ export const sessionWorktreeRecordSchema = z repo: salvagedOptional('repo', z.string().nullable()), path: salvagedOptional('path', z.string()), hostId: salvagedOptional('hostId', z.string()), + branch: salvagedOptional('branch', z.string().nullable()), diffComments: z.unknown().optional() }) ) @@ -22,6 +23,11 @@ export const sessionWorktreeRecordSchema = z ( reply ): - | (WorktreeDisplayNameSource & { path?: string; hostId?: string; diffComments?: unknown }) + | (WorktreeDisplayNameSource & { + path?: string + hostId?: string + branch?: string | null + diffComments?: unknown + }) | undefined => reply.worktree ) diff --git a/mobile/src/worktree/use-live-worktree-name.ts b/mobile/src/worktree/use-live-worktree-name.ts index 4501b3a1922..3a09dcb5650 100644 --- a/mobile/src/worktree/use-live-worktree-name.ts +++ b/mobile/src/worktree/use-live-worktree-name.ts @@ -30,6 +30,8 @@ export type LiveWorktreeName = { /** Where the worktree lives on its host; null until the host's record arrives. */ path: string | null hostId: string | null + /** The checked-out branch without refs/heads/; null for folders, detached heads and until the record arrives. */ + branch: string | null resolution: WorktreeShowResolution } @@ -48,6 +50,7 @@ export function useLiveWorktreeName({ name: string path?: string | null hostId?: string | null + branch?: string | null }>(() => ({ worktreeId, name: routeNameHint })) // Key verdicts by route so a previous workspace’s deletion cannot escape into the new one. const [resolved, setResolved] = useState<{ @@ -125,13 +128,16 @@ export function useLiveWorktreeName({ if (liveName) { const path = worktree?.path || null const hostId = worktree?.hostId ?? null + // Match desktop formatBranchName by hiding the refs/heads/ prefix. + const branch = worktree?.branch?.replace(/^refs\/heads\//, '') || null setWorktreeName((current) => current.worktreeId === worktreeId && current.name === liveName && current.path === path && - current.hostId === hostId + current.hostId === hostId && + current.branch === branch ? current - : { worktreeId, name: liveName, path, hostId } + : { worktreeId, name: liveName, path, hostId, branch } ) } hasSuccessfulRefresh = true @@ -197,12 +203,19 @@ export function useLiveWorktreeName({ ) if (isFloatingWorkspace) { - return { name: getFloatingWorkspaceTitle(), path: null, hostId: 'local', resolution: 'unknown' } + return { + name: getFloatingWorkspaceTitle(), + path: null, + hostId: 'local', + branch: null, + resolution: 'unknown' + } } return { name: worktreeName.worktreeId === worktreeId ? worktreeName.name : routeNameHint, path: worktreeName.worktreeId === worktreeId ? (worktreeName.path ?? null) : null, hostId: worktreeName.worktreeId === worktreeId ? (worktreeName.hostId ?? null) : null, + branch: worktreeName.worktreeId === worktreeId ? (worktreeName.branch ?? null) : null, resolution: resolved.worktreeId === worktreeId ? resolved.resolution : 'unknown' } } diff --git a/src/cli/handlers/folder-setup-support-warning.ts b/src/cli/handlers/folder-setup-support-warning.ts new file mode 100644 index 00000000000..35ac1902463 --- /dev/null +++ b/src/cli/handlers/folder-setup-support-warning.ts @@ -0,0 +1,37 @@ +import type { RuntimeClient } from '../runtime-client' +import type { RuntimeStatus } from '../../shared/runtime-types' +import { FOLDER_WORKSPACE_INSTANCE_SEPARATOR } from '../../shared/worktree/id' +import { WORKTREE_FOLDER_SETUP_RUNTIME_CAPABILITY } from '../../shared/worktree-runtime-capabilities' + +const FOLDER_SETUP_UNSUPPORTED_WARNING = + 'Setup did not run: this host runs an older Orca without folder workspace setup. Update Orca on that host to run it.' + +/** An older host makes folder workspaces without running setup; say so rather than imply it ran. */ +export async function folderSetupUnsupportedWarning( + client: RuntimeClient, + worktreeId: string | undefined, + create: { setupDecision?: unknown; runHooks?: unknown } +): Promise { + const setupRequested = create.setupDecision === 'run' || create.runHooks === true + if (!setupRequested || !worktreeId?.includes(FOLDER_WORKSPACE_INSTANCE_SEPARATOR)) { + return null + } + const status = await client.call('status.get').catch(() => null) + return status && !status.result.capabilities?.includes(WORKTREE_FOLDER_SETUP_RUNTIME_CAPABILITY) + ? FOLDER_SETUP_UNSUPPORTED_WARNING + : null +} + +/** Joins the warning onto a create result, so text output and --json both carry it. */ +export async function withFolderSetupSupportWarning< + T extends { worktree?: { id?: string }; warning?: string } +>( + client: RuntimeClient, + result: T, + create: { setupDecision?: unknown; runHooks?: unknown } +): Promise { + const warning = await folderSetupUnsupportedWarning(client, result.worktree?.id, create) + return warning + ? { ...result, warning: result.warning ? `${result.warning} ${warning}` : warning } + : result +} diff --git a/src/cli/handlers/orchestration/worker-agent-views.ts b/src/cli/handlers/orchestration/worker-agent-views.ts index ac76e9c214a..ca993bc66c1 100644 --- a/src/cli/handlers/orchestration/worker-agent-views.ts +++ b/src/cli/handlers/orchestration/worker-agent-views.ts @@ -108,6 +108,7 @@ export type WorkerListResult = { dispatchStatus: string agentTerminalHandle: string | null terminalState: string | null + coordinatedFrom?: string | null resource?: { worktreeId?: string | null; autoReleaseAt?: string | null } | null projection?: WorkerProjection }[] @@ -133,6 +134,7 @@ type WorkerListRow = { terminalState?: string workspace?: string host?: string + coordinatedFrom?: string attention?: string[] autoReleaseAt?: string next?: string @@ -168,6 +170,7 @@ export const WORKER_LIST_VIEW: OrchestrationAgentView('worktree.create', params), { @@ -74,6 +78,10 @@ export async function createWorktreeWithAgent(args: { } ) ) + const created = { + ...response, + result: await withFolderSetupSupportWarning(client, response.result, create) + } printHookWarning(created.result, json) printLineageSummary(created.result, json) printResult(created, json, formatWorktreeShow) @@ -93,6 +101,15 @@ export async function createWorktreeWithAgent(args: { launch.operationId !== undefined ) const worktree = await showLaunchedWorktree(client, launched.result.worktreeId) + const setupWarning = await folderSetupUnsupportedWarning( + client, + launched.result.worktreeId, + create + ) + if (setupWarning) { + // stderr keeps --json output parseable while still reporting the skipped setup. + console.error(`warning: ${setupWarning}`) + } const result: WorktreeAgentLaunchResult = { ...(worktree ? { diff --git a/src/cli/handlers/worktree.ts b/src/cli/handlers/worktree.ts index d1ff9d7bf72..5f4acb7f34b 100644 --- a/src/cli/handlers/worktree.ts +++ b/src/cli/handlers/worktree.ts @@ -1,3 +1,4 @@ +import { withFolderSetupSupportWarning } from './folder-setup-support-warning' import { withWorktreeSelectorRecovery } from '../worktree-selector-recovery' import type { RuntimeWorktreeListResult, @@ -207,9 +208,13 @@ export const WORKTREE_HANDLERS: Record = { const result = await withSetupDecisionRecovery( callNamingParentEnvironment(client, 'worktree.create', create) ) - printHookWarning(result.result, json) - printLineageSummary(result.result, json) - printResult(result, json, formatWorktreeShow) + const created = { + ...result, + result: await withFolderSetupSupportWarning(client, result.result, create) + } + printHookWarning(created.result, json) + printLineageSummary(created.result, json) + printResult(created, json, formatWorktreeShow) }, 'worktree set': async ({ flags, client, cwd, json }) => { assertWorktreeParentFlagsCompatible( diff --git a/src/main/acp/acp-dialects/antigravity-dialect.ts b/src/main/acp/acp-dialects/antigravity-dialect.ts index 332d6ea9f7f..a859f9993d7 100644 --- a/src/main/acp/acp-dialects/antigravity-dialect.ts +++ b/src/main/acp/acp-dialects/antigravity-dialect.ts @@ -1,6 +1,6 @@ import { z } from 'zod' import { legacyAgentSessionQuestionAnswers } from '../../../shared/agent-session/agent-session-question-answer' -import { AcpRpcError } from '../transport/acp-errors' +import { AcpRpcError, acpErrorDataWords, type AcpAgentError } from '../transport/acp-errors' import { readAcpPermissionRequest } from '../protocol/acp-permission-requests' import { acpPermissionPresentation } from '../requests/acp-timeline-requests' import type { ToolCallUpdate } from '../generated/acp-protocol.generated' @@ -107,9 +107,28 @@ function normalizeToolUpdate(update: ToolCallUpdate): ToolCallUpdate { } } +const cloudCodeErrorSchema = z.object({ + error: z.object({ message: z.string().trim().min(1) }) +}) + +function promptErrorDetail(error: AcpAgentError): string | undefined { + const text = acpErrorDataWords(error.data) ?? error.message + const prefix = /^Cloud Code Assist API error \(\d{3}\):\s*/.exec(text) + if (!prefix) { + return undefined + } + try { + return cloudCodeErrorSchema.safeParse(JSON.parse(text.slice(prefix[0].length))).data?.error + .message + } catch { + return undefined + } +} + export const ANTIGRAVITY_ACP_DIALECT: AcpDialect = { request: (method, params) => questionRequest(method, params) ?? warnedApproval(method, params), normalizeToolUpdate, + promptErrorDetail, // Avoid using the full command line as the tool name. toolName: (update) => (update.kind === 'execute' ? 'execute' : undefined), // Logout would clear the account shared by every Antigravity chat on this host. diff --git a/src/main/acp/session/acp-structured-antigravity-errors.test.ts b/src/main/acp/session/acp-structured-antigravity-errors.test.ts new file mode 100644 index 00000000000..fabcc889944 --- /dev/null +++ b/src/main/acp/session/acp-structured-antigravity-errors.test.ts @@ -0,0 +1,58 @@ +import { afterEach, expect, it } from 'vitest' +import { closeProviderTimelineRigs } from '../../native-chat/agent-session-timeline/provider-timeline-assembler-test-support' +import { acpLaunchSpecFor } from '../launch/acp-launch-registry' +import { + openAcpAdapterRig, + sendHello, + waitFor +} from './testing/acp-structured-adapter.test-support' + +afterEach(closeProviderTimelineRigs) + +const quotaError = `Cloud Code Assist API error (429): { + "error": { + "code": 429, + "message": "Individual quota reached. Please upgrade your subscription to increase your limits. Resets in 3h42m11s.", + "status": "RESOURCE_EXHAUSTED", + "details": [ + { + "@type": "type.googleapis.com/google.rpc.ErrorInfo", + "reason": "QUOTA_EXHAUSTED", + "domain": "cloudcode-pa.googleapis.com", + "metadata": { + "quotaResetDelay": "3h42m11.598227131s", + "quotaResetTimeStamp": "2026-11-10T15:58:51Z", + "uiMessage": "true", + "model": "claude-opus-5-5-high" + } + }, + { + "@type": "type.googleapis.com/google.rpc.RetryInfo", + "retryDelay": "13331.598227131s" + } + ] + } +}` + +it('publishes the Cloud Code Assist message instead of its JSON envelope in chat', async () => { + const rig = await openAcpAdapterRig({ + spec: acpLaunchSpecFor('antigravity')!, + script: (agent) => + agent.on('session/prompt', (frame) => + agent.fail(frame, -32603, 'Internal error', { details: quotaError }) + ) + }) + await rig.acquire() + await sendHello(rig, 'send-1') + await waitFor(async () => + expect((await rig.rig.rows()).filter((row) => row.body.kind === 'status')).toEqual([ + expect.objectContaining({ + body: { + kind: 'status', + tone: 'error', + text: 'Individual quota reached. Please upgrade your subscription to increase your limits. Resets in 3h42m11s.' + } + }) + ]) + ) +}) diff --git a/src/main/acp/transport/acp-errors.ts b/src/main/acp/transport/acp-errors.ts index d167f0fd609..2ee2afbf417 100644 --- a/src/main/acp/transport/acp-errors.ts +++ b/src/main/acp/transport/acp-errors.ts @@ -5,6 +5,17 @@ import { withProviderDiagnostic } from '../../../shared/agent-session/failures/agent-session-failure' +// Structured metadata is not user-facing diagnostic text. +export function acpErrorDataWords(data: unknown): string | undefined { + const words = + typeof data === 'string' + ? data + : typeof data === 'object' && data !== null && 'details' in data + ? data.details + : undefined + return typeof words === 'string' && words.trim() ? words : undefined +} + export class AcpRpcError extends Error { constructor( readonly code: number, diff --git a/src/main/acp/turns/acp-prompt-failure.ts b/src/main/acp/turns/acp-prompt-failure.ts index 5af36648fa8..18065efd4a6 100644 --- a/src/main/acp/turns/acp-prompt-failure.ts +++ b/src/main/acp/turns/acp-prompt-failure.ts @@ -6,7 +6,12 @@ import { import type { AcpDialect, AcpTurnEnding } from '../acp-dialects/acp-dialect' -import { AcpAgentError, AcpAuthRequiredError, AcpSignInPromptError } from '../transport/acp-errors' +import { + AcpAgentError, + AcpAuthRequiredError, + AcpSignInPromptError, + acpErrorDataWords +} from '../transport/acp-errors' /** Prefer provider error details over generic messages such as Internal error. */ export function acpPromptErrorDetail(dialect: AcpDialect, error: AcpAgentError): string { @@ -17,17 +22,6 @@ export function acpPromptErrorDetail(dialect: AcpDialect, error: AcpAgentError): return dialect.promptErrorDetail?.(error) ?? acpErrorDataWords(error.data) ?? error.message } -// Structured metadata is not user-facing diagnostic text. -function acpErrorDataWords(data: unknown): string | undefined { - const words = - typeof data === 'string' - ? data - : typeof data === 'object' && data !== null && 'details' in data - ? data.details - : undefined - return typeof words === 'string' && words.trim() ? words : undefined -} - export function acpAuthenticationRequired(dialect: AcpDialect, error: unknown): boolean { return ( error instanceof AcpAuthRequiredError || diff --git a/src/main/agent-hooks/runtime/agent-hook-runtime-deps.ts b/src/main/agent-hooks/runtime/agent-hook-runtime-deps.ts index 1d65427fe77..4d65da58001 100644 --- a/src/main/agent-hooks/runtime/agent-hook-runtime-deps.ts +++ b/src/main/agent-hooks/runtime/agent-hook-runtime-deps.ts @@ -19,6 +19,8 @@ export function agentHookRuntimeDeps( getAgentStatusSnapshot: () => server.getStatusSnapshot().filter((entry) => entry.providerSessionOnly !== true), getAgentStatusSnapshotForPane: (paneKey) => server.getStatusSnapshotForPane(paneKey), + getPublicAgentStatusSnapshotForPane: (paneKey) => + server.getPublicStatusSnapshotForPane(paneKey), // Include resume identities so mobile can locate provider transcripts, including Pi sessions. getAgentProviderSessionSnapshot: (tabId) => tabId === undefined diff --git a/src/main/agent-hooks/server/combined-agent-status-entries.ts b/src/main/agent-hooks/server/combined-agent-status-entries.ts new file mode 100644 index 00000000000..d1468ed141f --- /dev/null +++ b/src/main/agent-hooks/server/combined-agent-status-entries.ts @@ -0,0 +1,59 @@ +import { isTmuxInnerSubject } from '../../../shared/tmux-selected-status' +import { + getLegacyStatusListingOrder, + type HookListenerState +} from '../../../shared/agent-hook-listener/listener-state' +import { + serializeAgentStatusSubject, + type AgentStatusSubject +} from '../../../shared/agent-status/contracts/agent-status-subject' +import type { AgentStatusStore } from '../../../shared/agent-status/store/agent-status-store' +import type { EnrichedAgentHookEventPayload } from './server-types' +import { structuredStatusLegacyEvent } from './server-structured-status-row' +import type { ProgramStatusFacetStore } from './program-status/facet-store' + +const UNORDERED_STATUS_ROW = Number.MAX_SAFE_INTEGER + +export function combinedAgentStatusEntries( + source: { + state: HookListenerState + programStatusFacets: Pick + canonicalStatusStore: Pick + canonicalSubjectsByPane: ReadonlyMap> + canonicalListingOrder: ReadonlyMap + }, + paneKey?: string +): EnrichedAgentHookEventPayload[] { + const rows: { entry: EnrichedAgentHookEventPayload; order: number }[] = [] + const legacy = + paneKey === undefined + ? source.state.lastStatusByPaneKey + : source.state.lastStatusByPaneKey.has(paneKey) + ? [[paneKey, source.state.lastStatusByPaneKey.get(paneKey)!] as const] + : [] + for (const [paneKey, entry] of legacy) { + rows.push({ + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: Main admits enriched legacy rows; shared listeners expose only the base event type. + entry: source.programStatusFacets.stitch(entry as EnrichedAgentHookEventPayload), + order: getLegacyStatusListingOrder(source.state, paneKey) ?? UNORDERED_STATUS_ROW + }) + } + const parents = + paneKey === undefined + ? source.canonicalStatusStore.getParents() + : [...(source.canonicalSubjectsByPane.get(paneKey)?.values() ?? [])].flatMap( + (subject) => source.canonicalStatusStore.getParent(subject) ?? [] + ) + for (const parent of parents) { + if (!parent.status || isTmuxInnerSubject(parent.subject)) { + continue + } + rows.push({ + entry: structuredStatusLegacyEvent(parent.status), + order: + source.canonicalListingOrder.get(serializeAgentStatusSubject(parent.subject)) ?? + UNORDERED_STATUS_ROW + }) + } + return rows.sort((a, b) => a.order - b.order).map(({ entry }) => entry) +} diff --git a/src/main/agent-hooks/server/program-status/hook-precedence.ts b/src/main/agent-hooks/server/program-status/hook-precedence.ts index c6e1e332197..b04c6f77100 100644 --- a/src/main/agent-hooks/server/program-status/hook-precedence.ts +++ b/src/main/agent-hooks/server/program-status/hook-precedence.ts @@ -41,11 +41,19 @@ export function programStatusHookYieldEndsAt( ) { return Infinity } - // Settled turns are naturally silent; a later wait must prove intervening program work. - if (previous.payload.state === 'done' && payload.state === 'waiting') { - return programWorkingSince !== undefined && programWorkingSince > previous.receivedAt + // A settled turn yields only to program work begun after it (a replayed done keeps its own time): + // Codex re-reports the settled turn's working while a background terminal it started runs. + if ( + previous.payload.state === 'done' && + (payload.state === 'waiting' || payload.state === 'working') + ) { + const doneAt = previous.evidenceObservedAt ?? previous.receivedAt + if (programWorkingSince === undefined || programWorkingSince <= doneAt) { + return Infinity + } + return payload.state === 'waiting' ? undefined - : Infinity + : previous.receivedAt + HOOK_SILENCE_BEFORE_PROGRAM_STATUS_FALLBACK_MS } // A question sends no hooks while open, so a `working` that began before it (e.g. re-sent by the // lease renewal) proves nothing; a working transition after it keeps the silence fallback. diff --git a/src/main/agent-hooks/server/server-ingest-terminal.ts b/src/main/agent-hooks/server/server-ingest-terminal.ts index 184f4761918..a15b3514900 100644 --- a/src/main/agent-hooks/server/server-ingest-terminal.ts +++ b/src/main/agent-hooks/server/server-ingest-terminal.ts @@ -180,6 +180,13 @@ export abstract class AgentHookServerIngestTerminal extends AgentHookServerInges const previous = this.state.lastStatusByPaneKey.get(paneKey) as | EnrichedAgentHookEventPayload | undefined + // OSC 7501 names OpenCode 2 `opencode`; the row its hook or launch named keeps the generation. + const payload: ParsedAgentStatusPayload = + event.fromProgramStatus === true && + event.payload.agentType === 'opencode' && + previous?.payload.agentType === 'opencode2' + ? { ...event.payload, agentType: 'opencode2' } + : event.payload // OpenCode 1 run loads hooks in-process; a hook during the command owns its status. const hookOwnsCommand = event.yieldsToHookSince !== undefined && @@ -189,7 +196,7 @@ export abstract class AgentHookServerIngestTerminal extends AgentHookServerInges // Record ordering before removal, which also marks a program turn boundary. const workingSince = event.fromProgramStatus === true - ? this.programStatusFacets.noteState(paneKey, event.payload, now) + ? this.programStatusFacets.noteState(paneKey, payload, now) : undefined if (event.removesProgramStatusRow === true) { this.hookSilenceRechecks.cancel(paneKey) @@ -205,7 +212,7 @@ export abstract class AgentHookServerIngestTerminal extends AgentHookServerInges } const yieldEndsAt = event.fromProgramStatus === true - ? programStatusHookYieldEndsAt(previous, event.payload, workingSince) + ? programStatusHookYieldEndsAt(previous, payload, workingSince) : undefined const hookOwnsAgent = yieldEndsAt !== undefined && now < yieldEndsAt if (event.fromProgramStatus === true) { @@ -235,7 +242,7 @@ export abstract class AgentHookServerIngestTerminal extends AgentHookServerInges // OSC 7501 uses the hook precedence above; other terminal reports cannot settle child-held work. (event.fromProgramStatus !== true && previous?.payload.agentType === 'claude' && - event.payload.agentType === 'claude' && + payload.agentType === 'claude' && isAgentStatusHeldOpenByChildWork(previous.payload) && previous.payload.subagents?.some((subagent) => subagent.state === 'working') === true) ) { @@ -258,10 +265,10 @@ export abstract class AgentHookServerIngestTerminal extends AgentHookServerInges previous.worktreeId === worktreeId && // A terminal handle joins row identity; acquiring or replacing it requires publication. previous.terminalHandle === (terminalHandle ?? previous.terminalHandle) && - terminalStatusPayloadMatchesHook(previous.payload, event.payload, preserveActiveTurnStamp) && + terminalStatusPayloadMatchesHook(previous.payload, payload, preserveActiveTurnStamp) && // OSC 7501 child-only changes still require publication; absent children means none remain. (event.fromProgramStatus !== true || - agentSubagentsEqual(previous.payload.subagents, event.payload.subagents)) + agentSubagentsEqual(previous.payload.subagents, payload.subagents)) ) { // An authority transfer must refresh enriched subscribers even for an identical payload. this.refreshTerminalStatusEvidence( @@ -274,24 +281,22 @@ export abstract class AgentHookServerIngestTerminal extends AgentHookServerInges } // Terminal status carries no provider session; retain eligible cached identity without treating unknown as a mismatch (#10630). const claimedAgentType = - event.payload.agentType && event.payload.agentType !== 'unknown' - ? event.payload.agentType - : undefined + payload.agentType && payload.agentType !== 'unknown' ? payload.agentType : undefined // A live agent's turn after `done` keeps its session (OSC 7501 reports hookless slash commands); a new run or an exited agent's resume-only row does not. Launch seeds are not completed turns. const preservedProviderSession = previous?.providerSession && (claimedAgentType === undefined || claimedAgentType === previous.payload.agentType) && (previous.payload.state !== 'done' || - event.payload.state === 'done' || + payload.state === 'done' || previous.observation?.origin === 'launch' || (!newRun && previous.providerSessionOnly !== true)) ? previous.providerSession : undefined // Without a new main-agent fact, preserve it only while the row's state and agent still match. const preservedMainAgent = - event.payload.mainAgent ?? + payload.mainAgent ?? (previous?.payload.mainAgent && - previous.payload.state === event.payload.state && + previous.payload.state === payload.state && (claimedAgentType === undefined || claimedAgentType === previous.payload.agentType) ? previous.payload.mainAgent : undefined) @@ -304,9 +309,7 @@ export abstract class AgentHookServerIngestTerminal extends AgentHookServerInges connectionId, ...(preservedProviderSession ? { providerSession: preservedProviderSession } : {}), ...(terminalHandle ? { terminalHandle } : {}), - payload: preservedMainAgent - ? { ...event.payload, mainAgent: preservedMainAgent } - : event.payload + payload: preservedMainAgent ? { ...payload, mainAgent: preservedMainAgent } : payload }, undefined, event.origin ?? 'osc', diff --git a/src/main/agent-hooks/server/server-listeners.ts b/src/main/agent-hooks/server/server-listeners.ts index 7db72a6c592..ec8a7911ef7 100644 --- a/src/main/agent-hooks/server/server-listeners.ts +++ b/src/main/agent-hooks/server/server-listeners.ts @@ -1,15 +1,11 @@ import { cliWriterExecutionMatcher, type CliWriterExecutionMatches } from './cli-writer-observation' -import { isTmuxInnerSubject } from '../../../shared/tmux-selected-status' import type { AgentStatusClearIpcPayload, AgentStatusIpcPayload } from '../../../shared/agent-status/contracts/agent-status-ipc-payload' import type { ClaudeStatusLineRateLimits } from '../../../shared/claude-statusline-rate-limits' import type { HookTransportInterferenceReport } from '../../../shared/agent-hook-listener/transport/agent-hook-transport-interference' -import { - getLegacyStatusListingOrder, - type HookListenerState -} from '../../../shared/agent-hook-listener/listener-state' +import type { HookListenerState } from '../../../shared/agent-hook-listener/listener-state' import type { AgentHookAuthorityEvidence, AgentHookProviderSessionIdentity, @@ -20,15 +16,11 @@ import type { } from './server-types' import { toAgentStatusIpcPayload } from './server-status-identity' import { AgentHookServerState } from './server-state' -import { serializeAgentStatusSubject } from '../../../shared/agent-status/contracts/agent-status-subject' -import { structuredStatusLegacyEvent } from './server-structured-status-row' +import { combinedAgentStatusEntries } from './combined-agent-status-entries' import { PaneTimers } from './program-status/pane-timers' import { ProgramStatusFacetStore } from './program-status/facet-store' import { parsePaneKey } from '../../../shared/workspace-layout/stable-pane-id' -// Unassigned rows sort after the listing counter, which starts at 1. -const UNORDERED_STATUS_ROW = Number.MAX_SAFE_INTEGER - export abstract class AgentHookServerListeners extends AgentHookServerState { protected providerRowsByTab: Map | null = null protected statusChangeNotificationVersion = 0 @@ -76,27 +68,17 @@ export abstract class AgentHookServerListeners extends AgentHookServerState { this.providerRowsByTab = null } - private combinedStatusEntries(): EnrichedAgentHookEventPayload[] { - const rows: { entry: EnrichedAgentHookEventPayload; order: number }[] = [] - for (const [paneKey, entry] of this.state.lastStatusByPaneKey) { - rows.push({ - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: Main admits enriched legacy rows; shared listeners expose only the base event type. - entry: this.programStatusFacets.stitch(entry as EnrichedAgentHookEventPayload), - order: getLegacyStatusListingOrder(this.state, paneKey) ?? UNORDERED_STATUS_ROW - }) - } - for (const parent of this.canonicalStatusStore.getParents()) { - if (!parent.status || isTmuxInnerSubject(parent.subject)) { - continue - } - rows.push({ - entry: structuredStatusLegacyEvent(parent.status), - order: - this.canonicalListingOrder.get(serializeAgentStatusSubject(parent.subject)) ?? - UNORDERED_STATUS_ROW - }) - } - return rows.sort((a, b) => a.order - b.order).map(({ entry }) => entry) + private combinedStatusEntries(paneKey?: string): EnrichedAgentHookEventPayload[] { + return combinedAgentStatusEntries( + { + state: this.state, + programStatusFacets: this.programStatusFacets, + canonicalStatusStore: this.canonicalStatusStore, + canonicalSubjectsByPane: this.canonicalSubjectsByPane, + canonicalListingOrder: this.canonicalListingOrder + }, + paneKey + ) } /** Report repeated hook-body truncation once per process; fail-open handling otherwise hides it (#11217). */ setTransportInterferenceListener( @@ -248,6 +230,12 @@ export abstract class AgentHookServerListeners extends AgentHookServerState { return this.buildStatusChangeNotification().providerSessions } + getPublicStatusSnapshotForPane(paneKey: string): AgentStatusIpcPayload[] { + return this.combinedStatusEntries(paneKey) + .filter((entry) => entry.providerSessionOnly !== true) + .map(toAgentStatusIpcPayload) + } + getStatusSnapshotForPane(paneKey: string): AgentStatusIpcPayload[] { const legacy = this.state.lastStatusByPaneKey.get(paneKey) if (legacy) { diff --git a/src/main/agent-hooks/server/testing/identity/server-claude-resume-record-continuity.test.ts b/src/main/agent-hooks/server/testing/identity/server-claude-resume-record-continuity.test.ts index 6c356e7b35b..35b2bdc1a6e 100644 --- a/src/main/agent-hooks/server/testing/identity/server-claude-resume-record-continuity.test.ts +++ b/src/main/agent-hooks/server/testing/identity/server-claude-resume-record-continuity.test.ts @@ -4,7 +4,7 @@ import { join } from 'node:path' import { afterEach, beforeEach, expect, it, vi } from 'vitest' import { AgentHookServer } from '../../agent-hook-server' import { HOOK_SILENCE_BEFORE_PROGRAM_STATUS_FALLBACK_MS } from '../../program-status/hook-precedence' -import { buildBody, PANE, postHookEvent } from '../server.test-fixtures' +import { buildBody, ingestProgramStatusOsc, PANE, postHookEvent } from '../server.test-fixtures' const SESSION = '70efcb3f-ae17-4863-9318-649f5469408b' @@ -54,14 +54,7 @@ it('keeps the start folder and effort when a terminal status row precedes the ne vi.useFakeTimers({ toFake: ['Date'] }) vi.setSystemTime(Date.now() + HOOK_SILENCE_BEFORE_PROGRAM_STATUS_FALLBACK_MS) // Claude reports OSC 7501 `working` just before UserPromptSubmit. - server.ingestTerminalStatus({ - paneKey: PANE, - tabId: 'tab-1', - worktreeId: 'wt-1', - connectionId: null, - fromProgramStatus: true, - payload: { prompt: '', state: 'working', agentType: 'claude' } - }) + ingestProgramStatusOsc(server, '\x1b]7501;state=working:app=claude-code\x1b\\') await claudeHook({ hook_event_name: 'UserPromptSubmit', prompt: 'next', cwd: '/repo/sub' }) expect(recordedSession()).toMatchObject({ id: SESSION, cwd: '/repo', effort: 'max' }) diff --git a/src/main/agent-hooks/server/testing/providers/codex/server-codex-background-terminal-working.test.ts b/src/main/agent-hooks/server/testing/providers/codex/server-codex-background-terminal-working.test.ts new file mode 100644 index 00000000000..378a9a6739e --- /dev/null +++ b/src/main/agent-hooks/server/testing/providers/codex/server-codex-background-terminal-working.test.ts @@ -0,0 +1,40 @@ +import { afterEach, beforeEach, expect, it, vi } from 'vitest' +import { AgentHookServer } from '../../../agent-hook-server' +import { HOOK_SILENCE_BEFORE_PROGRAM_STATUS_FALLBACK_MS } from '../../../program-status/hook-precedence' +import { buildBody, ingestProgramStatusOsc, postHookEvent } from '../../server.test-fixtures' + +const TURN = { session_id: 'session-1', turn_id: 'turn-1' } + +let server: AgentHookServer + +beforeEach(async () => { + server = new AgentHookServer() + await server.start({ env: 'production' }) +}) + +afterEach(() => { + vi.useRealTimers() + server.stop() +}) + +async function codexHook(hookEventName: string, payload: Record = {}) { + const response = await postHookEvent( + server, + buildBody({ ...TURN, hook_event_name: hookEventName, ...payload }), + '/hook/codex' + ) + expect(response.status).toBe(204) +} + +it('keeps a finished Codex turn done while its background terminal keeps OSC 7501 working', async () => { + await codexHook('UserPromptSubmit', { prompt: 'start sleep 900 in the background' }) + // Codex 0.167 sends this at the turn start and nothing after it while `sleep 900` runs. + const working = ingestProgramStatusOsc(server, '\x1b]7501;state=working:app=codex\x1b\\') + await codexHook('Stop', { last_assistant_message: 'ok' }) + + vi.useFakeTimers({ toFake: ['Date', 'setTimeout', 'clearTimeout'] }) + server.ingestTerminalStatus({ ...working, renewsProgramStatusLease: true }) + vi.advanceTimersByTime(HOOK_SILENCE_BEFORE_PROGRAM_STATUS_FALLBACK_MS + 1) + + expect(server.getStatusSnapshot()[0]?.state).toBe('done') +}) diff --git a/src/main/agent-hooks/server/testing/providers/opencode/server-opencode2-program-status.test.ts b/src/main/agent-hooks/server/testing/providers/opencode/server-opencode2-program-status.test.ts new file mode 100644 index 00000000000..47bd88e71f0 --- /dev/null +++ b/src/main/agent-hooks/server/testing/providers/opencode/server-opencode2-program-status.test.ts @@ -0,0 +1,47 @@ +import { afterEach, expect, it, vi } from 'vitest' +import { AgentHookServer } from '../../../agent-hook-server' +import { buildBody, PANE, postHookEvent } from '../../server.test-fixtures' + +vi.mock('../../../../../telemetry/client', () => ({ track: vi.fn() })) +vi.mock('../../../../../telemetry/cohort-classifier', () => ({ getCohortAtEmit: () => ({}) })) + +let server: AgentHookServer | undefined +afterEach(() => { + server?.stop() +}) + +function oscStatus(state: 'working' | 'done'): void { + // OpenCode 2 reports OSC 7501 as `app=opencode`. + server!.ingestTerminalStatus({ + paneKey: PANE, + tabId: 'tab-1', + worktreeId: 'wt-1', + connectionId: null, + fromProgramStatus: true, + payload: { state, prompt: '', agentType: 'opencode' } + }) +} + +async function hook(hook_event_name: string, prompt = ''): Promise { + const body = buildBody({ hook_event_name, sessionID: 'ses_opencode2', prompt }) + expect((await postHookEvent(server!, body, '/hook/opencode2')).status).toBe(204) +} + +it('keeps OpenCode 2 hooks and their session on a pane its OSC 7501 reports as opencode', async () => { + server = new AgentHookServer() + await server.start({ env: 'production' }) + oscStatus('working') + await hook('SessionBusy', 'rename the branch') + expect(server.getStatusSnapshot()[0]).toMatchObject({ + agentType: 'opencode2', + prompt: 'rename the branch' + }) + + await hook('SessionIdle') + oscStatus('done') + expect(server.getStatusSnapshot()[0]).toMatchObject({ + agentType: 'opencode2', + state: 'done', + providerSession: { id: 'ses_opencode2' } + }) +}) diff --git a/src/main/agent-hooks/server/testing/server.test-fixtures.ts b/src/main/agent-hooks/server/testing/server.test-fixtures.ts index 9b380067b2f..4cd27a5c1d7 100644 --- a/src/main/agent-hooks/server/testing/server.test-fixtures.ts +++ b/src/main/agent-hooks/server/testing/server.test-fixtures.ts @@ -1,4 +1,5 @@ import { makePaneKey } from '../../../../shared/workspace-layout/stable-pane-id' +import { createProgramStatusProjector } from '../../../../shared/program-status/agent-status-projector' import type { AgentHookServer } from '../agent-hook-server' export const LEAF_1 = '11111111-1111-4111-8111-111111111111' @@ -44,6 +45,22 @@ export function buildBody(payload: Record, overrides: Partial ({ track: vi.fn() })) vi.mock('../../../../telemetry/cohort-classifier', () => ({ getCohortAtEmit: vi.fn(() => ({})) })) @@ -51,6 +52,53 @@ function terminal(server: AgentHookServer, paneKey: string): void { afterEach(() => vi.restoreAllMocks()) describe('structured canonical production slice', () => { + it('publishes the same public pane evidence while preserving resume-only provider identity', () => { + const server = new AgentHookServer() + const deps = agentHookRuntimeDeps(server, { read: () => ({ kind: 'unobserved' }) }, () => ({})) + server.recordLaunchResumeIdentity({ + paneKey: PANE, + agentType: 'codex', + providerSession: { key: 'session_id', id: 'resume-only' }, + launchedAt: 100 + }) + expect(deps.getPublicAgentStatusSnapshotForPane(PANE)).toEqual([]) + expect(deps.getAgentStatusSnapshotForPane(PANE)).toEqual([ + expect.objectContaining({ + providerSessionOnly: true, + providerSession: { key: 'session_id', id: 'resume-only' } + }) + ]) + expect(deps.getAgentProviderSessionRowsForPane(PANE)).toEqual([ + expect.objectContaining({ + providerSessionOnly: true, + providerSession: { key: 'session_id', id: 'resume-only' } + }) + ]) + terminal(server, PANE) + server.ingestStructuredStatus(summary(), SUBJECT) + const second = makeStructuredAgentStatusSubject( + { ...SCOPE, executionHostId: 'ssh:other' }, + SESSION + ) + server.ingestStructuredStatus({ ...summary(second), agent: 'claude', status: 'idle' }, second) + expect(deps.getAgentStatusSnapshotForPane(PANE).map(({ state }) => state)).toEqual(['working']) + expect( + deps + .getPublicAgentStatusSnapshotForPane(PANE_KEY) + .map(({ agentType, state }) => ({ agentType, state })) + ).toEqual([ + { agentType: 'codex', state: 'working' }, + { agentType: 'claude', state: 'done' } + ]) + expect(deps.getAgentStatusSnapshot().map(({ paneKey, state }) => ({ paneKey, state }))).toEqual( + [ + { paneKey: PANE, state: 'working' }, + { paneKey: PANE_KEY, state: 'working' }, + { paneKey: PANE_KEY, state: 'done' } + ] + ) + }) + it('isolates identical session identifiers across host, WSL and workspace kind scopes', () => { const server = new AgentHookServer() const scopes: AgentStatusExecutionScope[] = [ diff --git a/src/main/browser/cdp/commands/cdp-screenshot.ts b/src/main/browser/cdp/commands/cdp-screenshot.ts index f43f5c1e194..76cc4726365 100644 --- a/src/main/browser/cdp/commands/cdp-screenshot.ts +++ b/src/main/browser/cdp/commands/cdp-screenshot.ts @@ -1,4 +1,8 @@ -import type { CapturePaintHold } from '../debugger/guest-paint-hold' +import { + holdPaintUntilCdpCaptureSettles, + holdPaintUntilSettled, + type CapturePaintHold +} from '../debugger/guest-paint-hold' import type { WebContents } from 'electron' import { sendGuestCdpCommand } from '../debugger/guest-cdp-command' import { @@ -137,7 +141,8 @@ export function withTimeout( // Undrawn pages can leave captures pending; cheap probes trigger a frame for the original request. function captureUntilDrawn( webContents: WebContents, - params: Record + params: Record, + holdPaint: CapturePaintHold ): Promise<{ data: string } | null> { return new Promise((resolve, reject) => { let settled = false @@ -173,12 +178,12 @@ function captureUntilDrawn( } catch { // Guest teardown can reject repaint requests; still try CDP. } - return sendGuestCdpCommand(webContents, 'Page.captureScreenshot', requestParams).then( - (result) => { - const data = isRecord(result) ? result.data : undefined - return typeof data === 'string' ? { data } : undefined - } - ) + return holdPaintUntilCdpCaptureSettles(webContents, holdPaint, () => + sendGuestCdpCommand(webContents, 'Page.captureScreenshot', requestParams) + ).then((result) => { + const data = isRecord(result) ? result.data : undefined + return typeof data === 'string' ? { data } : undefined + }) } const deadline = setTimeout(() => finish(() => resolve(null)), SCREENSHOT_TIMEOUT_MS) let probes: NodeJS.Timeout[] = [] @@ -223,11 +228,15 @@ export async function captureFullPageScreenshot( if (!clip) { throw new Error('Unable to determine full-page screenshot bounds') } - const frame = await captureUntilDrawn(webContents, { - format, - captureBeyondViewport: true, - clip - }) + const frame = await captureUntilDrawn( + webContents, + { + format, + captureBeyondViewport: true, + clip + }, + holdPaint + ) if (!frame) { throw new Error(SCREENSHOT_TIMEOUT_MESSAGE) } @@ -269,13 +278,13 @@ export async function captureScreenshot( const release = holdPaint() try { - const frame = await captureUntilDrawn(webContents, screenshotParams) + const frame = await captureUntilDrawn(webContents, screenshotParams, holdPaint) if (frame) { return frame } const fallback = await readRemoteCliAdmittedPage(webContents.id, () => withTimeout( - Promise.resolve().then(() => webContents.capturePage()), + holdPaintUntilSettled(holdPaint, () => webContents.capturePage()), FALLBACK_CAPTURE_TIMEOUT_MS, SCREENSHOT_TIMEOUT_MESSAGE ) diff --git a/src/main/browser/cdp/debugger/guest-paint-hold.ts b/src/main/browser/cdp/debugger/guest-paint-hold.ts index 885a3e98a84..c235cf72541 100644 --- a/src/main/browser/cdp/debugger/guest-paint-hold.ts +++ b/src/main/browser/cdp/debugger/guest-paint-hold.ts @@ -1,2 +1,41 @@ +import type { WebContents } from 'electron' +import { acquireElectronDebugger } from './electron-debugger-lease' + /** Draws a hidden guest while a capture or agent input needs its frames; returns its release. */ export type CapturePaintHold = () => () => void + +function retainUntilSettled(acquire: () => () => void, run: () => Promise): Promise { + let release: () => void + try { + release = acquire() + } catch (error) { + return Promise.reject(error) + } + const pending = new Promise((resolve) => resolve(run())) + void pending.then(release, release) + return pending +} + +/** + * Holds paint until Chromium answers the capture, not just while the caller waits. A capture stays + * pending until the guest draws, and while pending it can hold macOS display sleep off ("Capturing"); + * timeouts do not cancel it (#24946). + */ +export function holdPaintUntilSettled( + holdPaint: CapturePaintHold, + capture: () => Promise +): Promise { + return retainUntilSettled(holdPaint, capture) +} + +/** Also keeps the debugger attached: a detach rejects the command while Chromium keeps the capture. */ +export function holdPaintUntilCdpCaptureSettles( + webContents: WebContents, + holdPaint: CapturePaintHold, + capture: () => Promise +): Promise { + return retainUntilSettled( + () => acquireElectronDebugger(webContents).release, + () => retainUntilSettled(holdPaint, capture) + ) +} diff --git a/src/main/browser/cdp/screencast/browser-screencast-first-frame-timeout.test.ts b/src/main/browser/cdp/screencast/browser-screencast-first-frame-timeout.test.ts index 797f2ff07a5..8129fb06766 100644 --- a/src/main/browser/cdp/screencast/browser-screencast-first-frame-timeout.test.ts +++ b/src/main/browser/cdp/screencast/browser-screencast-first-frame-timeout.test.ts @@ -24,6 +24,7 @@ function startOptions(viewport: boolean) { maxHeight: 1200, everyNthFrame: 2, minFrameIntervalMs: 0, + holdPaint: () => () => {}, ...(viewport ? { viewportWidth: 390, viewportHeight: 844 } : {}), onFrame: vi.fn(() => true), onError: vi.fn() @@ -59,6 +60,49 @@ describe('browser screencast first-frame deadline', () => { await session.done }) + it('keeps the page drawable until Chromium answers the captures the stream gave up on', async () => { + let settleCapture!: (image: unknown) => void + const webContents = Object.assign(createMockScreencastWebContents(), { + capturePage: vi.fn( + () => + new Promise((resolve) => { + settleCapture = resolve + }) + ) + }) + let settleScreenshot!: (result: unknown) => void + let rejectScreenshot!: (error: Error) => void + webContents.debugger.sendCommand.mockImplementation(async (method: string) => + method === 'Page.captureScreenshot' + ? new Promise((resolve, reject) => { + settleScreenshot = resolve + rejectScreenshot = reject + }) + : {} + ) + // Electron rejects pending commands on detach, but Chromium keeps the capture. + webContents.debugger.detach.mockImplementation(() => + rejectScreenshot(new Error('target closed while handling command')) + ) + const releasePaint = vi.fn() + const options = { ...startOptions(true), holdPaint: vi.fn(() => releasePaint) } + const session = await start(webContents, options) + + // capturePage's 10 s bound, then the CDP fallback's 8 s. + await vi.advanceTimersByTimeAsync(18_000) + session.stop() + await session.done + expect(options.holdPaint).toHaveBeenCalledTimes(2) + expect(webContents.debugger.detach).not.toHaveBeenCalled() + expect(releasePaint).not.toHaveBeenCalled() + + settleCapture({ getSize: () => ({ width: 0, height: 0 }) }) + settleScreenshot({}) + await vi.advanceTimersByTimeAsync(0) + expect(releasePaint).toHaveBeenCalledTimes(2) + expect(webContents.debugger.detach).toHaveBeenCalledOnce() + }) + it('drops a capture that settles after the limit', async () => { let settleCapture!: (image: unknown) => void const webContents = Object.assign(createMockScreencastWebContents(), { diff --git a/src/main/browser/cdp/screencast/browser-screencast-guest-view-limit.test.ts b/src/main/browser/cdp/screencast/browser-screencast-guest-view-limit.test.ts index 5968bf42069..a07487bfd5b 100644 --- a/src/main/browser/cdp/screencast/browser-screencast-guest-view-limit.test.ts +++ b/src/main/browser/cdp/screencast/browser-screencast-guest-view-limit.test.ts @@ -70,6 +70,7 @@ async function startOversizedStream(guest: ReturnType, onFra deviceScaleFactor: 2, everyNthFrame: 1, minFrameIntervalMs: 0, + holdPaint: () => () => {}, onFrame }) } diff --git a/src/main/browser/cdp/screencast/browser-screencast-lifecycle.test.ts b/src/main/browser/cdp/screencast/browser-screencast-lifecycle.test.ts index 09889e723c7..4443f28f7e3 100644 --- a/src/main/browser/cdp/screencast/browser-screencast-lifecycle.test.ts +++ b/src/main/browser/cdp/screencast/browser-screencast-lifecycle.test.ts @@ -35,6 +35,7 @@ describe('browser screencast lifecycle', () => { maxHeight: 2160, everyNthFrame: 2, minFrameIntervalMs: 0, + holdPaint: () => () => {}, onFrame }) @@ -80,6 +81,7 @@ describe('browser screencast lifecycle', () => { maxHeight: 1200, everyNthFrame: 2, minFrameIntervalMs: 0, + holdPaint: () => () => {}, onFrame: vi.fn() }, isClosed: () => false, diff --git a/src/main/browser/cdp/screencast/browser-screencast-live-frame-allocation.test.ts b/src/main/browser/cdp/screencast/browser-screencast-live-frame-allocation.test.ts index 0d61e942a80..86185d11b0b 100644 --- a/src/main/browser/cdp/screencast/browser-screencast-live-frame-allocation.test.ts +++ b/src/main/browser/cdp/screencast/browser-screencast-live-frame-allocation.test.ts @@ -40,6 +40,7 @@ function createLiveFrameRoute( maxHeight: 1200, everyNthFrame: 2, minFrameIntervalMs: 0, + holdPaint: () => () => {}, onFrame } const isClosed = () => false diff --git a/src/main/browser/cdp/screencast/browser-screencast-snapshot-capture.ts b/src/main/browser/cdp/screencast/browser-screencast-snapshot-capture.ts index 733a4cb542a..b9b3c1f037d 100644 --- a/src/main/browser/cdp/screencast/browser-screencast-snapshot-capture.ts +++ b/src/main/browser/cdp/screencast/browser-screencast-snapshot-capture.ts @@ -1,7 +1,11 @@ import { Buffer } from 'node:buffer' import type { Debugger, WebContents } from 'electron' import { readBrowserScreencastImageSize } from './browser-screencast-image-size' -import { sendDebuggerCommand } from './browser-screencast-debugger-command' +import { runDebuggerCommandWithTimeout } from './browser-screencast-debugger-command' +import { + holdPaintUntilCdpCaptureSettles, + holdPaintUntilSettled +} from '../debugger/guest-paint-hold' import type { BrowserScreencastOptions, PendingScreencastFrame @@ -35,6 +39,7 @@ export function createBrowserScreencastSnapshotCapture( ): BrowserScreencastSnapshotCapture { const { webContents, dbg, options, isClosed, isStopping, getSeq, queueFrame } = deps const { applyDeviceMetricsOverride } = deps + const { holdPaint } = options let snapshotGeneration = 0 let navigationCaptureTimer: ReturnType | null = null @@ -81,7 +86,9 @@ export function createBrowserScreencastSnapshotCapture( try { // Prefer capturePage to avoid CDP tiling; stopped compositing can leave it pending. const nativeImage = await withTimeout( - webContents.capturePage({ x: 0, y: 0, width: viewportWidth, height: viewportHeight }), + holdPaintUntilSettled(holdPaint, () => + webContents.capturePage({ x: 0, y: 0, width: viewportWidth, height: viewportHeight }) + ), SNAPSHOT_CAPTURE_TIMEOUT_MS, null ) @@ -101,7 +108,7 @@ export function createBrowserScreencastSnapshotCapture( } } if (!image) { - const result = await sendDebuggerCommand(dbg, 'Page.captureScreenshot', { + const screenshotParams = { format: options.format, ...(options.format === 'jpeg' ? { quality: options.quality } : {}), ...(viewportWidth && viewportHeight @@ -117,7 +124,12 @@ export function createBrowserScreencastSnapshotCapture( } : {}), captureBeyondViewport: false - }) + } + const result = await runDebuggerCommandWithTimeout('Page.captureScreenshot', () => + holdPaintUntilCdpCaptureSettles(webContents, holdPaint, () => + dbg.sendCommand('Page.captureScreenshot', screenshotParams) + ) + ) if (isSnapshotStale(initialOnly, generation)) { return } diff --git a/src/main/browser/cdp/screencast/browser-screencast-stream-types.ts b/src/main/browser/cdp/screencast/browser-screencast-stream-types.ts index 0676e970411..666bba266b2 100644 --- a/src/main/browser/cdp/screencast/browser-screencast-stream-types.ts +++ b/src/main/browser/cdp/screencast/browser-screencast-stream-types.ts @@ -2,6 +2,7 @@ import type { BrowserScreencastFormat, BrowserScreencastFrameMetadata } from '../../../../shared/browser/screencast/browser-screencast-protocol' +import type { CapturePaintHold } from '../debugger/guest-paint-hold' export type BrowserScreencastOptions = { format: BrowserScreencastFormat @@ -17,6 +18,7 @@ export type BrowserScreencastOptions = { onFrame: (bytes: Uint8Array) => boolean | void onEvent?: (event: BrowserScreencastEvent) => void onError?: (message: string) => void + holdPaint: CapturePaintHold } export type BrowserScreencastViewport = Pick< diff --git a/src/main/browser/cdp/screencast/browser-screencast-stream.test.ts b/src/main/browser/cdp/screencast/browser-screencast-stream.test.ts index 6870a27f172..456ff1f213c 100644 --- a/src/main/browser/cdp/screencast/browser-screencast-stream.test.ts +++ b/src/main/browser/cdp/screencast/browser-screencast-stream.test.ts @@ -27,6 +27,7 @@ describe('startBrowserScreencast', () => { maxHeight: 1200, everyNthFrame: 1, minFrameIntervalMs: 0, + holdPaint: () => () => {}, onFrame }) @@ -84,6 +85,7 @@ describe('startBrowserScreencast', () => { maxHeight: 1200, everyNthFrame: 1, minFrameIntervalMs: 100, + holdPaint: () => () => {}, onFrame }) @@ -136,6 +138,7 @@ describe('startBrowserScreencast', () => { maxHeight: 1200, everyNthFrame: 2, minFrameIntervalMs: 0, + holdPaint: () => () => {}, onFrame: vi.fn(), onEvent }) diff --git a/src/main/claude/claude-agent-sdk-process-spawn.test.ts b/src/main/claude/claude-agent-sdk-process-spawn.test.ts index a79821a55b3..65dbbbfaddc 100644 --- a/src/main/claude/claude-agent-sdk-process-spawn.test.ts +++ b/src/main/claude/claude-agent-sdk-process-spawn.test.ts @@ -90,6 +90,25 @@ describe('claude agent SDK process spawn', () => { expect(spawn.managed?.stderrTail().length).toBe(8192) }) + it('keeps native chat identity after SDK and configured environment defaults', () => { + const process = fakeSpawn() + createClaudeCodeProcessSpawn(process.spawnImpl, 'win32').spawn( + sdkOptions({ + env: { + CLAUDE_CODE_ENTRYPOINT: 'sdk-ts', + claude_code_entrypoint: 'account', + PATH: 'C:\\bin' + } + }) + ) + expect(process.specs[0]?.env).toMatchObject({ CLAUDE_CODE_ENTRYPOINT: 'orca', PATH: 'C:\\bin' }) + expect( + Object.keys(process.specs[0]?.env ?? {}).filter( + (key) => key.toUpperCase() === 'CLAUDE_CODE_ENTRYPOINT' + ) + ).toEqual(['CLAUDE_CODE_ENTRYPOINT']) + }) + it('preserves a Windows .cmd shim and its arguments for the host spawner', () => { const process = fakeSpawn() createClaudeCodeProcessSpawn(process.spawnImpl, 'win32').spawn( diff --git a/src/main/claude/claude-agent-sdk-process-spawn.ts b/src/main/claude/claude-agent-sdk-process-spawn.ts index a5eb7f49e55..71b6adcd9e3 100644 --- a/src/main/claude/claude-agent-sdk-process-spawn.ts +++ b/src/main/claude/claude-agent-sdk-process-spawn.ts @@ -1,3 +1,4 @@ +import { withOrcaClaudeChatEntrypoint } from '../../shared/agent-launch/startup/claude-chat-entrypoint' import type { ChildProcessWithoutNullStreams } from 'node:child_process' import type { PipedProcessSpawner } from '@orca/process-host/process-spec' import type { SpawnOptions as ClaudeAgentSdkSpawnOptions } from '@anthropic-ai/claude-agent-sdk' @@ -70,7 +71,7 @@ export function createClaudeCodeProcessSpawn( { spawnImpl, platform, - inheritedEnv: definedEnv(options.env), + inheritedEnv: withOrcaClaudeChatEntrypoint(definedEnv(options.env), platform), site: 'claude-stream-json-teardown', policy: (supervised) => claudeChildClosePolicy(supervised, platform), acceptClose: claudeChildCloseProven diff --git a/src/main/claude/claude-model-catalog-probe.ts b/src/main/claude/claude-model-catalog-probe.ts index e58d16209ea..cac6371c9d1 100644 --- a/src/main/claude/claude-model-catalog-probe.ts +++ b/src/main/claude/claude-model-catalog-probe.ts @@ -1,3 +1,4 @@ +import { withOrcaClaudeChatEntrypoint } from '../../shared/agent-launch/startup/claude-chat-entrypoint' import { waitForPromiseWithSignal } from '../../shared/abort-signal-reason' import { assertStructuredAgentResolutionCurrent, @@ -88,7 +89,11 @@ export async function runClaudeListing( stdin: request.stdin, ...(request.cwd ? { cwd: request.cwd } : {}) }, - { site: request.site, inheritedEnv: env, signal: request.signal } + { + site: request.site, + inheritedEnv: withOrcaClaudeChatEntrypoint(env, process.platform), + signal: request.signal + } ) } const result = await runClaudeBackgroundAttempts({ @@ -197,7 +202,10 @@ export function createClaudeModelCatalogProbe( { site: 'claude-model-catalog-probe', // The listing runs from the account folder; relative PATH entries still mean the chat's. - inheritedEnv: launchDirectory ? envWithPathRelativeTo(env, launchDirectory) : env, + inheritedEnv: withOrcaClaudeChatEntrypoint( + launchDirectory ? envWithPathRelativeTo(env, launchDirectory) : env, + process.platform + ), signal, partialOutput: { timeoutMs: 2_000, diff --git a/src/main/claude/claude-stream-json-connection.ts b/src/main/claude/claude-stream-json-connection.ts index df808c208e2..ae39fdfb007 100644 --- a/src/main/claude/claude-stream-json-connection.ts +++ b/src/main/claude/claude-stream-json-connection.ts @@ -1,3 +1,4 @@ +import { withOrcaClaudeChatEntrypoint } from '../../shared/agent-launch/startup/claude-chat-entrypoint' import { claudeStartupAnswerObservation } from './claude-startup-answer-observation' import type { PipedProcessSpawner } from '@orca/process-host/process-spec' import type * as ClaudeAgentSdk from '@anthropic-ai/claude-agent-sdk' @@ -123,7 +124,7 @@ export async function openClaudeStreamJsonConnection( options: { ...launch.options, cwd: launch.cwd, - env, + env: withOrcaClaudeChatEntrypoint(env, process.platform), pathToClaudeCodeExecutable: launch.pathToClaudeCodeExecutable, spawnClaudeCodeProcess: spawner.spawn, ...(handlers.canUseTool ? { canUseTool: handlers.canUseTool } : {}), diff --git a/src/main/claude/structured/launch/claude-structured-child-env.ts b/src/main/claude/structured/launch/claude-structured-child-env.ts index 84cb638c262..64d70bf7717 100644 --- a/src/main/claude/structured/launch/claude-structured-child-env.ts +++ b/src/main/claude/structured/launch/claude-structured-child-env.ts @@ -1,3 +1,4 @@ +import { withOrcaClaudeChatEntrypoint } from '../../../../shared/agent-launch/startup/claude-chat-entrypoint' import { waitForPromiseWithSignal } from '../../../../shared/abort-signal-reason' import { assertStructuredAgentResolutionCurrent, @@ -91,24 +92,6 @@ async function readClaudeChildEnvSources(deps: ClaudeEnvDeps): Promise, - overlay: Record | undefined, - platform: NodeJS.Platform -): Record { - const inherited = { ...inheritedEnv } - stripInheritedClaudeSessionEnv(inherited, { platform }) - // The SDK reads only the exact name and otherwise adds its own default, which Windows would pick. - return overlayEnvironmentVariables( - { ...inherited, [CLAUDE_ENTRYPOINT_ENV]: 'orca' }, - overlay, - platform - ) -} - // Merge onto the shell environment to retain PATH and ambient Anthropic auth. export function claudeChildEnv( sources: ClaudeChildEnvSources, @@ -116,13 +99,9 @@ export function claudeChildEnv( /** False when the session's seal pairs the CLI runtime itself, behind this app's CLI. */ { runtimeOnPath = true }: { runtimeOnPath?: boolean } = {} ): Record { - const env = decorateEnv( - withOrcaClaudeEntrypoint( - withoutInheritedClaudeConfigDir(sources.inheritedEnv, process.platform), - sources.overlay, - process.platform - ) - ) + const inherited = withoutInheritedClaudeConfigDir(sources.inheritedEnv, process.platform) + stripInheritedClaudeSessionEnv(inherited) + const env = decorateEnv(overlayEnvironmentVariables(inherited, sources.overlay, process.platform)) return runtimeOnPath ? withCliRuntimeOnPath(sources.command, env, { platform: process.platform }) : env @@ -130,12 +109,12 @@ export function claudeChildEnv( // Version probes need the launch runtime and PATH, without auth credentials. export function claudeProbeEnv(sources: ClaudeChildEnvSources): Record { - return applyClaudeEnvPatch( - claudeChildEnv(sources), - {}, - { - stripAuthEnv: true, - platform: process.platform - } + return withOrcaClaudeChatEntrypoint( + applyClaudeEnvPatch( + claudeChildEnv(sources), + {}, + { stripAuthEnv: true, platform: process.platform } + ), + process.platform ) } diff --git a/src/main/ipc/hooks/register-worktree-hook-check-handler.ts b/src/main/ipc/hooks/register-worktree-hook-check-handler.ts index fae4e6ce384..ae5ac61df6f 100644 --- a/src/main/ipc/hooks/register-worktree-hook-check-handler.ts +++ b/src/main/ipc/hooks/register-worktree-hook-check-handler.ts @@ -1,5 +1,10 @@ import { ipcMain } from 'electron' -import { getRepoDialableSshTargetId, type ExecutionHostId } from '../../../shared/execution-host' +import { + getRepoDialableSshTargetId, + isRepoOnCatalogHost, + type ExecutionHostId +} from '../../../shared/execution-host' +import { scopeHooksToRepoKind } from '../../../shared/folder-workspace-hooks' import { isFolderRepo } from '../../../shared/repo-kind' import { hasHooksFile, loadHooks, hasUnrecognizedOrcaYamlKeys } from '../../workspace-hooks/hooks' import { resolveRepoForExecutionHost } from '../worktrees/repo-host-ownership' @@ -23,7 +28,8 @@ export function registerWorktreeHookCheckHandler(context: WorktreeIpcContext): v mayNeedUpdate: false } } - if (isFolderRepo(repo)) { + // A folder owned by another host has no hooks here; its own host reports them. + if (isFolderRepo(repo) && !isRepoOnCatalogHost(repo)) { return { status: 'ok', hasHooks: false, hooks: null, mayNeedUpdate: false } } @@ -53,7 +59,7 @@ export function registerWorktreeHookCheckHandler(context: WorktreeIpcContext): v } const has = hasHooksFile(repo.path) - const hooks = has ? loadHooks(repo.path) : null + const hooks = scopeHooksToRepoKind(repo, has ? loadHooks(repo.path) : null) // Well-formed unknown keys may come from a newer Orca; suggest updating instead of parse repair. const mayNeedUpdate = has && !hooks && hasUnrecognizedOrcaYamlKeys(repo.path) return { diff --git a/src/main/ipc/worktrees/create/folder-workspace-creation.ts b/src/main/ipc/worktrees/create/folder-workspace-creation.ts index b35dad3b48c..b3225c00f54 100644 --- a/src/main/ipc/worktrees/create/folder-workspace-creation.ts +++ b/src/main/ipc/worktrees/create/folder-workspace-creation.ts @@ -7,12 +7,17 @@ import type { CreateWorktreeArgsWithSystemProvenance } from '../ipc-context-sche import { getFolderWorkspaceInstanceId, mergeFolderWorkspace } from '../folder-workspace-model' import { resolveWorktreeCreateDisplayNameRequest } from '../../worktree-display-name' import { hostWorktreeTargetForRepo } from '../../../persistence/host-qualified-worktree-meta' +import { + isPreparedFolderSetup, + prepareFolderWorktreeSetup +} from '../../../runtime/workspaces/creation/runtime-folder-worktree-setup' +import { getLocalProjectWorktreeGitOptions } from '../../../workspaces/execution-host/project-runtime-git-options' -export function createFolderWorkspace( +export async function createFolderWorkspace( args: CreateWorktreeArgsWithSystemProvenance, repo: Repo, store: Store -): CreateWorktreeResult { +): Promise { const now = Date.now() const instanceId = randomUUID() const worktreeId = getFolderWorkspaceInstanceId(repo, instanceId) @@ -64,5 +69,22 @@ export function createFolderWorkspace( ? { linkedTaskSourceContext: args.linkedTaskSourceContext } : {}) }) - return { worktree: mergeFolderWorkspace(repo, worktreeId, meta) } + const worktree = mergeFolderWorkspace(repo, worktreeId, meta) + // The window opens the Setup tab from `setup`, as for a new worktree. + const prepared = await prepareFolderWorktreeSetup({ + // A desktop create is the user's act, as for a new worktree. + request: { ...args, wslUserAct: true }, + repo, + worktree, + settings: store.getSettings(), + runtimeTarget: () => getLocalProjectWorktreeGitOptions(store, repo), + shouldUseSetupRunner: true + }) + const setup = isPreparedFolderSetup(prepared) ? prepared : undefined + return { + worktree, + ...(setup?.setup ? { setup: setup.setup } : {}), + ...(setup?.setupTrustMismatch ? { setupTrustMismatch: setup.setupTrustMismatch } : {}), + ...(prepared?.warning ? { warning: prepared.warning } : {}) + } } diff --git a/src/main/ipc/worktrees/create/register-worktree-create-handlers.ts b/src/main/ipc/worktrees/create/register-worktree-create-handlers.ts index b8caf67061b..60a43933f42 100644 --- a/src/main/ipc/worktrees/create/register-worktree-create-handlers.ts +++ b/src/main/ipc/worktrees/create/register-worktree-create-handlers.ts @@ -67,8 +67,8 @@ export function registerWorktreeCreateHandlers(context: WorktreeIpcContext): voi try { // Track operational failures; malformed IPC rejected above is outside the creation funnel. if (isFolderRepo(repo)) { - // Folder creation only registers metadata, so it needs no filesystem host route. - result = createFolderWorkspace(createArgs, repo, store) + // Folder creation registers metadata; its setup prep checks ownership itself. + result = await createFolderWorkspace(createArgs, repo, store) } else { // Resolve executionHostId-only SSH ownership before any local Git operation. const createRoute = requireWorktreeCreateRoute(repo) diff --git a/src/main/ipc/worktrees/removal/execute-worktree-removal.ts b/src/main/ipc/worktrees/removal/execute-worktree-removal.ts index deed7b0be72..45cd106494f 100644 --- a/src/main/ipc/worktrees/removal/execute-worktree-removal.ts +++ b/src/main/ipc/worktrees/removal/execute-worktree-removal.ts @@ -179,7 +179,8 @@ export async function executeWorktreeRemoval( canonicalWorktreePath, repo, undefined, - localWorktreeGitOptions + localWorktreeGitOptions, + { identity: { worktreeId: args.worktreeId } } ) archiveHookOverride = gateWorktreeRemovalOnArchiveHook({ worktreePath: canonicalWorktreePath, diff --git a/src/main/ipc/worktrees/removal/remove-folder-workspace.ts b/src/main/ipc/worktrees/removal/remove-folder-workspace.ts index 18e01cf0e7a..67783f1742e 100644 --- a/src/main/ipc/worktrees/removal/remove-folder-workspace.ts +++ b/src/main/ipc/worktrees/removal/remove-folder-workspace.ts @@ -13,6 +13,12 @@ import { getFolderWorkspaceRootId } from '../folder-workspace-model' import { preservedBranchCleanupByScope } from './preserved-branch-cleanup' import { removeWorktreeMetadataAndTransientState } from './worktree-removal-ownership' import { teardownStops } from '../../../runtime/workspaces/removal/owned-session-teardown-policy' +import { + gateFolderWorkspaceRemovalOnArchiveHook, + removeFolderWorkspaceRunnerFiles +} from '../../../workspaces/removal/folder-workspace-archive-hook' +import { readWorktreeMetaForRepo } from '../../../persistence/host-qualified-worktree-meta' +import { getLocalProjectWorktreeGitOptions } from '../../../workspaces/execution-host/project-runtime-git-options' export async function removeFolderWorkspace( context: WorktreeIpcContext, @@ -25,6 +31,19 @@ export async function removeFolderWorkspace( if (args.worktreeId === getFolderWorkspaceRootId(repo)) { throw new Error('Cannot delete the project root workspace. Remove the folder project instead.') } + // Archive failure must refuse before watcher, PTY or metadata teardown (#19334). + const archiveHookOverride = await gateFolderWorkspaceRemovalOnArchiveHook({ + repo, + worktreeId: args.worktreeId, + displayName: + ( + readWorktreeMetaForRepo(store, args.worktreeId, repo) ?? + store.getWorktreeMeta(args.worktreeId) + )?.displayName ?? repo.displayName, + runArchive: !args.skipArchive, + allowFailure: args.allowFailedArchiveHook === true, + runtimeTarget: () => getLocalProjectWorktreeGitOptions(store, repo) + }) const ownerHost = parseExecutionHostId(removalHostId) const gate = await runtime.acquireFileWatcherRemoval( repo.path, @@ -62,8 +81,9 @@ export async function removeFolderWorkspace( preservedBranchCleanupByScope.delete( preservedBranchCleanupScopeKey({ worktreeId: args.worktreeId, hostId: removalHostId }) ) + removeFolderWorkspaceRunnerFiles(repo, args.worktreeId) notifyWorktreesChanged(mainWindow, repoId) - return {} + return archiveHookOverride ? { archiveHookOverride } : {} } finally { await gate.finish(false) } diff --git a/src/main/linear/issue-context/includes.test.ts b/src/main/linear/issue-context/includes.test.ts index bc32b1f7855..7d5498b4c22 100644 --- a/src/main/linear/issue-context/includes.test.ts +++ b/src/main/linear/issue-context/includes.test.ts @@ -57,6 +57,19 @@ function requestWithComments(): LinearIssueRequest { } } +function requestWithActivity(): LinearIssueRequest { + return { + include: { + comments: false, + children: false, + attachments: false, + relations: false, + activity: true + }, + depth: 2 + } +} + function result(): LinearIssueContextResult { return { issue: resolvedIssue().issue, @@ -127,4 +140,41 @@ describe('Linear issue context includes', () => { } ]) }) + + it('does not treat an activity page without pageInfo as a complete history', async () => { + plainRawRequest + .mockResolvedValueOnce({ + data: { + issue: { + history: { + nodes: [{ id: 'life-1' }, { id: 'life-2' }], + pageInfo: { hasNextPage: true, endCursor: 'next' } + } + } + } + }) + .mockResolvedValueOnce({ + data: { issue: { history: { nodes: [] } } } + }) + const { readOptionalIncludes } = await import('./includes') + const output = result() + + await readOptionalIncludes( + resolvedIssue(), + requestWithActivity(), + output, + output.meta.includeErrors, + output.meta.sections + ) + + expect(output.activity).toBeUndefined() + expect(output.meta.sections.activity).toBeUndefined() + expect(output.meta.includeErrors).toEqual([ + expect.objectContaining({ + include: 'activity', + code: 'linear_include_failed' + }) + ]) + expect(plainRawRequest).toHaveBeenCalledTimes(2) + }) }) diff --git a/src/main/linear/issue-context/pagination.ts b/src/main/linear/issue-context/pagination.ts index beb1480bb7d..bd40abf39e1 100644 --- a/src/main/linear/issue-context/pagination.ts +++ b/src/main/linear/issue-context/pagination.ts @@ -1,4 +1,5 @@ import { LINEAR_ISSUE_API_PAGE_SIZE_MAX } from '../../../shared/linear/issue-read-limits' +import { linearError } from './errors' export type LinearPageVariables = { first: number; after?: string } @@ -10,6 +11,24 @@ export type LinearConnection = { } } | null +export function linearConnectionHasNextPage( + connection: { pageInfo?: { hasNextPage?: unknown } | null } | null | undefined +): boolean { + // Why: a null connection is an empty read. A connection whose hasNextPage is + // not boolean is not evidence that the caller already has the full set. + if (connection == null) { + return false + } + const hasNext = connection.pageInfo?.hasNextPage + if (typeof hasNext !== 'boolean') { + throw linearError( + 'linear_partial', + 'Linear omitted pageInfo, so this read cannot be treated as complete.' + ) + } + return hasNext +} + export async function readConnectionPages( limit: number, loadConnection: (page: LinearPageVariables) => Promise>, @@ -25,7 +44,7 @@ export async function readConnectionPages( const connection = await loadConnection(after ? { first, after } : { first }) const pageNodes = connection?.nodes ?? [] nodes.push(...pageNodes.slice(0, limit - nodes.length)) - hasMore = Boolean(connection?.pageInfo?.hasNextPage) + hasMore = linearConnectionHasNextPage(connection) const nextCursor = connection?.pageInfo?.endCursor ?? undefined if (!hasMore || !nextCursor || nextCursor === after || pageNodes.length === 0) { diff --git a/src/main/linear/issue-relation-write.test.ts b/src/main/linear/issue-relation-write.test.ts new file mode 100644 index 00000000000..9eb2ba48ae5 --- /dev/null +++ b/src/main/linear/issue-relation-write.test.ts @@ -0,0 +1,54 @@ +import { describe, expect, it, vi } from 'vitest' + +const { rawRequest } = vi.hoisted(() => ({ rawRequest: vi.fn() })) + +vi.mock('./linear-request-concurrency', () => ({ + acquire: vi.fn().mockResolvedValue(undefined), + release: vi.fn() +})) + +vi.mock('./linear-token-store', () => ({ + clearToken: vi.fn() +})) + +vi.mock('./client', () => ({ + getClients: () => [{ workspace: { id: 'workspace-1' }, client: { client: { rawRequest } } }], + isAuthError: () => false +})) + +import { writeIssueRelation } from './issue-relation-write' + +describe('writeIssueRelation', () => { + it('does not create a relation when the duplicate lookup omits pageInfo', async () => { + rawRequest.mockImplementation(async (query: string) => + query.includes('issueRelationCreate') + ? { + data: { + issueRelationCreate: { + success: true, + issueRelation: { + id: 'rel-new', + type: 'blocks', + issue: { id: 'issue-1' }, + relatedIssue: { id: 'issue-2' } + } + } + } + } + : { data: { issue: { relations: { nodes: [] } } } } + ) + const issue = { id: 'issue-1', identifier: 'LIN-1', title: 'One', url: 'https://x/1' } + const relatedIssue = { id: 'issue-2', identifier: 'LIN-2', title: 'Two', url: 'https://x/2' } + + await expect( + writeIssueRelation({ + issue, + relatedIssue, + relationship: 'blocks', + operation: 'add', + workspaceId: 'workspace-1' + }) + ).rejects.toMatchObject({ code: 'linear_partial' }) + expect(rawRequest).toHaveBeenCalledTimes(1) + }) +}) diff --git a/src/main/linear/issue-relation-write.ts b/src/main/linear/issue-relation-write.ts index 9b340d28bd1..e63e26fdb70 100644 --- a/src/main/linear/issue-relation-write.ts +++ b/src/main/linear/issue-relation-write.ts @@ -9,6 +9,7 @@ import { acquire, release } from './linear-request-concurrency' import { clearToken } from './linear-token-store' import { getClients, isAuthError } from './client' import { linearError } from './issue-context/errors' +import { linearConnectionHasNextPage } from './issue-context/pagination' import { INVERSE_RELATIONS_QUERY, RELATIONS_QUERY, @@ -135,7 +136,7 @@ async function findRelationInDirection( } inspected += nodes.length - const hasMore = connection?.pageInfo?.hasNextPage === true + const hasMore = linearConnectionHasNextPage(connection) const nextCursor = connection?.pageInfo?.endCursor ?? undefined if (!hasMore) { return { relation: null, hasMore: false } diff --git a/src/main/linear/linear-custom-view-queries.ts b/src/main/linear/linear-custom-view-queries.ts index fe225e644d3..0788a14d244 100644 --- a/src/main/linear/linear-custom-view-queries.ts +++ b/src/main/linear/linear-custom-view-queries.ts @@ -30,6 +30,7 @@ import { } from './linear-project-models' import { readCollection, readConcreteCollection } from './linear-project-collection-read' import { readIssueConnectionPages } from './linear-project-issue-queries' +import { linearConnectionHasNextPage } from './issue-context/pagination' export async function listCustomViews( model: LinearCustomViewModel, @@ -53,7 +54,7 @@ export async function listCustomViews( items: (connection?.nodes ?? []) .map((view) => mapCustomViewForWorkspace(entry, view)) .filter((view): view is LinearCustomViewSummary => !!view && view.model === model), - hasMore: !!connection?.pageInfo?.hasNextPage + hasMore: linearConnectionHasNextPage(connection) } }, force @@ -161,7 +162,7 @@ export async function listCustomViewProjects( const connection = view?.projects return { items: (connection?.nodes ?? []).map((project) => mapProjectForWorkspace(entry, project)), - hasMore: !!connection?.pageInfo?.hasNextPage + hasMore: linearConnectionHasNextPage(connection) } }, force diff --git a/src/main/linear/linear-issue-listing.ts b/src/main/linear/linear-issue-listing.ts index 290f5eeb133..32312042ede 100644 --- a/src/main/linear/linear-issue-listing.ts +++ b/src/main/linear/linear-issue-listing.ts @@ -27,6 +27,7 @@ import { shouldThrowAuthError, sortLimitAndDescribeIssues } from './linear-issue-query-support' +import { linearConnectionHasNextPage } from './issue-context/pagination' export type LinearListFilter = 'assigned' | 'created' | 'all' | 'completed' | 'open' @@ -111,7 +112,7 @@ async function readIssueConnectionPage( const nodes = connection?.nodes ?? [] return { items: nodes.map((issue) => mapRawIssueForWorkspace(entry, issue)), - hasMore: Boolean(connection?.pageInfo?.hasNextPage), + hasMore: linearConnectionHasNextPage(connection), endCursor: connection?.pageInfo?.endCursor ?? undefined } } diff --git a/src/main/linear/linear-issue-query-support.ts b/src/main/linear/linear-issue-query-support.ts index b2daf98f271..a20ccc1ce85 100644 --- a/src/main/linear/linear-issue-query-support.ts +++ b/src/main/linear/linear-issue-query-support.ts @@ -16,6 +16,7 @@ import { } from './linear-issue-query-documents' import type { LinearClientForWorkspace } from './client' import type { LinearListFilter } from './linear-issue-listing' +import { linearConnectionHasNextPage } from './issue-context/pagination' export async function mapIssueForWorkspace( entry: LinearClientForWorkspace, @@ -109,7 +110,7 @@ export async function readIssueConnectionPages( const connection = await loadConnection(after ? { first, after } : { first }) const nodes = connection?.nodes ?? [] items.push(...nodes.map((issue) => mapRawIssueForWorkspace(entry, issue))) - hasMore = Boolean(connection?.pageInfo?.hasNextPage) + hasMore = linearConnectionHasNextPage(connection) const nextCursor = connection?.pageInfo?.endCursor ?? undefined if (!hasMore || !nextCursor || nextCursor === after || nodes.length === 0) { diff --git a/src/main/linear/linear-project-issue-queries.ts b/src/main/linear/linear-project-issue-queries.ts index 49e1b89dd5f..4834ae9a0a2 100644 --- a/src/main/linear/linear-project-issue-queries.ts +++ b/src/main/linear/linear-project-issue-queries.ts @@ -17,6 +17,7 @@ import type { } from './linear-project-nodes' import { mapIssueForWorkspace, normalizeConcreteWorkspaceId } from './linear-project-models' import { readConcreteCollection } from './linear-project-collection-read' +import { linearConnectionHasNextPage } from './issue-context/pagination' export async function readIssueConnectionPages( entry: LinearClientForWorkspace, @@ -36,7 +37,7 @@ export async function readIssueConnectionPages( const connection = await loadConnection(after ? { first, after } : { first }) const nodes = connection?.nodes ?? [] items.push(...nodes.map((issue) => mapIssueForWorkspace(entry, issue))) - hasMore = Boolean(connection?.pageInfo?.hasNextPage) + hasMore = linearConnectionHasNextPage(connection) const nextCursor = connection?.pageInfo?.endCursor ?? undefined if (!hasMore || !nextCursor || nextCursor === after || nodes.length === 0) { diff --git a/src/main/linear/linear-project-queries.ts b/src/main/linear/linear-project-queries.ts index 24fcd13fed2..7c18347637e 100644 --- a/src/main/linear/linear-project-queries.ts +++ b/src/main/linear/linear-project-queries.ts @@ -29,6 +29,7 @@ import { normalizeConcreteWorkspaceId } from './linear-project-models' import { readCollection } from './linear-project-collection-read' +import { linearConnectionHasNextPage } from './issue-context/pagination' export async function listProjects( query: string | undefined, @@ -52,7 +53,7 @@ export async function listProjects( const connection = trimmed ? result.data?.searchProjects : result.data?.projects return { items: (connection?.nodes ?? []).map((project) => mapProjectForWorkspace(entry, project)), - hasMore: !!connection?.pageInfo?.hasNextPage + hasMore: linearConnectionHasNextPage(connection) } }, force, @@ -103,10 +104,10 @@ export async function listProjectsByExactName( } const nextCursor = connection?.pageInfo?.endCursor ?? undefined if ( - connection?.pageInfo?.hasNextPage !== true || + !linearConnectionHasNextPage(connection) || !nextCursor || nextCursor === after || - (connection.nodes ?? []).length === 0 + (connection?.nodes ?? []).length === 0 ) { break } diff --git a/src/main/linear/linear-project-team-queries.ts b/src/main/linear/linear-project-team-queries.ts index 56dc948d884..50552de451f 100644 --- a/src/main/linear/linear-project-team-queries.ts +++ b/src/main/linear/linear-project-team-queries.ts @@ -6,6 +6,7 @@ import { getClients, isAuthError } from './client' import { PROJECT_TEAMS_QUERY } from './linear-project-graphql' import type { LinearRawVariables, ProjectTeamsResponse } from './linear-project-nodes' import { coalesce, normalizeConcreteWorkspaceId } from './linear-project-models' +import { linearConnectionHasNextPage } from './issue-context/pagination' export async function listProjectTeams( projectId: string, @@ -55,7 +56,7 @@ export async function listProjectTeams( ) const nextCursor = connection?.pageInfo?.endCursor ?? undefined if ( - !connection?.pageInfo?.hasNextPage || + !linearConnectionHasNextPage(connection) || !nextCursor || nextCursor === after || nodes.length === 0 diff --git a/src/main/linear/mcp-issue-list-page-info.test.ts b/src/main/linear/mcp-issue-list-page-info.test.ts new file mode 100644 index 00000000000..cd4e71b6e98 --- /dev/null +++ b/src/main/linear/mcp-issue-list-page-info.test.ts @@ -0,0 +1,67 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest' + +const { rawRequest } = vi.hoisted(() => ({ rawRequest: vi.fn() })) + +vi.mock('./linear-request-concurrency', () => ({ + acquire: vi.fn().mockResolvedValue(undefined), + release: vi.fn() +})) + +vi.mock('./linear-token-store', () => ({ + clearToken: vi.fn() +})) + +vi.mock('./client', () => ({ + getClients: () => [ + { + workspace: { + id: 'workspace-1', + organizationId: 'workspace-1', + organizationName: 'Acme', + displayName: 'Ada', + email: 'ada@example.com' + }, + client: { client: { rawRequest } } + } + ], + getStatus: () => ({ workspaces: [] }), + isAuthError: () => false, + getPublicFileUrlClient: (entry: { client: unknown }) => entry.client +})) + +import { listMcpIssues } from './mcp-issue-list' + +function issueNode(id: string) { + return { + id, + identifier: id.toUpperCase(), + title: id, + url: `https://linear.app/acme/issue/${id}`, + labels: { nodes: [] }, + updatedAt: '2026-11-10T00:00:00.000Z' + } +} + +describe('Linear list pagination evidence', () => { + beforeEach(() => { + vi.clearAllMocks() + }) + + it('does not report a complete list when a later page omits pageInfo', async () => { + rawRequest + .mockResolvedValueOnce({ + data: { + issues: { + nodes: [issueNode('lin-1'), issueNode('lin-2')], + pageInfo: { hasNextPage: true, endCursor: 'next' } + } + } + }) + .mockResolvedValueOnce({ + data: { issues: { nodes: [] } } + }) + + await expect(listMcpIssues({})).rejects.toMatchObject({ code: 'linear_partial' }) + expect(rawRequest).toHaveBeenCalledTimes(2) + }) +}) diff --git a/src/main/linear/mcp-issue-list.ts b/src/main/linear/mcp-issue-list.ts index 6c43e4d510d..d96347127ab 100644 --- a/src/main/linear/mcp-issue-list.ts +++ b/src/main/linear/mcp-issue-list.ts @@ -11,6 +11,7 @@ import { type WorkspaceReadFailure } from './issue-context/fanout' import { ISSUE_FIELDS, mapIssue, type RawIssue } from './issue-context/raw' +import { linearConnectionHasNextPage } from './issue-context/pagination' import { resolveWorkspaceSelector } from './issue-context/workspaces' import { encodeIssueListCursor, resolveIssueListCursor } from './mcp-issue-list-cursor' import { buildIssueFilter } from './mcp-issue-list-filter' @@ -199,7 +200,7 @@ async function readIssueListWorkspace( workspace: { id: entry.workspace.id, name: entry.workspace.organizationName } }) } - hasMore = connection?.pageInfo?.hasNextPage === true + hasMore = linearConnectionHasNextPage(connection) nextCursor = connection?.pageInfo?.endCursor ?? undefined if (!hasMore || !nextCursor) { break diff --git a/src/main/remote-layout-snapshot/remote-layout-snapshot-persistence.test.ts b/src/main/remote-layout-snapshot/remote-layout-snapshot-persistence.test.ts index 9b80228c4c3..560749b1c21 100644 --- a/src/main/remote-layout-snapshot/remote-layout-snapshot-persistence.test.ts +++ b/src/main/remote-layout-snapshot/remote-layout-snapshot-persistence.test.ts @@ -153,5 +153,5 @@ it('keeps a title-only change without arming a save, and writes it with the next // Another domain's save writes only the domains marked dirty, which must include this one. store.updateSettings({ opencodeSessionCookie: 'cookie' }) store.flushOrThrow() - expect(open().getRemoteLayoutSnapshot('env')?.workspaces[workspace.worktree]).toEqual(retitled) + expect(open().getRemoteLayoutSnapshots().env?.workspaces[workspace.worktree]).toEqual(retitled) }) diff --git a/src/main/remote-layout-snapshot/remote-layout-snapshot-persistence.ts b/src/main/remote-layout-snapshot/remote-layout-snapshot-persistence.ts index 04560570a45..45186efd4dd 100644 --- a/src/main/remote-layout-snapshot/remote-layout-snapshot-persistence.ts +++ b/src/main/remote-layout-snapshot/remote-layout-snapshot-persistence.ts @@ -1,4 +1,7 @@ -import type { RemoteLayoutSnapshot } from '../../shared/remote-layout-snapshot' +import type { + RemoteLayoutSnapshot, + RemoteLayoutSnapshotWorkspace +} from '../../shared/remote-layout-snapshot' import type { StoreRuntimeState } from '../persistence/loading-store/store-runtime-state' import type { WriteSchedulingOperations } from '../persistence/loading-store/write-scheduling' import { scheduleSave } from '../persistence/loading-store/write-scheduling' @@ -11,6 +14,28 @@ type RemoteLayoutSnapshotPersistenceContext = { scheduling: WriteSchedulingOperations } +function writeSnapshotEntry(entries: Record, id: string, value: T): void { + // Admitted string identities must remain own keys even when named __proto__. + Object.defineProperty(entries, id, { + value, + configurable: true, + enumerable: true, + writable: true + }) +} + +function saveRemoteLayoutSnapshots( + { runtime, scheduling }: RemoteLayoutSnapshotPersistenceContext, + save: 'now' | 'later' +): void { + if (save === 'later') { + runtime.dirtyProfileStateDomains?.add('remoteLayoutSnapshots') + return + } + // Save only this domain without waking workspace-session listeners. + scheduleSave(scheduling, ['remoteLayoutSnapshots']) +} + export class RemoteLayoutSnapshotPersistence { readonly [remoteLayoutSnapshotPersistenceContext]: RemoteLayoutSnapshotPersistenceContext @@ -18,10 +43,18 @@ export class RemoteLayoutSnapshotPersistence { this[remoteLayoutSnapshotPersistenceContext] = { runtime, scheduling } } - getRemoteLayoutSnapshot(environmentId: string): RemoteLayoutSnapshot | undefined { - return this[remoteLayoutSnapshotPersistenceContext].runtime.state.remoteLayoutSnapshots?.[ - environmentId - ] + /** Recorder-only lookup; workspace values are replaced, never mutated. */ + getRemoteLayoutSnapshotWorkspace( + environmentId: string, + worktreeId: string + ): RemoteLayoutSnapshotWorkspace | undefined { + const snapshots = + this[remoteLayoutSnapshotPersistenceContext].runtime.state.remoteLayoutSnapshots + const snapshot = + snapshots && Object.hasOwn(snapshots, environmentId) ? snapshots[environmentId] : undefined + return snapshot && Object.hasOwn(snapshot.workspaces, worktreeId) + ? snapshot.workspaces[worktreeId] + : undefined } getRemoteLayoutSnapshots(): Record { @@ -31,7 +64,7 @@ export class RemoteLayoutSnapshotPersistence { return Object.fromEntries( Object.entries(stored).map(([environmentId, { workspaces }]) => [ environmentId, - { workspaces } + { workspaces: structuredClone(workspaces) } ]) ) } @@ -42,19 +75,36 @@ export class RemoteLayoutSnapshotPersistence { snapshot: RemoteLayoutSnapshot | null, save: 'now' | 'later' ): void { - const { runtime, scheduling } = this[remoteLayoutSnapshotPersistenceContext] - const { [environmentId]: previous, ...others } = runtime.state.remoteLayoutSnapshots ?? {} - if (snapshot === null && previous === undefined) { + const context = this[remoteLayoutSnapshotPersistenceContext] + const snapshots = (context.runtime.state.remoteLayoutSnapshots ??= {}) + if (snapshot === null && !Object.hasOwn(snapshots, environmentId)) { return } - runtime.state.remoteLayoutSnapshots = snapshot - ? { ...others, [environmentId]: snapshot } - : others - if (save === 'later') { - runtime.dirtyProfileStateDomains?.add('remoteLayoutSnapshots') - return + if (snapshot) { + writeSnapshotEntry(snapshots, environmentId, snapshot) + } else { + delete snapshots[environmentId] } - // Save only this domain without waking workspace-session listeners. - scheduleSave(scheduling, ['remoteLayoutSnapshots']) + saveRemoteLayoutSnapshots(context, save) + } + + setRemoteLayoutSnapshotWorkspace( + environmentId: string, + worktreeId: string, + workspace: RemoteLayoutSnapshotWorkspace | null, + save: 'now' | 'later' + ): void { + const context = this[remoteLayoutSnapshotPersistenceContext] + const snapshots = (context.runtime.state.remoteLayoutSnapshots ??= {}) + const workspaces = Object.hasOwn(snapshots, environmentId) + ? snapshots[environmentId].workspaces + : {} + if (workspace) { + writeSnapshotEntry(workspaces, worktreeId, workspace) + } else { + delete workspaces[worktreeId] + } + writeSnapshotEntry(snapshots, environmentId, { workspaces }) + saveRemoteLayoutSnapshots(context, save) } } diff --git a/src/main/remote-layout-snapshot/remote-layout-snapshot-recorder.test.ts b/src/main/remote-layout-snapshot/remote-layout-snapshot-recorder.test.ts index 516d53f820b..20f8ac06316 100644 --- a/src/main/remote-layout-snapshot/remote-layout-snapshot-recorder.test.ts +++ b/src/main/remote-layout-snapshot/remote-layout-snapshot-recorder.test.ts @@ -13,7 +13,18 @@ function memoryStore() { const snapshots = new Map() const saves: ('now' | 'later')[] = [] const store: RemoteLayoutSnapshotStore = { - getRemoteLayoutSnapshot: (environmentId) => snapshots.get(environmentId), + getRemoteLayoutSnapshotWorkspace: (environmentId, worktreeId) => + snapshots.get(environmentId)?.workspaces[worktreeId], + setRemoteLayoutSnapshotWorkspace: (environmentId, worktreeId, workspace, save) => { + saves.push(save) + const snapshot = snapshots.get(environmentId) ?? { workspaces: {} } + if (workspace) { + snapshot.workspaces[worktreeId] = workspace + } else { + delete snapshot.workspaces[worktreeId] + } + snapshots.set(environmentId, snapshot) + }, setRemoteLayoutSnapshot: (environmentId, snapshot, save) => { saves.push(save) if (snapshot) { diff --git a/src/main/remote-layout-snapshot/remote-layout-snapshot-recorder.ts b/src/main/remote-layout-snapshot/remote-layout-snapshot-recorder.ts index 36bec681970..78c3e040212 100644 --- a/src/main/remote-layout-snapshot/remote-layout-snapshot-recorder.ts +++ b/src/main/remote-layout-snapshot/remote-layout-snapshot-recorder.ts @@ -8,7 +8,16 @@ import type { RuntimeRpcResponse } from '../../shared/runtime-rpc-envelope' import type { RuntimeMobileSessionTabsResult } from '../../shared/runtime-session-contracts' export type RemoteLayoutSnapshotStore = { - getRemoteLayoutSnapshot(environmentId: string): RemoteLayoutSnapshot | undefined + getRemoteLayoutSnapshotWorkspace( + environmentId: string, + worktreeId: string + ): RemoteLayoutSnapshotWorkspace | undefined + setRemoteLayoutSnapshotWorkspace( + environmentId: string, + worktreeId: string, + workspace: RemoteLayoutSnapshotWorkspace | null, + save: 'now' | 'later' + ): void setRemoteLayoutSnapshot( environmentId: string, snapshot: RemoteLayoutSnapshot | null, @@ -77,16 +86,16 @@ export function recordRemoteLayoutFrame( return } const { type: _type, removed, ...result } = frame - const { [frame.worktree]: previous, ...others } = - store.getRemoteLayoutSnapshot(environmentId)?.workspaces ?? {} + const previous = store.getRemoteLayoutSnapshotWorkspace(environmentId, frame.worktree) if (removed) { - store.setRemoteLayoutSnapshot(environmentId, { workspaces: others }, 'now') + store.setRemoteLayoutSnapshotWorkspace(environmentId, frame.worktree, null, 'now') return } const workspace = displayed(result) - store.setRemoteLayoutSnapshot( + store.setRemoteLayoutSnapshotWorkspace( environmentId, - { workspaces: { ...others, [frame.worktree]: workspace } }, + frame.worktree, + workspace, structure(previous) === structure(workspace) ? 'later' : 'now' ) } diff --git a/src/main/runtime/agent-senders/runtime-agent-sender-history-triggers.ts b/src/main/runtime/agent-senders/runtime-agent-sender-history-triggers.ts index f2247f0d6c0..bc4a2a4f6a2 100644 --- a/src/main/runtime/agent-senders/runtime-agent-sender-history-triggers.ts +++ b/src/main/runtime/agent-senders/runtime-agent-sender-history-triggers.ts @@ -1,4 +1,5 @@ import { z } from 'zod' +import { projectionMutationTriggers } from '../orchestration/db/projection-mutation-triggers' import type { OrchestrationDb } from '../orchestration/db/orchestration-db' import { tolerant } from './agent-sender-row-decoding' @@ -65,26 +66,15 @@ CREATE TEMP TABLE IF NOT EXISTS agent_sender_tracked ( kind TEXT NOT NULL, key TEXT NOT NULL, PRIMARY KEY (kind, key)) WITHOUT ROWID; CREATE TEMP TABLE IF NOT EXISTS agent_sender_dirty ( kind TEXT NOT NULL, key TEXT NOT NULL, PRIMARY KEY (kind, key)) WITHOUT ROWID; -${HISTORY_TRIGGERS.flatMap((trigger) => { - const events: { name: string; event: string; marks: string[] }[] = [ - { name: 'insert', event: 'AFTER INSERT', marks: [markDirty('NEW', trigger)] }, - { name: 'delete', event: 'AFTER DELETE', marks: [markDirty('OLD', trigger)] }, - { - name: 'update', - event: `AFTER UPDATE OF ${trigger.columns}`, - marks: [markDirty('OLD', trigger), markDirty('NEW', trigger)] - } - ] - return events.map( - ({ - name, - event, - marks - }) => `CREATE TEMP TRIGGER IF NOT EXISTS agent_sender_${trigger.table}_${name} -${event} ON main.${trigger.table} -BEGIN UPDATE temp.agent_sender_generation SET history = history + 1; ${marks.join(' ')} END;` - ) -}).join('\n')} +${projectionMutationTriggers( + 'agent_sender', + HISTORY_TRIGGERS.map((trigger) => ({ + table: trigger.table, + columns: trigger.columns, + mark: (row) => markDirty(row, trigger) + })), + 'UPDATE temp.agent_sender_generation SET history = history + 1;' +)} ${['insert', 'delete', 'update'] .map( (name) => `CREATE TEMP TRIGGER IF NOT EXISTS agent_sender_federated_dispatches_${name} diff --git a/src/main/runtime/browser/screencast/browser-screencasts.ts b/src/main/runtime/browser/screencast/browser-screencasts.ts index 192aa7412ed..d8a97faa304 100644 --- a/src/main/runtime/browser/screencast/browser-screencasts.ts +++ b/src/main/runtime/browser/screencast/browser-screencasts.ts @@ -2,6 +2,7 @@ import type { BrowserScreencastResult } from '../../../../shared/browser/runtime import { BrowserError } from '../../../browser/browser-error' import { randomUUID } from 'node:crypto' import { startBrowserScreencast } from '../../../browser/cdp/screencast/browser-screencast-stream' +import { browserManager } from '../../../browser/guest-lifecycle/manager/browser-manager' import { rendererPublicationThrottle } from '../../../window/renderer-publication-throttle' import { mintBrowserScreencastSubscriptionId } from './browser-screencast-subscription-id' import { @@ -102,6 +103,7 @@ export class RuntimeBrowserScreencasts { format: params.format, ...budget, ...viewport, + holdPaint: () => browserManager.holdPaintForCapture(guest.id), onFrame: (bytes) => { const ghosts: string[] = [] for (const [subscriptionId, subscriber] of pendingRecord.subscribers) { diff --git a/src/main/runtime/browser/screencast/remote-browser-screencast-frame-admission.test.ts b/src/main/runtime/browser/screencast/remote-browser-screencast-frame-admission.test.ts index 6e5d0b3db0c..c87652a7309 100644 --- a/src/main/runtime/browser/screencast/remote-browser-screencast-frame-admission.test.ts +++ b/src/main/runtime/browser/screencast/remote-browser-screencast-frame-admission.test.ts @@ -92,6 +92,7 @@ describe('sendRemoteBrowserScreencastFrame', () => { maxHeight: 2160, everyNthFrame: 1, minFrameIntervalMs: 0, + holdPaint: () => () => {}, onFrame: (bytes) => sendRemoteBrowserScreencastFrame(transport.sendBinary, bytes) !== 'refused' }) diff --git a/src/main/runtime/client/events/runtime-notifier-contract.ts b/src/main/runtime/client/events/runtime-notifier-contract.ts index aeaacdf7d83..699cea69893 100644 --- a/src/main/runtime/client/events/runtime-notifier-contract.ts +++ b/src/main/runtime/client/events/runtime-notifier-contract.ts @@ -136,7 +136,8 @@ export type RuntimeNotifier = { focusTerminal(tabId: string, worktreeId: string, leafId?: string | null): void /** Raises the window onto a pane it shows; resolves false when the window does not know the worktree. */ revealTerminalPane?(target: TerminalPaneRevealTarget): Promise - focusEditorTab?(tabId: string, worktreeId: string): void + /** `userInitiated` lets a chat tab move the window to another worktree. */ + focusEditorTab?(tabId: string, worktreeId: string, options?: { userInitiated: true }): void closeSessionTab?(tabId: string, worktreeId: string): void | Promise moveSessionTab?(worktreeId: string, move: RuntimeMobileSessionTabMove): void /** The window moves a client's pane to a new tab, since it owns the layout; rejects when it cannot answer. */ diff --git a/src/main/runtime/construction/runtime-construction-dependencies.ts b/src/main/runtime/construction/runtime-construction-dependencies.ts index c1dd0251255..e7d30136582 100644 --- a/src/main/runtime/construction/runtime-construction-dependencies.ts +++ b/src/main/runtime/construction/runtime-construction-dependencies.ts @@ -33,6 +33,7 @@ export type RuntimeConstructionDependencies = { onClaudeTerminalEvidence?: (paneKey: string, evidence: ClaudeTerminalEvidence) => void getAgentStatusSnapshot?: () => AgentStatusIpcPayload[] getAgentStatusSnapshotForPane?: (paneKey: string) => AgentStatusIpcPayload[] + getPublicAgentStatusSnapshotForPane?: (paneKey: string) => AgentStatusIpcPayload[] structuredAgentStatusSink?: StructuredAgentSessionStatusSink readObservedAgentStatusPaneIdentity?: (paneKey: string) => ObservedAgentStatusPaneIdentity getAgentProviderSessionSnapshot?: (tabId?: string) => AgentStatusIpcPayload[] diff --git a/src/main/runtime/construction/runtime-construction-services.ts b/src/main/runtime/construction/runtime-construction-services.ts index d3ea3a29649..6c1c4baadcd 100644 --- a/src/main/runtime/construction/runtime-construction-services.ts +++ b/src/main/runtime/construction/runtime-construction-services.ts @@ -277,6 +277,7 @@ export abstract class RuntimeConstructionServices { protected abstract readonly getAgentStatusSnapshotForPaneFn: | ((paneKey: string) => AgentStatusIpcPayload[]) | null + protected abstract readonly publicPaneStatusFn?: (paneKey: string) => AgentStatusIpcPayload[] abstract readonly getAgentStatusSnapshotFn: (() => AgentStatusIpcPayload[]) | null protected abstract getTrackedDisplayTitleForPty(ptyId: string): string | null protected abstract getLeavesForPty(ptyId: string): readonly RuntimeLeafRecord[] diff --git a/src/main/runtime/construction/runtime-construction.ts b/src/main/runtime/construction/runtime-construction.ts index dfffdd783c4..797bbb1e977 100644 --- a/src/main/runtime/construction/runtime-construction.ts +++ b/src/main/runtime/construction/runtime-construction.ts @@ -1,7 +1,7 @@ import { collectSavedStructuredAgentSessionIds } from '../agent-session/lifecycle/saved-structured-agent-session-restoration' import { LOCAL_EXECUTION_HOST_ID } from '../../../shared/execution-host' import type { - RuntimeConstructionBindings, + RuntimeConstructionBindings as Bindings, RuntimeConstructionDependencies } from './runtime-construction-dependencies' import type { OrcaRuntimeWithRuntimeId as IdentityState } from './runtime-identity-state' @@ -75,11 +75,11 @@ export abstract class OrcaRuntimeWithStateFields extends OrcaRuntimeWithLinearCo declare protected readonly attestAgentHookCompatibilityAuthorityFn: HostServices['attestAgentHookCompatibilityAuthorityFn'] declare protected readonly retireAgentHookCompatibilityAuthorityFn: HostServices['retireAgentHookCompatibilityAuthorityFn'] declare protected readonly readHookCliWriterObservationFn: - | RuntimeConstructionBindings['readHookCliWriterObservation'] + | Bindings['readHookCliWriterObservation'] | null declare protected readonly checkHookAgentPresenceFn: HostServices['checkHookAgentPresenceFn'] declare readonly subscribeAgentProviderSessionChangesFn: - | RuntimeConstructionBindings['subscribeAgentProviderSessionChanges'] + | Bindings['subscribeAgentProviderSessionChanges'] | null declare protected readonly reconcileAgentStatusForEndedProcessFn: HostServices['reconcileAgentStatusForEndedProcessFn'] declare protected readonly forgetHookAgentExitFn: HostServices['forgetHookAgentExitFn'] @@ -115,14 +115,14 @@ export abstract class OrcaRuntimeWithStateFields extends OrcaRuntimeWithLinearCo readonly workspaceSleepPlatform: WorkspaceSleepPlatform | null - protected readonly getAgentStatusSnapshotForPaneFn: - | RuntimeConstructionBindings['getAgentStatusSnapshotForPane'] - | null + declare protected readonly getAgentStatusSnapshotForPaneFn: HostServices['getAgentStatusSnapshotForPaneFn'] + + protected readonly publicPaneStatusFn?: Bindings['getPublicAgentStatusSnapshotForPane'] /** The agent's full final reply for that finished lead turn; status rows carry only a capped preview. */ - readonly getAcceptedAgentReply: RuntimeConstructionBindings['getAcceptedAgentReply'] + readonly getAcceptedAgentReply: Bindings['getAcceptedAgentReply'] /** Synchronous on every hook status row change, including clears. */ - readonly subscribeAgentStatusRowChanges: RuntimeConstructionBindings['subscribeAgentStatusRowChanges'] + readonly subscribeAgentStatusRowChanges: Bindings['subscribeAgentStatusRowChanges'] protected readonly machineName = new RuntimeMachineName( () => this.store?.getSettings?.().machineName @@ -253,6 +253,7 @@ export abstract class OrcaRuntimeWithStateFields extends OrcaRuntimeWithLinearCo } this.getAgentStatusSnapshotFn = deps?.getAgentStatusSnapshot ?? null this.getAgentStatusSnapshotForPaneFn = deps?.getAgentStatusSnapshotForPane ?? null + this.publicPaneStatusFn = deps?.getPublicAgentStatusSnapshotForPane this.structuredAgentStatusSinkFn = deps?.structuredAgentStatusSink ?? null this.readObservedAgentStatusPaneIdentityFn = deps?.readObservedAgentStatusPaneIdentity ?? (() => ({ kind: 'unobserved' })) diff --git a/src/main/runtime/orca-runtime-tests/orca-runtime-test-lifecycle.spec.ts b/src/main/runtime/orca-runtime-tests/orca-runtime-test-lifecycle.spec.ts index 9c45911318a..02c12808101 100644 --- a/src/main/runtime/orca-runtime-tests/orca-runtime-test-lifecycle.spec.ts +++ b/src/main/runtime/orca-runtime-tests/orca-runtime-test-lifecycle.spec.ts @@ -211,7 +211,8 @@ function resetRuntimeTestMocks(): void { vi.mocked(shouldRunSetupForCreate).mockReset() vi.mocked(shouldRunSetupForCreate).mockImplementation((_repo, decision) => decision === 'run') vi.mocked(getEffectiveHooks).mockReturnValue(null) - vi.mocked(getEffectiveHooksFromConfig).mockReturnValue(null) + // Setup derives effective hooks from the parsed orca.yaml; tests steer it through getEffectiveHooks. + vi.mocked(getEffectiveHooksFromConfig).mockImplementation((repo) => getEffectiveHooks(repo)) vi.mocked(getDefaultTabsLaunch).mockReturnValue(undefined) vi.mocked(loadHooks).mockReturnValue(null) vi.mocked(resolveSetupRunnerShell).mockReturnValue(undefined) diff --git a/src/main/runtime/orca-runtime-tests/orca-runtime-test-scenario-builders.spec.ts b/src/main/runtime/orca-runtime-tests/orca-runtime-test-scenario-builders.spec.ts index 0054a769df0..2bab325844f 100644 --- a/src/main/runtime/orca-runtime-tests/orca-runtime-test-scenario-builders.spec.ts +++ b/src/main/runtime/orca-runtime-tests/orca-runtime-test-scenario-builders.spec.ts @@ -218,6 +218,7 @@ function makePostRevealWorkerRecoveryHarness( // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: This recovery fixture reaches only the listed planner, terminal settlement and authority lookup methods. runtime.setOrchestrationDb({ crewChanges: new CrewChanges(), + hasAnyDispatchContexts: () => true, listSessionDispatchesForPresentation: () => [], reconcileMissingWorkerTerminal: vi.fn(), getActiveDispatchForTerminal: () => undefined, diff --git a/src/main/runtime/orca-runtime-tests/worktree-setup-and-startup-part-03.spec.ts b/src/main/runtime/orca-runtime-tests/worktree-setup-and-startup-part-03.spec.ts index 782d9eea2c3..e6afa712318 100644 --- a/src/main/runtime/orca-runtime-tests/worktree-setup-and-startup-part-03.spec.ts +++ b/src/main/runtime/orca-runtime-tests/worktree-setup-and-startup-part-03.spec.ts @@ -9,8 +9,11 @@ import { ensurePathWithinWorkspaceMock } from '../orca-runtime-test-mocks/setup.spec' import { createSetupRunnerScript } from '../../workspace-hooks/worktree-runner-script' -import { shouldRunSetupForCreate } from '../../workspace-hooks/effective-hook-config' -import { getEffectiveHooks } from '../../workspace-hooks/hooks' +import { + getEffectiveHooksFromConfig, + shouldRunSetupForCreate +} from '../../workspace-hooks/effective-hook-config' +import { getEffectiveHooks, loadHooks } from '../../workspace-hooks/hooks' import { listWorktrees } from '../../git/worktrees/catalog/worktree-scan-cache' import type { WorktreeMeta } from '../../../shared/worktree/meta-types' import { @@ -144,6 +147,12 @@ describe('OrcaRuntimeService', () => { vi.mocked(getEffectiveHooks).mockImplementation((_repo, worktreePath) => worktreePath ? { scripts: { setup: 'pnpm worktree:setup' } } : null ) + vi.mocked(loadHooks).mockImplementation((path) => + path === '/tmp/workspaces/runtime-branch-added-setup' + ? { scripts: { setup: 'pnpm worktree:setup' } } + : null + ) + vi.mocked(getEffectiveHooksFromConfig).mockImplementation((_repo, yamlHooks) => yamlHooks) // Model an ask-policy repo that refuses an undecided create. vi.mocked(shouldRunSetupForCreate).mockImplementation((_repo, decision) => { if (decision === 'run' || decision === 'skip') { diff --git a/src/main/runtime/orca-runtime.ts b/src/main/runtime/orca-runtime.ts index aeebd8bad02..456f346a079 100644 --- a/src/main/runtime/orca-runtime.ts +++ b/src/main/runtime/orca-runtime.ts @@ -62,6 +62,7 @@ import { getHostDisplayLabelOverrides } from '../../shared/host-setting-override import type { OrchestrationDb } from './orchestration/db/orchestration-db' import { continueRestoredWorkerMailSoon } from './rpc/methods/orchestration/messaging/settled-worker-follow-through' import { PeerMailRelay } from './orchestration/federation/peer-mail/peer-mail-relay' +import { structuredAgentSessionHostTabId } from '../../shared/agent-session/view/structured-agent-session-host-tab-id' const OrcaRuntimeSidebarBase: typeof OrcaRuntimeWithAgentTransitions = ORCA_SIDEBAR_INPUTS_IS_MAIN ? OrcaRuntimeWithSidebarTemporal @@ -222,6 +223,13 @@ class OrcaRuntimeService extends OrcaRuntimeSidebarBase { return this.notifier.publishAgentLaunchTab(request) } + /** The window follows a listed active chat only on its own intent (#5435), so a focused launch names it. */ + focusLaunchedChatInHostWindow(worktreeId: string, sessionId: string): void { + this.notifier?.focusEditorTab?.(structuredAgentSessionHostTabId(sessionId), worktreeId, { + userInitiated: true + }) + } + /** Retain final verdicts, clear settled ones, and remove withdrawn panes without removing split siblings. */ reportAgentLaunchPaneVerdict( pane: AgentLaunchPaneAddress, diff --git a/src/main/runtime/orchestration/addressing/orchestration-caller-identity.ts b/src/main/runtime/orchestration/addressing/orchestration-caller-identity.ts index 5d5c12dd857..232428348e0 100644 --- a/src/main/runtime/orchestration/addressing/orchestration-caller-identity.ts +++ b/src/main/runtime/orchestration/addressing/orchestration-caller-identity.ts @@ -1,4 +1,5 @@ import type { RunRow } from '../db/orchestration-records' +import type { PeerRunRow } from '../db/peer-runs/peer-run-store' import { isEquivalentPaneKey } from '../db/pane-key-match' import { currentRunCoordinatorOrcaSessionId } from '../db/runs/run-coordinator-orca-session' import { @@ -16,6 +17,7 @@ export type OrchestrationCoordinatorKey = Pick< /** A caller the dispatch entry resolved from the Orca session id in its injected environment. */ export type OrchestrationSessionCaller = OrchestrationCallerIdentity & Readonly<{ + kind?: undefined orcaSessionId: OrcaSessionId /** The session record the request came from. */ sessionId: OrcaSessionId @@ -23,6 +25,50 @@ export type OrchestrationSessionCaller = OrchestrationCallerIdentity & workspaceId: string }> +/** A paired Orca acting as the coordinator of its Run here, as its authenticated frame names it. + * Its handle and binding key are its address, which no terminal or session here can have. */ +export type OrchestrationPeerCaller = OrchestrationCallerIdentity & + Readonly<{ + kind: 'peer' + terminalHandle: string + paneKey: string + orcaSessionId: null + peerRun: PeerRunRow + }> + +/** The caller the dispatch entry resolved, which wins over any declared handle: a session from + * its environment, or a paired Orca from its pairing. */ +export type OrchestrationEntryCaller = OrchestrationSessionCaller | OrchestrationPeerCaller + +/** The address, and Run binding key, of the paired Orca coordinating a conversation's Run here. */ +export function peerCoordinatorAddress(conversationId: string): string { + return `${PEER_ADDRESS_PREFIX}${conversationId}` +} + +const PEER_ADDRESS_PREFIX = 'peer:' + +export function isPeerCoordinatorAddress(value: string | null | undefined): boolean { + return !!value?.startsWith(PEER_ADDRESS_PREFIX) +} + +export function peerCoordinatorCaller(peerRun: PeerRunRow): OrchestrationPeerCaller { + const address = peerCoordinatorAddress(peerRun.conversation_id) + return Object.freeze({ + kind: 'peer', + address, + terminalHandle: address, + paneKey: address, + orcaSessionId: null, + peerRun + }) +} + +export function isPeerCaller( + caller: OrchestrationCallerIdentity | null | undefined +): caller is OrchestrationPeerCaller { + return !!caller && 'kind' in caller && caller.kind === 'peer' +} + /** A caller with neither a pane nor an Orca session id can never be bound to a Run. */ export function hasRunBindingKey(caller: OrchestrationCoordinatorKey): boolean { return caller.paneKey !== null || caller.orcaSessionId !== null diff --git a/src/main/runtime/orchestration/addressing/orchestration-fleet-agent-status-snapshot.ts b/src/main/runtime/orchestration/addressing/orchestration-fleet-agent-status-snapshot.ts index 946aab137ce..8b04deb002d 100644 --- a/src/main/runtime/orchestration/addressing/orchestration-fleet-agent-status-snapshot.ts +++ b/src/main/runtime/orchestration/addressing/orchestration-fleet-agent-status-snapshot.ts @@ -1,3 +1,4 @@ +import { orchestrationProjectionFacts } from '../crew/orchestration-projection-facts' import type { TerminalIdentityReadContext } from '../../terminal/query/terminal-identity-read-context' import { conversationRecordReader } from './session-lineage/structured-session-lineage' import { getStructuredAgentSessionHost } from '../../../native-chat/agent-session-wire/host/structured-agent-session-registry' @@ -39,17 +40,22 @@ export function readCapturedOrchestrationFleetAgentStatusSnapshot( dependencies: RuntimeAgentOrchestrationDependencies ): readonly FleetAgentStatusEvidence[] { const projection = new RuntimeAgentOrchestrationProjection(dependencies) + const raw = dependencies.getDb() + const sourceFacts = raw?.db ? orchestrationProjectionFacts(raw) : undefined + const db = sourceFacts?.view ?? raw let scope: ReturnType | undefined return readOrchestrationFleetAgentStatusSnapshot({ ...source, getAgentStatusOrchestrationContextForPaneKey: (paneKey) => { + if (raw?.db && !sourceFacts) { + return undefined + } const handle = source.getAgentStatusTerminalHandleForPaneKey?.(paneKey) if (!handle) { return undefined } - const db = dependencies.getDb() scope ??= createOrchestrationProjectionScope(db, dependencies) - return projection.getForHandle(handle, db, { paneKey }, scope) + return projection.getForHandle(handle, db, { paneKey, deferAttention: true }, scope) } }) } diff --git a/src/main/runtime/orchestration/crew/crew-host-derivation.ts b/src/main/runtime/orchestration/crew/crew-host-derivation.ts index a7e24cc5b20..e42c44f6d4c 100644 --- a/src/main/runtime/orchestration/crew/crew-host-derivation.ts +++ b/src/main/runtime/orchestration/crew/crew-host-derivation.ts @@ -9,12 +9,10 @@ import { readCrewAssignments, type CrewAssignmentRow } from './crew-query' import { createCrewSourceInputs } from './crew-source-inputs' import type { CrewReadDependencies } from './crew-read-dependencies' -export function createCrewHostDerivation( - deps: CrewReadDependencies, - now: number, - capacity?: () => number -) { +export function createCrewHostDerivation(deps: CrewReadDependencies, capacity?: () => number) { const { statuses, ...sources } = captureCrewIdentityInputs(deps) + // Reading statuses can refresh the same source; capture its cutoff afterwards. + const now = deps.now ?? Date.now() const registry = createCrewPartyRegistry({ ...sources, statuses }) const { alias } = registry const identity = deps.openIdentityRead?.() diff --git a/src/main/runtime/orchestration/crew/crew-party-snapshot.ts b/src/main/runtime/orchestration/crew/crew-party-snapshot.ts index 5138af1f54a..a29e6e4aaa2 100644 --- a/src/main/runtime/orchestration/crew/crew-party-snapshot.ts +++ b/src/main/runtime/orchestration/crew/crew-party-snapshot.ts @@ -39,7 +39,7 @@ function preview(body: string): string { export function buildCrewSnapshot( address: string, deps: CrewReadDependencies, - host = createCrewHostDerivation(deps, deps.now ?? Date.now()) + host = createCrewHostDerivation(deps) ): OrchestrationCrewSnapshot { deps = { ...host.deps, now: deps.now } const db = deps.db diff --git a/src/main/runtime/orchestration/crew/crew-read-model.ts b/src/main/runtime/orchestration/crew/crew-read-model.ts index 34ca2b7a173..f861a2becb9 100644 --- a/src/main/runtime/orchestration/crew/crew-read-model.ts +++ b/src/main/runtime/orchestration/crew/crew-read-model.ts @@ -86,9 +86,7 @@ export class CrewReadModel { deps = { ...deps, records: previous.deps.records } } // A one-shot read has no watch to keep captured truth current. - const host = createCrewHostDerivation(deps, deps.now ?? now, () => - Math.max(32, this.listeners.size * 2) - ) + const host = createCrewHostDerivation(deps, () => Math.max(32, this.listeners.size * 2)) if (this.listeners.size === 0) { return buildCrewSnapshot(address, { ...host.deps, now }, host) } @@ -104,10 +102,8 @@ export class CrewReadModel { previous.registry.refreshRecordNames(deps.records, renamed) this.host = isDeepStrictEqual(identities(previous.deps.statuses), identities(statuses)) ? refreshCrewStatuses(previous, statuses) - : createCrewHostDerivation( - { ...sources, records: previous.deps.records, statuses }, - now, - () => Math.max(32, this.listeners.size * 2) + : createCrewHostDerivation({ ...sources, records: previous.deps.records, statuses }, () => + Math.max(32, this.listeners.size * 2) ) } else { this.host = previous diff --git a/src/main/runtime/orchestration/crew/dispatch-presentation-deadlines.ts b/src/main/runtime/orchestration/crew/dispatch-presentation-deadlines.ts new file mode 100644 index 00000000000..e8a7961419e --- /dev/null +++ b/src/main/runtime/orchestration/crew/dispatch-presentation-deadlines.ts @@ -0,0 +1,13 @@ +import { DispatchPresentationPriority } from './dispatch-presentation-priority' + +/** One addressable deadline per eligible dispatch; removing its owner also removes its deadline. */ +export class DispatchPresentationDeadlines extends DispatchPresentationPriority { + *expired(now: number): Iterable { + let next = this.peek() + while (next && next.priority < now) { + this.delete(next.id) + yield next.id + next = this.peek() + } + } +} diff --git a/src/main/runtime/orchestration/crew/dispatch-presentation-priority.ts b/src/main/runtime/orchestration/crew/dispatch-presentation-priority.ts new file mode 100644 index 00000000000..009fc22302d --- /dev/null +++ b/src/main/runtime/orchestration/crew/dispatch-presentation-priority.ts @@ -0,0 +1,79 @@ +/** Addressable dispatch priorities; arbitrary removal leaves no stale entries. */ +export class DispatchPresentationPriority { + private readonly positions = new Map() + private readonly items: { id: string; priority: number }[] = [] + + set(id: string, priority: number): void { + this.delete(id) + this.items.push({ id, priority }) + this.positions.set(id, this.items.length - 1) + this.up(this.items.length - 1) + } + + delete(id: string): void { + const index = this.positions.get(id) + if (index === undefined) { + return + } + const last = this.items.pop()! + this.positions.delete(id) + if (index >= this.items.length) { + return + } + this.items[index] = last + this.positions.set(last.id, index) + const moved = this.up(index) + if (moved === index) { + this.down(index) + } + } + + get size(): number { + return this.items.length + } + + peek(): Readonly<{ id: string; priority: number }> | undefined { + return this.items[0] + } + + clear(): void { + this.items.length = 0 + this.positions.clear() + } + + private swap(a: number, b: number): void { + const entry = this.items[a] + this.items[a] = this.items[b] + this.items[b] = entry + this.positions.set(this.items[a].id, a) + this.positions.set(this.items[b].id, b) + } + + private up(index: number): number { + while (index > 0) { + const parent = (index - 1) >> 1 + if (this.items[parent].priority <= this.items[index].priority) { + break + } + this.swap(index, parent) + index = parent + } + return index + } + + private down(index: number): void { + for (;;) { + const left = index * 2 + 1 + const right = left + 1 + const child = + right < this.items.length && this.items[right].priority < this.items[left].priority + ? right + : left + if (child >= this.items.length || this.items[index].priority <= this.items[child].priority) { + return + } + this.swap(index, child) + index = child + } + } +} diff --git a/src/main/runtime/orchestration/crew/orchestration-dispatch-context.ts b/src/main/runtime/orchestration/crew/orchestration-dispatch-context.ts new file mode 100644 index 00000000000..b16edee66b2 --- /dev/null +++ b/src/main/runtime/orchestration/crew/orchestration-dispatch-context.ts @@ -0,0 +1,140 @@ +import type { AgentStatusOrchestrationContext } from '../../../../shared/agent-status/contracts/agent-status-types' +import { creatorFirstParent, crewTaskDisplay } from './crew-rules' +import { parsePaneKey } from '../../../../shared/workspace-layout/stable-pane-id' +import type { OrchestrationDb } from '../db/orchestration-db' +import { buildWorkerAttentionContext } from '../workers/reports/worker-attention-context' +import { worktreeIdsEqual } from '../../../../shared/worktree/id' +import type { createOrchestrationProjectionScope } from './runtime-agent-orchestration-scope' +import { currentRunCoordinatorOrcaSessionId } from '../db/runs/run-coordinator-orca-session' +import type { DispatchContextRow } from '../db/orchestration-records' +import type { + DispatchProjectionOptions, + RuntimeAgentOrchestrationDependencies +} from './runtime-agent-orchestration-projection' + +export function composeOrchestrationDispatch( + deps: RuntimeAgentOrchestrationDependencies, + dispatch: DispatchContextRow, + handle: string, + db: OrchestrationDb | null, + options: DispatchProjectionOptions, + scope: ReturnType +): AgentStatusOrchestrationContext { + const { paneKey, evidence, deferAttention = false } = options + const session = options.observeSession?.(dispatch) + const task = scope.task(dispatch.task_id, dispatch.run_id) + const display = crewTaskDisplay(task) + const owningRun = + task?.run_id && task.run_id === dispatch.run_id ? scope.run(dispatch.run_id) : undefined + const runCoordinatorHandle = owningRun?.coordinator_handle ?? undefined + const legacyActiveRun = + owningRun?.legacy === 1 && (dispatch.status === 'pending' || dispatch.status === 'dispatched') + ? db?.getActiveCoordinatorRun?.() + : undefined + const handleWorktreeId = legacyActiveRun ? deps.getWorktreeId(handle) : null + const coordinatorWorktreeId = legacyActiveRun + ? deps.getWorktreeId(legacyActiveRun.coordinator_handle) + : null + const scopedLegacyRun = + legacyActiveRun && + handleWorktreeId && + coordinatorWorktreeId && + worktreeIdsEqual(coordinatorWorktreeId, handleWorktreeId) + ? legacyActiveRun + : undefined + const coordinatorHandle = runCoordinatorHandle ?? scopedLegacyRun?.coordinator_handle + const orchestrationRunId = owningRun?.legacy === 0 ? owningRun.id : scopedLegacyRun?.id + const creatorPaneKey = task?.created_by_pane_key + const creatorPaneHandle = creatorPaneKey ? deps.getHandleForPaneKey(creatorPaneKey) : null + const creatorAuthority = creatorPaneHandle ? deps.getDispatchAuthority(creatorPaneHandle) : null + const storedCreatorPane = creatorPaneKey ? parsePaneKey(creatorPaneKey) : null + const currentCreatorPane = creatorAuthority?.paneKey + ? parsePaneKey(creatorAuthority.paneKey) + : null + const sameCreatorPane = Boolean( + creatorPaneKey && + creatorAuthority?.paneKey && + (creatorPaneKey === creatorAuthority.paneKey || + (storedCreatorPane && + currentCreatorPane && + storedCreatorPane.leafId === currentCreatorPane.leafId)) + ) + const paneRuns = creatorPaneKey ? scope.paneRuns(creatorPaneKey) : [] + const paneRun = paneRuns.find((run) => run.id === owningRun?.id) ?? paneRuns[0] + const sameRunCreatorDispatch = Boolean( + task?.creator_dispatch_id && + task.creator_dispatch_run_id === owningRun?.id && + task.creator_dispatch_pane_key && + task.creator_dispatch_process_incarnation === task.created_by_process_incarnation && + parsePaneKey(task.creator_dispatch_pane_key)?.leafId === storedCreatorPane?.leafId + ) + // Durable Run membership identifies the creator; live incarnation/handle checks only decide mutation authority. + const creatorLineageInRun = Boolean( + owningRun?.legacy === 0 && + task?.created_by_run_generation === owningRun.consumer_generation && + creatorPaneKey && + (paneRun + ? paneRun.id === owningRun.id && + paneRun.consumer_generation === task.created_by_run_generation + : sameRunCreatorDispatch) + ) + const currentCreatorHandle = + creatorLineageInRun && + task?.created_by_process_incarnation === creatorAuthority?.processIncarnation && + sameCreatorPane + ? (creatorPaneHandle ?? undefined) + : undefined + const selfSession = dispatch.assignee_orca_session_id + const selfPane = selfSession ? scope.resolve(selfSession) : paneKey + const coordinatorSession = + owningRun?.legacy === 0 ? currentRunCoordinatorOrcaSessionId(owningRun) : null + // Why: a chat party nests by its visible row; its handle and minted pane key match no row. + const coordinator: { handle?: string; paneKey?: string } = coordinatorSession + ? { paneKey: scope.resolve(coordinatorSession) } + : scope.resolveTerminal( + coordinatorHandle, + owningRun?.legacy === 0 ? owningRun.coordinator_pane_key : null + ) + const creatorSession = + dispatch.creator_orca_session_id && dispatch.creator_orca_session_id !== selfSession + ? dispatch.creator_orca_session_id + : null + const creator: { handle?: string; paneKey?: string } | undefined = creatorSession + ? { paneKey: scope.resolve(creatorSession) } + : currentCreatorHandle + ? scope.resolveTerminal(currentCreatorHandle, creatorAuthority?.paneKey ?? null) + : creatorLineageInRun + ? scope.resolveTerminal(creatorPaneHandle, creatorPaneKey ?? null) + : undefined + const coordinatorIsSelf = + coordinator.handle === handle || + (coordinatorSession !== null && coordinatorSession === selfSession) || + (paneKey !== undefined && coordinator.paneKey !== undefined && coordinator.paneKey === paneKey) + // Why: a creator whose pane is gone still has a coordinator to nest under. + const parent = + creatorFirstParent( + (creator?.handle || (creatorSession && creator?.paneKey)) && + (!selfPane || creator?.paneKey !== selfPane) && + creator?.handle !== handle + ? creator + : undefined, + coordinator, + coordinatorIsSelf || coordinator.paneKey === selfPane + ) ?? {} + const attention = + !deferAttention && db && typeof db.getWorkerAttentionFacts === 'function' + ? buildWorkerAttentionContext({ db, dispatch, task, evidence, session, now: scope.now }) + : undefined + return { + taskId: dispatch.task_id, + dispatchId: dispatch.id, + dispatchStatus: dispatch.status, + ...(display.taskTitle ? { taskTitle: display.taskTitle } : {}), + ...(display.displayName ? { displayName: display.displayName } : {}), + ...(parent.handle ? { parentTerminalHandle: parent.handle } : {}), + ...(parent.paneKey ? { parentPaneKey: parent.paneKey } : {}), + ...(coordinator.handle ? { coordinatorHandle: coordinator.handle } : {}), + ...(orchestrationRunId ? { orchestrationRunId } : {}), + ...(attention ? { attention } : {}) + } +} diff --git a/src/main/runtime/orchestration/crew/orchestration-projection-debt.ts b/src/main/runtime/orchestration/crew/orchestration-projection-debt.ts new file mode 100644 index 00000000000..386a6e9aedd --- /dev/null +++ b/src/main/runtime/orchestration/crew/orchestration-projection-debt.ts @@ -0,0 +1,37 @@ +import type { OrchestrationDb } from '../db/orchestration-db' + +const state = 'orchestration_projection_state' +const dirty = 'orchestration_projection_dirty' +const MIN_CANDIDATE_CAPACITY = 64 + +export const projectionDebtSchema = `CREATE TEMP TABLE IF NOT EXISTS ${state}( + id INTEGER PRIMARY KEY CHECK(id = 1), queued INTEGER NOT NULL, + capacity INTEGER NOT NULL, rebuild INTEGER NOT NULL); + INSERT OR IGNORE INTO ${state} VALUES(1, 0, ${MIN_CANDIDATE_CAPACITY}, 0);` + +export function markProjectionCandidate(row: string): string { + return `INSERT OR IGNORE INTO ${dirty}(key) + SELECT 'candidate:' || ${row}.id FROM ${state} WHERE id = 1 AND rebuild = 0; + UPDATE ${state} SET queued = queued + changes(), + rebuild = (queued + changes() > capacity) WHERE id = 1 AND rebuild = 0;` +} + +export function projectionNeedsRebuild(db: OrchestrationDb): boolean { + return db.db.prepare(`SELECT rebuild FROM temp.${state} WHERE id = 1`).get()?.rebuild === 1 +} + +/** Retire debt only after current source facts have loaded successfully. */ +export function acknowledgeProjectionDebt(db: OrchestrationDb, candidates: number): void { + db.db.exec('SAVEPOINT orchestration_projection_ack') + try { + db.db.prepare(`DELETE FROM temp.${dirty}`).run() + db.db + .prepare(`UPDATE temp.${state} SET queued = 0, rebuild = 0, capacity = ? WHERE id = 1`) + .run(Math.max(MIN_CANDIDATE_CAPACITY, candidates)) + db.db.exec('RELEASE orchestration_projection_ack') + } catch (error) { + db.db.exec('ROLLBACK TO orchestration_projection_ack') + db.db.exec('RELEASE orchestration_projection_ack') + throw error + } +} diff --git a/src/main/runtime/orchestration/crew/orchestration-projection-facts.ts b/src/main/runtime/orchestration/crew/orchestration-projection-facts.ts new file mode 100644 index 00000000000..14b2d857666 --- /dev/null +++ b/src/main/runtime/orchestration/crew/orchestration-projection-facts.ts @@ -0,0 +1,294 @@ +import type { OrchestrationDb } from '../db/orchestration-db' +import { paneKeyMatchSuffix } from '../db/pane-key-match' +import { + readWorkerAttentionInputs, + projectWorkerAttentionInput +} from '../db/worker-terminal/worker-terminal-attention-query' +import { + installProjectionInvalidations, + projectionDirtyKeys, + trackProjectionKey +} from './orchestration-projection-invalidations' +import { projectionNeedsRebuild, acknowledgeProjectionDebt } from './orchestration-projection-debt' +import { PresentationDispatchIndex } from './presentation-dispatch-index' +import { withPresentationCompletionSource } from '../db/dispatch-context/presentation-completion-source' +type Fact = { value: unknown; dependencies: readonly string[]; owners: Set } +const sources = new WeakMap() +const views = new WeakMap() + +/** The connection owns persisted facts; every presentation still reads live identities and time. */ +export class OrchestrationProjectionFacts { + readonly view: OrchestrationDb + private readonly candidates: PresentationDispatchIndex + private readonly facts = new Map() + private readonly dependencies = new Map>() + private readonly owned = new Map>() + private owner: string | undefined + private version: unknown + private revision: number | undefined + private cold = true + private previousNow = -Infinity + + constructor( + private readonly db: OrchestrationDb, + private readonly transient = false + ) { + this.candidates = new PresentationDispatchIndex( + db, + (owner, key, dependencies, read) => + this.withDispatch(owner, () => this.memo(key, dependencies, read)), + (id) => this.release(id) + ) + if (!transient) { + installProjectionInvalidations(db) + } + // This facade is used only by projection readers; mutations and admission retain the real DB. + this.view = Object.create(db, { + getActiveDispatchForTerminal: { + value: (handle: string, pane?: string) => this.candidates.activeFor(handle, pane) + }, + getLatestDispatchForTerminal: { value: (handle: string) => this.candidates.latest(handle) }, + getTask: { + value: (id: string, run?: string) => + this.memo( + `task:${id}:${run ?? ''}`, + [`task:${id}`], + () => (run === undefined ? db.getTask(id) : db.getTask(id, run)), + (task) => + task?.created_by_terminal_handle ? [`handle:${task.created_by_terminal_handle}`] : [] + ) + }, + getRun: { value: (id: string) => this.memo(`run:${id}`, [`run:${id}`], () => db.getRun(id)) }, + runsBoundToPane: { + value: (pane: string) => + this.memo(`bound:${pane}`, [`bound:${paneKeyMatchSuffix(pane)}`], () => + db.runsBoundToPane(pane) + ) + }, + getActiveCoordinatorRun: { + value: () => this.memo('legacy', ['legacy'], () => db.getActiveCoordinatorRun()) + }, + getWorkerTerminalResourceByHandle: { + value: (handle: string) => + this.memo(`resource-handle:${handle}`, [`resource-handle:${handle}`], () => + db.getWorkerTerminalResourceByHandle(handle) + ) + }, + getWorkerTerminalResourceByProcessIncarnation: { + value: (process: string) => + this.memo(`resource-process:${process}`, [`resource-process:${process}`], () => + db.getWorkerTerminalResourceByProcessIncarnation(process) + ) + }, + hasRecordedStructuredWorkerSession: { + value: (session: string, process: string) => + this.memo(`recorded:${session}:${process}`, [`session:${session}`], () => + db.hasRecordedStructuredWorkerSession(session, process) + ) + }, + getWorkerAttentionFactsForDispatches: { + value: (ids: readonly string[], now: number) => this.attention(ids, now) + }, + getWorkerAttentionFacts: { + value: (id: string, now: number) => { + const result = this.attention([id], now).get(id) + if (!result) { + throw new Error(`Dispatch ${id} was not found.`) + } + return result + } + }, + listSessionDispatchesForPresentation: { + value: (now: number, sessions?: readonly string[]) => + this.candidates.sessions(now, sessions) + } + }) + views.set(this.view, this) + } + + refresh(now: number): void { + try { + withPresentationCompletionSource(this.db.db, now, ({ version, revision }) => { + const overflow = !this.transient && projectionNeedsRebuild(this.db) + const cold = + this.cold || + version !== this.version || + revision !== this.revision || + now < this.previousNow || + overflow + if (cold) { + this.reset() + } + const previousSize = this.candidates.size + const dirty = this.transient || cold ? [] : projectionDirtyKeys(this.db) + const affected = new Set() + for (const key of dirty) { + for (const factKey of this.dependencies.get(key) ?? []) { + for (const owner of this.facts.get(factKey)?.owners ?? []) { + affected.add(owner) + } + } + } + for (const owner of affected) { + this.release(owner) + } + this.candidates.refresh(now, dirty, cold) + if ( + !this.transient && + (cold || dirty.length > 0 || this.candidates.size !== previousSize) + ) { + acknowledgeProjectionDebt(this.db, this.candidates.size) + } + this.cold = false + this.version = version + this.revision = revision + this.previousNow = now + }) + } catch (error) { + // A retry discards partial indexes before consuming the still-unacknowledged obligation. + this.cold = true + throw error + } + } + + rows(): ReturnType { + return this.candidates.rows() + } + + withDispatch(id: string, read: () => T): T { + const previous = this.owner + this.owner = id + try { + return read() + } finally { + this.owner = previous + } + } + + private attention(ids: readonly string[], now: number) { + const missing = ids.filter((id) => !this.facts.has(`attention:${id}`)) + if (missing.length) { + for (const [id, input] of readWorkerAttentionInputs(this.db, missing)) { + this.withDispatch(id, () => + this.memo(`attention:${id}`, [`dispatch:${id}`, `task:${input.row.task_id}`], () => input) + ) + } + } + return new Map( + ids.flatMap((id) => { + const fact = this.facts.get(`attention:${id}`) + return fact + ? [ + [ + id, + projectWorkerAttentionInput( + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: attention entries are populated only from readWorkerAttentionInputs above. + fact.value as Parameters[0], + now + ) + ] as const + ] + : [] + }) + ) + } + + private memo( + key: string, + dependencies: readonly string[], + read: () => T, + valueDependencies?: (value: T) => readonly string[] + ): T { + let fact = this.facts.get(key) + if (!this.owner || !this.candidates.has(this.owner)) { + return read() + } + if (!fact) { + const value = read() + dependencies = [...dependencies, ...(valueDependencies?.(value) ?? [])] + fact = { value, dependencies, owners: new Set() } + this.facts.set(key, fact) + for (const dependency of dependencies) { + const keys = this.dependencies.get(dependency) ?? new Set() + if (keys.size === 0 && !this.transient) { + trackProjectionKey(this.db, dependency, true) + } + keys.add(key) + this.dependencies.set(dependency, keys) + } + } + fact.owners.add(this.owner) + const keys = this.owned.get(this.owner) ?? new Set() + keys.add(key) + this.owned.set(this.owner, keys) + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: each concrete domain key is written by one typed read function. + return fact.value as T + } + + private forget(key: string): void { + const fact = this.facts.get(key) + if (!fact) { + return + } + for (const owner of fact.owners) { + this.owned.get(owner)?.delete(key) + } + for (const dependency of fact.dependencies) { + const keys = this.dependencies.get(dependency) + keys?.delete(key) + if (keys?.size === 0) { + this.dependencies.delete(dependency) + if (!this.transient) { + trackProjectionKey(this.db, dependency, false) + } + } + } + this.facts.delete(key) + } + + private release(id: string): void { + for (const key of this.owned.get(id) ?? []) { + const fact = this.facts.get(key) + fact?.owners.delete(id) + if (fact?.owners.size === 0) { + this.forget(key) + } + } + this.owned.delete(id) + } + + private reset(): void { + if (!this.transient) { + // Rollback can restore SQL memberships after a failed refresh cleared the JS owners. + this.db.db.prepare('DELETE FROM temp.orchestration_projection_tracked').run() + } + this.facts.clear() + this.dependencies.clear() + this.candidates.clear() + this.owned.clear() + this.cold = true + } +} + +export function orchestrationProjectionFacts( + db: OrchestrationDb, + now = Date.now() +): OrchestrationProjectionFacts | undefined { + const view = views.get(db) + if (view) { + return view + } + let source = db.db.isTransaction ? undefined : sources.get(db) + if (!source) { + // An uncached probe also sees raw/local and external inserts after an empty read. + if (!db.db.prepare('SELECT 1 FROM dispatch_contexts LIMIT 1').get()) { + return undefined + } + source = new OrchestrationProjectionFacts(db, db.db.isTransaction) + if (!db.db.isTransaction) { + sources.set(db, source) + } + } + source.refresh(now) + return source +} diff --git a/src/main/runtime/orchestration/crew/orchestration-projection-invalidations.ts b/src/main/runtime/orchestration/crew/orchestration-projection-invalidations.ts new file mode 100644 index 00000000000..8a103db760e --- /dev/null +++ b/src/main/runtime/orchestration/crew/orchestration-projection-invalidations.ts @@ -0,0 +1,85 @@ +import type { OrchestrationDb } from '../db/orchestration-db' +import { projectionDebtSchema, markProjectionCandidate } from './orchestration-projection-debt' +import { projectionMutationTriggers } from '../db/projection-mutation-triggers' + +const table = 'orchestration_projection' +const pane = (value: string) => `substr(${value}, instr(${value}, ':') + 1)` +const tracked = (key: string) => `INSERT OR IGNORE INTO ${table}_dirty(key) + SELECT ${key} WHERE ${key} IS NOT NULL AND EXISTS (SELECT 1 FROM ${table}_tracked WHERE key = ${key});` + +export function installProjectionInvalidations(db: OrchestrationDb): void { + const specifications = [ + { + table: 'dispatch_contexts', + mark: (r: string) => + `${markProjectionCandidate(r)}${[ + `'dispatch:' || ${r}.id`, + `'task:' || ${r}.task_id`, + `'handle:' || ${r}.assignee_handle`, + `'session:' || ${r}.assignee_orca_session_id` + ] + .map(tracked) + .join(' ')}` + }, + { table: 'tasks', mark: (r: string) => tracked(`'task:' || ${r}.id`) }, + { + table: 'runs', + mark: (r: string) => + [ + tracked(`'run:' || ${r}.id`), + tracked(`'bound:' || ${pane(`${r}.coordinator_pane_key`)}`) + ].join(' ') + }, + { table: 'coordinator_runs', mark: () => tracked("'legacy'") }, + { + table: 'worker_dispatches', + mark: (r: string) => + tracked(`'dispatch:' || ${r}.dispatch_id`) + + tracked(`'task:' || (SELECT task_id FROM dispatch_contexts WHERE id = ${r}.dispatch_id)`) + }, + { + table: 'attempt_observation_facts', + mark: (r: string) => tracked(`'dispatch:' || ${r}.dispatch_id`) + }, + { table: 'question_threads', mark: (r: string) => tracked(`'dispatch:' || ${r}.dispatch_id`) }, + { table: 'decision_gates', mark: (r: string) => tracked(`'task:' || ${r}.task_id`) }, + { + table: 'worker_terminal_resources', + mark: (r: string) => + ['owner_dispatch_id', 'origin_dispatch_id'] + .map((key) => tracked(`'dispatch:' || ${r}.${key}`)) + .join(' ') + + tracked(`'resource-handle:' || ${r}.terminal_handle`) + + tracked(`'resource-process:' || ${r}.process_incarnation`) + }, + { + table: 'messages', + columns: 'run_id, to_handle, read, delivery_contract, type', + mark: (r: string) => `INSERT OR IGNORE INTO ${table}_dirty(key) + SELECT 'dispatch:' || substr(${r}.to_handle, 10) + WHERE ${r}.type <> 'heartbeat' AND substr(${r}.to_handle, 1, 9) = 'dispatch:' + AND EXISTS (SELECT 1 FROM ${table}_tracked WHERE key = 'dispatch:' || substr(${r}.to_handle, 10));` + } + ] + db.db.exec(`CREATE TEMP TABLE IF NOT EXISTS ${table}_tracked(key TEXT PRIMARY KEY) WITHOUT ROWID; + CREATE TEMP TABLE IF NOT EXISTS ${table}_dirty(key TEXT PRIMARY KEY) WITHOUT ROWID; + ${projectionDebtSchema} + ${projectionMutationTriggers(table, specifications)}`) +} + +export function projectionDirtyKeys(db: OrchestrationDb): string[] { + return db.db + .prepare(`SELECT key FROM temp.${table}_dirty`) + .all() + .flatMap((row) => (typeof row.key === 'string' ? [row.key] : [])) +} + +export function trackProjectionKey(db: OrchestrationDb, key: string, retained: boolean): void { + db.db + .prepare( + retained + ? `INSERT OR IGNORE INTO temp.${table}_tracked VALUES (?)` + : `DELETE FROM temp.${table}_tracked WHERE key = ?` + ) + .run(key) +} diff --git a/src/main/runtime/orchestration/crew/orchestration-terminal-candidates.ts b/src/main/runtime/orchestration/crew/orchestration-terminal-candidates.ts new file mode 100644 index 00000000000..ad90ea1da65 --- /dev/null +++ b/src/main/runtime/orchestration/crew/orchestration-terminal-candidates.ts @@ -0,0 +1,114 @@ +import { parsePaneKey } from '../../../../shared/workspace-layout/stable-pane-id' +import type { + RuntimeLeafRecord, + RuntimePtyWorktreeRecord +} from '../../terminal/records/runtime-terminal-state-records' +import type { PtyPaneOf } from '../../terminal/surface/pty-pane-query' + +/** One capture returns an unchanged, complete array per stable leaf or exact legacy pane. */ +export type OrchestrationTerminalCandidates = (pane: string) => readonly { + paneKey: string + handles: Iterable +}[] + +/** One read scope, retaining source order without choosing a terminal from dispatch insertion order. */ +export function captureOrchestrationTerminalCandidates(source: { + leaves: ReadonlyMap + ptys: ReadonlyMap + leafKey(tab: string, leaf: string): string + leavesForId(id: string): Iterable + ptysForPane?: (pane: string) => Iterable + capturePaneOf(): PtyPaneOf + paneOf?: PtyPaneOf + makePaneKey(leaf: RuntimeLeafRecord): string + issueLeaf(leaf: RuntimeLeafRecord): string + issuePty(pty: RuntimePtyWorktreeRecord): string +}): OrchestrationTerminalCandidates { + let captured: + | { panes: Map; leaves: Map; read: PtyPaneOf } + | undefined + const ptysFor = (pane: string): Iterable => { + if (source.ptysForPane) { + return source.ptysForPane(pane) + } + if (!captured) { + captured = { panes: new Map(), leaves: new Map(), read: source.capturePaneOf() } + for (const pty of source.ptys.values()) { + const key = captured.read(pty).paneKey + if (!key) { + continue + } + const leaf = parsePaneKey(key)?.leafId + for (const [map, address] of [ + [captured.panes, key], + [captured.leaves, leaf] + ] as const) { + if (!address) { + continue + } + const ids = map.get(address) ?? [] + ids.push(pty.ptyId) + map.set(address, ids) + } + } + } + const leaf = parsePaneKey(pane)?.leafId + return leaf ? (captured.leaves.get(leaf) ?? []) : (captured.panes.get(pane) ?? []) + } + const paneOf = (pty: RuntimePtyWorktreeRecord) => + (source.paneOf ?? captured?.read ?? source.capturePaneOf())(pty).paneKey + const requests = new Map>() + return (pane) => { + const parsed = parsePaneKey(pane) + const key = parsed ? `leaf:${parsed.leafId}` : `pane:${pane}` + const cached = requests.get(key) + if (cached) { + return cached + } + const panes = new Map() + if (parsed) { + for (const id of source.leavesForId(parsed.leafId)) { + const leaf = source.leaves.get(id) + if (leaf?.ptyId) { + panes.set(source.makePaneKey(leaf), []) + } + } + } + for (const id of ptysFor(pane)) { + const pty = source.ptys.get(id) + const address = pty && paneOf(pty) + if (pty && address) { + const records = panes.get(address) ?? [] + records.push(pty) + panes.set(address, records) + } + } + const groups = [...panes].map(([paneKey, ptys]) => ({ + paneKey, + handles: { + *[Symbol.iterator]() { + const seen = new Set() + const parsed = parsePaneKey(paneKey) + const leaf = parsed + ? source.leaves.get(source.leafKey(parsed.tabId, parsed.leafId)) + : undefined + if (leaf?.ptyId) { + const handle = source.issueLeaf(leaf) + seen.add(handle) + yield handle + } + // Mint fallback identities only if the preceding candidate had no context. + for (const pty of ptys) { + const handle = source.issuePty(pty) + if (!seen.has(handle)) { + seen.add(handle) + yield handle + } + } + } + } + })) + requests.set(key, groups) + return groups + } +} diff --git a/src/main/runtime/orchestration/crew/presentation-dispatch-index.ts b/src/main/runtime/orchestration/crew/presentation-dispatch-index.ts new file mode 100644 index 00000000000..d7b138008dd --- /dev/null +++ b/src/main/runtime/orchestration/crew/presentation-dispatch-index.ts @@ -0,0 +1,211 @@ +import { DispatchPresentationDeadlines } from './dispatch-presentation-deadlines' +import { DispatchPresentationPriority } from './dispatch-presentation-priority' +import { dispatchCompletionEpoch } from '../db/dispatch-context/dispatch-completion-epoch' +import { AGENT_STATUS_STALE_AFTER_MS } from '../../../../shared/agent-status/contracts/agent-status-freshness' +import type { OrchestrationDb } from '../db/orchestration-db' +import type { DispatchContextRow } from '../db/orchestration-records' +import { DISPATCH_CONTEXT_COLUMN_LIST } from '../db/row-column-lists' +import { + readPresentationDispatchCandidates, + isRecentPresentationDispatch +} from '../db/dispatch-context/dispatch-presentation' +import { paneKeyMatchSuffix } from '../db/pane-key-match' +import { parsePaneKey } from '../../../../shared/workspace-layout/stable-pane-id' + +type Candidate = DispatchContextRow & { presentation_order: number } +const active = (row: DispatchContextRow) => row.status === 'pending' || row.status === 'dispatched' +const paneAddress = (key: string) => `pane:${parsePaneKey(key) ? paneKeyMatchSuffix(key) : key}` +type Read = (owner: string, key: string, dependencies: readonly string[], read: () => T) => T + +export class PresentationDispatchIndex { + private readonly candidates = new Map() + private readonly addresses = new Map>() + private readonly allWinners = new Map() + private readonly activeWinners = new Map() + private readonly expiry = new DispatchPresentationDeadlines() + constructor( + private readonly db: OrchestrationDb, + private readonly read: Read, + private readonly release: (id: string) => void + ) {} + refresh(now: number, dirty: readonly string[], cold: boolean): void { + if (cold) { + for (const row of readPresentationDispatchCandidates(this.db, now)) { + if (active(row) || isRecentPresentationDispatch(row, now)) { + this.put(row) + } + } + } else { + for (const key of dirty) { + if (!key.startsWith('candidate:')) { + continue + } + const id = key.slice(10) + this.remove(id) + const raw = this.db.db + .prepare( + `SELECT rowid AS presentation_order, ${DISPATCH_CONTEXT_COLUMN_LIST} FROM dispatch_contexts WHERE id = ?` + ) + .get(id) + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: complete schema-owned dispatch projection plus SQLite rowid. + const row = raw as Candidate | undefined + if (row && (active(row) || isRecentPresentationDispatch(row, now))) { + this.put(row) + } + } + } + for (const id of this.expiry.expired(now)) { + this.remove(id) + } + } + get size(): number { + return this.candidates.size + } + rows(): IterableIterator { + return this.candidates.values() + } + has(id: string): boolean { + return this.candidates.has(id) + } + clear(): void { + this.expiry.clear() + this.candidates.clear() + this.addresses.clear() + this.allWinners.clear() + this.activeWinners.clear() + } + private keys(row: DispatchContextRow): string[] { + return [ + ...(row.assignee_handle ? [`handle:${row.assignee_handle}`] : []), + ...(row.assignee_pane_key + ? [paneAddress(row.assignee_pane_key), `exact:${row.assignee_pane_key}`] + : []), + ...(row.assignee_orca_session_id ? [`session:${row.assignee_orca_session_id}`] : []) + ] + } + + private put(row: Candidate): void { + this.candidates.set(row.id, row) + if (!active(row) && row.completed_at) { + const completed = dispatchCompletionEpoch(row.completed_at) + if (completed !== null) { + this.expiry.set(row.id, completed + AGENT_STATUS_STALE_AFTER_MS) + } + } + for (const key of this.keys(row)) { + const bucket = this.addresses.get(key) ?? new Set() + bucket.add(row.id) + this.addresses.set(key, bucket) + this.order(this.allWinners, key, row) + if (active(row)) { + this.order(this.activeWinners, key, row) + } + } + } + + private remove(id: string): void { + const row = this.candidates.get(id) + if (row) { + for (const key of this.keys(row)) { + const bucket = this.addresses.get(key) + this.unorder(this.allWinners, key, id) + this.unorder(this.activeWinners, key, id) + bucket?.delete(id) + if (bucket?.size === 0) { + this.addresses.delete(key) + } + } + } + this.expiry.delete(id) + this.candidates.delete(id) + this.release(id) + } + + private order( + buckets: Map, + key: string, + row: Candidate + ): void { + const bucket = buckets.get(key) ?? new DispatchPresentationPriority() + bucket.set(row.id, -row.presentation_order) + buckets.set(key, bucket) + } + + private unorder( + buckets: Map, + key: string, + id: string + ): void { + const bucket = buckets.get(key) + bucket?.delete(id) + if (bucket?.size === 0) { + buckets.delete(key) + } + } + + private newest(key: string, onlyActive = true): Candidate | undefined { + const id = (onlyActive ? this.activeWinners : this.allWinners).get(key)?.peek()?.id + return id === undefined ? undefined : this.candidates.get(id) + } + + activeFor(handle: string, pane?: string): Candidate | undefined { + return ( + this.newest(`handle:${handle}`) ?? + (pane + ? (this.newest(`exact:${pane}`) ?? + (parsePaneKey(pane) ? this.newest(paneAddress(pane)) : undefined)) + : undefined) + ) + } + + latest(handle: string): DispatchContextRow | undefined { + const candidate = this.newest(`handle:${handle}`, false) + return candidate + ? this.read(candidate.id, `latest:${handle}`, [`handle:${handle}`], () => + this.db.getLatestDispatchForTerminal(handle) + ) + : undefined + } + + sessions(now: number, sessions?: readonly string[]) { + const candidates = sessions + ? sessions.flatMap((id) => + [...(this.addresses.get(`session:${id}`) ?? [])].flatMap( + (key) => this.candidates.get(key) ?? [] + ) + ) + : [...this.candidates.values()].filter((row) => row.assignee_orca_session_id) + const selected = new Map() + for (const row of candidates) { + const address = row.assignee_handle + ? `handle:${row.assignee_handle}` + : `session:${row.assignee_orca_session_id}` + const previous = selected.get(address) + if ( + !previous || + (active(row) && !active(previous)) || + (active(row) === active(previous) && row.presentation_order > previous.presentation_order) + ) { + selected.set(address, row) + } + } + return [...selected].flatMap(([key, row]) => { + const latest = + active(row) && !row.assignee_handle + ? this.newest(`session:${row.assignee_orca_session_id}`) + : this.read(row.id, `session-latest:${active(row)}:${key}`, [key], () => + this.db.db + .prepare( + `SELECT rowid AS n FROM dispatch_contexts WHERE ${row.assignee_handle ? 'assignee_handle' : 'assignee_orca_session_id'} = ? ${active(row) ? "AND status IN ('pending', 'dispatched')" : ''} ORDER BY rowid DESC LIMIT 1` + ) + .get(row.assignee_handle || row.assignee_orca_session_id) + ) + const order = + latest && ('presentation_order' in latest ? latest.presentation_order : latest.n) + return order === row.presentation_order && + (active(row) || isRecentPresentationDispatch(row, now)) + ? [{ dispatch: row, order: row.presentation_order }] + : [] + }) + } +} diff --git a/src/main/runtime/orchestration/crew/runtime-agent-orchestration-dependencies.ts b/src/main/runtime/orchestration/crew/runtime-agent-orchestration-dependencies.ts index ff691472a91..9cd3b898457 100644 --- a/src/main/runtime/orchestration/crew/runtime-agent-orchestration-dependencies.ts +++ b/src/main/runtime/orchestration/crew/runtime-agent-orchestration-dependencies.ts @@ -1,10 +1,43 @@ +import { ORCA_LAYOUT_OWNER_IS_MAIN } from '../../../../shared/layout-owner-switch' +import { captureOrchestrationTerminalCandidates } from './orchestration-terminal-candidates' +import { + mintAgentStatusFleetEvidence, + type ObservedAgentStatusPaneIdentity +} from '../../../ipc/agent-status-ipc-boundary' import { readAgentOrchestrationProjectionRecords } from '../addressing/orchestration-fleet-agent-status-snapshot' import type { RuntimeAgentOrchestrationDependencies } from './runtime-agent-orchestration-projection' import { OrcaRuntimeWithRuntimeId } from '../../construction/runtime-identity-state' +import type { AgentStatusOrchestrationContext } from '../../../../shared/agent-status/contracts/agent-status-types' export abstract class OrcaRuntimeWithAgentOrchestrationDependencies extends OrcaRuntimeWithRuntimeId { + abstract getAgentStatusTerminalHandleForPaneKey(paneKey: string): string | undefined + abstract getAgentStatusOrchestrationContextForPaneKey( + paneKey: string + ): AgentStatusOrchestrationContext | undefined + abstract readonly readObservedAgentStatusPaneIdentityFn: ( + paneKey: string + ) => ObservedAgentStatusPaneIdentity + protected agentOrchestrationDependencies(bound?: Partial) { return { + captureTerminalCandidates: () => + captureOrchestrationTerminalCandidates({ + leaves: this.leaves, + ptys: this.ptysById, + leafKey: (tab, leaf) => this.getLeafKey(tab, leaf), + leavesForId: (id) => this.terminalIdentity.paneCandidates.leavesForId(id), + capturePaneOf: () => this.captureTerminalPaneReader(), + ...(!ORCA_LAYOUT_OWNER_IS_MAIN + ? { + ptysForPane: (pane: string) => + this.terminalIdentity.paneCandidates.ptysForPane(pane), + paneOf: (pty: Parameters[0]) => this.paneOfPty(pty) + } + : {}), + makePaneKey: (leaf) => this.makeRuntimePaneKey(leaf), + issueLeaf: (leaf) => this.issueHandle(leaf), + issuePty: (pty) => this.issuePtyHandle(pty) + }), getDb: () => this.getOrchestrationDbIfAvailable(), getLeaves: () => this.leaves.values(), getPtys: () => this.ptysById.values(), @@ -17,6 +50,21 @@ export abstract class OrcaRuntimeWithAgentOrchestrationDependencies extends Orca getPaneKey: (handle) => this.getPaneKeyForTerminalHandle(handle), getDispatchAuthority: (handle) => this.getOrchestrationDispatchAuthority(handle), getAgentStatusSnapshot: () => this.getOrchestrationFleetAgentStatusSnapshot(), + getAgentStatusForPaneKey: (paneKey, contextForPane) => + (this.publicPaneStatusFn?.(paneKey) ?? []).map((entry) => + mintAgentStatusFleetEvidence( + entry, + { + getAgentStatusTerminalHandleForPaneKey: (pane) => + this.getAgentStatusTerminalHandleForPaneKey(pane), + getTerminalProcessIncarnation: (handle) => this.getTerminalProcessIncarnation(handle), + getAgentStatusOrchestrationContextForPaneKey: + contextForPane ?? + ((pane) => this.getAgentStatusOrchestrationContextForPaneKey(pane)) + }, + this.readObservedAgentStatusPaneIdentityFn(paneKey) + ) + ), getSessionRecords: () => readAgentOrchestrationProjectionRecords(), ...bound } satisfies RuntimeAgentOrchestrationDependencies diff --git a/src/main/runtime/orchestration/crew/runtime-agent-orchestration-projection.test.ts b/src/main/runtime/orchestration/crew/runtime-agent-orchestration-projection.test.ts index f0e5e13b716..10d7334e522 100644 --- a/src/main/runtime/orchestration/crew/runtime-agent-orchestration-projection.test.ts +++ b/src/main/runtime/orchestration/crew/runtime-agent-orchestration-projection.test.ts @@ -1,3 +1,4 @@ +import { runLifecycleWriteTransaction } from '../db/lifecycle-write-transaction-runner' import 'node:fs' import 'node:os' import 'node:path' @@ -8,7 +9,11 @@ import '../../../native-chat/agent-session-wire/host/testing/structured-agent-se import '../../orca-runtime' import { afterEach, describe, expect, it, vi } from 'vitest' -import '../../../../shared/agent-session/lifecycle/agent-session-conversation-view' +import { agentSessionConversationView } from '../../../../shared/agent-session/lifecycle/agent-session-conversation-view' +import { + agentSessionLeaseFixture, + agentSessionRecordFixture +} from '../../../../shared/agent-session/lifecycle/agent-session-record.test-fixture' import '../../rpc/orchestration-session-caller-test-fixture' import '../../../../shared/orca-session-address' @@ -95,9 +100,10 @@ describe('RuntimeAgentOrchestrationProjection chat lineage', () => { issueLeafHandle: () => TERMINAL_WORKER_HANDLE, issuePtyHandle: () => '', makePaneKey: () => TERMINAL_WORKER_PANE, - getWorktreeId: () => null, - getHandleForPaneKey: () => null, - getPaneKey: () => null, + getWorktreeId: (handle) => (handle === TERMINAL_WORKER_HANDLE ? leaf.worktreeId : null), + getHandleForPaneKey: (pane) => + pane === TERMINAL_WORKER_PANE ? TERMINAL_WORKER_HANDLE : null, + getPaneKey: (handle) => (handle === TERMINAL_WORKER_HANDLE ? TERMINAL_WORKER_PANE : null), getDispatchAuthority: () => null, getAgentStatusSnapshot: () => [], getSessionRecords: () => null @@ -107,8 +113,314 @@ describe('RuntimeAgentOrchestrationProjection chat lineage', () => { expect(contexts?.[chatRow(WORKER_CHAT)]?.parentPaneKey).toBe(chatRow(COORDINATOR_CHAT)) expect(contexts?.[TERMINAL_WORKER_PANE]?.parentPaneKey).toBe(chatRow(COORDINATOR_CHAT)) + expect(projection.getForPaneKey(TERMINAL_WORKER_PANE)).toEqual(contexts?.[TERMINAL_WORKER_PANE]) + expect(projection.getForPaneKey(chatRow(WORKER_CHAT))).toEqual(contexts?.[chatRow(WORKER_CHAT)]) // The minted pane key authorizes the worker's mailbox; it must never reach a renderer. expect(JSON.stringify(contexts)).not.toContain(chatWorker.paneKey) expect(JSON.stringify(contexts)).not.toContain(chatWorker.handle) }) }) + +describe('keyed orchestration presentation', () => { + it('reads current task facts across commits, rollback and completion expiry', () => { + const db = new OrchestrationDb(':memory:') + const clock = vi.spyOn(Date, 'now').mockReturnValue(Date.parse('2026-11-09T12:00:00Z')) + try { + const run = db.createRun({ + objective: 'Keyed presentation', + coordinatorHandle: 'coordinator', + coordinatorPaneKey: null + }) + const task = db.createTask({ runId: run.id, spec: 'Original title' }) + const dispatch = db.createDispatchContext({ + taskId: task.id, + assigneeHandle: TERMINAL_WORKER_HANDLE, + assigneePaneKey: TERMINAL_WORKER_PANE, + creator: { kind: 'system' }, + maxDepth: 99 + }) + const projection = new RuntimeAgentOrchestrationProjection({ + getDb: () => db, + getLeaves: () => [], + getPtys: () => [], + paneOf: () => ({ tabId: null, paneKey: null, recordedAtGraphSequence: 0 }), + issueLeafHandle: () => '', + issuePtyHandle: () => '', + makePaneKey: () => '', + getWorktreeId: (handle) => (handle === TERMINAL_WORKER_HANDLE ? 'folder:/workspace' : null), + getHandleForPaneKey: (pane) => + pane === TERMINAL_WORKER_PANE ? TERMINAL_WORKER_HANDLE : null, + getPaneKey: (handle) => (handle === TERMINAL_WORKER_HANDLE ? TERMINAL_WORKER_PANE : null), + getDispatchAuthority: () => null, + getAgentStatusSnapshot: () => [], + getAgentStatusForPaneKey: () => [], + getSessionRecords: () => null + }) + expect(projection.getForPaneKey(TERMINAL_WORKER_PANE)?.taskTitle).toBe('Original title') + db.db.prepare('UPDATE tasks SET task_title = ? WHERE id = ?').run('Committed title', task.id) + expect(projection.getForPaneKey(TERMINAL_WORKER_PANE)?.taskTitle).toBe('Committed title') + expect(() => + runLifecycleWriteTransaction(db.db, 'projection_rollback', () => { + db.db + .prepare('UPDATE tasks SET task_title = ? WHERE id = ?') + .run('Rolled back title', task.id) + expect(projection.getForPaneKey(TERMINAL_WORKER_PANE)?.taskTitle).toBe( + 'Rolled back title' + ) + throw new Error('rollback') + }) + ).toThrow('rollback') + expect(projection.getForPaneKey(TERMINAL_WORKER_PANE)?.taskTitle).toBe('Committed title') + db.db + .prepare("UPDATE dispatch_contexts SET status = 'completed', completed_at = ? WHERE id = ?") + .run('2026-11-09 12:00:00', dispatch.id) + expect(projection.getForPaneKey(TERMINAL_WORKER_PANE)?.dispatchStatus).toBe('completed') + clock.mockReturnValue(Date.parse('2026-11-10T12:00:00Z')) + expect(projection.getForPaneKey(TERMINAL_WORKER_PANE)).toBeUndefined() + clock.mockReturnValue(Date.parse('2026-11-09T12:00:00Z')) + expect(projection.getForPaneKey(TERMINAL_WORKER_PANE)?.dispatchId).toBe(dispatch.id) + } finally { + db.close() + clock.mockRestore() + } + }) +}) + +function terminalProjection(db: OrchestrationDb) { + const panes = new Map([ + [TERMINAL_WORKER_HANDLE, TERMINAL_WORKER_PANE], + ['creator', 'tab-creator:cccccccc-cccc-4ccc-8ccc-cccccccccccc'], + ['coordinator', 'tab-coordinator:dddddddd-dddd-4ddd-8ddd-dddddddddddd'] + ]) + return new RuntimeAgentOrchestrationProjection({ + getDb: () => db, + getLeaves: () => [], + getPtys: () => [], + paneOf: () => ({ tabId: null, paneKey: null, recordedAtGraphSequence: 0 }), + issueLeafHandle: () => '', + issuePtyHandle: () => '', + makePaneKey: () => '', + getWorktreeId: (handle) => (panes.has(handle) ? 'folder:/workspace' : null), + getHandleForPaneKey: (pane) => [...panes].find(([, key]) => key === pane)?.[0] ?? null, + getPaneKey: (handle) => panes.get(handle) ?? null, + getDispatchAuthority: (handle) => ({ + paneKey: panes.get(handle)!, + processIncarnation: 'creator-process', + runtimeId: 'runtime', + terminalHandle: handle, + ptyId: `pty-${handle}`, + worktreeId: 'folder:/workspace', + launchTokenHash: null, + hostScope: { kind: 'local', hostId: 'local' } + }), + getAgentStatusSnapshot: () => [], + getAgentStatusForPaneKey: () => [], + getSessionRecords: () => null + }) +} + +it('updates child nesting when its creator dispatch settles without a child task write', () => { + const db = new OrchestrationDb(':memory:') + try { + const run = db.createRun({ + objective: 'Creator proof', + coordinatorHandle: 'coordinator', + coordinatorPaneKey: 'tab-coordinator:dddddddd-dddd-4ddd-8ddd-dddddddddddd' + }) + const creator = db.createDispatchContext({ + taskId: db.createTask({ runId: run.id, spec: 'Creator' }).id, + assigneeHandle: 'creator', + assigneePaneKey: 'tab-creator:cccccccc-cccc-4ccc-8ccc-cccccccccccc', + processIncarnation: 'creator-process', + creator: { kind: 'system' }, + maxDepth: 99 + }) + const task = db.createTask({ runId: run.id, spec: 'Child' }) + db.db + .prepare( + `UPDATE tasks SET created_by_terminal_handle = 'creator', created_by_pane_key = 'tab-creator:cccccccc-cccc-4ccc-8ccc-cccccccccccc', created_by_process_incarnation = 'creator-process', created_by_run_generation = ? WHERE id = ?` + ) + .run(run.consumer_generation, task.id) + db.createDispatchContext({ + taskId: task.id, + assigneeHandle: TERMINAL_WORKER_HANDLE, + assigneePaneKey: TERMINAL_WORKER_PANE, + creator: { kind: 'system' }, + maxDepth: 99 + }) + const projection = terminalProjection(db) + expect(projection.getForPaneKey(TERMINAL_WORKER_PANE)?.parentTerminalHandle).toBe('creator') + db.db + .prepare( + "UPDATE dispatch_contexts SET status = 'completed', completed_at = datetime('now') WHERE id = ?" + ) + .run(creator.id) + expect(projection.getForPaneKey(TERMINAL_WORKER_PANE)?.parentTerminalHandle).toBe('coordinator') + } finally { + db.close() + } +}) + +it('updates legacy nesting when a coordinator starts and finishes without a dispatch write', () => { + const db = new OrchestrationDb(':memory:') + try { + const legacy = db.createRun({ + objective: 'Legacy work', + coordinatorHandle: null, + coordinatorPaneKey: null + }) + db.db.prepare('UPDATE runs SET legacy = 1 WHERE id = ?').run(legacy.id) + db.createDispatchContext({ + taskId: db.createTask({ runId: legacy.id, spec: 'Legacy worker' }).id, + assigneeHandle: TERMINAL_WORKER_HANDLE, + assigneePaneKey: TERMINAL_WORKER_PANE, + creator: { kind: 'system' }, + maxDepth: 99 + }) + const projection = terminalProjection(db) + expect(projection.getForPaneKey(TERMINAL_WORKER_PANE)?.parentTerminalHandle).toBeUndefined() + const run = db.createCoordinatorRun({ + spec: 'Legacy coordinator', + coordinatorHandle: 'coordinator' + }) + expect(projection.getForPaneKey(TERMINAL_WORKER_PANE)?.parentTerminalHandle).toBe('coordinator') + db.updateCoordinatorRun(run.id, 'completed') + expect(projection.getForPaneKey(TERMINAL_WORKER_PANE)?.parentTerminalHandle).toBeUndefined() + } finally { + db.close() + } +}) + +it('keeps a cleared chat worker under its coordinator in the keyed attention read', () => { + const db = new OrchestrationDb(':memory:') + try { + const successor = testOrcaSessionId('bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb') + const run = db.createRun({ + objective: 'Cleared worker', + coordinatorHandle: null, + coordinatorPaneKey: null, + coordinatorOrcaSessionId: COORDINATOR_CHAT + }) + db.createDispatchContext({ + taskId: db.createTask({ runId: run.id, spec: 'Chat worker' }).id, + assigneeHandle: `orca_session_id:${WORKER_CHAT}`, + creator: { kind: 'system' }, + maxDepth: 99 + }) + const root = agentSessionRecordFixture(agentSessionLeaseFixture({ sessionId: WORKER_CHAT })) + root.conversationCommand = { + command: 'clear', + runtimeFence: 7, + operationId: 'clear-worker', + callerKey: 'renderer', + phase: 'committed', + state: 'completed', + replacementSessionId: successor + } + const records = new Map>([ + [WORKER_CHAT, agentSessionConversationView(root)], + [ + successor, + agentSessionConversationView( + agentSessionRecordFixture(agentSessionLeaseFixture({ sessionId: successor })) + ) + ], + [ + COORDINATOR_CHAT, + agentSessionConversationView( + agentSessionRecordFixture(agentSessionLeaseFixture({ sessionId: COORDINATOR_CHAT })) + ) + ] + ]) + const projection = new RuntimeAgentOrchestrationProjection({ + getDb: () => db, + getLeaves: () => [], + getPtys: () => [], + paneOf: () => ({ tabId: null, paneKey: null, recordedAtGraphSequence: 0 }), + issueLeafHandle: () => '', + issuePtyHandle: () => '', + makePaneKey: () => '', + getWorktreeId: () => null, + getHandleForPaneKey: () => null, + getPaneKey: () => null, + getDispatchAuthority: () => null, + getAgentStatusSnapshot: () => [], + getAgentStatusForPaneKey: () => [], + getSessionRecords: () => ({ + getRecord: (id) => records.get(id) ?? null, + listRecords: () => [...records.values()], + listClearedFrom: (id) => (id === successor ? [WORKER_CHAT] : []) + }) + }) + expect(projection.getForPaneKey(chatRow(successor))?.parentPaneKey).toBe( + chatRow(COORDINATOR_CHAT) + ) + expect(projection.getForPaneKey(chatRow(successor))).toEqual( + projection.buildByPaneKey()?.[chatRow(successor)] + ) + expect(projection.getForPaneKey(chatRow(WORKER_CHAT))).toBeUndefined() + } finally { + db.close() + } +}) + +it('reveals an accepted failure after only its sibling worker settles, and retires read guidance', () => { + const db = new OrchestrationDb(':memory:') + try { + const run = db.createRun({ + objective: 'Attention changes', + coordinatorHandle: 'coordinator', + coordinatorPaneKey: null + }) + const task = db.createTask({ runId: run.id, spec: 'Retrying work' }) + const first = db.createDispatchContext({ + taskId: task.id, + assigneeHandle: TERMINAL_WORKER_HANDLE, + assigneePaneKey: TERMINAL_WORKER_PANE, + creator: { kind: 'system' }, + maxDepth: 99 + }) + // A retry shares the task; lifecycle writers can change only its worker row. + db.db + .prepare( + "INSERT INTO dispatch_contexts(id,run_id,task_id,assignee_handle,status) VALUES('retry',?,?,?,'dispatched')" + ) + .run(run.id, task.id, 'retry-worker') + db.db.prepare("INSERT INTO worker_dispatches(dispatch_id,state) VALUES('retry','ready')").run() + db.recordAttemptObservation({ + id: 'accepted-failure', + dispatchId: first.id, + sequence: 1, + authorityId: 'home', + authorityClock: 'home', + facet: 'worker_report', + payload: { status: 'accepted', outcome: 'failed' }, + homeReceivedAt: Date.now() + }) + const projection = terminalProjection(db) + expect(projection.getForPaneKey(TERMINAL_WORKER_PANE)?.attention?.categories).not.toContain( + 'failure' + ) + db.db.prepare("UPDATE worker_dispatches SET state='stopped' WHERE dispatch_id='retry'").run() + expect(projection.getForPaneKey(TERMINAL_WORKER_PANE)?.attention?.categories).toContain( + 'failure' + ) + db.db + .prepare( + "INSERT INTO messages(id,run_id,from_handle,to_handle,subject) VALUES('guidance',?,'coordinator',?,'Please check the output')" + ) + .run(run.id, `dispatch:${first.id}`) + expect(projection.getForPaneKey(TERMINAL_WORKER_PANE)?.attention?.categories).toContain( + 'guidance' + ) + db.db.prepare("UPDATE messages SET read=1 WHERE id='guidance'").run() + expect(projection.getForPaneKey(TERMINAL_WORKER_PANE)?.attention?.categories).not.toContain( + 'guidance' + ) + expect(projection.buildByPaneKey()?.[TERMINAL_WORKER_PANE]?.attention?.categories).toContain( + 'failure' + ) + } finally { + db.close() + } +}) diff --git a/src/main/runtime/orchestration/crew/runtime-agent-orchestration-projection.ts b/src/main/runtime/orchestration/crew/runtime-agent-orchestration-projection.ts index 5653a51832f..8ffc08116f3 100644 --- a/src/main/runtime/orchestration/crew/runtime-agent-orchestration-projection.ts +++ b/src/main/runtime/orchestration/crew/runtime-agent-orchestration-projection.ts @@ -1,6 +1,12 @@ +import type { OrchestrationTerminalCandidates } from './orchestration-terminal-candidates' +import { composeOrchestrationDispatch } from './orchestration-dispatch-context' +import { orchestrationProjectionFacts } from './orchestration-projection-facts' +import { + structuredAgentSessionPaneKey, + structuredAgentSessionTabId +} from '../../../../shared/agent-session/view/structured-agent-session-projection' import type { AgentStatusOrchestrationContext } from '../../../../shared/agent-status/contracts/agent-status-types' import type { FleetAgentStatusEvidence } from '../../../../shared/orchestration/fleet/orchestration-fleet-agent-status-evidence' -import { creatorFirstParent, crewTaskDisplay } from './crew-rules' import { parsePaneKey } from '../../../../shared/workspace-layout/stable-pane-id' import type { OrchestrationCompatibilityTerminalAuthority } from '../terminal-authority/orchestration-compatibility-authority' import type { @@ -8,15 +14,10 @@ import type { RuntimePtyWorktreeRecord } from '../../terminal/records/runtime-terminal-state-records' import type { OrchestrationDb } from '../db/orchestration-db' -import { - buildWorkerAttentionContext, - projectWorkerAttentionContext -} from '../workers/reports/worker-attention-context' -import { worktreeIdsEqual } from '../../../../shared/worktree/id' +import { projectWorkerAttentionContext } from '../workers/reports/worker-attention-context' import type { AgentSessionRecordReader } from '../addressing/session-lineage/structured-session-lineage' import { createOrchestrationProjectionScope } from './runtime-agent-orchestration-scope' -import { isRecentPresentationDispatch } from '../db/dispatch-context/dispatch-lookup' -import { currentRunCoordinatorOrcaSessionId } from '../db/runs/run-coordinator-orca-session' +import { isRecentPresentationDispatch } from '../db/dispatch-context/dispatch-presentation' import type { DispatchContextRow } from '../db/orchestration-records' import type { PtyPaneOf } from '../../terminal/surface/pty-pane-query' import { @@ -25,6 +26,7 @@ import { } from '../workers/lifecycle/session-worker-liveness' export type RuntimeAgentOrchestrationDependencies = { + captureTerminalCandidates?(): OrchestrationTerminalCandidates getDb(): OrchestrationDb | null getLeaves(): Iterable getPtys(): Iterable @@ -37,10 +39,14 @@ export type RuntimeAgentOrchestrationDependencies = { getPaneKey(handle: string): string | null getDispatchAuthority(handle: string): OrchestrationCompatibilityTerminalAuthority | null getAgentStatusSnapshot(): readonly FleetAgentStatusEvidence[] + getAgentStatusForPaneKey?( + paneKey: string, + contextForPane?: (paneKey: string) => AgentStatusOrchestrationContext | undefined + ): readonly FleetAgentStatusEvidence[] getSessionRecords(): AgentSessionRecordReader | null } -type DispatchProjectionOptions = { +export type DispatchProjectionOptions = { // Handles are process-local; pane identity still names the Dispatch after restart. paneKey?: string evidence?: FleetAgentStatusEvidence @@ -52,66 +58,82 @@ export class RuntimeAgentOrchestrationProjection { constructor(private readonly deps: RuntimeAgentOrchestrationDependencies) {} buildByPaneKey(): Record | undefined { - const db = this.deps.getDb() - if (!db || db.hasAnyDispatchContexts?.() === false) { + const raw = this.deps.getDb() + const source = raw?.db ? orchestrationProjectionFacts(raw) : undefined + if (raw?.db && !source) { + return undefined + } + const db = source?.view ?? raw + if (!db || (source ? source.rows().next().done : db.hasAnyDispatchContexts?.() === false)) { return undefined } const scope = createOrchestrationProjectionScope(db, this.deps) const contexts: Record = {} - const statuses = this.deps.getAgentStatusSnapshot() + const terminals = new Map>() + const terminalCandidates = this.deps.captureTerminalCandidates?.() + const expanded = new Set>() + for (const candidate of source?.rows() ?? []) { + const handle = + candidate.assignee_handle && this.deps.getWorktreeId(candidate.assignee_handle) !== null + ? candidate.assignee_handle + : candidate.assignee_pane_key + ? this.deps.getHandleForPaneKey(candidate.assignee_pane_key) + : null + const paneKey = handle ? this.deps.getPaneKey(handle) : null + for (const address of new Set([paneKey, candidate.assignee_pane_key])) { + if (!address) { + continue + } + const groups = + terminalCandidates?.(address) ?? + (handle && paneKey ? [{ paneKey, handles: [handle] }] : []) + if (expanded.has(groups)) { + continue + } + expanded.add(groups) + for (const group of groups) { + if (!terminals.has(group.paneKey)) { + terminals.set(group.paneKey, group.handles) + } + } + } + } + const statuses = + source && this.deps.getAgentStatusForPaneKey + ? [ + ...new Set([ + ...terminals.keys(), + ...[...source.rows()].flatMap((row) => + row.assignee_orca_session_id ? [scope.resolve(row.assignee_orca_session_id)] : [] + ) + ]) + ].flatMap((pane) => + this.deps.getAgentStatusForPaneKey!(pane, (key) => this.identityContext(key, db, scope)) + ) + : this.deps.getAgentStatusSnapshot() const evidenceByPaneKey = new Map( statuses.map((evidence) => [evidence.activity.paneKey, evidence]) ) const sessions = createDispatchSessionLivenessReader(db, statuses, scope.records) const observeSession = sessions.observe - // Batch attention queries below; per-pane reads would repeat every 16ms publication. const batchAttention = typeof db.getWorkerAttentionFactsForDispatches === 'function' - const queriedHandles = new Set() - for (const leaf of this.deps.getLeaves()) { - if (!leaf.ptyId) { - continue - } - const handle = this.deps.issueLeafHandle(leaf) - queriedHandles.add(handle) - const paneKey = this.deps.makePaneKey(leaf) - const context = this.getForHandle( - handle, - db, - { - paneKey, - evidence: evidenceByPaneKey.get(paneKey), - observeSession, - deferAttention: batchAttention - }, - scope - ) - if (context) { - contexts[paneKey] = context - } - } - for (const pty of this.deps.getPtys()) { - const { paneKey } = this.deps.paneOf(pty) - if (!paneKey || contexts[paneKey]) { - continue - } - const handle = this.deps.issuePtyHandle(pty) - if (queriedHandles.has(handle)) { - continue - } - queriedHandles.add(handle) - const context = this.getForHandle( - handle, - db, - { - paneKey, - evidence: evidenceByPaneKey.get(paneKey), - observeSession, - deferAttention: batchAttention - }, - scope - ) - if (context) { - contexts[paneKey] = context + for (const [paneKey, handles] of terminals) { + for (const handle of handles) { + const context = this.getForHandle( + handle, + db, + { + paneKey, + evidence: evidenceByPaneKey.get(paneKey), + observeSession, + deferAttention: batchAttention + }, + scope + ) + if (context) { + contexts[paneKey] = context + break + } } } for (const [paneKey, { dispatch }] of scope.sessionDispatches()) { @@ -159,19 +181,106 @@ export class RuntimeAgentOrchestrationProjection { return contexts } + getForPaneKey(paneKey: string): AgentStatusOrchestrationContext | undefined { + const raw = this.deps.getDb() + if (!raw) { + return undefined + } + const source = raw.db ? orchestrationProjectionFacts(raw) : undefined + if (raw.db && !source) { + return undefined + } + const db = source?.view ?? raw + const scope = createOrchestrationProjectionScope(db, this.deps) + const statuses = + this.deps.getAgentStatusForPaneKey?.(paneKey, (key) => + this.identityContext(key, db, scope) + ) ?? this.deps.getAgentStatusSnapshot().filter((entry) => entry.activity.paneKey === paneKey) + const options = { + paneKey, + evidence: statuses.at(-1), + observeSession: createDispatchSessionLivenessReader(db, statuses, scope.records).observe + } + const groups = this.deps.captureTerminalCandidates?.()(paneKey) + const fallback = this.deps.getHandleForPaneKey(paneKey) + const handles = + groups?.find((group) => group.paneKey === paneKey)?.handles ?? (fallback ? [fallback] : []) + for (const handle of handles) { + const terminal = this.getForHandle(handle, db, options, scope) + if (terminal) { + return terminal + } + } + const parsed = parsePaneKey(paneKey) + const prefix = 'structured-agent-session-' + if (!parsed?.tabId.startsWith(prefix)) { + return undefined + } + const session = parsed.tabId.slice(prefix.length) + if (structuredAgentSessionPaneKey(structuredAgentSessionTabId(session), session) !== paneKey) { + return undefined + } + const ids = new Set([session]) + const visit = (id: string) => { + for (const predecessor of scope.records?.listClearedFrom?.(id) ?? []) { + if (!ids.has(predecessor)) { + ids.add(predecessor) + visit(predecessor) + } + } + } + visit(session) + // Old record readers have no predecessor index; only their compatibility path enumerates. + if (scope.records && !scope.records.listClearedFrom) { + for (const record of scope.records.listRecords()) { + ids.add(record.sessionId) + } + } + const candidate = scope.sessionDispatches([...ids]).get(paneKey) + return candidate + ? this.projectDispatch( + candidate.dispatch, + candidate.dispatch.assignee_handle ?? '', + db, + options, + scope + ) + : undefined + } + + private identityContext( + paneKey: string, + db: OrchestrationDb, + scope: ReturnType + ) { + const handle = this.deps.getHandleForPaneKey(paneKey) + return handle + ? this.getForHandle(handle, db, { paneKey, deferAttention: true }, scope) + : undefined + } + getForHandle( handle: string, db = this.deps.getDb(), options: DispatchProjectionOptions = {}, scope = createOrchestrationProjectionScope(db, this.deps) ): AgentStatusOrchestrationContext | undefined { + const facts = db?.db ? orchestrationProjectionFacts(db, scope.now) : undefined + if (db?.db && !facts) { + return undefined + } + if (facts && facts.view !== db) { + db = facts.view + scope = createOrchestrationProjectionScope(db, this.deps, scope.now) + } const { paneKey } = options const dispatch = db?.getActiveDispatchForTerminal?.(handle, paneKey) ?? this.getRecent(handle, db, scope.now) if (!dispatch) { return undefined } - return this.projectDispatch(dispatch, handle, db, options, scope) + const read = () => this.projectDispatch(dispatch, handle, db, options, scope) + return facts ? facts.withDispatch(dispatch.id, read) : read() } private projectDispatch( @@ -181,127 +290,15 @@ export class RuntimeAgentOrchestrationProjection { options: DispatchProjectionOptions, scope: ReturnType ): AgentStatusOrchestrationContext { - const { paneKey, evidence, deferAttention = false } = options - const session = options.observeSession?.(dispatch) - const task = scope.task(dispatch.task_id, dispatch.run_id) - const display = crewTaskDisplay(task) - const owningRun = - task?.run_id && task.run_id === dispatch.run_id ? scope.run(dispatch.run_id) : undefined - const runCoordinatorHandle = owningRun?.coordinator_handle ?? undefined - const legacyActiveRun = - owningRun?.legacy === 1 && (dispatch.status === 'pending' || dispatch.status === 'dispatched') - ? db?.getActiveCoordinatorRun?.() - : undefined - const handleWorktreeId = legacyActiveRun ? this.deps.getWorktreeId(handle) : null - const coordinatorWorktreeId = legacyActiveRun - ? this.deps.getWorktreeId(legacyActiveRun.coordinator_handle) - : null - const scopedLegacyRun = - legacyActiveRun && - handleWorktreeId && - coordinatorWorktreeId && - worktreeIdsEqual(coordinatorWorktreeId, handleWorktreeId) - ? legacyActiveRun - : undefined - const coordinatorHandle = runCoordinatorHandle ?? scopedLegacyRun?.coordinator_handle - const orchestrationRunId = owningRun?.legacy === 0 ? owningRun.id : scopedLegacyRun?.id - const creatorPaneKey = task?.created_by_pane_key - const creatorPaneHandle = creatorPaneKey ? this.deps.getHandleForPaneKey(creatorPaneKey) : null - const creatorAuthority = creatorPaneHandle - ? this.deps.getDispatchAuthority(creatorPaneHandle) - : null - const storedCreatorPane = creatorPaneKey ? parsePaneKey(creatorPaneKey) : null - const currentCreatorPane = creatorAuthority?.paneKey - ? parsePaneKey(creatorAuthority.paneKey) - : null - const sameCreatorPane = Boolean( - creatorPaneKey && - creatorAuthority?.paneKey && - (creatorPaneKey === creatorAuthority.paneKey || - (storedCreatorPane && - currentCreatorPane && - storedCreatorPane.leafId === currentCreatorPane.leafId)) - ) - const paneRuns = creatorPaneKey ? scope.paneRuns(creatorPaneKey) : [] - const paneRun = paneRuns.find((run) => run.id === owningRun?.id) ?? paneRuns[0] - const sameRunCreatorDispatch = Boolean( - task?.creator_dispatch_id && - task.creator_dispatch_run_id === owningRun?.id && - task.creator_dispatch_pane_key && - task.creator_dispatch_process_incarnation === task.created_by_process_incarnation && - parsePaneKey(task.creator_dispatch_pane_key)?.leafId === storedCreatorPane?.leafId - ) - // Durable Run membership identifies the creator; live incarnation/handle checks only decide mutation authority. - const creatorLineageInRun = Boolean( - owningRun?.legacy === 0 && - task?.created_by_run_generation === owningRun.consumer_generation && - creatorPaneKey && - (paneRun - ? paneRun.id === owningRun.id && - paneRun.consumer_generation === task.created_by_run_generation - : sameRunCreatorDispatch) - ) - const currentCreatorHandle = - creatorLineageInRun && - task?.created_by_process_incarnation === creatorAuthority?.processIncarnation && - sameCreatorPane - ? (creatorPaneHandle ?? undefined) - : undefined - const selfSession = dispatch.assignee_orca_session_id - const selfPane = selfSession ? scope.resolve(selfSession) : paneKey - const coordinatorSession = - owningRun?.legacy === 0 ? currentRunCoordinatorOrcaSessionId(owningRun) : null - // Why: a chat party nests by its visible row; its handle and minted pane key match no row. - const coordinator: { handle?: string; paneKey?: string } = coordinatorSession - ? { paneKey: scope.resolve(coordinatorSession) } - : scope.resolveTerminal( - coordinatorHandle, - owningRun?.legacy === 0 ? owningRun.coordinator_pane_key : null - ) - const creatorSession = - dispatch.creator_orca_session_id && dispatch.creator_orca_session_id !== selfSession - ? dispatch.creator_orca_session_id - : null - const creator: { handle?: string; paneKey?: string } | undefined = creatorSession - ? { paneKey: scope.resolve(creatorSession) } - : currentCreatorHandle - ? scope.resolveTerminal(currentCreatorHandle, creatorAuthority?.paneKey ?? null) - : creatorLineageInRun - ? scope.resolveTerminal(creatorPaneHandle, creatorPaneKey ?? null) - : undefined - const coordinatorIsSelf = - coordinator.handle === handle || - (coordinatorSession !== null && coordinatorSession === selfSession) || - (paneKey !== undefined && - coordinator.paneKey !== undefined && - coordinator.paneKey === paneKey) - // Why: a creator whose pane is gone still has a coordinator to nest under. - const parent = - creatorFirstParent( - (creator?.handle || (creatorSession && creator?.paneKey)) && - (!selfPane || creator?.paneKey !== selfPane) && - creator?.handle !== handle - ? creator - : undefined, - coordinator, - coordinatorIsSelf || coordinator.paneKey === selfPane - ) ?? {} - const attention = - !deferAttention && db && typeof db.getWorkerAttentionFacts === 'function' - ? buildWorkerAttentionContext({ db, dispatch, task, evidence, session, now: scope.now }) - : undefined - return { - taskId: dispatch.task_id, - dispatchId: dispatch.id, - dispatchStatus: dispatch.status, - ...(display.taskTitle ? { taskTitle: display.taskTitle } : {}), - ...(display.displayName ? { displayName: display.displayName } : {}), - ...(parent.handle ? { parentTerminalHandle: parent.handle } : {}), - ...(parent.paneKey ? { parentPaneKey: parent.paneKey } : {}), - ...(coordinator.handle ? { coordinatorHandle: coordinator.handle } : {}), - ...(orchestrationRunId ? { orchestrationRunId } : {}), - ...(attention ? { attention } : {}) + const facts = db?.db ? orchestrationProjectionFacts(db, scope.now) : undefined + if (facts && db !== facts.view) { + db = facts.view } + return facts + ? facts.withDispatch(dispatch.id, () => + composeOrchestrationDispatch(this.deps, dispatch, handle, db, options, scope) + ) + : composeOrchestrationDispatch(this.deps, dispatch, handle, db, options, scope) } private getRecent(handle: string, db: OrchestrationDb | null, now: number) { diff --git a/src/main/runtime/orchestration/crew/runtime-agent-orchestration-scope.ts b/src/main/runtime/orchestration/crew/runtime-agent-orchestration-scope.ts index b00b5da501a..0d10868dac3 100644 --- a/src/main/runtime/orchestration/crew/runtime-agent-orchestration-scope.ts +++ b/src/main/runtime/orchestration/crew/runtime-agent-orchestration-scope.ts @@ -5,24 +5,24 @@ import { isStructuredWorkerHandle } from '../../../../shared/orchestration/worke export function createOrchestrationProjectionScope( db: OrchestrationDb | null, - deps: RuntimeAgentOrchestrationDependencies + deps: RuntimeAgentOrchestrationDependencies, + now = Date.now() ) { const tasks = new Map>() const runs = new Map>() const panes = new Map>() - const now = Date.now() const records = deps.getSessionRecords() const resolve = createCanonicalSessionPaneResolver(records) return { now, records, resolve, - sessionDispatches: () => { + sessionDispatches: (sessions?: readonly string[]) => { const destinations = new Map< string, ReturnType[number] >() - for (const candidate of db?.listSessionDispatchesForPresentation(now) ?? []) { + for (const candidate of db?.listSessionDispatchesForPresentation(now, sessions) ?? []) { if (!candidate.dispatch.assignee_orca_session_id) { continue } diff --git a/src/main/runtime/orchestration/db/attach-orchestration-db-methods.ts b/src/main/runtime/orchestration/db/attach-orchestration-db-methods.ts index 7d5bc369062..68624a6ade3 100644 --- a/src/main/runtime/orchestration/db/attach-orchestration-db-methods.ts +++ b/src/main/runtime/orchestration/db/attach-orchestration-db-methods.ts @@ -11,6 +11,7 @@ import { attachFederationRelayAck } from './federation/federation-relay-ack' import { attachLegacyRemoteDbMethods } from '../legacy-remote/legacy-remote-db-methods' import { attachLegacyRemoteHomeDbMethods } from '../legacy-remote-home/legacy-remote-home-db-methods' import { attachPeerMailStore } from './federation/peer-mail-store' +import { attachPeerRunStore } from './peer-runs/peer-run-store' import { attachLegacyAskOperation } from './legacy/legacy-ask-operation' import { attachLegacyCompatibilityCandidates } from './legacy/legacy-compatibility-candidates' import { attachLegacyCompatibilityPrincipals } from './legacy/legacy-compatibility-principals' @@ -107,6 +108,7 @@ export function attachOrchestrationDbMethods(ctor: { prototype: object }): void attachLegacyRemoteDbMethods(ctor) attachFederationRelayAck(ctor) attachPeerMailStore(ctor) + attachPeerRunStore(ctor) attachWorkerTerminalResourceStore(ctor) attachWorkerTerminalTransfer(ctor) attachWorkerTerminalRelease(ctor) diff --git a/src/main/runtime/orchestration/db/dispatch-context/dispatch-completion-epoch.ts b/src/main/runtime/orchestration/db/dispatch-context/dispatch-completion-epoch.ts new file mode 100644 index 00000000000..6d702735967 --- /dev/null +++ b/src/main/runtime/orchestration/db/dispatch-context/dispatch-completion-epoch.ts @@ -0,0 +1,8 @@ +/** Preserve the existing ISO/local and SQLite/UTC completion timestamp contract. */ +export function dispatchCompletionEpoch(value: unknown): number | null { + if (typeof value !== 'string') { + return null + } + const epoch = Date.parse(value.includes('T') ? value : `${value.replace(' ', 'T')}Z`) + return Number.isFinite(epoch) ? epoch : null +} diff --git a/src/main/runtime/orchestration/db/dispatch-context/dispatch-lookup.ts b/src/main/runtime/orchestration/db/dispatch-context/dispatch-lookup.ts index 60a50128f61..87b1370e9d0 100644 --- a/src/main/runtime/orchestration/db/dispatch-context/dispatch-lookup.ts +++ b/src/main/runtime/orchestration/db/dispatch-context/dispatch-lookup.ts @@ -1,4 +1,4 @@ -import { AGENT_STATUS_STALE_AFTER_MS } from '../../../../../shared/agent-status/contracts/agent-status-freshness' +import { listSessionDispatchesForPresentation } from './dispatch-presentation' import { parsePaneKey } from '../../../../../shared/workspace-layout/stable-pane-id' import type { DispatchContextRow } from '../orchestration-records' import { @@ -30,120 +30,17 @@ const ASSIGNEE_SQL = { latest: assigneeLookups('') } -function presentationAddressKey(column: string, address: string | null): string { - return `${column}:${address}` -} - -/** Preserve the terminal projection's exact ISO/SQLite recency contract, including future dates. */ -export function isRecentPresentationDispatch(dispatch: DispatchContextRow, now: number): boolean { - if (!dispatch.completed_at || dispatch.status === 'pending' || dispatch.status === 'dispatched') { - return false - } - const completedAt = Date.parse( - dispatch.completed_at.includes('T') - ? dispatch.completed_at - : `${dispatch.completed_at.replace(' ', 'T')}Z` - ) - return Number.isFinite(completedAt) && now - completedAt <= AGENT_STATUS_STALE_AFTER_MS -} - -/** Active first, otherwise latest per address; an older eligible completion never resurfaces. */ -export function listSessionDispatchesForPresentation( +export function hasRecordedStructuredWorkerSession( this: OrchestrationDb, - now: number -): { dispatch: DispatchContextRow; order: number }[] { - const lowerBound = new Date(now - AGENT_STATUS_STALE_AFTER_MS - 86_400_000).toISOString() - const rawCandidates = this.db - .prepare(` - SELECT rowid AS presentation_order, ${DISPATCH_CONTEXT_COLUMN_LIST} FROM dispatch_contexts - INDEXED BY idx_dispatch_session_presentation - WHERE assignee_orca_session_id IS NOT NULL AND status IN ('pending', 'dispatched') - UNION ALL - SELECT rowid AS presentation_order, ${DISPATCH_CONTEXT_COLUMN_LIST} FROM dispatch_contexts - INDEXED BY idx_dispatch_session_presentation - WHERE assignee_orca_session_id IS NOT NULL - AND status IN ('completed', 'failed', 'circuit_broken') AND completed_at >= ? - `) - .all(lowerBound) - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: The complete schema-pinned Dispatch projection restores the persisted-row contract; the default integer wrapper normalizes rowid to a safe number. - const candidates = rawCandidates as (DispatchContextRow & { presentation_order: number })[] - const newestActiveOrderBySession = new Map() - const selected = new Map() - for (const candidate of candidates) { - // Include handled rows even when a newer non-public row later suppresses their address. - if (candidate.status === 'pending' || candidate.status === 'dispatched') { - const session = candidate.assignee_orca_session_id - if (session) { - newestActiveOrderBySession.set( - session, - Math.max(newestActiveOrderBySession.get(session) ?? 0, candidate.presentation_order) - ) - } - } - const address = presentationAddressKey( - candidate.assignee_handle ? 'assignee_handle' : 'assignee_orca_session_id', - candidate.assignee_handle || candidate.assignee_orca_session_id - ) - const previous = selected.get(address) - const active = candidate.status === 'pending' || candidate.status === 'dispatched' - const previousActive = previous?.status === 'pending' || previous?.status === 'dispatched' - if ( - !previous || - (active && !previousActive) || - (active === previousActive && candidate.presentation_order > previous.presentation_order) - ) { - selected.set(address, candidate) - } - } - const eligible = [...selected].filter( - ([, candidate]) => - candidate.status === 'pending' || - candidate.status === 'dispatched' || - isRecentPresentationDispatch(candidate, now) + session: string, + process: string +): boolean { + return Boolean( + this.db + .prepare(`SELECT 1 FROM dispatch_contexts + WHERE assignee_orca_session_id = ? AND process_incarnation = ? LIMIT 1`) + .get(session, process) ) - const latestOrderByAddress = new Map() - for (const [column, active] of [ - ['assignee_handle', true], - ['assignee_handle', false], - ['assignee_orca_session_id', false] - ] as const) { - const addresses = eligible - .filter( - ([, candidate]) => - Boolean(candidate.assignee_handle) === (column === 'assignee_handle') && - (candidate.status === 'pending' || candidate.status === 'dispatched') === active - ) - .map(([, candidate]) => candidate[column]) - if (addresses.length === 0) { - continue - } - // Batch native calls, retaining one equality-index seek per selected address. - const latest = this.db - .prepare(`SELECT requested.value AS address, (SELECT rowid AS n FROM dispatch_contexts - WHERE ${column} = requested.value - ${active ? "AND status IN ('pending', 'dispatched')" : ''} - ORDER BY rowid DESC LIMIT 1) AS n FROM json_each(?) requested`) - .all(JSON.stringify(addresses)) - for (const row of latest) { - if (typeof row.address === 'string' && typeof row.n === 'number') { - latestOrderByAddress.set(presentationAddressKey(column, row.address), row.n) - } - } - } - const result: { dispatch: DispatchContextRow; order: number }[] = [] - for (const [address, candidate] of eligible) { - const { presentation_order, ...dispatch } = candidate - const active = dispatch.status === 'pending' || dispatch.status === 'dispatched' - const latest = - active && !candidate.assignee_handle - ? newestActiveOrderBySession.get(candidate.assignee_orca_session_id ?? '') - : latestOrderByAddress.get(address) - if (latest !== presentation_order) { - continue - } - result.push({ dispatch, order: presentation_order }) - } - return result } export function getActiveDispatchForTerminal( @@ -303,6 +200,7 @@ export function hasOpenHelperDispatch(this: OrchestrationDb, dispatchId: string) } export type DispatchLookupMethods = { + hasRecordedStructuredWorkerSession: typeof hasRecordedStructuredWorkerSession getActiveDispatchForTerminal: typeof getActiveDispatchForTerminal hasAnyDispatchContexts: typeof hasAnyDispatchContexts getActiveDispatchForIdentity: typeof getActiveDispatchForIdentity @@ -316,6 +214,7 @@ export type DispatchLookupMethods = { export function attachDispatchLookup(ctor: { prototype: object }): void { Object.assign(ctor.prototype, { + hasRecordedStructuredWorkerSession, getActiveDispatchForTerminal, hasAnyDispatchContexts, getActiveDispatchForIdentity, diff --git a/src/main/runtime/orchestration/db/dispatch-context/dispatch-presentation.ts b/src/main/runtime/orchestration/db/dispatch-context/dispatch-presentation.ts new file mode 100644 index 00000000000..1781b43ce64 --- /dev/null +++ b/src/main/runtime/orchestration/db/dispatch-context/dispatch-presentation.ts @@ -0,0 +1,134 @@ +import { AGENT_STATUS_STALE_AFTER_MS } from '../../../../../shared/agent-status/contracts/agent-status-freshness' +import type { DispatchContextRow } from '../orchestration-records' +import type { OrchestrationDb } from '../orchestration-db' +import { + DISPATCH_CONTEXT_COLUMN_LIST, + DISPATCH_CONTEXT_COLUMNS, + selectColumns +} from '../row-column-lists' +import { dispatchCompletionEpoch } from './dispatch-completion-epoch' +import { withPresentationCompletionSource } from './presentation-completion-source' +import { completionTable } from './presentation-completion-schema' +function presentationAddressKey(column: string, address: string | null): string { + return `${column}:${address}` +} + +/** Preserve the terminal projection's exact ISO/SQLite recency contract, including future dates. */ +export function isRecentPresentationDispatch(dispatch: DispatchContextRow, now: number): boolean { + if (!dispatch.completed_at || dispatch.status === 'pending' || dispatch.status === 'dispatched') { + return false + } + const completedAt = dispatchCompletionEpoch(dispatch.completed_at) + return completedAt !== null && now - completedAt <= AGENT_STATUS_STALE_AFTER_MS +} + +export type PresentationDispatchCandidate = DispatchContextRow & { presentation_order: number } + +/** Active/recent source facts shared by the keyed index and session presentation. */ +export function readPresentationDispatchCandidates( + db: OrchestrationDb, + now: number +): PresentationDispatchCandidate[] { + return withPresentationCompletionSource(db.db, now, () => { + const rows = db.db + .prepare(`SELECT rowid AS presentation_order, ${DISPATCH_CONTEXT_COLUMN_LIST} + FROM dispatch_contexts WHERE status IN ('pending', 'dispatched') + UNION ALL SELECT d.rowid AS presentation_order, ${selectColumns(DISPATCH_CONTEXT_COLUMNS, 'd')} + FROM temp.${completionTable} c INDEXED BY orchestration_presentation_completion_epoch + CROSS JOIN dispatch_contexts d ON d.id = c.id WHERE c.epoch >= ?`) + .all(now - AGENT_STATUS_STALE_AFTER_MS) + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: complete schema-owned dispatch projection plus SQLite rowid. + return (rows as PresentationDispatchCandidate[]).sort( + (a, b) => a.presentation_order - b.presentation_order + ) + }) +} + +/** Active first, otherwise latest per address; an older eligible completion never resurfaces. */ +export function listSessionDispatchesForPresentation( + this: OrchestrationDb, + now: number, + sessions?: readonly string[] +): { dispatch: DispatchContextRow; order: number }[] { + const candidates = readPresentationDispatchCandidates(this, now).filter( + (row) => + row.assignee_orca_session_id && (!sessions || sessions.includes(row.assignee_orca_session_id)) + ) + const newestActiveOrderBySession = new Map() + const selected = new Map() + for (const candidate of candidates) { + // Include handled rows even when a newer non-public row later suppresses their address. + if (candidate.status === 'pending' || candidate.status === 'dispatched') { + const session = candidate.assignee_orca_session_id + if (session) { + newestActiveOrderBySession.set( + session, + Math.max(newestActiveOrderBySession.get(session) ?? 0, candidate.presentation_order) + ) + } + } + const address = presentationAddressKey( + candidate.assignee_handle ? 'assignee_handle' : 'assignee_orca_session_id', + candidate.assignee_handle || candidate.assignee_orca_session_id + ) + const previous = selected.get(address) + const active = candidate.status === 'pending' || candidate.status === 'dispatched' + const previousActive = previous?.status === 'pending' || previous?.status === 'dispatched' + if ( + !previous || + (active && !previousActive) || + (active === previousActive && candidate.presentation_order > previous.presentation_order) + ) { + selected.set(address, candidate) + } + } + const eligible = [...selected].filter( + ([, candidate]) => + candidate.status === 'pending' || + candidate.status === 'dispatched' || + isRecentPresentationDispatch(candidate, now) + ) + const latestOrderByAddress = new Map() + for (const [column, active] of [ + ['assignee_handle', true], + ['assignee_handle', false], + ['assignee_orca_session_id', false] + ] as const) { + const addresses = eligible + .filter( + ([, candidate]) => + Boolean(candidate.assignee_handle) === (column === 'assignee_handle') && + (candidate.status === 'pending' || candidate.status === 'dispatched') === active + ) + .map(([, candidate]) => candidate[column]) + if (addresses.length === 0) { + continue + } + // Batch native calls, retaining one equality-index seek per selected address. + const latest = this.db + .prepare(`SELECT requested.value AS address, (SELECT rowid AS n FROM dispatch_contexts + WHERE ${column} = requested.value + ${active ? "AND status IN ('pending', 'dispatched')" : ''} + ORDER BY rowid DESC LIMIT 1) AS n FROM json_each(?) requested`) + .all(JSON.stringify(addresses)) + for (const row of latest) { + if (typeof row.address === 'string' && typeof row.n === 'number') { + latestOrderByAddress.set(presentationAddressKey(column, row.address), row.n) + } + } + } + const result: { dispatch: DispatchContextRow; order: number }[] = [] + for (const [address, candidate] of eligible) { + const { presentation_order, ...dispatch } = candidate + const active = dispatch.status === 'pending' || dispatch.status === 'dispatched' + const latest = + active && !candidate.assignee_handle + ? newestActiveOrderBySession.get(candidate.assignee_orca_session_id ?? '') + : latestOrderByAddress.get(address) + if (latest !== presentation_order) { + continue + } + result.push({ dispatch, order: presentation_order }) + } + return result +} diff --git a/src/main/runtime/orchestration/db/dispatch-context/presentation-completion-schema.ts b/src/main/runtime/orchestration/db/dispatch-context/presentation-completion-schema.ts new file mode 100644 index 00000000000..ca393021e15 --- /dev/null +++ b/src/main/runtime/orchestration/db/dispatch-context/presentation-completion-schema.ts @@ -0,0 +1,32 @@ +import { AGENT_STATUS_STALE_AFTER_MS } from '../../../../../shared/agent-status/contracts/agent-status-freshness' + +export const completionTable = 'orchestration_presentation_completions' +export const completionState = 'orchestration_presentation_completion_state' + +const operationNow = `(SELECT operation_now FROM ${completionState} WHERE id = 1)` +const expire = `DELETE FROM ${completionTable} WHERE epoch < ${operationNow} - ${AGENT_STATUS_STALE_AFTER_MS};` +const clock = `UPDATE ${completionState} SET operation_now = orchestration_presentation_now() WHERE id = 1; + UPDATE ${completionState} SET recovery = recovery OR operation_now < stamp, + stamp = operation_now WHERE id = 1; ${expire}` +const replace = `INSERT INTO ${completionTable}(id, epoch) + SELECT NEW.id, epoch FROM (SELECT orchestration_completion_epoch(NEW.completed_at) AS epoch) + WHERE NEW.status NOT IN ('pending', 'dispatched') + AND epoch >= ${operationNow} - ${AGENT_STATUS_STALE_AFTER_MS};` + +export const presentationCompletionSchema = ` + CREATE TEMP TABLE IF NOT EXISTS ${completionTable}(id TEXT PRIMARY KEY, epoch REAL NOT NULL); + CREATE INDEX IF NOT EXISTS temp.orchestration_presentation_completion_epoch ON ${completionTable}(epoch, id); + CREATE TEMP TABLE IF NOT EXISTS ${completionState}( + id INTEGER PRIMARY KEY CHECK(id = 1), ready INTEGER NOT NULL DEFAULT 0, + version INTEGER, zone TEXT, stamp REAL NOT NULL DEFAULT 0, + recovery INTEGER NOT NULL DEFAULT 0, revision INTEGER NOT NULL DEFAULT 0, + operation_now REAL NOT NULL DEFAULT 0); + INSERT OR IGNORE INTO ${completionState}(id) VALUES(1); + CREATE TEMP TRIGGER IF NOT EXISTS orchestration_presentation_completion_insert + AFTER INSERT ON main.dispatch_contexts BEGIN ${clock} ${replace} END; + CREATE TEMP TRIGGER IF NOT EXISTS orchestration_presentation_completion_update + AFTER UPDATE OF id, status, completed_at ON main.dispatch_contexts + BEGIN ${clock} DELETE FROM ${completionTable} WHERE id = OLD.id; ${replace} END; + CREATE TEMP TRIGGER IF NOT EXISTS orchestration_presentation_completion_delete + AFTER DELETE ON main.dispatch_contexts + BEGIN ${clock} DELETE FROM ${completionTable} WHERE id = OLD.id; END;` diff --git a/src/main/runtime/orchestration/db/dispatch-context/presentation-completion-source.test.ts b/src/main/runtime/orchestration/db/dispatch-context/presentation-completion-source.test.ts new file mode 100644 index 00000000000..1568e5a8615 --- /dev/null +++ b/src/main/runtime/orchestration/db/dispatch-context/presentation-completion-source.test.ts @@ -0,0 +1,92 @@ +import { mkdtempSync, rmSync } from 'node:fs' +import { join } from 'node:path' +import { tmpdir } from 'node:os' +import { afterEach, expect, it, vi } from 'vitest' +import { OrchestrationDb } from '../orchestration-db' +import { readPresentationDispatchCandidates } from './dispatch-presentation' +import { withPresentationCompletionSource } from './presentation-completion-source' +import { orchestrationProjectionFacts } from '../../crew/orchestration-projection-facts' + +const now = Date.parse('2026-11-09T12:00:00Z') +afterEach(() => vi.restoreAllMocks()) + +function add(db: OrchestrationDb, id: string, completedAt: string) { + db.db + .prepare( + "INSERT INTO dispatch_contexts(id,task_id,assignee_handle,status,completed_at) VALUES(?,'task',?,'completed',?)" + ) + .run(id, id, completedAt) +} + +it('reinstalls a completion source whose first initialization rolled back with its caller', () => { + const db = new OrchestrationDb(':memory:') + try { + db.db.exec('BEGIN; SAVEPOINT caller') + add(db, 'rolled-back', '2026-11-09T12:00:00Z') + expect(readPresentationDispatchCandidates(db, now).map((row) => row.id)).toEqual([ + 'rolled-back' + ]) + db.db.exec('ROLLBACK TO caller; RELEASE caller; ROLLBACK') + add(db, 'committed', '2026-11-09 12:00:00') + expect(readPresentationDispatchCandidates(db, now).map((row) => row.id)).toEqual(['committed']) + db.db + .prepare( + "UPDATE dispatch_contexts SET id='renamed',completed_at='2020-01-01T00:00:00Z' WHERE id='committed'" + ) + .run() + expect(readPresentationDispatchCandidates(db, now)).toEqual([]) + } finally { + db.close() + } +}) + +it('rebuilds warm projection membership when the runtime timezone changes local completion meaning', () => { + const prior = process.env.TZ + const db = new OrchestrationDb(':memory:') + vi.spyOn(Date, 'now').mockReturnValue(now) + try { + process.env.TZ = 'UTC' + add(db, 'local-completion', '2026-11-09T04:00:00') + expect([...orchestrationProjectionFacts(db, now)!.rows()]).toEqual([]) + process.env.TZ = 'America/Los_Angeles' + expect([...orchestrationProjectionFacts(db, now)!.rows()].map((row) => row.id)).toEqual([ + 'local-completion' + ]) + process.env.TZ = 'UTC' + expect([...orchestrationProjectionFacts(db, now)!.rows()]).toEqual([]) + } finally { + if (prior === undefined) { + delete process.env.TZ + } else { + process.env.TZ = prior + } + db.close() + } +}) + +it('keeps normalization and candidate retrieval on one snapshot across an ordinary external commit', () => { + const folder = mkdtempSync(join(tmpdir(), 'orca-completion-source-')) + const path = join(folder, 'orchestration.sqlite') + const db = new OrchestrationDb(path) + db.db.pragma('journal_mode = WAL') + const other = new OrchestrationDb(path) + try { + add(db, 'first', '2026-11-09T12:00:00Z') + withPresentationCompletionSource(db.db, now, () => { + add(other, 'external', '2026-11-09T12:00:00Z') + expect(readPresentationDispatchCandidates(db, now).map((row) => row.id)).toEqual(['first']) + }) + expect(readPresentationDispatchCandidates(db, now).map((row) => row.id)).toEqual([ + 'first', + 'external' + ]) + other.db + .prepare("UPDATE dispatch_contexts SET completed_at='2020-01-01T00:00:00Z' WHERE id='first'") + .run() + expect(readPresentationDispatchCandidates(db, now).map((row) => row.id)).toEqual(['external']) + } finally { + other.close() + db.close() + rmSync(folder, { recursive: true, force: true }) + } +}) diff --git a/src/main/runtime/orchestration/db/dispatch-context/presentation-completion-source.ts b/src/main/runtime/orchestration/db/dispatch-context/presentation-completion-source.ts new file mode 100644 index 00000000000..7153d6dcfbb --- /dev/null +++ b/src/main/runtime/orchestration/db/dispatch-context/presentation-completion-source.ts @@ -0,0 +1,121 @@ +import type Database from '../../../../sqlite/sync-database' +import { AGENT_STATUS_STALE_AFTER_MS } from '../../../../../shared/agent-status/contracts/agent-status-freshness' +import { dispatchCompletionEpoch } from './dispatch-completion-epoch' +import { + completionTable, + completionState, + presentationCompletionSchema +} from './presentation-completion-schema' + +type Snapshot = { revision: number; version: number } +const sources = new WeakMap() + +/** Normalization belongs to the connection, independently of disposable projection caches. */ +class PresentationCompletionSource { + private installed = false + private snapshot: Snapshot | undefined + + constructor(private readonly db: Database.Database) { + db.function('orchestration_completion_epoch', dispatchCompletionEpoch) + db.function('orchestration_presentation_now', () => Date.now()) + } + + read(now: number, read: (snapshot: Snapshot) => T): T { + if (this.snapshot) { + return read(this.snapshot) + } + const outer = this.db.isTransaction + this.db.exec('SAVEPOINT orchestration_presentation_source') + try { + this.install() + // Acquire the main snapshot before observing its data_version, including an empty source. + this.db.prepare('SELECT rowid FROM main.dispatch_contexts LIMIT 1').get() + const state = this.db + .prepare(`SELECT *, (SELECT data_version FROM pragma_data_version) AS current_version + FROM temp.${completionState} WHERE id = 1`) + .get() + if ( + !state || + typeof state.current_version !== 'number' || + typeof state.revision !== 'number' + ) { + throw new Error('Orchestration presentation source is unavailable') + } + const zone = `${process.env.TZ ?? ''}|${Intl.DateTimeFormat().resolvedOptions().timeZone}` + let revision = state.revision + if ( + state.ready !== 1 || + state.recovery === 1 || + state.version !== state.current_version || + state.zone !== zone || + typeof state.stamp !== 'number' || + now < state.stamp + ) { + this.rebuild(now) + revision++ + this.db + .prepare(`UPDATE temp.${completionState} SET ready = 1, version = ?, zone = ?, + recovery = 0, revision = ? WHERE id = 1`) + .run(state.current_version, zone, revision) + } + this.db + .prepare(`DELETE FROM temp.${completionTable} WHERE epoch < ?`) + .run(now - AGENT_STATUS_STALE_AFTER_MS) + this.db.prepare(`UPDATE temp.${completionState} SET stamp = ? WHERE id = 1`).run(now) + this.snapshot = { revision, version: state.current_version } + const result = read(this.snapshot) + this.db.exec('RELEASE orchestration_presentation_source') + if (!outer) { + this.installed = true + } + return result + } catch (error) { + this.db.exec('ROLLBACK TO orchestration_presentation_source') + this.db.exec('RELEASE orchestration_presentation_source') + throw error + } finally { + this.snapshot = undefined + } + } + + private install(): void { + if (this.installed) { + return + } + // First initialization inside a caller transaction may have rolled back its TEMP schema. + if ( + !this.db + .prepare('SELECT 1 FROM sqlite_temp_master WHERE type = ? AND name = ?') + .get('table', completionState) + ) { + this.db.exec(presentationCompletionSchema) + } + } + + private rebuild(now: number): void { + this.db.prepare(`DELETE FROM temp.${completionTable}`).run() + const insert = this.db.prepare(`INSERT INTO temp.${completionTable}(id, epoch) VALUES (?, ?)`) + for (const row of this.db + .prepare(`SELECT id, completed_at FROM dispatch_contexts + WHERE status NOT IN ('pending', 'dispatched')`) + .iterate()) { + const epoch = dispatchCompletionEpoch(row.completed_at) + if (epoch !== null && epoch >= now - AGENT_STATUS_STALE_AFTER_MS) { + insert.run(row.id, epoch) + } + } + } +} + +export function withPresentationCompletionSource( + db: Database.Database, + now: number, + read: (snapshot: Snapshot) => T +): T { + let source = sources.get(db) + if (!source) { + source = new PresentationCompletionSource(db) + sources.set(db, source) + } + return source.read(now, read) +} diff --git a/src/main/runtime/orchestration/db/dispatch-context/worker-report-settlement.ts b/src/main/runtime/orchestration/db/dispatch-context/worker-report-settlement.ts index 9152202ada9..4f812539964 100644 --- a/src/main/runtime/orchestration/db/dispatch-context/worker-report-settlement.ts +++ b/src/main/runtime/orchestration/db/dispatch-context/worker-report-settlement.ts @@ -168,6 +168,10 @@ export function settleWorkerReportInTransaction( let dispatchUpdate: { changes: number } let taskUpdate: { changes: number } if (settledByUnobservedPrompt) { + // A paired coordinator gets the correction once, after all its writes; see peer_run_corrections. + this.db + .prepare('INSERT INTO peer_run_corrections (dispatch_id) VALUES (?)') + .run(params.dispatchId) const now = new Date().toISOString() const dispatchTransition = transitionLifecycleWithDb(this.db, { entity: 'dispatch', @@ -239,6 +243,7 @@ export function settleWorkerReportInTransaction( projection: { stage: 'settled', updated_at: new Date().toISOString() }, correction: 'unobserved_prompt_report' }) + this.db.prepare('DELETE FROM peer_run_corrections WHERE dispatch_id = ?').run(params.dispatchId) } else if ((unprovenWorker || reportingStart) && params.outcome === 'succeeded') { transitionLifecycleWithDb(this.db, { entity: 'worker', diff --git a/src/main/runtime/orchestration/db/federation/peer-mail-store.ts b/src/main/runtime/orchestration/db/federation/peer-mail-store.ts index da829b40e5e..ffe1e3b2cb9 100644 --- a/src/main/runtime/orchestration/db/federation/peer-mail-store.ts +++ b/src/main/runtime/orchestration/db/federation/peer-mail-store.ts @@ -78,7 +78,7 @@ export function listHomePeerMailEnvironments(this: OrchestrationDb): string[] { export function listPeerConversationIds(this: OrchestrationDb, peerFingerprint: string): string[] { const statement = this.db.prepare( `SELECT conversation_id FROM peer_mail_conversations - WHERE role = 'peer' AND peer_fingerprint = ?` + WHERE role = 'peer' AND peer_fingerprint = ? ORDER BY conversation_id` ) // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: SELECT over this table returns exactly these columns. const rows = statement.all(peerFingerprint) as { conversation_id: string }[] @@ -118,6 +118,14 @@ export function insertPeerMailMessage( | { message: MessageRow | undefined; duplicate: true } { this.db.exec('SAVEPOINT peer_mail_insert') try { + // A peer Run's conversation keeps its own queue sequence, so it never carries peer mail. + if (this.getPeerRunForConversation(params.conversationId)) { + throw new OrchestrationError( + 'request_mismatch', + `Conversation ${params.conversationId} belongs to a coordinated Run. Nothing was delivered.`, + { effectsApplied: false } + ) + } if (params.peerFingerprint !== undefined) { const conversation = this.getPeerMailConversation(params.conversationId) if ( diff --git a/src/main/runtime/orchestration/db/lifecycle-transition.ts b/src/main/runtime/orchestration/db/lifecycle-transition.ts index 5eefd879ecb..f0b44ee85ae 100644 --- a/src/main/runtime/orchestration/db/lifecycle-transition.ts +++ b/src/main/runtime/orchestration/db/lifecycle-transition.ts @@ -1,6 +1,7 @@ import type Database from '../../../sqlite/sync-database' import { OrchestrationError } from '../orchestration-error' import type { OrchestrationDb } from './orchestration-db' +import { notifyPeerMailQueued } from '../federation/peer-mail/peer-mail-waiters' /** Callers own transactions so lifecycle projections and mailbox effects commit atomically together. */ export type LifecycleEntity = 'task' | 'dispatch' | 'worker' @@ -189,7 +190,8 @@ export function transitionLifecycleWithDb( `${params.entity} ${params.id} changed while transitioning.` ) } - + // A peer Run's change is queued home by trigger in this statement. + notifyPeerMailQueued(db) return { changed: true } } diff --git a/src/main/runtime/orchestration/db/messages/message-inbox.ts b/src/main/runtime/orchestration/db/messages/message-inbox.ts index e0ec891fd63..f201d19e808 100644 --- a/src/main/runtime/orchestration/db/messages/message-inbox.ts +++ b/src/main/runtime/orchestration/db/messages/message-inbox.ts @@ -226,11 +226,14 @@ export function markAsReadAndDelivered(this: OrchestrationDb, ids: string[]): vo ) } -export function getInbox(this: OrchestrationDb, limit = 20): MessageRow[] { +export function getInbox(this: OrchestrationDb, limit = 20, runId?: string): MessageRow[] { return exposeMessageListTimestamps( + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: SELECT * over messages returns the row shape its schema and MessageRow define, like every row cast in db/. this.db - .prepare('SELECT * FROM messages ORDER BY sequence DESC LIMIT ?') - .all(limit) as MessageRow[] + .prepare( + 'SELECT * FROM messages WHERE (?1 IS NULL OR run_id = ?1) ORDER BY sequence DESC LIMIT ?2' + ) + .all(runId ?? null, limit) as MessageRow[] ) } @@ -239,22 +242,19 @@ export function getAllMessagesForHandle( this: OrchestrationDb, toHandle: string, limit = 100, - types?: MessageType[] + types?: MessageType[], + runId?: string ): MessageRow[] { - if (types && types.length > 0) { - const placeholders = types.map(() => '?').join(',') - return exposeMessageListTimestamps( - this.db - .prepare( - `SELECT * FROM messages WHERE to_handle = ? AND type IN (${placeholders}) ORDER BY sequence DESC LIMIT ?` - ) - .all(toHandle, ...types, limit) as MessageRow[] - ) - } + const typed = types && types.length > 0 + const typeFilter = typed ? `AND type IN (${types.map(() => '?').join(',')})` : '' return exposeMessageListTimestamps( + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: SELECT * over messages returns the row shape its schema and MessageRow define, like every row cast in db/. this.db - .prepare('SELECT * FROM messages WHERE to_handle = ? ORDER BY sequence DESC LIMIT ?') - .all(toHandle, limit) as MessageRow[] + .prepare( + `SELECT * FROM messages WHERE to_handle = ? AND (? IS NULL OR run_id = ?) ${typeFilter} + ORDER BY sequence DESC LIMIT ?` + ) + .all(toHandle, runId ?? null, runId ?? null, ...(typed ? types : []), limit) as MessageRow[] ) } diff --git a/src/main/runtime/orchestration/db/messages/message-insert.ts b/src/main/runtime/orchestration/db/messages/message-insert.ts index cc590b76b1a..24c45a19e7d 100644 --- a/src/main/runtime/orchestration/db/messages/message-insert.ts +++ b/src/main/runtime/orchestration/db/messages/message-insert.ts @@ -8,6 +8,7 @@ import { generateId } from '../generated-id' import { exposeMessageTimestamps } from '../utc-timestamp' import type { OrchestrationDb } from '../orchestration-db' import { runLifecycleWriteTransaction } from '../lifecycle-write-transaction-runner' +import { notifyPeerMailQueued } from '../../federation/peer-mail/peer-mail-waiters' import { ORCHESTRATION_UNBOUND_RUN_ID as UNBOUND_RUN_ID } from '../../../../../shared/orchestration/orchestration-rpc-contract' const MESSAGE_INSERT_SAVEPOINT = 'message_insert_batch' @@ -27,6 +28,8 @@ export type MessageInsert = { runId?: string answerSenderSnapshot?: string deliveryContract?: MessageDeliveryContract + /** The Dispatch whose worker sent this, as the sender's own check found it; kept for a peer Run's queue. */ + senderDispatchId?: string } export function insertMessage(this: OrchestrationDb, msg: MessageInsert): MessageRow { @@ -44,6 +47,16 @@ export function insertMessage(this: OrchestrationDb, msg: MessageInsert): Messag this.requireRun(runId) const id = msg.id ?? generateId('msg') const type = msg.type ?? 'status' + if (msg.senderDispatchId) { + // Before the insert, whose trigger queues a peer Run's mail home with it; immutable after. + this.db + .prepare( + `INSERT OR IGNORE INTO message_dispatch_provenance (message_id, dispatch_id, task_id) + SELECT ?, d.id, d.task_id FROM dispatch_contexts d + WHERE d.id = ? AND d.run_id IN (SELECT run_id FROM peer_runs)` + ) + .run(id, msg.senderDispatchId) + } // Heartbeats only record liveness: store them handled so they never reach a mailbox or wake it. const handled = type === 'heartbeat' ? 1 : 0 const stmt = this.db.prepare(` @@ -70,6 +83,8 @@ export function insertMessage(this: OrchestrationDb, msg: MessageInsert): Messag handled, handled ) + // Mail filed in a peer Run is queued home by trigger in this statement. + notifyPeerMailQueued(this.db) return exposeMessageTimestamps( this.db.prepare('SELECT * FROM messages WHERE id = ?').get(id) as MessageRow ) diff --git a/src/main/runtime/orchestration/db/orchestration-db-methods.ts b/src/main/runtime/orchestration/db/orchestration-db-methods.ts index 0e06a05191d..9072fe5c5fe 100644 --- a/src/main/runtime/orchestration/db/orchestration-db-methods.ts +++ b/src/main/runtime/orchestration/db/orchestration-db-methods.ts @@ -10,6 +10,7 @@ import type { FederationRelayAckMethods } from './federation/federation-relay-ac import type { LegacyRemoteDbMethods } from '../legacy-remote/legacy-remote-db-methods' import type { LegacyRemoteHomeDbMethods } from '../legacy-remote-home/legacy-remote-home-db-methods' import type { PeerMailStoreMethods } from './federation/peer-mail-store' +import type { PeerRunStoreMethods } from './peer-runs/peer-run-store' import type { LegacyAskOperationMethods } from './legacy/legacy-ask-operation' import type { LegacyCompatibilityCandidatesMethods } from './legacy/legacy-compatibility-candidates' import type { LegacyCompatibilityPrincipalsMethods } from './legacy/legacy-compatibility-principals' @@ -104,6 +105,7 @@ export type OrchestrationDbMethods = AttemptObservationStoreMethods & LegacyRemoteDbMethods & FederationRelayAckMethods & PeerMailStoreMethods & + PeerRunStoreMethods & StructuredMailSendStoreMethods & WorkerTerminalResourceStoreMethods & WorkerTerminalTransferMethods & diff --git a/src/main/runtime/orchestration/db/orchestration-db.ts b/src/main/runtime/orchestration/db/orchestration-db.ts index 25bec3ae31c..3fcd88f18b1 100644 --- a/src/main/runtime/orchestration/db/orchestration-db.ts +++ b/src/main/runtime/orchestration/db/orchestration-db.ts @@ -15,6 +15,7 @@ import { rememberCurrentRunCoordinatorHandles } from './runs/run-coordinator-mail-routing' import { createTables } from './schema/create-tables' +import { createPeerRunQueueTriggers } from './peer-runs/peer-run-queue-sql' import { migrate } from './schema/migrate' import { backfillStructuredWorkerOrcaSessionIds } from './schema/structured-worker-orca-session-backfill' import { reconcileSettledWorkerDispatches } from './worker-dispatch/worker-dispatch-settlement' @@ -63,6 +64,7 @@ class OrchestrationDbCore { } } createRunCoordinatorAddressTriggers(this.db) + createPeerRunQueueTriggers(this.db) backfillFederatedStubHomeRuns(this.db) // After every open step that creates Runs, before any step that deletes work. installRemovedWorkCapture(this.db, removedWorkCaptureWasIntact) diff --git a/src/main/runtime/orchestration/db/peer-runs/peer-run-queue-sql.ts b/src/main/runtime/orchestration/db/peer-runs/peer-run-queue-sql.ts new file mode 100644 index 00000000000..c2862a64508 --- /dev/null +++ b/src/main/runtime/orchestration/db/peer-runs/peer-run-queue-sql.ts @@ -0,0 +1,175 @@ +import type Database from '../../../../sqlite/sync-database' +import { REMOTE_OWNED_WIRE_VERSION } from '../../../../../shared/orchestration/remote-owned-wire' + +/** + * A Run here whose coordinator is a paired Orca, keyed by the conversation its queue goes home + * under. It outlives this Orca's resets, so the conversation keeps its Run ID and its sequence. + * Each conversation's next `to_home` sequence is persistent too, so a reset never reuses one. + * A worker message's Dispatch is recorded when it is filed, before any reroute into the Run. + */ +export const PEER_RUN_SCHEMA_SQL = ` +CREATE TABLE IF NOT EXISTS peer_runs ( + run_id TEXT PRIMARY KEY, + conversation_id TEXT NOT NULL UNIQUE, + peer_fingerprint TEXT NOT NULL, + home_run_id TEXT NOT NULL, + home_label TEXT NOT NULL, + state TEXT NOT NULL DEFAULT 'open' CHECK(state IN ('open', 'closed')), + created_at TEXT NOT NULL DEFAULT (datetime('now')) +); + +CREATE TABLE IF NOT EXISTS federation_relay_sequences ( + dispatch_id TEXT NOT NULL, + direction TEXT NOT NULL, + last_sequence INTEGER NOT NULL, + PRIMARY KEY (dispatch_id, direction) +); + +-- A Dispatch whose report owner's correction is being written: its edges queue nothing until the +-- row is removed, which queues the corrected state once, flagged. +CREATE TABLE IF NOT EXISTS peer_run_corrections ( + dispatch_id TEXT PRIMARY KEY +); + +CREATE TABLE IF NOT EXISTS message_dispatch_provenance ( + message_id TEXT PRIMARY KEY, + dispatch_id TEXT NOT NULL, + task_id TEXT NOT NULL +); +` + +/** A peer-Run Dispatch as a `worker_state` item carries it, with its Task and Run. */ +const PEER_RUN_DISPATCH_STATE_VIEW_SQL = ` +DROP VIEW IF EXISTS peer_run_dispatch_state; +CREATE VIEW peer_run_dispatch_state AS +SELECT d.id AS dispatch_id, pr.conversation_id, pr.home_run_id, pr.run_id AS peer_run_id, + json_object( + 'id', d.id, 'taskId', d.task_id, 'status', d.status, 'workerState', w.state, + 'lastFailure', d.last_failure, 'agent', json_extract(w.start_options, '$.agent') + ) AS dispatch_json, + json_object('status', t.status, 'result', t.result) AS task_json +FROM dispatch_contexts d +JOIN peer_runs pr ON pr.run_id = d.run_id +JOIN tasks t ON t.id = d.task_id +LEFT JOIN worker_dispatches w ON w.dispatch_id = d.id; +` + +const SEQUENCE = `(SELECT last_sequence FROM federation_relay_sequences + WHERE dispatch_id = conversation_id AND direction = 'to_home')` + +/** + * Takes the conversation's next sequence, then queues the item under it. `rows` selects at most one + * row with `conversation_id` and the item's `message_id` and `payload`; both statements read it. + */ +function queueItemStatements(rows: string, kind: string): [string, string] { + return [ + `INSERT INTO federation_relay_sequences (dispatch_id, direction, last_sequence) + SELECT conversation_id, 'to_home', 1 FROM (${rows}) WHERE true + ON CONFLICT(dispatch_id, direction) DO UPDATE SET last_sequence = last_sequence + 1`, + `INSERT INTO federation_relay_items + (dispatch_id, direction, sequence, message_id, kind, payload, byte_count) + SELECT conversation_id, 'to_home', ${SEQUENCE}, message_id, '${kind}', payload, length(payload) + FROM (${rows})` + ] +} + +/** One `worker_state` item for a peer-Run Dispatch; its ID is the sequence it is queued under. */ +export function peerRunDispatchStateStatements( + dispatchId: string, + corrected: boolean, + removed: string +): [string, string] { + return queueItemStatements( + `SELECT conversation_id, 'state_' || ${SEQUENCE} AS message_id, + json_object( + 'v', ${REMOTE_OWNED_WIRE_VERSION}, 'id', 'state_' || ${SEQUENCE}, + 'homeRunId', home_run_id, 'peerRunId', peer_run_id, + 'dispatch', json(dispatch_json), 'task', json(task_json), + 'correctedUnobservedPrompt', json('${corrected}'), + 'removed', ${removed} + ) AS payload + FROM peer_run_dispatch_state WHERE dispatch_id = ${dispatchId}`, + 'worker_state' + ) +} + +/** A message filed in a peer Run's mailbox, once, with the Dispatch its sender worked for. */ +function peerRunMailStatements(row: string): [string, string] { + return queueItemStatements( + `SELECT pr.conversation_id, ${row}.id AS message_id, + json_object( + 'v', ${REMOTE_OWNED_WIRE_VERSION}, 'id', ${row}.id, + 'homeRunId', pr.home_run_id, 'peerRunId', pr.run_id, + 'message', json_object( + 'from', ${row}.from_handle, 'type', ${row}.type, 'subject', ${row}.subject, + 'body', ${row}.body, 'payload', ${row}.payload, 'priority', ${row}.priority, + 'threadId', ${row}.thread_id + ), + 'dispatchId', p.dispatch_id, 'taskId', p.task_id + ) AS payload + FROM peer_runs pr + LEFT JOIN message_dispatch_provenance p ON p.message_id = ${row}.id + WHERE ${row}.to_handle = 'run:' || pr.run_id + AND NOT EXISTS ( + SELECT 1 FROM federation_relay_items + WHERE dispatch_id = pr.conversation_id AND direction = 'to_home' + AND message_id = ${row}.id + )`, + 'worker_mail' + ) +} + +const LATEST_TASK_DISPATCH = (taskId: string) => + `(SELECT id FROM dispatch_contexts WHERE task_id = ${taskId} ORDER BY rowid DESC LIMIT 1)` + +const NOT_CORRECTING = (dispatchId: string) => + `NOT EXISTS (SELECT 1 FROM peer_run_corrections WHERE dispatch_id = ${dispatchId})` + +const trigger = (statements: [string, string]) => `BEGIN ${statements.join(';\n')}; END;` + +/** + * Every final message of a peer Run's mailbox and every lifecycle change of its Dispatches, their + * workers and their Tasks queue home in the transaction that made them. Rebuilt on every open. + * The report owner's unobserved-prompt correction queues once, flagged, after all its writes. + */ +export function createPeerRunQueueTriggers(db: Database.Database): void { + db.exec('BEGIN IMMEDIATE') + try { + db.exec(` + ${PEER_RUN_DISPATCH_STATE_VIEW_SQL} + DROP TRIGGER IF EXISTS trg_peer_run_mail_insert; + DROP TRIGGER IF EXISTS trg_peer_run_mail_reroute; + DROP TRIGGER IF EXISTS trg_peer_run_dispatch_insert; + DROP TRIGGER IF EXISTS trg_peer_run_dispatch_status; + DROP TRIGGER IF EXISTS trg_peer_run_worker_state; + DROP TRIGGER IF EXISTS trg_peer_run_task_status; + DROP TRIGGER IF EXISTS trg_peer_run_correction; + CREATE TRIGGER trg_peer_run_mail_insert AFTER INSERT ON messages + WHEN NEW.to_handle LIKE 'run:%' AND NEW.type <> 'heartbeat' + ${trigger(peerRunMailStatements('NEW'))} + CREATE TRIGGER trg_peer_run_mail_reroute AFTER UPDATE OF to_handle ON messages + WHEN NEW.to_handle LIKE 'run:%' AND NEW.to_handle <> OLD.to_handle AND NEW.type <> 'heartbeat' + ${trigger(peerRunMailStatements('NEW'))} + CREATE TRIGGER trg_peer_run_dispatch_insert AFTER INSERT ON dispatch_contexts + ${trigger(peerRunDispatchStateStatements('NEW.id', false, 'NULL'))} + CREATE TRIGGER trg_peer_run_dispatch_status AFTER UPDATE OF status ON dispatch_contexts + WHEN NEW.status <> OLD.status AND ${NOT_CORRECTING('NEW.id')} + ${trigger(peerRunDispatchStateStatements('NEW.id', false, 'NULL'))} + CREATE TRIGGER trg_peer_run_worker_state AFTER UPDATE OF state ON worker_dispatches + WHEN NEW.state <> OLD.state AND ${NOT_CORRECTING('NEW.dispatch_id')} + ${trigger(peerRunDispatchStateStatements('NEW.dispatch_id', false, 'NULL'))} + CREATE TRIGGER trg_peer_run_task_status AFTER UPDATE OF status ON tasks + WHEN NEW.status <> OLD.status AND NOT EXISTS ( + SELECT 1 FROM peer_run_corrections c JOIN dispatch_contexts d ON d.id = c.dispatch_id + WHERE d.task_id = NEW.id + ) + ${trigger(peerRunDispatchStateStatements(LATEST_TASK_DISPATCH('NEW.id'), false, 'NULL'))} + CREATE TRIGGER trg_peer_run_correction AFTER DELETE ON peer_run_corrections + ${trigger(peerRunDispatchStateStatements('OLD.dispatch_id', true, 'NULL'))} + `) + db.exec('COMMIT') + } catch (error) { + db.exec('ROLLBACK') + throw error + } +} diff --git a/src/main/runtime/orchestration/db/peer-runs/peer-run-queue.test.ts b/src/main/runtime/orchestration/db/peer-runs/peer-run-queue.test.ts new file mode 100644 index 00000000000..a8b9bd4ce3b --- /dev/null +++ b/src/main/runtime/orchestration/db/peer-runs/peer-run-queue.test.ts @@ -0,0 +1,265 @@ +import { afterEach, beforeEach, describe, expect, it } from 'vitest' +import { OrchestrationDb } from '../orchestration-db' +import { generateId } from '../generated-id' +import { + RemoteOwnedWorkerMail, + RemoteOwnedWorkerState +} from '../../../../../shared/orchestration/remote-owned-wire' +import { AGENT_PROMPT_STALLED_ERROR } from '../../../terminal/input/agent-prompt-submission-verification' +import type { PeerRunRow } from './peer-run-store' + +describe("a paired Orca's Run: its queue home", () => { + let db: OrchestrationDb + let peerRun: PeerRunRow + + beforeEach(() => { + db = new OrchestrationDb(':memory:') + peerRun = db.admitPeerRun({ + peerFingerprint: 'fingerprint_a', + peerRun: { runId: 'run_home', conversationId: generateId('peerconv'), label: 'devA' } + }) + }) + + afterEach(() => db.close()) + + function start(params: { adoptTaskId?: string; retryOf?: string } = {}) { + return db.createStartingWorkerDispatch({ + taskSpec: 'Build it', + taskRunId: peerRun.run_id, + startOptions: { agent: 'claude' }, + creator: { kind: 'system' }, + maxDepth: 5, + ...params + }) + } + + function pending() { + return db.listPendingFederationRelay(peerRun.conversation_id, 'to_home', 500) + } + + function states() { + return pending() + .filter((item) => item.kind === 'worker_state') + .map((item) => RemoteOwnedWorkerState.parse(JSON.parse(item.payload))) + } + + function fail(dispatchId: string, taskId: string) { + db.transitionLifecycle({ entity: 'worker', id: dispatchId, from: 'starting', to: 'failed' }) + db.transitionLifecycle({ entity: 'dispatch', id: dispatchId, from: 'pending', to: 'failed' }) + db.transitionLifecycle({ entity: 'task', id: taskId, from: 'dispatched', to: 'failed' }) + } + + it('queues every lifecycle change of a Dispatch and its Task, in order, as the wire schema', () => { + const { dispatch, task } = start({ adoptTaskId: 'task_home1' }) + fail(dispatch.id, task.id) + + expect(task.id).toBe('task_home1') + const items = pending() + expect(items.map((item) => item.sequence)).toEqual(items.map((_, index) => index + 1)) + expect( + states().map((state) => [ + state.dispatch.status, + state.dispatch.workerState, + state.task.status + ]) + ).toEqual([ + ['pending', null, 'ready'], + ['pending', 'starting', 'dispatched'], + ['pending', 'failed', 'dispatched'], + ['failed', 'failed', 'dispatched'], + ['failed', 'failed', 'failed'] + ]) + expect(states().every((state) => state.homeRunId === 'run_home')).toBe(true) + for (const item of items) { + expect(JSON.parse(item.payload).id).toBe(item.message_id) + } + }) + + it("queues the report owner's unobserved-prompt correction once, flagged, with its result", () => { + const { dispatch, task } = start() + fail(dispatch.id, task.id) + db.transitionLifecycle({ + entity: 'dispatch', + id: dispatch.id, + from: 'failed', + to: 'failed', + projection: { last_failure: AGENT_PROMPT_STALLED_ERROR } + }) + const before = states().length + + db.settleWorkerReport({ + taskId: task.id, + dispatchId: dispatch.id, + outcome: 'succeeded', + result: 'actually done' + }) + + expect(states().slice(before)).toEqual([ + expect.objectContaining({ + correctedUnobservedPrompt: true, + dispatch: expect.objectContaining({ status: 'completed', workerState: 'succeeded' }), + task: { status: 'completed', result: 'actually done' } + }) + ]) + }) + + it('holds back the Task change of a correction even when a newer attempt is the latest', () => { + const first = start() + fail(first.dispatch.id, first.task.id) + db.transitionLifecycle({ + entity: 'dispatch', + id: first.dispatch.id, + from: 'failed', + to: 'failed', + projection: { last_failure: AGENT_PROMPT_STALLED_ERROR } + }) + const retry = start({ adoptTaskId: first.task.id }) + fail(retry.dispatch.id, first.task.id) + const before = states().length + + db.settleWorkerReport({ + taskId: first.task.id, + dispatchId: first.dispatch.id, + outcome: 'succeeded', + result: 'actually done' + }) + + expect(states().slice(before)).toEqual([ + expect.objectContaining({ + correctedUnobservedPrompt: true, + dispatch: expect.objectContaining({ id: first.dispatch.id }) + }) + ]) + }) + + it("queues a worker's question with its thread, so the coordinator can answer in it", () => { + const { dispatch } = start() + const { message } = db.createQuestion({ + runId: peerRun.run_id, + dispatchId: dispatch.id, + askerHandle: 'term_w', + question: 'Which branch?' + }) + const queued = pending().find((item) => item.message_id === message.id)! + expect(RemoteOwnedWorkerMail.parse(JSON.parse(queued.payload)).message.threadId).toBe( + message.id + ) + }) + + it('never reuses a sequence after a reset, and a reset tells the coordinator what it removed', () => { + const first = start() + const throughOld = Math.max(...pending().map((item) => item.sequence)) + + db.resetTasks() + const removed = states().filter((state) => state.removed) + expect(removed.map((state) => [state.dispatch.id, state.removed?.reason])).toEqual([ + [first.dispatch.id, 'reset on the server running it'] + ]) + start() + db.acknowledgeFederationRelay({ + dispatchId: peerRun.conversation_id, + direction: 'to_home', + throughSequence: throughOld + }) + + const after = pending() + expect(after.length).toBeGreaterThan(0) + expect(after.every((item) => item.sequence > throughOld)).toBe(true) + }) + + it('keeps the queue and the Run ID through a full reset, with a removed item per Dispatch', () => { + const { dispatch } = start() + db.resetAll() + + expect(states().find((state) => state.removed)?.dispatch.id).toBe(dispatch.id) + const again = db.admitPeerRun({ + peerFingerprint: 'fingerprint_a', + peerRun: { runId: 'run_home', conversationId: peerRun.conversation_id, label: 'devA' } + }) + expect(again.run_id).toBe(peerRun.run_id) + expect(db.getRun(peerRun.run_id)).toBeDefined() + }) + + it('attributes mail rerouted into the Run to the Dispatch its sender worked for when it sent it', () => { + const coordinator = `peer:${peerRun.conversation_id}` + const first = start() + const note = db.insertMessage({ + from: 'term_w', + to: 'term_unbound', + subject: 'late note', + runId: peerRun.run_id, + senderDispatchId: first.dispatch.id + }) + fail(first.dispatch.id, first.task.id) + start() + db.db.prepare('UPDATE messages SET to_handle = ? WHERE id = ?').run(coordinator, note.id) + db.db + .prepare('UPDATE messages SET to_handle = ? WHERE id = ?') + .run(`run:${peerRun.run_id}`, note.id) + + const mail = pending() + .filter((item) => item.kind === 'worker_mail') + .map((item) => RemoteOwnedWorkerMail.parse(JSON.parse(item.payload))) + expect(mail.map((item) => [item.id, item.dispatchId, item.taskId])).toEqual([ + [note.id, first.dispatch.id, first.task.id] + ]) + }) + + it('reopens an adopted Task whose last attempt settled, so the coordinator can run it again', () => { + const first = start({ adoptTaskId: 'task_home1' }) + fail(first.dispatch.id, first.task.id) + + const again = start({ adoptTaskId: 'task_home1' }) + expect(again.task.id).toBe('task_home1') + expect(again.dispatch.id).not.toBe(first.dispatch.id) + expect(() => start({ adoptTaskId: 'task_home1' })).toThrow(/only a ready Task can start/) + }) + + it('keeps a peer Run conversation and a peer-mail conversation apart, so their sequences never collide', () => { + const mailConversation = generateId('peerconv') + db.insertPeerMailMessage({ + conversationId: mailConversation, + peerFingerprint: 'fingerprint_a', + remoteParty: null, + message: { id: generateId('msg'), from: 'devA:term_x', to: 'term_w', subject: 'hi' } + }) + expect(() => + db.admitPeerRun({ + peerFingerprint: 'fingerprint_a', + peerRun: { runId: 'run_home2', conversationId: mailConversation, label: 'devA' } + }) + ).toThrow(expect.objectContaining({ code: 'request_mismatch' })) + expect(() => + db.insertPeerMailMessage({ + conversationId: peerRun.conversation_id, + peerFingerprint: 'fingerprint_a', + remoteParty: null, + message: { id: generateId('msg'), from: 'devA:term_x', to: 'term_w', subject: 'hi' } + }) + ).toThrow(expect.objectContaining({ code: 'request_mismatch' })) + }) + + it("follows a rename of the coordinating Orca's machine", () => { + const renamed = db.admitPeerRun({ + peerFingerprint: 'fingerprint_a', + peerRun: { runId: 'run_home', conversationId: peerRun.conversation_id, label: 'devA2' } + }) + expect(renamed.home_label).toBe('devA2') + }) + + it('leaves an adopted Task that still waits on its dependencies waiting', () => { + const dependency = db.createTask({ spec: 'first', runId: peerRun.run_id }) + const task = db.createTask({ + spec: 'second', + runId: peerRun.run_id, + deps: [dependency.id] + }) + expect(() => start({ adoptTaskId: task.id })).toThrow(/only a ready Task can start/) + expect(db.getTask(task.id)?.status).toBe('pending') + }) + + it('admits no start into a Run its coordinator cancelled', () => { + db.closePeerRun(peerRun.run_id) + expect(() => start()).toThrow(/cancelled by devA/) + }) +}) diff --git a/src/main/runtime/orchestration/db/peer-runs/peer-run-store.ts b/src/main/runtime/orchestration/db/peer-runs/peer-run-store.ts new file mode 100644 index 00000000000..20f70500176 --- /dev/null +++ b/src/main/runtime/orchestration/db/peer-runs/peer-run-store.ts @@ -0,0 +1,146 @@ +import type { RemoteOwnedPeerRun } from '../../../../../shared/orchestration/remote-owned-wire' +import { OrchestrationError } from '../../orchestration-error' +import { generateId } from '../generated-id' +import type { OrchestrationDb } from '../orchestration-db' +import { peerRunDispatchStateStatements } from './peer-run-queue-sql' +import { peerCoordinatorAddress } from '../../addressing/orchestration-caller-identity' + +export type PeerRunRow = { + run_id: string + conversation_id: string + peer_fingerprint: string + home_run_id: string + home_label: string + state: 'open' | 'closed' + created_at: string +} + +const NO_EFFECTS = { effectsApplied: false } as const + +/** + * The Run a paired Orca coordinates here for one conversation, written when its frame arrives and + * before any await, so a later frame of the same conversation (a cancel) always finds it. The Run + * keeps its ID across this Orca's resets: a reset that removed its row gets it back on the next call. + */ +export function admitPeerRun( + this: OrchestrationDb, + params: { peerFingerprint: string; peerRun: RemoteOwnedPeerRun } +): PeerRunRow { + const { peerFingerprint, peerRun } = params + this.db.exec('BEGIN IMMEDIATE') + try { + const conversation = this.getPeerMailConversation(peerRun.conversationId) + const existing = this.getPeerRunForConversation(peerRun.conversationId) + // A peer-mail conversation keeps its own queue sequence, so it never becomes a peer Run's. + if ( + existing + ? existing.peer_fingerprint !== peerFingerprint || existing.home_run_id !== peerRun.runId + : conversation + ) { + throw new OrchestrationError( + 'request_mismatch', + `Conversation ${peerRun.conversationId} belongs to another Run or pairing. No effects were applied.`, + NO_EFFECTS + ) + } + const runId = existing?.run_id ?? generateId('run') + if (existing && existing.home_label !== peerRun.label) { + this.db + .prepare('UPDATE peer_runs SET home_label = ? WHERE run_id = ?') + .run(peerRun.label, runId) + } + if (!existing) { + this.db + .prepare( + `INSERT OR IGNORE INTO peer_mail_conversations (conversation_id, role, peer_fingerprint) + VALUES (?, 'peer', ?)` + ) + .run(peerRun.conversationId, peerFingerprint) + this.db + .prepare( + `INSERT INTO peer_runs (run_id, conversation_id, peer_fingerprint, home_run_id, home_label) + VALUES (?, ?, ?, ?, ?)` + ) + .run(runId, peerRun.conversationId, peerFingerprint, peerRun.runId, peerRun.label) + } + if (!this.getRunRaw(runId)) { + const coordinator = peerCoordinatorAddress(peerRun.conversationId) + this.insertRunRow(runId, { + objective: `Coordinated from ${peerRun.label}`, + coordinatorHandle: coordinator, + coordinatorPaneKey: coordinator + }) + } + this.db.exec('COMMIT') + } catch (error) { + this.db.exec('ROLLBACK') + throw error + } + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the committed transaction above wrote or found this conversation's row. + return this.getPeerRunForConversation(peerRun.conversationId) as PeerRunRow +} + +export function getPeerRun(this: OrchestrationDb, runId: string): PeerRunRow | undefined { + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: SELECT * over this table returns exactly its row shape. + return this.db.prepare('SELECT * FROM peer_runs WHERE run_id = ?').get(runId) as + | PeerRunRow + | undefined +} + +export function hasPeerRuns(this: OrchestrationDb): boolean { + return this.db.prepare('SELECT 1 FROM peer_runs LIMIT 1').get() !== undefined +} + +export function getPeerRunForConversation( + this: OrchestrationDb, + conversationId: string +): PeerRunRow | undefined { + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: SELECT * over this table returns exactly its row shape. + return this.db + .prepare('SELECT * FROM peer_runs WHERE conversation_id = ?') + .get(conversationId) as PeerRunRow | undefined +} + +/** Closed for good: the claim refuses every start, follow-up and helper into it from now on. */ +export function closePeerRun(this: OrchestrationDb, runId: string): void { + this.db.prepare(`UPDATE peer_runs SET state = 'closed' WHERE run_id = ?`).run(runId) +} + +/** Inside a reset's transaction, before it deletes them: one final item per peer-Run Dispatch. */ +export function queueRemovedPeerRunDispatches(this: OrchestrationDb, reason: string): void { + const [allocate, queue] = peerRunDispatchStateStatements( + '?1', + false, + `json_object('reason', ?2)` + ).map((sql) => this.db.prepare(sql)) + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: SELECT of one column returns exactly that column. + const dispatches = this.db + .prepare( + `SELECT d.id FROM dispatch_contexts d JOIN peer_runs pr ON pr.run_id = d.run_id ORDER BY d.rowid` + ) + .all() as { id: string }[] + for (const { id } of dispatches) { + allocate.run(id, reason) + queue.run(id, reason) + } +} + +export type PeerRunStoreMethods = { + admitPeerRun: typeof admitPeerRun + getPeerRun: typeof getPeerRun + getPeerRunForConversation: typeof getPeerRunForConversation + hasPeerRuns: typeof hasPeerRuns + closePeerRun: typeof closePeerRun + queueRemovedPeerRunDispatches: typeof queueRemovedPeerRunDispatches +} + +export function attachPeerRunStore(ctor: { prototype: object }): void { + Object.assign(ctor.prototype, { + admitPeerRun, + getPeerRun, + getPeerRunForConversation, + hasPeerRuns, + closePeerRun, + queueRemovedPeerRunDispatches + }) +} diff --git a/src/main/runtime/orchestration/db/projection-mutation-triggers.ts b/src/main/runtime/orchestration/db/projection-mutation-triggers.ts new file mode 100644 index 00000000000..bd0a3a415d8 --- /dev/null +++ b/src/main/runtime/orchestration/db/projection-mutation-triggers.ts @@ -0,0 +1,30 @@ +export type ProjectionMutationTrigger = { + table: string + columns?: string + mark: (row: 'NEW' | 'OLD') => string +} + +/** Connection-local invalidations share the writer's transaction, including rollback. */ +export function projectionMutationTriggers( + name: string, + triggers: readonly ProjectionMutationTrigger[], + changed = '' +): string { + return triggers + .flatMap((trigger) => + [ + { name: 'insert', event: 'AFTER INSERT', rows: ['NEW'] as const }, + { name: 'delete', event: 'AFTER DELETE', rows: ['OLD'] as const }, + { + name: 'update', + event: trigger.columns ? `AFTER UPDATE OF ${trigger.columns}` : 'AFTER UPDATE', + rows: ['OLD', 'NEW'] as const + } + ].map( + (event) => `CREATE TEMP TRIGGER IF NOT EXISTS ${name}_${trigger.table}_${event.name} +${event.event} ON main.${trigger.table} +BEGIN ${changed} ${event.rows.map(trigger.mark).join(' ')} END;` + ) + ) + .join('\n') +} diff --git a/src/main/runtime/orchestration/db/questions/question-threads.ts b/src/main/runtime/orchestration/db/questions/question-threads.ts index 4f0be287206..5741dc5750a 100644 --- a/src/main/runtime/orchestration/db/questions/question-threads.ts +++ b/src/main/runtime/orchestration/db/questions/question-threads.ts @@ -2,6 +2,7 @@ import type { MessageRow, QuestionRow } from '../orchestration-records' import { OrchestrationError } from '../../orchestration-error' import { exposeQuestionTimestamps } from '../utc-timestamp' import type { OrchestrationDb } from '../orchestration-db' +import { generateId } from '../generated-id' import { handHelperMailToRun } from '../messages/helper-mailbox-hand-back' export function createQuestion( @@ -27,7 +28,11 @@ export function createQuestion( `Dispatch ${params.dispatchId} is not in Run ${params.runId}.` ) } + // A question is its own thread, set at insert so mail queued for a paired coordinator carries it. + const id = generateId('msg') const message = this.insertMessage({ + id, + threadId: id, from: `dispatch:${params.dispatchId}`, to: params.to ?? `run:${params.runId}`, subject: 'Question', @@ -39,9 +44,9 @@ export function createQuestion( question: params.question, options: params.options ?? [] }), + senderDispatchId: dispatch.id, runId: params.runId }) - this.db.prepare('UPDATE messages SET thread_id = ? WHERE id = ?').run(message.id, message.id) this.db .prepare( `INSERT INTO question_threads ( diff --git a/src/main/runtime/orchestration/db/reset/orchestration-reset.ts b/src/main/runtime/orchestration/db/reset/orchestration-reset.ts index ac68ba65767..b8af86962be 100644 --- a/src/main/runtime/orchestration/db/reset/orchestration-reset.ts +++ b/src/main/runtime/orchestration/db/reset/orchestration-reset.ts @@ -1,5 +1,6 @@ import { ORCHESTRATION_LEGACY_RUN_ID as LEGACY_RUN_ID } from '../../../../../shared/orchestration/orchestration-rpc-contract' import type { OrchestrationDb } from '../orchestration-db' +import { notifyPeerMailQueued } from '../../federation/peer-mail/peer-mail-waiters' import type { ResetRemovedWork } from '../../../../../shared/orchestration/orchestration-removed-work' import { readRemovedWorkWatermark, @@ -7,13 +8,22 @@ import { } from './removed-orchestration-work-read' /** Returns the removed-work watermark, read inside the transaction so the reply counts only this reset. */ -export function runResetTransaction(this: OrchestrationDb, statements: string): number { +export function runResetTransaction( + this: OrchestrationDb, + statements: string, + { removesDispatches = false }: { removesDispatches?: boolean } = {} +): number { this.db.exec('BEGIN IMMEDIATE') try { // Why unguarded: an error that ends the transaction must roll the whole reset back, not let the deletes autocommit. const watermark = readRemovedWorkWatermark(this.db) + if (removesDispatches) { + // Their paired coordinator learns of it from its queue, which the reset keeps. + this.queueRemovedPeerRunDispatches('reset on the server running it') + } this.db.exec(statements) this.db.exec('COMMIT') + notifyPeerMailQueued(this.db) return watermark } catch (error) { try { @@ -27,7 +37,8 @@ export function runResetTransaction(this: OrchestrationDb, statements: string): export function resetAll(this: OrchestrationDb): void { // Keep receipts so a lost reset reply cannot replay the mutation. - this.runResetTransaction(` + this.runResetTransaction( + ` DELETE FROM coordinator_runs; DELETE FROM decision_gates; DELETE FROM remote_questions; @@ -37,7 +48,7 @@ export function resetAll(this: OrchestrationDb): void { DELETE FROM legacy_operation_receipts; DELETE FROM legacy_compatibility_principals; DELETE FROM legacy_adoptions; - DELETE FROM federation_relay_items; + DELETE FROM federation_relay_items WHERE NOT (direction = 'to_home' AND dispatch_id IN (SELECT conversation_id FROM peer_runs)); DELETE FROM remote_dispatch_attachments; DELETE FROM federated_dispatches; DELETE FROM worker_terminal_archives; @@ -48,18 +59,22 @@ export function resetAll(this: OrchestrationDb): void { DELETE FROM dispatch_contexts; DELETE FROM tasks; DELETE FROM messages; + DELETE FROM message_dispatch_provenance; DELETE FROM run_coordinator_handles; DELETE FROM runs; DELETE FROM removed_orchestration_work; INSERT INTO runs (id, objective, home_database, consumer_generation, legacy) VALUES ('${LEGACY_RUN_ID}', 'Legacy orchestration state (inspect only)', 'this_database', 0, 1); - `) + `, + { removesDispatches: true } + ) this.hasAnyDispatchContextsCache = undefined } export function resetTasks(this: OrchestrationDb): ResetRemovedWork | undefined { // Messages survive, and so do replies waiting for a paired Orca to pull them; close threads so orphaned questions cannot masquerade as generic replies. - const watermark = this.runResetTransaction(` + const watermark = this.runResetTransaction( + ` DELETE FROM coordinator_runs; DELETE FROM decision_gates; DELETE FROM remote_questions; @@ -70,7 +85,7 @@ export function resetTasks(this: OrchestrationDb): ResetRemovedWork | undefined DELETE FROM legacy_operation_receipts; DELETE FROM legacy_compatibility_principals; DELETE FROM legacy_adoptions; - DELETE FROM federation_relay_items WHERE kind <> 'peer_mail'; + DELETE FROM federation_relay_items WHERE kind <> 'peer_mail' AND NOT (direction = 'to_home' AND dispatch_id IN (SELECT conversation_id FROM peer_runs)); DELETE FROM remote_dispatch_attachments; DELETE FROM federated_dispatches; DELETE FROM worker_terminal_archives; @@ -80,7 +95,9 @@ export function resetTasks(this: OrchestrationDb): ResetRemovedWork | undefined DELETE FROM worker_dispatches; DELETE FROM dispatch_contexts; DELETE FROM tasks; - `) + `, + { removesDispatches: true } + ) this.hasAnyDispatchContextsCache = undefined return summarizeRemovedWorkSince(this.db, watermark) } @@ -92,6 +109,7 @@ export function resetMessages(this: OrchestrationDb): void { DELETE FROM question_threads; DELETE FROM deliveries; DELETE FROM messages; + DELETE FROM message_dispatch_provenance; DELETE FROM structured_pointer_operations; `) } diff --git a/src/main/runtime/orchestration/db/runs/run-binding.ts b/src/main/runtime/orchestration/db/runs/run-binding.ts index 0d47fd2e34c..6950c8cba8b 100644 --- a/src/main/runtime/orchestration/db/runs/run-binding.ts +++ b/src/main/runtime/orchestration/db/runs/run-binding.ts @@ -42,6 +42,15 @@ export function bindRun( return undefined } const sameBinding = runBoundToCoordinator(run, coordinator) + const peerRun = this.getPeerRun(params.runId) + if (peerRun && !sameBinding) { + // A paired Orca's Run has that Orca as its only consumer; it never binds anything here. + throw new OrchestrationError( + 'consumer_fenced', + `Run ${params.runId} is coordinated from ${peerRun.home_label}, which stays its only coordinator. No effects were applied.`, + { effectsApplied: false } + ) + } const explicitTakeover = params.takeoverLegacy === true // Why: before the legacy gate, so a worker never sees its --takeover-legacy recovery command. const workerRefusal = sameBinding diff --git a/src/main/runtime/orchestration/db/runs/run-create.ts b/src/main/runtime/orchestration/db/runs/run-create.ts index 53b17414ea6..6ce7877082c 100644 --- a/src/main/runtime/orchestration/db/runs/run-create.ts +++ b/src/main/runtime/orchestration/db/runs/run-create.ts @@ -4,42 +4,19 @@ import type { OrchestrationDb } from '../orchestration-db' import type { OrcaSessionId } from '../../../../../shared/orca-session-address' import { mailboxAddressOf } from '../../addressing/orchestration-caller-identity' -export function createRun( - this: OrchestrationDb, - params: { - objective: string - coordinatorHandle: string | null - coordinatorPaneKey: string | null - /** The coordinator's bare Orca session id when it is a structured session; see orca-session-address. */ - coordinatorOrcaSessionId?: OrcaSessionId | null - } -): RunRow { - const coordinator = { - terminalHandle: params.coordinatorHandle, - paneKey: params.coordinatorPaneKey, - orcaSessionId: params.coordinatorOrcaSessionId ?? null - } +type RunCoordinatorParams = { + objective: string + coordinatorHandle: string | null + coordinatorPaneKey: string | null + /** The coordinator's bare Orca session id when it is a structured session; see orca-session-address. */ + coordinatorOrcaSessionId?: OrcaSessionId | null +} + +export function createRun(this: OrchestrationDb, params: RunCoordinatorParams): RunRow { const id = generateId('run') this.db.exec('BEGIN IMMEDIATE') try { - this.db - .prepare( - `INSERT INTO runs ( - id, objective, coordinator_handle, coordinator_pane_key, coordinator_orca_session_id, - coordinator_orca_session_id_generation, consumer_generation, legacy - ) VALUES (?, ?, ?, ?, ?, 1, 1, 0)` - ) - .run( - id, - params.objective, - coordinator.terminalHandle, - coordinator.paneKey, - coordinator.orcaSessionId - ) - const address = mailboxAddressOf(coordinator) - if (address !== null) { - this.rememberRunCoordinatorHandle(id, address) - } + this.insertRunRow(id, params) this.db.exec('COMMIT') } catch (error) { this.db.exec('ROLLBACK') @@ -48,12 +25,45 @@ export function createRun( return this.getRun(id) as RunRow } +/** Writes a Run bound to its coordinator inside the caller's transaction. */ +export function insertRunRow( + this: OrchestrationDb, + id: string, + params: RunCoordinatorParams +): void { + const coordinator = { + terminalHandle: params.coordinatorHandle, + paneKey: params.coordinatorPaneKey, + orcaSessionId: params.coordinatorOrcaSessionId ?? null + } + this.db + .prepare( + `INSERT INTO runs ( + id, objective, coordinator_handle, coordinator_pane_key, coordinator_orca_session_id, + coordinator_orca_session_id_generation, consumer_generation, legacy + ) VALUES (?, ?, ?, ?, ?, 1, 1, 0)` + ) + .run( + id, + params.objective, + coordinator.terminalHandle, + coordinator.paneKey, + coordinator.orcaSessionId + ) + const address = mailboxAddressOf(coordinator) + if (address !== null) { + this.rememberRunCoordinatorHandle(id, address) + } +} + export type RunCreateMethods = { createRun: typeof createRun + insertRunRow: typeof insertRunRow } export function attachRunCreate(ctor: { prototype: object }): void { Object.assign(ctor.prototype, { - createRun + createRun, + insertRunRow }) } diff --git a/src/main/runtime/orchestration/db/schema/create-tables.ts b/src/main/runtime/orchestration/db/schema/create-tables.ts index 1895230e847..5378ee71629 100644 --- a/src/main/runtime/orchestration/db/schema/create-tables.ts +++ b/src/main/runtime/orchestration/db/schema/create-tables.ts @@ -3,9 +3,12 @@ import { createCoreTablesSql } from './create-core-tables-sql' import { createGraphTablesSql } from './create-graph-tables-sql' import { DERIVED_DELIVERY_SCHEMA_SQL } from './migrate-v41' import { REMOVED_WORK_SCHEMA_SQL } from '../reset/removed-orchestration-work-store' +import { PEER_RUN_SCHEMA_SQL } from '../peer-runs/peer-run-queue-sql' export function createTables(this: OrchestrationDb): void { - this.db.exec(`${createCoreTablesSql()}\n${createGraphTablesSql()}\n${REMOVED_WORK_SCHEMA_SQL}`) + this.db.exec( + `${createCoreTablesSql()}\n${createGraphTablesSql()}\n${REMOVED_WORK_SCHEMA_SQL}\n${PEER_RUN_SCHEMA_SQL}` + ) // Unreleased builds saved each send's fence as NOT NULL; nothing reads it, and new rows carry none. if (this.hasColumn('structured_mail_sends', 'fence')) { this.db.exec('ALTER TABLE structured_mail_sends DROP COLUMN fence') diff --git a/src/main/runtime/orchestration/db/tasks/task-store.ts b/src/main/runtime/orchestration/db/tasks/task-store.ts index 401d3d68544..aebef0d890f 100644 --- a/src/main/runtime/orchestration/db/tasks/task-store.ts +++ b/src/main/runtime/orchestration/db/tasks/task-store.ts @@ -10,6 +10,8 @@ import { selectColumns, TASK_COLUMNS } from '../row-column-lists' export function createTask( this: OrchestrationDb, task: { + /** Set only for a Task placed on a paired server: one ID for it here and there, from the start's retry key. */ + id?: string spec: string taskTitle?: string displayName?: string @@ -39,7 +41,7 @@ export function createTask( throw new Error(`Dependency task ${depId} must belong to run ${runId}`) } } - const id = generateId('task') + const id = task.id ?? generateId('task') const depsJson = JSON.stringify(task.deps ?? []) const display = buildOrchestrationTaskDisplayMetadata({ spec: task.spec, diff --git a/src/main/runtime/orchestration/db/worker-dispatch/worker-dispatch-start.ts b/src/main/runtime/orchestration/db/worker-dispatch/worker-dispatch-start.ts index b65da6e2f61..f45cf6677e0 100644 --- a/src/main/runtime/orchestration/db/worker-dispatch/worker-dispatch-start.ts +++ b/src/main/runtime/orchestration/db/worker-dispatch/worker-dispatch-start.ts @@ -18,6 +18,8 @@ export function createStartingWorkerDispatch( params: { taskId?: string taskSpec?: string + /** The paired coordinator's ID for this Task: an existing one is reopened, else the new one takes it. */ + adoptTaskId?: string taskRunId?: string taskCreatedByTerminalHandle?: string taskCreatedByPaneKey?: string @@ -89,26 +91,42 @@ export function createStartingWorkerDispatch( { followUpDispatchId: claimedFollowUp.id } ) } + const adopted = params.adoptTaskId ? this.getTask(params.adoptTaskId) : undefined + if (adopted && !params.retryOf) { + reopenSettledAdoptedTask(this, adopted, params.taskRunId) + } const task = params.taskId ? this.getTask(params.taskId) - : params.taskSpec - ? this.createTask({ - spec: params.taskSpec, - taskTitle: params.taskTitle, - deps: params.taskDeps, - parentId: params.taskParentId, - createdByTerminalHandle: params.taskCreatedByTerminalHandle, - createdByPaneKey: params.taskCreatedByPaneKey, - createdByProcessIncarnation: params.taskCreatedByProcessIncarnation, - createdByRunGeneration: params.taskCreatedByRunGeneration, - runId: params.taskRunId - }) - : undefined + : adopted + ? this.getTask(adopted.id) + : params.taskSpec + ? this.createTask({ + id: params.adoptTaskId, + spec: params.taskSpec, + taskTitle: params.taskTitle, + deps: params.taskDeps, + parentId: params.taskParentId, + createdByTerminalHandle: params.taskCreatedByTerminalHandle, + createdByPaneKey: params.taskCreatedByPaneKey, + createdByProcessIncarnation: params.taskCreatedByProcessIncarnation, + createdByRunGeneration: params.taskCreatedByRunGeneration, + runId: params.taskRunId + }) + : undefined if (!task) { // An inline spec already creates its Task; missing rows here imply an explicit id. const taskId = params.taskId ?? '' throw taskNotFoundError(`Task ${taskId} was not found.`, { taskId }) } + const peerRun = this.getPeerRun(task.run_id) + if (peerRun?.state === 'closed') { + // Starts, follow-ups and helpers alike: its coordinator cancelled it. + throw new OrchestrationError( + 'run_not_found', + `Run ${task.run_id} was cancelled by ${peerRun.home_label}. No effects were applied.`, + { effectsApplied: false } + ) + } let priorFailures = 0 if (params.retryOf) { const prior = this.getDispatchContextById(params.retryOf) @@ -251,3 +269,30 @@ export function attachWorkerDispatchStart(ctor: { prototype: object }): void { createStartingWorkerDispatch }) } + +/** A Task its paired coordinator reopened gets a new attempt here once its latest attempt settled. */ +function reopenSettledAdoptedTask( + db: OrchestrationDb, + task: TaskRow, + runId: string | undefined +): void { + if (task.run_id !== runId) { + throw taskNotFoundError(`Task ${task.id} was not found in Run ${runId ?? ''}.`, { + taskId: task.id + }) + } + const latest = db.getDispatchContext(task.id) + const worker = latest ? db.getWorkerDispatch(latest.id) : undefined + const settled = worker + ? ['succeeded', 'failed', 'stopped', 'abandoned'].includes(worker.state) + : !latest || ['completed', 'failed', 'circuit_broken'].includes(latest.status) + // A pending Task still waits on its dependencies; the ordinary promotion readies it. + if (settled && task.status !== 'ready' && task.status !== 'pending') { + transitionLifecycleWithDb(db.db, { + entity: 'task', + id: task.id, + from: task.status, + to: 'ready' + }) + } +} diff --git a/src/main/runtime/orchestration/db/worker-terminal/worker-terminal-attention-query.ts b/src/main/runtime/orchestration/db/worker-terminal/worker-terminal-attention-query.ts index bb908a26d07..a4c81f024cb 100644 --- a/src/main/runtime/orchestration/db/worker-terminal/worker-terminal-attention-query.ts +++ b/src/main/runtime/orchestration/db/worker-terminal/worker-terminal-attention-query.ts @@ -27,18 +27,39 @@ export type WorkerAttentionFacts = { releaseState?: string | null } -export function getWorkerAttentionFactsForDispatches( - this: OrchestrationDb, - dispatchIds: readonly string[], - authorityNow: number -): Map { +type WorkerAttentionRow = { + dispatch_id: string + task_id: string + dispatch_status: DispatchStatus + termination_reason: TerminalExitCause['kind'] | null + worker_state: WorkerDispatchState | null + worker_stage: string | null + parent_task_id: string | null + resource_id: string | null + host_scope: string | null + release_state: string | null + pending_input: number + pending_approval: number + pending_guidance: number + active_sibling: number +} + +export type WorkerAttentionInput = { + row: WorkerAttentionRow + observations: ReturnType[] +} + +export function readWorkerAttentionInputs( + db: OrchestrationDb, + dispatchIds: readonly string[] +): Map { const ids = [...new Set(dispatchIds)] if (ids.length === 0) { return new Map() } const serializedIds = JSON.stringify(ids) - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: this row cast is unchanged and matches every other row cast in db/; the gate flags it only because this diff adds a column inside its span. - const rows = this.db + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the query selects each schema-owned WorkerAttentionRow column. + const rows = db.db .prepare( `SELECT d.id AS dispatch_id, d.task_id, d.status AS dispatch_status, d.termination_reason, w.state AS worker_state, w.stage AS worker_stage, @@ -64,26 +85,17 @@ export function getWorkerAttentionFactsForDispatches( LEFT JOIN worker_terminal_resources r ON r.owner_dispatch_id = d.id WHERE d.id IN (SELECT value FROM json_each(?))` ) - .all(serializedIds) as { - dispatch_id: string - task_id: string - dispatch_status: DispatchStatus - termination_reason: TerminalExitCause['kind'] | null - worker_state: WorkerDispatchState | null - worker_stage: string | null - parent_task_id: string | null - resource_id: string | null - host_scope: string | null - release_state: string | null - pending_input: number - pending_approval: number - pending_guidance: number - active_sibling: number - }[] - const observationRows = this.db + .all(serializedIds) as WorkerAttentionRow[] + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the query selects the schema-owned observation column list. + const observationRows = db.db .prepare( `SELECT ${ATTEMPT_OBSERVATION_FACT_COLUMN_LIST} FROM attempt_observation_facts - WHERE dispatch_id IN (SELECT value FROM json_each(?)) + WHERE rowid IN ( + SELECT (SELECT rowid FROM attempt_observation_facts + WHERE dispatch_id = requested.value AND facet = facets.value + ORDER BY sequence DESC LIMIT 1) + FROM json_each(?) requested, json_each('["process_turn","artifact_git","worker_report","coordinator_ack","liveness","outcome"]') facets + ) ORDER BY dispatch_id, sequence, rowid` ) .all(serializedIds) as AttemptObservationStorageRow[] @@ -95,34 +107,58 @@ export function getWorkerAttentionFactsForDispatches( } return new Map( rows.map((row) => { - const projected = projectAttemptOutcome({ - dispatchId: row.dispatch_id, - taskId: row.task_id, - facts: factsByDispatch.get(row.dispatch_id) ?? [], - activeSibling: row.active_sibling === 1, - authorityNow: { home: authorityNow } - }).taskOutcome - return [ - row.dispatch_id, - { - outcome: projected, - pendingInput: row.pending_input === 1, - pendingGuidance: row.pending_guidance === 1, - pendingApproval: row.pending_approval === 1, - terminationReason: row.termination_reason, - isRoot: row.parent_task_id === null, - workerState: row.worker_state, - workerStage: row.worker_stage, - dispatchStatus: row.dispatch_status, - ...(row.resource_id === null - ? {} - : { hostScope: row.host_scope, releaseState: row.release_state }) + const latest = new Map>() + for (const fact of factsByDispatch.get(row.dispatch_id) ?? []) { + const previous = latest.get(fact.facet) + if (!previous || previous.sequence < fact.sequence) { + latest.set(fact.facet, fact) } - ] + } + return [row.dispatch_id, { row, observations: [...latest.values()] }] }) ) } +export function projectWorkerAttentionInput( + input: WorkerAttentionInput, + authorityNow: number +): WorkerAttentionFacts { + const { row, observations } = input + return { + outcome: projectAttemptOutcome({ + dispatchId: row.dispatch_id, + taskId: row.task_id, + facts: observations, + activeSibling: row.active_sibling === 1, + authorityNow: { home: authorityNow } + }).taskOutcome, + pendingInput: row.pending_input === 1, + pendingGuidance: row.pending_guidance === 1, + pendingApproval: row.pending_approval === 1, + terminationReason: row.termination_reason, + isRoot: row.parent_task_id === null, + workerState: row.worker_state, + workerStage: row.worker_stage, + dispatchStatus: row.dispatch_status, + ...(row.resource_id === null + ? {} + : { hostScope: row.host_scope, releaseState: row.release_state }) + } +} + +export function getWorkerAttentionFactsForDispatches( + this: OrchestrationDb, + dispatchIds: readonly string[], + authorityNow: number +): Map { + return new Map( + [...readWorkerAttentionInputs(this, dispatchIds)].map(([id, input]) => [ + id, + projectWorkerAttentionInput(input, authorityNow) + ]) + ) +} + export function getWorkerAttentionFacts( this: OrchestrationDb, dispatchId: string, diff --git a/src/main/runtime/orchestration/db/worker-terminal/worker-terminal-listing.ts b/src/main/runtime/orchestration/db/worker-terminal/worker-terminal-listing.ts index 3e625c2126c..c2ce51ded5e 100644 --- a/src/main/runtime/orchestration/db/worker-terminal/worker-terminal-listing.ts +++ b/src/main/runtime/orchestration/db/worker-terminal/worker-terminal-listing.ts @@ -103,6 +103,8 @@ export function listWorkerTerminalResources( pendingApproval: boolean terminationReason: TerminalExitCause['kind'] | null resource: WorkerTerminalResourceRow | null + /** The paired Orca's name when its Run here coordinates this worker. */ + coordinatedFrom: string | null createdAt: string databaseId: number }[] { @@ -170,6 +172,7 @@ export function listWorkerTerminalResources( t.parent_id AS parent_task_id, d.task_id, d.run_id, d.status AS dispatch_status, d.termination_reason, + (SELECT home_label FROM peer_runs WHERE run_id = d.run_id) AS coordinated_from, EXISTS ( SELECT 1 FROM question_threads q WHERE q.dispatch_id = d.id AND q.status = 'pending' @@ -199,6 +202,7 @@ export function listWorkerTerminalResources( termination_reason: TerminalExitCause['kind'] | null pending_input: number pending_approval: number + coordinated_from: string | null created_at: string database_id: number }[] @@ -236,6 +240,7 @@ export function listWorkerTerminalResources( pendingApproval: row.pending_approval === 1, terminationReason: row.termination_reason, resource, + coordinatedFrom: row.coordinated_from, createdAt: row.created_at, databaseId: row.database_id } diff --git a/src/main/runtime/orchestration/federation/peer-mail/peer-mail-waiters.ts b/src/main/runtime/orchestration/federation/peer-mail/peer-mail-waiters.ts index 0e2b13c329d..5b88ac6206d 100644 --- a/src/main/runtime/orchestration/federation/peer-mail/peer-mail-waiters.ts +++ b/src/main/runtime/orchestration/federation/peer-mail/peer-mail-waiters.ts @@ -1,17 +1,18 @@ -import type { OrchestrationDb } from '../../db/orchestration-db' +import type Database from '../../../../sqlite/sync-database' -const waiters = new WeakMap void>>() +const waiters = new WeakMap void>>() -/** Wakes every pull waiting on this store; each re-reads its own conversations. */ -export function notifyPeerMailQueued(db: OrchestrationDb): void { +/** Wakes every pull waiting on this database; each re-reads its own conversations. Called by every + * write that can queue an item home: a reply, a message filed in a Run, a lifecycle change, a reset. */ +export function notifyPeerMailQueued(db: Database.Database): void { for (const wake of waiters.get(db) ?? []) { wake() } } -/** Resolves when a reply is queued, the wait ends, or the caller goes away. */ +/** Resolves when an item may have been queued, the wait ends, or the caller goes away. */ export function waitForPeerMail( - db: OrchestrationDb, + db: Database.Database, timeoutMs: number, signal?: AbortSignal ): Promise { diff --git a/src/main/runtime/orchestration/legacy-remote-home/federated-worker-child-parent.ts b/src/main/runtime/orchestration/legacy-remote-home/federated-worker-child-parent.ts index e0249544e10..be0580a0127 100644 --- a/src/main/runtime/orchestration/legacy-remote-home/federated-worker-child-parent.ts +++ b/src/main/runtime/orchestration/legacy-remote-home/federated-worker-child-parent.ts @@ -1,5 +1,5 @@ import type { OrcaRuntimeService } from '../../orca-runtime' -import type { OrchestrationSessionCaller } from '../addressing/orchestration-caller-identity' +import type { OrchestrationEntryCaller } from '../addressing/orchestration-caller-identity' import { OrchestrationError } from '../orchestration-error' import { readCallerStoreInstallationId } from '../../hosts/platform-probe/host-descriptor' import { getCanonicalUserDataPath } from '../../../persistence/loading-store/user-data-path' @@ -22,7 +22,7 @@ export async function resolveFederatedChildParent(args: { | 'getRuntimeId' > from: string - callerSession: OrchestrationSessionCaller | undefined + callerSession: OrchestrationEntryCaller | undefined serverCapabilities: readonly string[] | undefined serverName: string }): Promise< diff --git a/src/main/runtime/orchestration/legacy-remote-home/federated-worker-start-request.ts b/src/main/runtime/orchestration/legacy-remote-home/federated-worker-start-request.ts index 21dd2d80613..d4a6950dfc6 100644 --- a/src/main/runtime/orchestration/legacy-remote-home/federated-worker-start-request.ts +++ b/src/main/runtime/orchestration/legacy-remote-home/federated-worker-start-request.ts @@ -1,4 +1,4 @@ -import type { OrchestrationSessionCaller } from '../addressing/orchestration-caller-identity' +import type { OrchestrationEntryCaller } from '../addressing/orchestration-caller-identity' import type { OrcaRuntimeService } from '../../orca-runtime' import type { OrchestrationDb } from '../db/orchestration-db' import type { WorkerStartInput } from '../../rpc/methods/orchestration/worker/worker-start-schema' @@ -14,5 +14,5 @@ export type FederatedWorkerStartRequest = { taskDeps: string[] | undefined orchestrationMutation?: WorkerStartMutation /** The coordinator's resolved session, when it is one; recorded as the Dispatch creator. */ - callerSession?: OrchestrationSessionCaller + callerSession?: OrchestrationEntryCaller } diff --git a/src/main/runtime/orchestration/mailbox/routing/terminal-pane-mail-routing.ts b/src/main/runtime/orchestration/mailbox/routing/terminal-pane-mail-routing.ts index d253ae3a55d..795e9c18cc8 100644 --- a/src/main/runtime/orchestration/mailbox/routing/terminal-pane-mail-routing.ts +++ b/src/main/runtime/orchestration/mailbox/routing/terminal-pane-mail-routing.ts @@ -1,7 +1,6 @@ -import { - ptyRecordForPaneKey, - type TerminalIdentityReadContext -} from '../../../terminal/query/terminal-identity-read-context' +import { ORCA_LAYOUT_OWNER_IS_MAIN } from '../../../../../shared/layout-owner-switch' +import type { TerminalIdentityReadContext } from '../../../terminal/query/terminal-identity-read-context' +import { ptyRecordForPaneKey } from '../../../terminal/query/pty-pane-record' import type { RuntimeTerminalAgentPresenceOptions } from '../../../terminal/query/runtime-terminal-agent-presence' import { OrcaRuntimeWithPruneMobileSessionTabGroupLayout } from '../../../session-lifecycle/projection/prune-mobile-session-tab-group-layout' import type { RuntimePtyWorktreeRecord } from '../../../terminal/records/runtime-terminal-state-records' @@ -52,7 +51,14 @@ export abstract class OrcaRuntimeWithGetPtyRecordForPaneKey extends OrcaRuntimeW leaves: this.leaves, ptys: this.ptysById, leafKey: (tab, leaf) => this.getLeafKey(tab, leaf), - capturePaneOf: () => this.captureTerminalPaneReader() + capturePaneOf: () => this.captureTerminalPaneReader(), + ...(!ORCA_LAYOUT_OWNER_IS_MAIN + ? { + paneOf: (pty: Parameters[0]) => this.paneOfPty(pty), + leavesForId: (id: string) => this.terminalIdentity.paneCandidates.leavesForId(id), + ptysForPane: (pane: string) => this.terminalIdentity.paneCandidates.ptysForPane(pane) + } + : {}) }, context ) diff --git a/src/main/runtime/orchestration/mailbox/terminal-pointer/in-memory-orchestration-messages.spec.ts b/src/main/runtime/orchestration/mailbox/terminal-pointer/in-memory-orchestration-messages.spec.ts index 264b99b1f56..b7d5ab26485 100644 --- a/src/main/runtime/orchestration/mailbox/terminal-pointer/in-memory-orchestration-messages.spec.ts +++ b/src/main/runtime/orchestration/mailbox/terminal-pointer/in-memory-orchestration-messages.spec.ts @@ -5,6 +5,10 @@ import type { MessagePriority, MessageRow, MessageType } from '../../db/orchestr export class InMemoryOrchestrationMessages { readonly crewChanges = new CrewChanges() + hasAnyDispatchContexts(): boolean { + return false + } + private sequence = 0 private activeCoordinatorRun: { coordinator_handle: string } | null = null diff --git a/src/main/runtime/orchestration/terminal-authority/structured-sessions/structured-worker-authority.ts b/src/main/runtime/orchestration/terminal-authority/structured-sessions/structured-worker-authority.ts index 7745cf67b03..1f3ce8ca6c5 100644 --- a/src/main/runtime/orchestration/terminal-authority/structured-sessions/structured-worker-authority.ts +++ b/src/main/runtime/orchestration/terminal-authority/structured-sessions/structured-worker-authority.ts @@ -106,13 +106,9 @@ export function isRecordedStructuredWorkerSession( sessionId: OrcaSessionId, db: OrchestrationDb ): boolean { - return Boolean( - db.db - .prepare( - `SELECT 1 FROM dispatch_contexts - WHERE assignee_orca_session_id = ? AND process_incarnation = ? LIMIT 1` - ) - .get(sessionId, structuredWorkerProcessIncarnation(sessionId)) + return db.hasRecordedStructuredWorkerSession( + sessionId, + structuredWorkerProcessIncarnation(sessionId) ) } diff --git a/src/main/runtime/orchestration/workers/launch/worker-dispatch-preamble.ts b/src/main/runtime/orchestration/workers/launch/worker-dispatch-preamble.ts index bc1fa776441..a68c56d5f2e 100644 --- a/src/main/runtime/orchestration/workers/launch/worker-dispatch-preamble.ts +++ b/src/main/runtime/orchestration/workers/launch/worker-dispatch-preamble.ts @@ -10,6 +10,8 @@ export type PreambleParams = { taskSpec: string /** A terminal handle, or a session's `orca_session_id:`; each is labelled by its kind. */ coordinatorHandle: string + /** The paired Orca's name when it coordinates this worker's Run from another computer. */ + coordinatedFrom?: string workerHandle: string devMode?: boolean // Packaged WSL uses orca-ide; other hosts retain their existing launcher. @@ -38,9 +40,11 @@ function isSessionHandle(handle: string): boolean { /** Terminal agents keep their handle's wording; only a session is named by its Orca session ID. */ function dispatchIdentityLines(params: PreambleParams): string { return [ - isSessionHandle(params.coordinatorHandle) - ? `Your coordinator's Orca session ID is: ${params.coordinatorHandle}` - : `Your coordinator's terminal handle is: ${params.coordinatorHandle}`, + params.coordinatedFrom + ? `You are coordinated from ${params.coordinatedFrom}. Your coordinator's address here is: ${params.coordinatorHandle}` + : isSessionHandle(params.coordinatorHandle) + ? `Your coordinator's Orca session ID is: ${params.coordinatorHandle}` + : `Your coordinator's terminal handle is: ${params.coordinatorHandle}`, `Your task ID is: ${params.taskId}`, ...(isSessionHandle(params.workerHandle) ? [`Your Orca session ID is: ${params.workerHandle}`] diff --git a/src/main/runtime/orchestration/workers/launch/worker-start-card.ts b/src/main/runtime/orchestration/workers/launch/worker-start-card.ts index 7f114fd9544..c68dca11f1a 100644 --- a/src/main/runtime/orchestration/workers/launch/worker-start-card.ts +++ b/src/main/runtime/orchestration/workers/launch/worker-start-card.ts @@ -6,7 +6,7 @@ import type { import type { AgentMessageSender } from '../../../../../shared/agent-session/agent-session-message-source' import type { AgentType } from '../../../../../shared/agent-status/contracts/agent-status-types' import type { OrcaRuntimeService } from '../../../orca-runtime' -import type { OrchestrationSessionCaller } from '../../addressing/orchestration-caller-identity' +import type { OrchestrationEntryCaller } from '../../addressing/orchestration-caller-identity' export type AgentCreationCard = AgentJournalAgentStartItem | AgentJournalAgentHandoffItem @@ -48,7 +48,7 @@ export function startedAgentSender( export function prepareWorkerStartCard( runtime: OrcaRuntimeService, - callerSession: OrchestrationSessionCaller | undefined + callerSession: OrchestrationEntryCaller | undefined ): (args: { dispatchId: string workerAddress: string @@ -56,7 +56,10 @@ export function prepareWorkerStartCard( /** What this start launched; the only kind known for a worker on another host. */ agent: AgentType | null }) => void { - const publish = prepareAgentCreationCard(callerSession?.sessionId) + // A paired Orca has no chat here to show the card in. + const publish = prepareAgentCreationCard( + callerSession?.kind === 'peer' ? undefined : callerSession?.sessionId + ) if (!publish) { return () => {} } diff --git a/src/main/runtime/repositories/runtime-repository-hooks-commands.ts b/src/main/runtime/repositories/runtime-repository-hooks-commands.ts index fd36b658d24..844dc691151 100644 --- a/src/main/runtime/repositories/runtime-repository-hooks-commands.ts +++ b/src/main/runtime/repositories/runtime-repository-hooks-commands.ts @@ -1,4 +1,5 @@ -import { getRepoDialableSshTargetId } from '../../../shared/execution-host' +import { getRepoDialableSshTargetId, isRepoOnCatalogHost } from '../../../shared/execution-host' +import { scopeHooksToRepoKind } from '../../../shared/folder-workspace-hooks' import { windowsFsPath } from '../../wsl/filesystem/wsl-unc-drive-fs-path' import { readFile } from 'node:fs/promises' import type { Repo } from '../../../shared/repo-types' @@ -29,8 +30,8 @@ export class RuntimeRepositoryHooksCommands { async getRepoHooks(repoSelector: string) { const repo = await this.deps.resolveRepo(repoSelector) const connectionId = getRepoDialableSshTargetId(repo) - // Why: an `ssh:` repo is not served here; it reports no hooks file. - if (connectionId) { + // Why: an `ssh:` repo is not served here, nor a folder another host owns; neither reports hooks. + if (connectionId || (isFolderRepo(repo) && !isRepoOnCatalogHost(repo))) { return { hasHooksFile: false, hooks: null, @@ -40,8 +41,8 @@ export class RuntimeRepositoryHooksCommands { } const hasFile = hasHooksFile(repo.path) const hooks = getEffectiveHooks(repo) - const sharedHooks = hasFile ? loadHooks(repo.path) : null - const setupConfig = isFolderRepo(repo) ? null : getSetupConfig(repo, sharedHooks) + const sharedHooks = scopeHooksToRepoKind(repo, hasFile ? loadHooks(repo.path) : null) + const setupConfig = getSetupConfig(repo, sharedHooks) return { hasHooksFile: hasFile, hooks, @@ -61,7 +62,7 @@ export class RuntimeRepositoryHooksCommands { async checkRepoHooks(repoSelector: string, options: { background?: boolean } = {}) { const repo = await this.deps.resolveRepo(repoSelector) - if (isFolderRepo(repo)) { + if (isFolderRepo(repo) && !isRepoOnCatalogHost(repo)) { return { status: 'ok' as const, hasHooks: false, hooks: null, mayNeedUpdate: false } } const connectionId = getRepoDialableSshTargetId(repo) @@ -83,7 +84,7 @@ export class RuntimeRepositoryHooksCommands { } } const has = hasHooksFile(repo.path) - const hooks = has ? loadHooks(repo.path) : null + const hooks = scopeHooksToRepoKind(repo, has ? loadHooks(repo.path) : null) return { status: 'ok' as const, hasHooks: has, @@ -123,10 +124,6 @@ function archiveTrust( repo: Repo, sharedHooks: OrcaHooks | null ): { contentHash: string; scriptContent: string } | null { - // Folder removal never runs hooks. - if (isFolderRepo(repo)) { - return null - } const localArchive = repo.hookSettings?.scripts.archive?.trim() const policy = resolveHookCommandSourcePolicy(repo.hookSettings?.commandSourcePolicy, { hasLocalScript: Boolean(localArchive) diff --git a/src/main/runtime/rpc/core.ts b/src/main/runtime/rpc/core.ts index 729f5cf8e54..f135d2ae3f8 100644 --- a/src/main/runtime/rpc/core.ts +++ b/src/main/runtime/rpc/core.ts @@ -20,7 +20,7 @@ import type { DelegatedMobileDeviceSyncResult } from '../../../shared/delegated-mobile-device-contract' import type { OrchestrationCompatibilityEvidence } from '../../../shared/orchestration/orchestration-compatibility-evidence' -import type { OrchestrationSessionCaller } from '../orchestration/addressing/orchestration-caller-identity' +import type { OrchestrationEntryCaller } from '../orchestration/addressing/orchestration-caller-identity' import type { RpcCallerIdentity } from './rpc-caller-identity' import type { OrcadPeerDesktopsResult } from '../../../shared/orcad-peer-desktops-contract' import type { RpcBinarySender } from './rpc-binary-sender' @@ -91,6 +91,8 @@ export type RpcRequest = { params?: unknown orchestrationContractVersion?: number orchestrationRequestId?: string + // Untrusted wire input; only a paired Orca's runtime pairing admits it (orchestration-peer-caller). + orchestrationPeerRun?: unknown compatibilityInvocationId?: string orchestrationCompatibilityEvidence?: OrchestrationCompatibilityEvidence // Untrusted wire evidence; runtime-source-admission validates it. @@ -151,8 +153,8 @@ export type RpcContext = { replayedMutationReceipt?: unknown // Compare declared Run handles against request attestation. orchestrationCompatibilityEvidence?: OrchestrationCompatibilityEvidence - // Resolve the injected Orca session id once at dispatch; session identity wins. - orchestrationCaller?: OrchestrationSessionCaller + // Resolved once at dispatch from a session's environment or a paired Orca's pairing; it wins. + orchestrationCaller?: OrchestrationEntryCaller // Only the trusted compatibility router sets this; params cannot bypass Run consumer binding. legacyCoordinatorRunId?: string legacyCoordinatorAuthority?: LegacyCoordinatorAuthorityProof diff --git a/src/main/runtime/rpc/dispatcher-stream-options.ts b/src/main/runtime/rpc/dispatcher-stream-options.ts index 551b7db074d..21b77e43870 100644 --- a/src/main/runtime/rpc/dispatcher-stream-options.ts +++ b/src/main/runtime/rpc/dispatcher-stream-options.ts @@ -1,6 +1,6 @@ import type { OrcaRuntimeService } from '../orca-runtime' import { captureStructuredAgentCliSource } from '../../native-chat/structured-agent-cli-source' -import type { OrchestrationSessionCaller } from '../orchestration/addressing/orchestration-caller-identity' +import type { OrchestrationEntryCaller } from '../orchestration/addressing/orchestration-caller-identity' import { isRegistrationFencedUnsubscribe, type RpcContext, type RpcRequest } from './core' import { resolveRpcCallerIdentity } from './rpc-caller-identity' import type { RpcCallerScope } from './rpc-caller-scope' @@ -41,7 +41,7 @@ export function rpcContextFromTransport( runtime: OrcaRuntimeService, request: RpcRequest, options: RpcDispatchStreamingOptions | undefined, - orchestrationCaller: OrchestrationSessionCaller | undefined, + orchestrationCaller: OrchestrationEntryCaller | undefined, params?: unknown ): RpcContext { return { diff --git a/src/main/runtime/rpc/dispatcher.ts b/src/main/runtime/rpc/dispatcher.ts index a4daf612975..8ad691b1fda 100644 --- a/src/main/runtime/rpc/dispatcher.ts +++ b/src/main/runtime/rpc/dispatcher.ts @@ -15,7 +15,7 @@ import { withoutMethodsThisHostDoesNotServe } from './methods/terminal/session-t import { emulatorProbe, emulatorProbeError } from '../../emulator/emulator-probe' import type { OrcaRuntimeService } from '../orca-runtime' import { isDurableMutation } from '../../../shared/orchestration/orchestration-rpc-contract' -import type { OrchestrationSessionCaller } from '../orchestration/addressing/orchestration-caller-identity' +import type { OrchestrationEntryCaller } from '../orchestration/addressing/orchestration-caller-identity' import { getOrchestrationMutationExecutor, type DurableMutationInvocation, @@ -45,7 +45,7 @@ type AdmittedUnaryCall = { request: RpcRequest method: RpcMethod params: unknown - caller: OrchestrationSessionCaller | undefined + caller: OrchestrationEntryCaller | undefined } export class RpcDispatcher { @@ -231,7 +231,11 @@ export class RpcDispatcher { return desktopBrowser.result } - const compatibility = await legacyOrchestration.tryHandle(request, params, context.signal) + // A paired Orca is never a legacy caller, so its calls reach only the declared access check. + const compatibility = + caller?.kind === 'peer' + ? { handled: false as const } + : await legacyOrchestration.tryHandle(request, params, context.signal) if (compatibility.handled) { return compatibility.result } @@ -275,7 +279,7 @@ export class RpcDispatcher { effectiveParams, invoke, callerFingerprint, - context.orchestrationCaller?.orcaSessionId + context.orchestrationCaller ) if (request.method.startsWith('orchestration.')) { queueMicrotask(() => { diff --git a/src/main/runtime/rpc/methods/agent-launch/agent-launch-caller-selection.test.ts b/src/main/runtime/rpc/methods/agent-launch/agent-launch-caller-selection.test.ts index 97f3bcf9a9d..9258ac71ab0 100644 --- a/src/main/runtime/rpc/methods/agent-launch/agent-launch-caller-selection.test.ts +++ b/src/main/runtime/rpc/methods/agent-launch/agent-launch-caller-selection.test.ts @@ -24,6 +24,7 @@ vi.mock('./agent-launch-terminal-prompt', () => ({ })) const { AGENT_LAUNCH_METHODS } = await import('./agent-launch') const AGENT_LAUNCH_REPLAY = methodNamed(AGENT_LAUNCH_METHODS, 'agent.launchReplay') +const AGENT_LAUNCH = methodNamed(AGENT_LAUNCH_METHODS, 'agent.launch') const TAB_ID = '9b1deb4d-3b7d-4bad-9bdd-2b0d7b3dcb6d' const LEAF_ID = '3f2504e0-4f89-41d3-9a0c-0305e82c3301' @@ -76,3 +77,14 @@ describe('a replayed launch', () => { expect(replay.selectCreatedMobileSessionTabForClient).not.toHaveBeenCalled() }) }) + +describe('a focused chat launch from the local CLI', () => { + it('asks the host window to select the chat', async () => { + const runtime = Object.assign(runtimeStub({}), { focusLaunchedChatInHostWindow: vi.fn() }) + const params = AGENT_LAUNCH.params.parse({ ...EXISTING_LAUNCH, presentation: 'focused' }) + + await AGENT_LAUNCH.handler(params, rpcContext(runtime, {})) + + expect(runtime.focusLaunchedChatInHostWindow).toHaveBeenCalledWith('wt-7', 'sess-1') + }) +}) diff --git a/src/main/runtime/rpc/methods/agent-launch/agent-launch-caller-selection.ts b/src/main/runtime/rpc/methods/agent-launch/agent-launch-caller-selection.ts index be3595a64eb..4876683f976 100644 --- a/src/main/runtime/rpc/methods/agent-launch/agent-launch-caller-selection.ts +++ b/src/main/runtime/rpc/methods/agent-launch/agent-launch-caller-selection.ts @@ -11,6 +11,8 @@ import { parsePaneKey } from '../../../../../shared/workspace-layout/stable-pane import type { OrcaRuntimeService } from '../../../orca-runtime' import type { RpcContext } from '../../core' import { clientRendersStructuredAgent } from '../structured-sessions/structured-agent-session-policy' +import type { AgentLaunchParams } from '../../../../../shared/rpc-contract/agent-launch-params' +import { agentLaunchTabViewerRule } from './agent-launch-tab-publication' /** The paired client whose view this launch should move, or null when it moves the host's. */ export function agentLaunchCallerNavigationId( @@ -23,7 +25,7 @@ export function agentLaunchCallerNavigationId( } /** Bookkeeping, never a gate: the agent already runs, so a failure here only leaves the view as it was. */ -export function selectAgentLaunchTabForCaller( +function selectAgentLaunchTabForCaller( runtime: Pick, surface: AgentLaunchPublishedSurface, clientNavigationId: string @@ -54,6 +56,28 @@ export function selectAgentLaunchTabForCaller( } } +/** Moves the view the launch asked for: the paired caller's own, or the host window's to a focused chat. */ +export function selectLaunchedTab( + context: Pick, + surface: AgentLaunchPublishedSurface, + presentation: AgentLaunchParams['presentation'], + callerNavigationId: string | null +): void { + if (callerNavigationId !== null) { + if (presentation !== 'background') { + selectAgentLaunchTabForCaller(context.runtime, surface, callerNavigationId) + } + return + } + // A terminal's reveal selects its own tab; a chat's listing alone never moves the window (#5435). + if ( + surface.outcome.kind === 'structured' && + agentLaunchTabViewerRule(context, presentation) === 'focus-window' + ) { + context.runtime.focusLaunchedChatInHostWindow(surface.worktreeId, surface.outcome.sessionId) + } +} + /** * `agent.launch.v2` was defined when Claude and Codex were the only chats, so it vouches for those * two. Any other agent's chat needs the client to say it reads it, by the rule tabs and restart diff --git a/src/main/runtime/rpc/methods/agent-launch/agent-launch.ts b/src/main/runtime/rpc/methods/agent-launch/agent-launch.ts index 9153c60688d..ce81b25b229 100644 --- a/src/main/runtime/rpc/methods/agent-launch/agent-launch.ts +++ b/src/main/runtime/rpc/methods/agent-launch/agent-launch.ts @@ -42,7 +42,7 @@ import { import { agentLaunchCallerNavigationId, callerRendersLaunchedChat, - selectAgentLaunchTabForCaller + selectLaunchedTab } from './agent-launch-caller-selection' import { agentLaunchWorkspaceFactory } from './agent-launch-worktree-creation' import { @@ -89,9 +89,7 @@ async function runAgentLaunch( } view.early?.surfacePublished(surface) replaySafe?.recordSurface(withPlacement(surface, view)) - if (callerNavigationId !== null && view.presentation !== 'background') { - selectAgentLaunchTabForCaller(context.runtime, surface, callerNavigationId) - } + selectLaunchedTab(context, surface, view.presentation, callerNavigationId) } }) return withPlacement(result, view) diff --git a/src/main/runtime/rpc/methods/orchestration/access/orchestration-access-outcomes.test.ts b/src/main/runtime/rpc/methods/orchestration/access/orchestration-access-outcomes.test.ts index 0165250f962..694ff102ae1 100644 --- a/src/main/runtime/rpc/methods/orchestration/access/orchestration-access-outcomes.test.ts +++ b/src/main/runtime/rpc/methods/orchestration/access/orchestration-access-outcomes.test.ts @@ -223,6 +223,7 @@ const CASES = { }) }, peerMailPull: { method: 'orchestration.peerMailPull', params: () => ({ waitMs: 0 }) }, + peerRunCancel: { method: 'orchestration.peerRunCancel', params: () => ({}) }, replyHelperQuestion: { method: 'orchestration.reply', params: (from, ids) => ({ id: ids.helperQuestion, body: 'a', from }) @@ -376,6 +377,7 @@ const EXPECTED: Record & Record = { 'mail_requires_server_pairing mail_requires_server_pairing mail_requires_server_pairing mail_requires_server_pairing', peerMailPull: 'mail_requires_server_pairing mail_requires_server_pairing mail_requires_server_pairing mail_requires_server_pairing', + peerRunCancel: 'forbidden forbidden forbidden forbidden', replyHelperQuestion: 'ok consumer_fenced consumer_fenced ok', replyMail: 'ok ok ok ok', replyQuestion: 'ok consumer_fenced consumer_fenced worker_cannot_coordinate_own_run', diff --git a/src/main/runtime/rpc/methods/orchestration/access/orchestration-method-access.ts b/src/main/runtime/rpc/methods/orchestration/access/orchestration-method-access.ts index 01c58ffda86..c36f9dd7336 100644 --- a/src/main/runtime/rpc/methods/orchestration/access/orchestration-method-access.ts +++ b/src/main/runtime/rpc/methods/orchestration/access/orchestration-method-access.ts @@ -3,6 +3,11 @@ import { types } from 'node:util' import type { ZodType } from 'zod' import type { RpcContext, RpcTypedMethod, RpcTypedStreamingMethod } from '../../../core' +import { + checkPeerAccess, + refusePeerAddressClaim, + refuseServerCallFromPeerRun +} from './peer-run-access' type ParsedParams = TSchema extends ZodType ? TSchema['_output'] @@ -28,6 +33,9 @@ export type OrchestrationSubjectKind = /** A field naming who is calling, as opposed to what the call acts on. */ export type OrchestrationCallerField = 'from' | 'terminal' | 'callerTerminalHandle' +/** The pane key a caller sends with its caller field, which only its own host can fill. */ +export type OrchestrationCallerPaneField = 'terminalPaneKey' | 'senderPaneKey' + type FieldOf

= P extends object ? Extract : never export type OrchestrationAccessRuleInput

= { @@ -43,6 +51,9 @@ export type OrchestrationAccessRule = (input: OrchestrationAccessRuleInput export type OrchestrationMethodAccess = { readonly kind: OrchestrationAccessKind readonly caller?: Extract, OrchestrationCallerField> + readonly callerPane?: Extract, OrchestrationCallerPaneField> + /** The field that sends the call on to a paired server (`--on`). */ + readonly server?: Extract, 'on'> /** Every field naming something the call acts on, kept apart from the caller field. */ readonly targets: Readonly, OrchestrationSubjectKind>>> /** A read returning a collection; a narrower caller restricts its query, never its page. */ @@ -54,32 +65,55 @@ export type OrchestrationMethodAccess = { export type OrchestrationMethodAccessDeclaration = { readonly kind: OrchestrationAccessKind readonly caller?: OrchestrationCallerField + readonly callerPane?: OrchestrationCallerPaneField + readonly server?: 'on' readonly targets: Readonly>> readonly collection?: true readonly rule?: OrchestrationAccessRule } -/** The one access check: every caller on this Orca is held to the method's own rule. */ +/** The one access check: every caller on this Orca is held to the method's own rule, and a paired + * Orca also to the Run it coordinates here. Returns the params the method runs with and its grant. */ export function checkOrchestrationAccess( access: OrchestrationMethodAccess, params: P, ctx: RpcContext -): G { +): { params: P; grant: G } { + const caller = ctx.orchestrationCaller + if (caller?.kind !== 'peer') { + refusePeerAddressClaim(access.caller && fieldValue(access.caller, params)) + refusePeerAddressClaim(access.callerPane && fieldValue(access.callerPane, params)) + } + const scoped = + caller?.kind === 'peer' + ? checkPeerAccess(access, params, ctx.runtime.getOrchestrationDb(), caller) + : params + if (access.server && fieldValue(access.server, scoped) !== undefined) { + refuseServerCallFromPeerRun(ctx, declaredCaller(access.caller, scoped)) + } if (!access.rule) { // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: G defaults to undefined exactly when a method declares no rule. - return undefined as G + return { params: scoped, grant: undefined as G } + } + return { + params: scoped, + grant: access.rule({ params: scoped, ctx, caller: declaredCaller(access.caller, scoped) }) } - return access.rule({ params, ctx, caller: declaredCaller(access.caller, params) }) } function declaredCaller

( field: Extract, OrchestrationCallerField> | undefined, params: P ): string | undefined { - if (field === undefined) { - return undefined - } - const value: unknown = params[field] + return field === undefined ? undefined : fieldValue(field, params) +} + +function isRecord(value: unknown): value is Record { + return typeof value === 'object' && value !== null +} + +function fieldValue(field: string, params: unknown): string | undefined { + const value: unknown = isRecord(params) ? params[field] : undefined return typeof value === 'string' ? value : undefined } @@ -154,7 +188,8 @@ export function defineOrchestrationMethod< // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: a replay returns the receipt this handler produced when the call was accepted; a promise-returning handler's wrapper is async. return replayed.receipt as TResult } - return handler(params, ctx, checkOrchestrationAccess(access, params, ctx)) + const checked = checkOrchestrationAccess(access, params, ctx) + return handler(checked.params, ctx, checked.grant) }) } } @@ -191,8 +226,10 @@ export function defineOrchestrationStreamingMethod< handler: checked( handler, declaration, - (params: ParsedParams, ctx: RpcContext, emit: (result: unknown) => void) => - handler(params, ctx, emit, checkOrchestrationAccess(access, params, ctx)) + (params: ParsedParams, ctx: RpcContext, emit: (result: unknown) => void) => { + const checked = checkOrchestrationAccess(access, params, ctx) + return handler(checked.params, ctx, emit, checked.grant) + } ) } } diff --git a/src/main/runtime/rpc/methods/orchestration/access/peer-run-access.ts b/src/main/runtime/rpc/methods/orchestration/access/peer-run-access.ts new file mode 100644 index 00000000000..6755ba30dbb --- /dev/null +++ b/src/main/runtime/rpc/methods/orchestration/access/peer-run-access.ts @@ -0,0 +1,208 @@ +import type { OrchestrationDb } from '../../../../orchestration/db/orchestration-db' +import { + isPeerCoordinatorAddress, + type OrchestrationPeerCaller +} from '../../../../orchestration/addressing/orchestration-caller-identity' +import { OrchestrationError } from '../../../../orchestration/orchestration-error' +import { parseOrcaSessionAddress } from '../../../../../../shared/orca-session-address' +import type { RpcContext } from '../../../core' +import { resolveDispatchCreator } from '../runs/dispatch-creator' +import type { + OrchestrationMethodAccessDeclaration, + OrchestrationSubjectKind +} from './orchestration-method-access' + +const NO_EFFECTS = { effectsApplied: false } as const + +/** Kinds named by an ID: one this Orca does not have is in no Run, and the method answers it as + * not found. Addresses also name terminals and sessions that work in no Run, so they must resolve. */ +const ID_KINDS: ReadonlySet = new Set([ + 'dispatch', + 'task', + 'message', + 'gate' +]) + +/** + * A paired Orca acts only inside the Run it coordinates here: every subject a call names must be in + * that Run, and a collection read is narrowed to it before its query runs, so counts and cursors + * stay right. Calls that act on this Orca as a whole are this Orca's own. Returns the params the + * method runs with. + */ +export function checkPeerAccess

( + access: OrchestrationMethodAccessDeclaration, + params: P, + db: OrchestrationDb, + peer: OrchestrationPeerCaller +): P { + const { run_id: runId, home_label: label } = peer.peerRun + if (access.kind === 'localOnly') { + throw new OrchestrationError( + 'forbidden', + `This command acts on this server as a whole, so only this server can run it, not ${label}. No effects were applied.`, + NO_EFFECTS + ) + } + const values: Record = + params && typeof params === 'object' ? { ...(params as Record) } : {} + for (const [field, kind] of Object.entries(access.targets)) { + for (const subject of subjectsOf(values[field])) { + const subjectRunId = kind && resolveSubjectRunId(db, kind, subject, peer) + if (kind && subjectRunId !== runId && !(subjectRunId === undefined && ID_KINDS.has(kind))) { + throw new OrchestrationError( + 'forbidden', + `${subject} is not in the Run ${label} coordinates here. No effects were applied.`, + NO_EFFECTS + ) + } + } + } + if (access.collection) { + const runField = Object.entries(access.targets).find(([, kind]) => kind === 'run')?.[0] + if (!runField) { + throw new OrchestrationError( + 'forbidden', + `This list spans every Run on this server, so ${label} cannot read it. No effects were applied.`, + NO_EFFECTS + ) + } + values[runField] = runId + } + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the same params with at most the declared Run field set to a string, which every Run field accepts. + return (params && typeof params === 'object' ? values : params) as P +} + +function subjectsOf(value: unknown): string[] { + if (Array.isArray(value)) { + return value.filter((item): item is string => typeof item === 'string') + } + if (typeof value !== 'string' || value === '') { + return [] + } + if (!value.startsWith('[') && !value.startsWith('{')) { + return [value] + } + // A JSON list of IDs (`--deps`), or send's JSON payload, which names its Dispatch by `dispatchId`. + let parsed: unknown + try { + parsed = JSON.parse(value) + } catch { + return [value] + } + if (Array.isArray(parsed)) { + return subjectsOf(parsed) + } + const dispatchId = + parsed && typeof parsed === 'object' && 'dispatchId' in parsed ? parsed.dispatchId : undefined + return typeof dispatchId === 'string' ? [dispatchId] : [] +} + +/** The Run a subject belongs to on this Orca, or undefined when it names nothing here. */ +export function resolveSubjectRunId( + db: OrchestrationDb, + kind: OrchestrationSubjectKind, + subject: string, + peer: OrchestrationPeerCaller +): string | undefined { + switch (kind) { + case 'run': + return subject + case 'dispatch': + return db.getDispatchContextById(subject)?.run_id + case 'task': + return db.getTask(subject)?.run_id + case 'message': + return db.getMessageById(subject)?.run_id + case 'gate': + return db.getGate(subject)?.run_id + case 'request': + // Receipts are keyed by the pairing, so they are its own; the same paired Orca may read another of its Runs' receipts. + return peer.peerRun.run_id + case 'worker': + case 'session': + return assigneeRunId(db, subject) + case 'party': + return partyRunId(db, subject, peer) + case 'conversation': + return undefined + } +} + +function partyRunId( + db: OrchestrationDb, + address: string, + peer: OrchestrationPeerCaller +): string | undefined { + if (address === peer.address) { + return peer.peerRun.run_id + } + if (address.startsWith('run:')) { + return address.slice('run:'.length) + } + if (address.startsWith('dispatch:')) { + return db.getDispatchContextById(address.slice('dispatch:'.length))?.run_id + } + // A group spans Runs, so it never resolves into one. + return address.startsWith('@') ? undefined : assigneeRunId(db, address) +} + +/** The Run of the newest Dispatch a terminal, pane or session was given. */ +function assigneeRunId(db: OrchestrationDb, subject: string): string | undefined { + const session = parseOrcaSessionAddress(subject) ?? subject + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: SELECT of one column returns exactly that column. + const row = db.db + .prepare( + `SELECT run_id FROM dispatch_contexts + WHERE assignee_handle = ?1 OR assignee_pane_key = ?1 OR assignee_orca_session_id = ?2 + ORDER BY rowid DESC LIMIT 1` + ) + .get(subject, session) as { run_id: string } | undefined + return row?.run_id +} + +/** Only a paired Orca's own frames speak as it: its address is predictable, so no other caller may + * declare it as its handle or pane and read or bind its Run's mail. */ +export function refusePeerAddressClaim(declared: string | undefined): void { + if (isPeerCoordinatorAddress(declared)) { + throw new OrchestrationError( + 'forbidden', + `${declared} is a paired Orca's coordinator address, and only that Orca can act as it. No effects were applied.`, + NO_EFFECTS + ) + } +} + +/** Pairing is one-way: work running in a paired Orca's Run, its helpers' included, never calls on + * to another server, and neither does that Orca through this one. */ +export function refuseServerCallFromPeerRun( + ctx: RpcContext, + callerHandle: string | undefined +): void { + const db = ctx.runtime.getOrchestrationDb() + const caller = ctx.orchestrationCaller + // Most servers coordinate no paired Orca's Run, and then the creator lookup (which can refuse) is skipped. + const peerRun = + caller?.kind === 'peer' + ? caller.peerRun + : db.hasPeerRuns() + ? peerRunOfCallerWork(ctx, db, callerHandle) + : undefined + if (peerRun) { + throw new OrchestrationError( + 'forbidden', + `This work is coordinated from ${peerRun.home_label}, so it cannot use --on. Ask that coordinator instead. No effects were applied.`, + NO_EFFECTS + ) + } +} + +function peerRunOfCallerWork( + ctx: RpcContext, + db: OrchestrationDb, + callerHandle: string | undefined +): ReturnType { + const creator = resolveDispatchCreator(ctx.runtime, callerHandle, ctx.orchestrationCaller) + const dispatchId = db.resolveCreatorDispatchId(creator) + const runId = dispatchId ? db.getDispatchContextById(dispatchId)?.run_id : undefined + return runId ? db.getPeerRun(runId) : undefined +} diff --git a/src/main/runtime/rpc/methods/orchestration/caller-show.ts b/src/main/runtime/rpc/methods/orchestration/caller-show.ts index 9ee58a20e4d..5d0acbef31b 100644 --- a/src/main/runtime/rpc/methods/orchestration/caller-show.ts +++ b/src/main/runtime/rpc/methods/orchestration/caller-show.ts @@ -75,9 +75,13 @@ export const ORCHESTRATION_CALLER_METHODS = [ _params, { orchestrationCaller, orchestrationCompatibilityEvidence, runtime } ): OrchestrationCallerShowResult => ({ - caller: orchestrationCaller - ? { orcaSessionId: formatOrcaSessionAddress(orchestrationCaller.orcaSessionId), live: true } - : null, + caller: + orchestrationCaller && orchestrationCaller.kind !== 'peer' + ? { + orcaSessionId: formatOrcaSessionAddress(orchestrationCaller.orcaSessionId), + live: true + } + : null, // An Orca-launched agent's own pane and launch secret prove it is one; no hook needs to have fired. terminal: !orchestrationCaller && diff --git a/src/main/runtime/rpc/methods/orchestration/federation/federation-methods.ts b/src/main/runtime/rpc/methods/orchestration/federation/federation-methods.ts index c0e0e2f50a8..5d4c9640030 100644 --- a/src/main/runtime/rpc/methods/orchestration/federation/federation-methods.ts +++ b/src/main/runtime/rpc/methods/orchestration/federation/federation-methods.ts @@ -4,10 +4,12 @@ import { ORCHESTRATION_FEDERATION_RELAY_METHODS } from '../../../../orchestration/legacy-remote/legacy-remote' import { ORCHESTRATION_PEER_MAIL_METHODS } from './peer-mail-methods' +import { ORCHESTRATION_PEER_RUN_METHODS } from './peer-run-methods' export const ORCHESTRATION_FEDERATION_METHODS = [ ...ORCHESTRATION_FEDERATION_ATTACH_METHODS, ...ORCHESTRATION_FEDERATION_RELAY_METHODS, ...ORCHESTRATION_FEDERATION_CONTROL_METHODS, - ...ORCHESTRATION_PEER_MAIL_METHODS + ...ORCHESTRATION_PEER_MAIL_METHODS, + ...ORCHESTRATION_PEER_RUN_METHODS ] diff --git a/src/main/runtime/rpc/methods/orchestration/federation/peer-coordinator.test.ts b/src/main/runtime/rpc/methods/orchestration/federation/peer-coordinator.test.ts new file mode 100644 index 00000000000..8d06f4d4123 --- /dev/null +++ b/src/main/runtime/rpc/methods/orchestration/federation/peer-coordinator.test.ts @@ -0,0 +1,437 @@ +import { mkdtempSync, rmSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { ORCHESTRATION_CONTRACT_VERSION } from '../../../../../../shared/orchestration/orchestration-runtime-capabilities' +import { OrcaRuntimeService } from '../../../../orca-runtime' +import { OrchestrationDb } from '../../../../orchestration/db/orchestration-db' +import { generateId } from '../../../../orchestration/db/generated-id' +import { createRootDispatch } from '../../../../orchestration/db/root-dispatch-test-fixture' +import { RpcDispatcher } from '../../../dispatcher' +import type { RpcResponse } from '../../../core' +import { ORCHESTRATION_METHODS } from '../orchestration' +import { startWorker } from '../worker/workers' +import { peerCoordinatorCaller } from '../../../../orchestration/addressing/orchestration-caller-identity' + +const WORKER_PANE = 'tab_w:11111111-1111-4111-8111-111111111111' +const OTHER_PANE = 'tab_o:22222222-2222-4222-8222-222222222222' +const LOCAL_PANE = 'tab_l:33333333-3333-4333-8333-333333333333' +const PAIRED = { + authenticatedCallerFingerprint: 'fingerprint_a', + pairedDeviceId: 'device_a', + clientKind: 'runtime' as const +} + +describe('a paired Orca coordinating its Run on this server', () => { + let dir: string + let db: OrchestrationDb + let runtime: OrcaRuntimeService + let dispatcher: RpcDispatcher + let conversationId: string + let sequence = 0 + + beforeEach(() => { + dir = mkdtempSync(join(tmpdir(), 'orca-peer-coordinator-')) + db = new OrchestrationDb(join(dir, 'b.db')) + runtime = new OrcaRuntimeService(null) + const panes: Record = { + term_w: WORKER_PANE, + term_o: OTHER_PANE, + term_l: LOCAL_PANE + } + vi.spyOn(runtime, 'getTerminalPaneKey').mockImplementation((handle) => panes[handle] ?? null) + vi.spyOn(runtime, 'getLiveTerminalPaneKey').mockImplementation( + (handle) => panes[handle] ?? null + ) + runtime.setOrchestrationDb(db) + dispatcher = new RpcDispatcher({ runtime, methods: ORCHESTRATION_METHODS }) + conversationId = generateId('peerconv') + }) + + afterEach(() => { + db.close() + rmSync(dir, { recursive: true, force: true }) + vi.restoreAllMocks() + vi.useRealTimers() + }) + + function peerCall( + method: string, + params: Record, + options: { requestId?: string; conversation?: string } = {} + ): Promise { + sequence += 1 + return dispatcher.dispatch( + { + id: `peer_${sequence}`, + authToken: 'token', + method, + params, + orchestrationContractVersion: ORCHESTRATION_CONTRACT_VERSION, + orchestrationPeerRun: { + runId: 'run_home', + conversationId: options.conversation ?? conversationId, + label: 'devA' + }, + ...(options.requestId ? { orchestrationRequestId: options.requestId } : {}) + }, + PAIRED + ) + } + + function localCall(method: string, params: Record): Promise { + sequence += 1 + return dispatcher.dispatch({ + id: `local_${sequence}`, + authToken: 'token', + method, + params, + orchestrationContractVersion: ORCHESTRATION_CONTRACT_VERSION + }) + } + + function peerRunId(): string { + return db.getPeerRunForConversation(conversationId)!.run_id + } + + /** The peer's Run with one worker in it, and a local Run with another. */ + async function twoRuns() { + await peerCall('orchestration.runCurrent', {}) + const peerTask = db.createTask({ spec: 'peer work', runId: peerRunId() }) + const peerWork = createRootDispatch(db, peerTask.id, 'term_w', WORKER_PANE) + const localRun = db.createRun({ + objective: 'local', + coordinatorHandle: 'term_l', + coordinatorPaneKey: LOCAL_PANE + }) + const localTask = db.createTask({ spec: 'local work', runId: localRun.id }) + const localWork = createRootDispatch(db, localTask.id, 'term_o', OTHER_PANE) + return { peerWork, localRun, localWork } + } + + async function pull(id: string, params: Record = {}) { + const response = await dispatcher.dispatch( + { + id, + authToken: 'token', + method: 'orchestration.peerMailPull', + params, + orchestrationContractVersion: ORCHESTRATION_CONTRACT_VERSION + }, + PAIRED + ) + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the pull's result schema; a refusal reads as an empty page. + return (response.ok ? response.result : { items: [] }) as { + items: { conversationId: string; kind: string }[] + } + } + + function refused(response: RpcResponse): string | undefined { + return response.ok ? undefined : response.error.code + } + + it("writes the peer's Run when its frame arrives, before the call awaits anything", () => { + const pending = peerCall('orchestration.runCurrent', {}) + const run = db.getPeerRunForConversation(conversationId) + expect(run).toMatchObject({ home_run_id: 'run_home', home_label: 'devA', state: 'open' }) + expect(db.getRun(run!.run_id)).toBeDefined() + return pending + }) + + it('admits a peer Run only from a runtime pairing', async () => { + sequence += 1 + const response = await dispatcher.dispatch( + { + id: 'mobile', + authToken: 'token', + method: 'orchestration.runCurrent', + params: {}, + orchestrationContractVersion: ORCHESTRATION_CONTRACT_VERSION, + orchestrationPeerRun: { runId: 'run_home', conversationId, label: 'devA' } + }, + { ...PAIRED, clientKind: 'mobile' } + ) + expect(refused(response)).toBe('mail_requires_server_pairing') + expect(db.getPeerRunForConversation(conversationId)).toBeUndefined() + }) + + it('refuses commands that act on this server as a whole', async () => { + const { localRun } = await twoRuns() + expect(refused(await peerCall('orchestration.reset', { all: true }))).toBe('forbidden') + expect(refused(await peerCall('orchestration.runUse', { id: localRun.id }))).toBe('forbidden') + expect(db.getRun(localRun.id)).toBeDefined() + }) + + it("keeps another Run's worker out of reach by terminal, pane or session, but not its own", async () => { + const { peerWork, localWork } = await twoRuns() + db.db + .prepare('UPDATE dispatch_contexts SET assignee_orca_session_id = ? WHERE id = ?') + .run('33333333-3333-4333-8333-333333333334', localWork.id) + + for (const target of [ + { terminal: 'term_o' }, + { paneKey: OTHER_PANE }, + { sessionId: '33333333-3333-4333-8333-333333333334' } + ]) { + expect( + refused(await peerCall('orchestration.workerKeepOpen', { ...target, keep: true })) + ).toBe('forbidden') + } + expect(peerWork.assignee_handle).toBe('term_w') + expect( + (await peerCall('orchestration.workerKeepOpen', { terminal: 'term_w', keep: true })).ok + ).toBe(true) + }) + + it('reads only its own Run from an unqualified worker list and inbox', async () => { + const { peerWork, localRun } = await twoRuns() + db.insertMessage({ + from: 'term_w', + to: `run:${peerRunId()}`, + subject: 'mine', + runId: peerRunId() + }) + db.insertMessage({ + from: 'term_o', + to: `run:${localRun.id}`, + subject: 'theirs', + runId: localRun.id + }) + + const list = await peerCall('orchestration.workerList', { paginate: true }) + const inbox = await peerCall('orchestration.inbox', {}) + + expect(list.ok && list.result).toMatchObject({ + workers: [{ dispatchId: peerWork.id, coordinatedFrom: 'devA' }], + page: { total: 1 } + }) + expect(inbox.ok && inbox.result).toMatchObject({ messages: [{ subject: 'mine' }], count: 1 }) + }) + + it('sends and replies only inside its own Run, by any address form', async () => { + const { localRun, localWork } = await twoRuns() + const question = db.insertMessage({ + from: 'term_o', + to: `run:${localRun.id}`, + subject: 'Question', + type: 'question', + runId: localRun.id + }) + for (const to of ['term_o', `dispatch:${localWork.id}`, `run:${localRun.id}`, '@all']) { + expect(refused(await peerCall('orchestration.send', { to, subject: 'hi' }))).toBe('forbidden') + } + expect(refused(await peerCall('orchestration.reply', { id: question.id, body: 'yes' }))).toBe( + 'forbidden' + ) + }) + + it('cannot reach its former worker once that terminal coordinates local work', async () => { + await twoRuns() + db.createRun({ + objective: 'later local', + coordinatorHandle: 'term_w', + coordinatorPaneKey: WORKER_PANE + }) + expect(refused(await peerCall('orchestration.send', { to: 'term_w', subject: 'hi' }))).toBe( + 'forbidden' + ) + }) + + it('refuses a start that would place in its workspace, which it has none of here', async () => { + for (const worktree of ['current', 'new-child']) { + const response = await peerCall('orchestration.workerStart', { spec: 'work', worktree }) + expect(response.ok ? undefined : response.error).toMatchObject({ + code: 'invalid_argument', + message: expect.stringContaining('--on requires an exact remote worktree selector') + }) + } + }) + + it('follows up with a finished worker where that worker ran, though it has no workspace here', async () => { + await peerCall('orchestration.runCurrent', {}) + const peer = peerCoordinatorCaller(db.getPeerRunForConversation(conversationId)!) + const placed = startWorker( + { from: peer.address, run: peerRunId(), spec: 'One more thing' }, + { + runtime, + orchestrationMutation: undefined, + orchestrationCompatibilityEvidence: undefined, + orchestrationCaller: peer + }, + { + of: 'ctx_finished', + addressed: 'ctx_finished', + place: async () => { + throw new Error('placed where the worker ran') + } + } + ) + await expect(placed).rejects.toThrow('placed where the worker ran') + }) + + it("never answers one Run's cancel with another Run's receipt", async () => { + const other = generateId('peerconv') + await peerCall('orchestration.peerRunCancel', {}, { requestId: 'cancel:1.1' }) + const second = await peerCall( + 'orchestration.peerRunCancel', + {}, + { requestId: 'cancel:1.1', conversation: other } + ) + expect(second.ok && second.result).not.toMatchObject({ mutation: { replayed: true } }) + }) + + it('stays the only coordinator of its Run: a local terminal cannot bind it', async () => { + await twoRuns() + const response = await localCall('orchestration.runUse', { id: peerRunId(), from: 'term_l' }) + expect(refused(response)).toBe('consumer_fenced') + expect(db.getRun(peerRunId())?.coordinator_handle).toBe(`peer:${conversationId}`) + }) + + it('cannot be impersonated by a local caller declaring its address', async () => { + await twoRuns() + const address = `peer:${conversationId}` + const mail = db.insertMessage({ + from: 'term_w', + to: address, + subject: 'done', + runId: peerRunId() + }) + const check = await localCall('orchestration.check', { + terminal: address, + terminalPaneKey: address + }) + expect(refused(check)).toBe('forbidden') + expect(db.getMessageById(mail.id)?.read).toBe(0) + const send = await localCall('orchestration.send', { + from: 'term_l', + senderPaneKey: address, + to: 'term_w', + subject: 'hi' + }) + expect(refused(send)).toBe('forbidden') + }) + + it('keeps work in its Run, helpers included, from calling on to another server', async () => { + const { localRun } = await twoRuns() + const helperTask = db.createTask({ spec: 'helper', runId: peerRunId() }) + createRootDispatch(db, helperTask.id, 'term_l', LOCAL_PANE) + for (const [method, params] of [ + ['orchestration.send', { from: 'term_w', to: 'term_x', subject: 'hi', on: 'devC' }], + ['orchestration.workerStart', { from: 'term_l', spec: 'more', on: 'devC' }] + ] as const) { + const response = await localCall(method, params) + expect(response.ok ? undefined : response.error.message).toMatch(/coordinated from devA/) + } + expect(localRun.id).toBeDefined() + }) + + it('cancels over the ordinary stop and answers what it could not yet prove stopped', async () => { + await peerCall('orchestration.runCurrent', {}) + const task = db.createTask({ spec: 'peer work', runId: peerRunId() }) + const { dispatch } = db.createStartingWorkerDispatch({ + taskId: task.id, + startOptions: {}, + creator: { kind: 'system' }, + maxDepth: 5 + }) + const remaining = async (requestId: string) => { + const response = await peerCall('orchestration.peerRunCancel', {}, { requestId }) + return response.ok ? response.result : response.error + } + + // A worker still starting cannot be stopped yet, so the cancel is owed again. + expect(await remaining('cancel:1.1')).toMatchObject({ remaining: 1 }) + expect(db.getPeerRunForConversation(conversationId)?.state).toBe('closed') + db.transitionLifecycle({ entity: 'worker', id: dispatch.id, from: 'starting', to: 'failed' }) + // A lost answer's retry replays it; a new attempt runs the stops again. + expect(await remaining('cancel:1.1')).toMatchObject({ + remaining: 1, + mutation: { replayed: true } + }) + expect(await remaining('cancel:1.2')).toMatchObject({ remaining: 0 }) + }) + + it('cancels a Run it never had, and closes it', async () => { + const response = await peerCall('orchestration.peerRunCancel', {}, { requestId: 'cancel:1.1' }) + expect(response.ok && response.result).toMatchObject({ remaining: 0 }) + expect(db.getPeerRunForConversation(conversationId)?.state).toBe('closed') + // A closed Run still admits its coordinator's cancel. + const again = await peerCall('orchestration.peerRunCancel', {}, { requestId: 'cancel:1.2' }) + expect(again.ok && again.result).toMatchObject({ remaining: 0 }) + }) + + it('gives every conversation a share of each pull, so an unimportable head starves no other', async () => { + const stuck = conversationId + const other = generateId('peerconv') + await peerCall('orchestration.runCurrent', {}) + await peerCall('orchestration.runCurrent', {}, { conversation: other }) + const stuckRun = db.getPeerRunForConversation(stuck)!.run_id + const otherRun = db.getPeerRunForConversation(other)!.run_id + for (let index = 0; index < 60; index += 1) { + db.insertMessage({ + from: 'term_w', + to: `run:${stuckRun}`, + subject: `s${index}`, + runId: stuckRun + }) + } + db.insertMessage({ from: 'term_w', to: `run:${otherRun}`, subject: 'done', runId: otherRun }) + + const items = await pull('pull') + expect(items.items.filter((item) => item.conversationId === other)).toEqual([ + expect.objectContaining({ kind: 'worker_mail' }) + ]) + }) + + it('fits every pending conversation in one page when they number fewer than its size', async () => { + const conversations = Array.from({ length: 30 }, () => generateId('peerconv')) + for (const conversation of conversations) { + await peerCall('orchestration.runCurrent', {}, { conversation }) + const runId = db.getPeerRunForConversation(conversation)!.run_id + for (const subject of ['one', 'two']) { + db.insertMessage({ from: 'term_w', to: `run:${runId}`, subject, runId }) + } + } + const page = await pull('pull') + expect(new Set(page.items.map((item) => item.conversationId)).size).toBe(30) + }) + + it('rotates the page when more conversations are pending than it holds, so none starves', async () => { + const conversations = Array.from({ length: 51 }, () => generateId('peerconv')) + for (const conversation of conversations) { + await peerCall('orchestration.runCurrent', {}, { conversation }) + const runId = db.getPeerRunForConversation(conversation)!.run_id + db.insertMessage({ from: 'term_w', to: `run:${runId}`, subject: 'stuck', runId }) + } + const seen = new Set() + for (const id of ['pull_1', 'pull_2']) { + for (const item of (await pull(id)).items) { + seen.add(item.conversationId) + } + } + expect(seen.size).toBe(51) + }) + + it('wakes a waiting pull when a worker in its Run changes state', async () => { + await peerCall('orchestration.runCurrent', {}) + const task = db.createTask({ spec: 'peer work', runId: peerRunId() }) + const { dispatch } = db.createStartingWorkerDispatch({ + taskId: task.id, + startOptions: {}, + creator: { kind: 'system' }, + maxDepth: 5 + }) + db.acknowledgeFederationRelay({ + dispatchId: conversationId, + direction: 'to_home', + throughSequence: 1_000 + }) + // The pull's own deadline never passes, so only the state change can answer it. + vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] }) + const waiting = pull('pull', { waitMs: 20_000 }) + await new Promise((resolve) => setImmediate(resolve)) + db.transitionLifecycle({ entity: 'worker', id: dispatch.id, from: 'starting', to: 'ready' }) + + expect((await waiting).items).toEqual([expect.objectContaining({ kind: 'worker_state' })]) + }) +}) diff --git a/src/main/runtime/rpc/methods/orchestration/federation/peer-mail-methods.ts b/src/main/runtime/rpc/methods/orchestration/federation/peer-mail-methods.ts index 6d79a0577dd..7c7b5df0a94 100644 --- a/src/main/runtime/rpc/methods/orchestration/federation/peer-mail-methods.ts +++ b/src/main/runtime/rpc/methods/orchestration/federation/peer-mail-methods.ts @@ -35,17 +35,24 @@ function requireRuntimePairing( return ctx.authenticatedCallerFingerprint } +// Where each pairing's next page starts, per database, when more conversations are pending than a page holds. +const pullRotations = new WeakMap>() + +/** Every conversation with pending items gets an equal share of the page, so an item the paired Orca + * cannot import yet, which stays at its conversation's head, never starves another conversation. */ function pendingReplies(db: OrchestrationDb, peerFingerprint: string): FederationRelayItemRow[] { - const items: FederationRelayItemRow[] = [] - for (const conversationId of db.listPeerConversationIds(peerFingerprint)) { - if (items.length >= PULL_PAGE_SIZE) { - break - } - items.push( - ...db.listPendingFederationRelay(conversationId, 'to_home', PULL_PAGE_SIZE - items.length) - ) - } - return items + const pending = db + .listPeerConversationIds(peerFingerprint) + .filter((id) => db.listPendingFederationRelay(id, 'to_home', 1).length > 0) + const share = Math.max(1, Math.floor(PULL_PAGE_SIZE / pending.length)) + const pullRotation = pullRotations.get(db.db) ?? new Map() + pullRotations.set(db.db, pullRotation) + const start = pending.length > PULL_PAGE_SIZE ? (pullRotation.get(peerFingerprint) ?? 0) : 0 + pullRotation.set(peerFingerprint, (start + PULL_PAGE_SIZE) % Math.max(1, pending.length)) + return [...pending.slice(start), ...pending.slice(0, start)] + .slice(0, PULL_PAGE_SIZE) + .flatMap((id) => db.listPendingFederationRelay(id, 'to_home', share)) + .slice(0, PULL_PAGE_SIZE) } export const ORCHESTRATION_PEER_MAIL_METHODS = [ @@ -154,8 +161,10 @@ export const ORCHESTRATION_PEER_MAIL_METHODS = [ const db = ctx.runtime.getOrchestrationDb() let items = pendingReplies(db, peerFingerprint) const waitMs = Math.min(Math.max(params.waitMs ?? 0, 0), MAX_PULL_WAIT_MS) - if (items.length === 0 && waitMs > 0) { - await waitForPeerMail(db, waitMs, ctx.signal) + const deadline = Date.now() + waitMs + // A wake is any queued change on this Orca, so one that queued nothing for this peer waits on. + while (items.length === 0 && Date.now() < deadline && !ctx.signal?.aborted) { + await waitForPeerMail(db.db, deadline - Date.now(), ctx.signal) items = pendingReplies(ctx.runtime.getOrchestrationDb(), peerFingerprint) } return { @@ -163,6 +172,7 @@ export const ORCHESTRATION_PEER_MAIL_METHODS = [ conversationId: item.dispatch_id, sequence: item.sequence, messageId: item.message_id, + kind: item.kind, payload: item.payload })) } diff --git a/src/main/runtime/rpc/methods/orchestration/federation/peer-mail.test.ts b/src/main/runtime/rpc/methods/orchestration/federation/peer-mail.test.ts index c624b2989fa..3ee7865d728 100644 --- a/src/main/runtime/rpc/methods/orchestration/federation/peer-mail.test.ts +++ b/src/main/runtime/rpc/methods/orchestration/federation/peer-mail.test.ts @@ -385,7 +385,7 @@ describe('agent mail between paired Orca servers', () => { a.db.resetMessages() // The ack was lost: the server serves the stored reply again. b.db['db'].prepare('UPDATE federation_relay_items SET acked_at = NULL').run() - notifyPeerMailQueued(b.db) + notifyPeerMailQueued(b.db.db) await vi.waitFor(() => expect(b.db.listPendingFederationRelay(conversationId!, 'to_home')).toEqual([]) diff --git a/src/main/runtime/rpc/methods/orchestration/federation/peer-run-methods.ts b/src/main/runtime/rpc/methods/orchestration/federation/peer-run-methods.ts new file mode 100644 index 00000000000..a64ce31c976 --- /dev/null +++ b/src/main/runtime/rpc/methods/orchestration/federation/peer-run-methods.ts @@ -0,0 +1,54 @@ +import { defineOrchestrationMethod } from '../access/orchestration-method-access' +import { OrchestrationError } from '../../../../orchestration/orchestration-error' +import type { OrchestrationDb } from '../../../../orchestration/db/orchestration-db' +import { WORKER_SETTLED_STATES } from '../../../../orchestration/terminal-authority/release/worker-terminal-ownership' +import { + PeerRunCancelParams, + type PeerRunCancelResult +} from '../../../../../../shared/orchestration/remote-owned-wire' +import type { z } from 'zod' +import { stopWorkerAndHelpers } from '../worker/worker-stop' + +export const ORCHESTRATION_PEER_RUN_METHODS = [ + defineOrchestrationMethod({ + name: 'orchestration.peerRunCancel', + access: { kind: 'writes', targets: {} }, + permission: 'workspace', + params: PeerRunCancelParams, + /** The paired Orca reset its Run: close it here, then run the ordinary stop on each live worker. */ + handler: async (_params, { runtime, orchestrationCaller }) => { + if (orchestrationCaller?.kind !== 'peer') { + throw new OrchestrationError( + 'forbidden', + 'Only the paired Orca that coordinates a Run cancels it. No effects were applied.', + { effectsApplied: false } + ) + } + const db = runtime.getOrchestrationDb() + const runId = orchestrationCaller.peerRun.run_id + // Committed before any stop, so nothing more starts in it while the stops run. + db.closePeerRun(runId) + for (const dispatchId of liveWorkerDispatchIds(db, runId)) { + // Each stop's own outcome stays on its Dispatch; the count below is the answer. + await stopWorkerAndHelpers(runtime, dispatchId, undefined).catch(() => undefined) + } + const result: z.infer = { + remaining: liveWorkerDispatchIds(db, runId).length + } + return result + } + }) +] + +/** Workers in the Run not yet proven settled; a Run this Orca never had work in has none. */ +function liveWorkerDispatchIds(db: OrchestrationDb, runId: string): string[] { + const settled = WORKER_SETTLED_STATES.map(() => '?').join(', ') + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: SELECT of one column returns exactly that column. + const rows = db.db + .prepare( + `SELECT d.id FROM dispatch_contexts d JOIN worker_dispatches w ON w.dispatch_id = d.id + WHERE d.run_id = ? AND w.state NOT IN (${settled}) ORDER BY d.rowid` + ) + .all(runId, ...WORKER_SETTLED_STATES) as { id: string }[] + return rows.map((row) => row.id) +} diff --git a/src/main/runtime/rpc/methods/orchestration/messaging/check-methods.ts b/src/main/runtime/rpc/methods/orchestration/messaging/check-methods.ts index cc9251aeff5..11af8dd3c25 100644 --- a/src/main/runtime/rpc/methods/orchestration/messaging/check-methods.ts +++ b/src/main/runtime/rpc/methods/orchestration/messaging/check-methods.ts @@ -22,6 +22,7 @@ export const ORCHESTRATION_CHECK_METHODS = [ access: { kind: 'writes', caller: 'terminal', + callerPane: 'terminalPaneKey', targets: { run: 'run', ack: 'message' }, collection: true }, diff --git a/src/main/runtime/rpc/methods/orchestration/messaging/check-run-pending-mail.ts b/src/main/runtime/rpc/methods/orchestration/messaging/check-run-pending-mail.ts index 2b90558c392..31ec54fb285 100644 --- a/src/main/runtime/rpc/methods/orchestration/messaging/check-run-pending-mail.ts +++ b/src/main/runtime/rpc/methods/orchestration/messaging/check-run-pending-mail.ts @@ -7,7 +7,7 @@ import { acknowledgedOnlyReceipt, handsOverBatch } from './mailbox-message-recei import { currentDispatchAssigneeRun } from './recipient-routing' import { callerHoldsDispatchPane, dispatchFenced } from './dispatch-mailbox-fence' import { orchestrationCallerIdentity } from '../runs/run-scope' -import type { OrchestrationSessionCaller } from '../../../../orchestration/addressing/orchestration-caller-identity' +import type { OrchestrationEntryCaller } from '../../../../orchestration/addressing/orchestration-caller-identity' import type { CheckParams } from '../../../../../../shared/rpc-contract/orchestration-params' import type { z } from 'zod' @@ -18,7 +18,7 @@ export async function checkRunPendingMail(args: { run: RunRow handle: string paneKey: string | undefined - callerSession: OrchestrationSessionCaller | undefined + callerSession: OrchestrationEntryCaller | undefined typeFilter: MessageType[] | undefined signal: AbortSignal | undefined revalidateConsumer: () => void diff --git a/src/main/runtime/rpc/methods/orchestration/messaging/check-run.ts b/src/main/runtime/rpc/methods/orchestration/messaging/check-run.ts index 49ef6a58dbe..b52ac709c7e 100644 --- a/src/main/runtime/rpc/methods/orchestration/messaging/check-run.ts +++ b/src/main/runtime/rpc/methods/orchestration/messaging/check-run.ts @@ -11,7 +11,7 @@ import { routeAllMailboxPages } from './mailbox-page-routing' import { resolveRunScope } from '../runs/run-scope' import type { CheckParams } from '../../../../../../shared/rpc-contract/orchestration-params' import type { z } from 'zod' -import type { OrchestrationSessionCaller } from '../../../../orchestration/addressing/orchestration-caller-identity' +import type { OrchestrationEntryCaller } from '../../../../orchestration/addressing/orchestration-caller-identity' import { checkRunPendingMail } from './check-run-pending-mail' import { FEDERATION_RELAY_WAIT_REARM_MS } from '../../../../orchestration/federation/relay/federation-relay-scheduler' @@ -23,7 +23,7 @@ export async function checkRunMailbox(args: { db: OrchestrationDb handle: string paneKey: string | undefined - callerSession: OrchestrationSessionCaller | undefined + callerSession: OrchestrationEntryCaller | undefined typeFilter: MessageType[] | undefined signal: AbortSignal | undefined legacyCoordinatorRunId: string | undefined diff --git a/src/main/runtime/rpc/methods/orchestration/messaging/helper-question-answerer.ts b/src/main/runtime/rpc/methods/orchestration/messaging/helper-question-answerer.ts index d38486eb25d..944a3dfcb14 100644 --- a/src/main/runtime/rpc/methods/orchestration/messaging/helper-question-answerer.ts +++ b/src/main/runtime/rpc/methods/orchestration/messaging/helper-question-answerer.ts @@ -1,5 +1,5 @@ import type { OrchestrationCompatibilityEvidence } from '../../../../../../shared/orchestration/orchestration-compatibility-evidence' -import type { OrchestrationSessionCaller } from '../../../../orchestration/addressing/orchestration-caller-identity' +import type { OrchestrationEntryCaller } from '../../../../orchestration/addressing/orchestration-caller-identity' import type { MessageRow } from '../../../../orchestration/db/orchestration-records' import type { OrcaRuntimeService } from '../../../../orca-runtime' import { assertCallerHandleMatchesEvidence, orchestrationCallerIdentity } from '../runs/run-scope' @@ -10,7 +10,7 @@ export function helperQuestionAnswerer( args: { question: MessageRow from: string | undefined - session: OrchestrationSessionCaller | undefined + session: OrchestrationEntryCaller | undefined evidence: OrchestrationCompatibilityEvidence | undefined } ): { dispatchId: string; consumerGeneration: number } | undefined { diff --git a/src/main/runtime/rpc/methods/orchestration/messaging/message-methods.ts b/src/main/runtime/rpc/methods/orchestration/messaging/message-methods.ts index 027c7f424e3..fff196ea676 100644 --- a/src/main/runtime/rpc/methods/orchestration/messaging/message-methods.ts +++ b/src/main/runtime/rpc/methods/orchestration/messaging/message-methods.ts @@ -18,16 +18,18 @@ export const ORCHESTRATION_MESSAGE_METHODS = [ name: 'orchestration.inbox', permission: 'workspace', params: InboxParams, - access: { kind: 'reads', targets: { terminal: 'party' }, collection: true }, + access: { kind: 'reads', targets: { terminal: 'party', run: 'run' }, collection: true }, handler: (params, { runtime }) => { const db = runtime.getOrchestrationDb() // Return empty for stale/unknown handles because historical mail outlives handle deletion (design doc §3.3). const messages = params.terminal ? db.getAllMessagesForHandle( resolveOrchestrationParty(params.terminal, db).address, - params.limit + params.limit, + undefined, + params.run ) - : db.getInbox(params.limit) + : db.getInbox(params.limit, params.run) return { messages: messages.map(({ answer_sender_snapshot: _answer, ...message }) => message), count: messages.length diff --git a/src/main/runtime/rpc/methods/orchestration/messaging/peer-mail-reply.ts b/src/main/runtime/rpc/methods/orchestration/messaging/peer-mail-reply.ts index e78a9abda6a..f23c85fdc82 100644 --- a/src/main/runtime/rpc/methods/orchestration/messaging/peer-mail-reply.ts +++ b/src/main/runtime/rpc/methods/orchestration/messaging/peer-mail-reply.ts @@ -1,5 +1,5 @@ import type { OrcaRuntimeService } from '../../../../orca-runtime' -import type { OrchestrationSessionCaller } from '../../../../orchestration/addressing/orchestration-caller-identity' +import type { OrchestrationEntryCaller } from '../../../../orchestration/addressing/orchestration-caller-identity' import type { PeerMailMessageRow } from '../../../../orchestration/db/federation/peer-mail-store' import type { MessageRow } from '../../../../orchestration/db/orchestration-records' import { OrchestrationError } from '../../../../orchestration/orchestration-error' @@ -21,7 +21,7 @@ export async function replyOverPeerMail(args: { original: MessageRow route: PeerMailMessageRow params: { body: string; from?: string; on?: string } - orchestrationCaller: OrchestrationSessionCaller | undefined + orchestrationCaller: OrchestrationEntryCaller | undefined orchestrationMutation: { callerFingerprint: string; requestId: string } | undefined recordMutationReceipt: ((receipt: unknown) => void) | undefined }): Promise { @@ -67,7 +67,7 @@ export async function replyOverPeerMail(args: { return recordReceiptBeforeNudge( args.recordMutationReceipt, { message: { id, subject }, to: original.from_handle }, - () => notifyPeerMailQueued(db), + () => notifyPeerMailQueued(db.db), { kind: 'messages', targets: [] } ) } diff --git a/src/main/runtime/rpc/methods/orchestration/messaging/peer-mail-send.ts b/src/main/runtime/rpc/methods/orchestration/messaging/peer-mail-send.ts index a9fa69344b3..a18969d81c4 100644 --- a/src/main/runtime/rpc/methods/orchestration/messaging/peer-mail-send.ts +++ b/src/main/runtime/rpc/methods/orchestration/messaging/peer-mail-send.ts @@ -1,6 +1,6 @@ import type { z } from 'zod' import type { OrcaRuntimeService } from '../../../../orca-runtime' -import type { OrchestrationSessionCaller } from '../../../../orchestration/addressing/orchestration-caller-identity' +import type { OrchestrationEntryCaller } from '../../../../orchestration/addressing/orchestration-caller-identity' import type { OrchestrationCompatibilityCallerAuthority } from '../../../../orchestration/terminal-authority/orchestration-compatibility-authority' import { OrchestrationError } from '../../../../orchestration/orchestration-error' import { @@ -20,7 +20,7 @@ const NOTHING_SENT = { effectsApplied: false } as const export function peerMailLocalCaller(args: { runtime: OrcaRuntimeService from: string | undefined - orchestrationCaller: OrchestrationSessionCaller | undefined + orchestrationCaller: OrchestrationEntryCaller | undefined attestedCaller: OrchestrationCompatibilityCallerAuthority | undefined }): { address: string; paneKey: string | null } { if (args.orchestrationCaller) { @@ -51,7 +51,7 @@ export function peerMailLocalCaller(args: { export async function sendPeerMail(args: { params: z.infer & { on: string } runtime: OrcaRuntimeService - orchestrationCaller: OrchestrationSessionCaller | undefined + orchestrationCaller: OrchestrationEntryCaller | undefined attestedCaller: OrchestrationCompatibilityCallerAuthority | undefined orchestrationMutation: { callerFingerprint: string; requestId: string } | undefined recordMutationReceipt: ((receipt: unknown) => void) | undefined diff --git a/src/main/runtime/rpc/methods/orchestration/messaging/reply-method.ts b/src/main/runtime/rpc/methods/orchestration/messaging/reply-method.ts index 94e0996ac2d..19d52a02e68 100644 --- a/src/main/runtime/rpc/methods/orchestration/messaging/reply-method.ts +++ b/src/main/runtime/rpc/methods/orchestration/messaging/reply-method.ts @@ -29,6 +29,7 @@ export const ORCHESTRATION_REPLY_METHOD = defineOrchestrationMethod({ access: { kind: 'writes', caller: 'from', + server: 'on', targets: { id: 'message', run: 'run' }, rule: replyAccess }, diff --git a/src/main/runtime/rpc/methods/orchestration/messaging/send-methods.ts b/src/main/runtime/rpc/methods/orchestration/messaging/send-methods.ts index 1d9c485e919..a0ad726c0cd 100644 --- a/src/main/runtime/rpc/methods/orchestration/messaging/send-methods.ts +++ b/src/main/runtime/rpc/methods/orchestration/messaging/send-methods.ts @@ -39,6 +39,8 @@ export const ORCHESTRATION_SEND_METHODS = [ access: { kind: 'writes', caller: 'from', + callerPane: 'senderPaneKey', + server: 'on', targets: { to: 'party', threadId: 'message', run: 'run', payload: 'dispatch' } }, permission: 'workspace', @@ -172,6 +174,17 @@ export const ORCHESTRATION_SEND_METHODS = [ if (!recipient.ok) { throw new OrchestrationError(recipient.code, recipient.message) } + // A paired Orca's former worker may since have taken up local work; it is no longer its to reach. + if ( + orchestrationCaller?.kind === 'peer' && + recipient.runId !== orchestrationCaller.peerRun.run_id + ) { + throw new OrchestrationError( + 'forbidden', + `${params.to} now works outside the Run ${orchestrationCaller.peerRun.home_label} coordinates here. No effects were applied.`, + { effectsApplied: false } + ) + } to = recipient.to messageRunId = recipient.runId if (recipient.warning) { diff --git a/src/main/runtime/rpc/methods/orchestration/messaging/send-point-to-point.ts b/src/main/runtime/rpc/methods/orchestration/messaging/send-point-to-point.ts index 56273cfec5a..85752b5aa3d 100644 --- a/src/main/runtime/rpc/methods/orchestration/messaging/send-point-to-point.ts +++ b/src/main/runtime/rpc/methods/orchestration/messaging/send-point-to-point.ts @@ -8,6 +8,7 @@ import { reconcileLifecycleMessage } from '../../../../orchestration/workers/lif import { bindCoordinatorMutationPayload } from '../../../../orchestration/workers/reports/dispatch-message-binding' import { isDispatchMutationMessageType } from '../../../../../../shared/rpc-contract/orchestration-params' import { parseMessageTaskId } from './message-payload' +import { isDispatchAssignee } from '../../../../orchestration/db/dispatch-context/dispatch-lookup' import type { SendParams } from './send-params' import { legacyWorkerDeliveryContract } from '../routing' import { exposeMessage } from './mailbox-message-receipt' @@ -74,6 +75,8 @@ export function sendPointToPointMessage(args: { ? bindCoordinatorMutationPayload(messageType, params.payload, dispatch.id) : params.payload, senderPaneKey, + senderDispatchId: + dispatch && isDispatchAssignee(dispatch, from, senderPaneKey) ? dispatch.id : undefined, runId: messageRunId, deliveryContract: legacyWorkerDeliveryContract( runtime, diff --git a/src/main/runtime/rpc/methods/orchestration/messaging/settled-worker-follow-through.ts b/src/main/runtime/rpc/methods/orchestration/messaging/settled-worker-follow-through.ts index fc223637a6a..3aec8ace463 100644 --- a/src/main/runtime/rpc/methods/orchestration/messaging/settled-worker-follow-through.ts +++ b/src/main/runtime/rpc/methods/orchestration/messaging/settled-worker-follow-through.ts @@ -10,7 +10,11 @@ import { receivesMailWhole } from '../../../../orchestration/db/dispatch-context/worker-follow-up-lineage' import { FOLLOW_UP_MESSAGE_TYPES } from '../../../../orchestration/db/dispatch-context/worker-follow-up-plan' -import type { OrchestrationSessionCaller } from '../../../../orchestration/addressing/orchestration-caller-identity' +import { + peerCoordinatorAddress, + peerCoordinatorCaller, + type OrchestrationEntryCaller +} from '../../../../orchestration/addressing/orchestration-caller-identity' import { resolveOrcaSessionParty } from '../../../../orchestration/addressing/orchestration-party' import { readStructuredAgentSessionRecord } from '../../../../orchestration/terminal-authority/structured-sessions/structured-worker-authority' import { createHash } from 'node:crypto' @@ -111,7 +115,7 @@ async function continueUnreadMail( outcome = plan?.kind === 'start' ? await startWorkerFollowUp({ - ctx: { runtime, orchestrationCaller: senderSession(db, first.from_handle) }, + ctx: { runtime, orchestrationCaller: senderCaller(db, first) }, db, plan, from: first.from_handle, @@ -304,7 +308,16 @@ export function continueAllUnreadWorkerMail( } } -function senderSession(db: OrchestrationDb, from: string): OrchestrationSessionCaller | undefined { +/** The sender continues as itself: a session as its session, a paired Orca as the coordinator of its Run. */ +function senderCaller( + db: OrchestrationDb, + message: { from_handle: string; run_id: string } +): OrchestrationEntryCaller | undefined { + const peerRun = db.getPeerRun(message.run_id) + if (peerRun && message.from_handle === peerCoordinatorAddress(peerRun.conversation_id)) { + return peerCoordinatorCaller(peerRun) + } + const from = message.from_handle const sessionId = parseOrcaSessionAddress(from) const record = sessionId ? readStructuredAgentSessionRecord(sessionId) : null return sessionId && record diff --git a/src/main/runtime/rpc/methods/orchestration/orchestration-caller-workspace.ts b/src/main/runtime/rpc/methods/orchestration/orchestration-caller-workspace.ts index d22964215f7..ce78dca6226 100644 --- a/src/main/runtime/rpc/methods/orchestration/orchestration-caller-workspace.ts +++ b/src/main/runtime/rpc/methods/orchestration/orchestration-caller-workspace.ts @@ -2,14 +2,18 @@ * showTerminal requires a real PTY; fabricating its writable fields would break terminal verbs for chat workers. */ import type { OrcaRuntimeService } from '../../../orca-runtime' -import type { OrchestrationSessionCaller } from '../../../orchestration/addressing/orchestration-caller-identity' +import type { OrchestrationEntryCaller } from '../../../orchestration/addressing/orchestration-caller-identity' import { isStructuredWorkerHandle } from '../../../../../shared/orchestration/workers/structured-worker-handle' export async function resolveDispatchCallerWorktreeId( runtime: Pick, callerHandle: string, - callerSession: OrchestrationSessionCaller | undefined + callerSession: OrchestrationEntryCaller | undefined ): Promise { + // A paired Orca has no workspace here, so `current` and `new-child` refuse as for an unmanaged one. + if (callerSession?.kind === 'peer') { + return PEER_COORDINATOR_HAS_NO_WORKSPACE + } // A session caller's workspace is on its record, whichever owner (chat or terminal) holds it. if (callerSession) { return callerSession.workspaceId @@ -22,3 +26,5 @@ export async function resolveDispatchCallerWorktreeId( } return (await runtime.showTerminal(callerHandle)).worktreeId } + +const PEER_COORDINATOR_HAS_NO_WORKSPACE = 'peer-coordinator-has-no-workspace' diff --git a/src/main/runtime/rpc/methods/orchestration/runs/dispatch-creator.ts b/src/main/runtime/rpc/methods/orchestration/runs/dispatch-creator.ts index c43da58338e..fb415f5b858 100644 --- a/src/main/runtime/rpc/methods/orchestration/runs/dispatch-creator.ts +++ b/src/main/runtime/rpc/methods/orchestration/runs/dispatch-creator.ts @@ -1,5 +1,5 @@ import type { DispatchCreator } from '../../../../orchestration/db/dispatch-depth' -import type { OrchestrationSessionCaller } from '../../../../orchestration/addressing/orchestration-caller-identity' +import type { OrchestrationEntryCaller } from '../../../../orchestration/addressing/orchestration-caller-identity' import type { OrcaRuntimeService } from '../../../../orca-runtime' import { orchestrationCallerIdentity } from './run-scope' @@ -7,7 +7,7 @@ import { orchestrationCallerIdentity } from './run-scope' export function resolveDispatchCreator( runtime: OrcaRuntimeService, callerHandle: string | undefined, - callerSession: OrchestrationSessionCaller | undefined + callerSession: OrchestrationEntryCaller | undefined ): DispatchCreator { if (!callerHandle) { // No declared caller resolves no parent; retain legacy Run-binding depth zero. diff --git a/src/main/runtime/rpc/methods/orchestration/runs/run-scope.ts b/src/main/runtime/rpc/methods/orchestration/runs/run-scope.ts index a5993600973..5d59eb85261 100644 --- a/src/main/runtime/rpc/methods/orchestration/runs/run-scope.ts +++ b/src/main/runtime/rpc/methods/orchestration/runs/run-scope.ts @@ -8,7 +8,7 @@ import { hasRunBindingKey, mailboxAddressOf, runCoordinatorKey, - type OrchestrationSessionCaller + type OrchestrationEntryCaller } from '../../../../orchestration/addressing/orchestration-caller-identity' import type { OrchestrationPartyIdentity as OrchestrationCallerIdentity } from '../../../../../../shared/orchestration/mailbox/orchestration-party-identity' import { resolveDeclaredCallerParty } from '../../../../orchestration/addressing/orchestration-party' @@ -24,7 +24,7 @@ export type RunScopeParams = { callerTerminalHandle?: string callerPaneKey?: string /** Resolved at the dispatch entry; when set it is the caller, whatever the declared handle. */ - callerSession: OrchestrationSessionCaller | undefined + callerSession: OrchestrationEntryCaller | undefined requireCurrentConsumer: boolean legacyCoordinatorRunId?: string // Attest user-supplied handles against this trusted handle. @@ -56,7 +56,7 @@ export function orchestrationCallerIdentity( caller: { handle: string paneKey: string | null | undefined - session: OrchestrationSessionCaller | undefined + session: OrchestrationEntryCaller | undefined } ): OrchestrationCallerIdentity { if (caller.session) { @@ -70,7 +70,7 @@ export type OrchestrationCallerParams = { callerTerminalHandle: string callerEvidence?: OrchestrationCompatibilityEvidence callerAuthority?: OrchestrationCompatibilityCallerAuthority - callerSession: OrchestrationSessionCaller | undefined + callerSession: OrchestrationEntryCaller | undefined /** Preserve legacy callers that treated a missing pane as an ordinary fence. */ requireStablePane?: boolean /** Only skip attestation when the caller does it after the legacy-takeover check (run-use); omitting that reopens impersonation. */ diff --git a/src/main/runtime/rpc/methods/orchestration/worker/deliver-worker-dispatch-preamble.ts b/src/main/runtime/rpc/methods/orchestration/worker/deliver-worker-dispatch-preamble.ts index da0075d287c..dc79fd4eef1 100644 --- a/src/main/runtime/rpc/methods/orchestration/worker/deliver-worker-dispatch-preamble.ts +++ b/src/main/runtime/rpc/methods/orchestration/worker/deliver-worker-dispatch-preamble.ts @@ -60,6 +60,7 @@ export async function deliverWorkerDispatchPreamble(args: { dispatchId: args.dispatchId, taskSpec: args.taskSpec, coordinatorHandle: orcaSessionIdOrHandle(args.coordinatorHandle, args.db), + coordinatedFrom: args.db.getPeerRun(args.runId)?.home_label, // Its mailbox stays keyed by the handle; its commands name its Orca session ID, which binds to it. workerHandle: structuredSession && isOrcaSessionId(structuredSession.identity.sessionId) diff --git a/src/main/runtime/rpc/methods/orchestration/worker/explicit-worker-terminal-validation.ts b/src/main/runtime/rpc/methods/orchestration/worker/explicit-worker-terminal-validation.ts index a2d53e01de2..6adb724d6f9 100644 --- a/src/main/runtime/rpc/methods/orchestration/worker/explicit-worker-terminal-validation.ts +++ b/src/main/runtime/rpc/methods/orchestration/worker/explicit-worker-terminal-validation.ts @@ -1,5 +1,6 @@ import type { OrcaRuntimeService } from '../../../../orca-runtime' import { OrchestrationError } from '../../../../orchestration/orchestration-error' +import { isPeerCaller } from '../../../../orchestration/addressing/orchestration-caller-identity' import { isStructuredWorkerHandle } from '../../../../../../shared/orchestration/workers/structured-worker-handle' import type { OrchestrationPartyIdentity as OrchestrationCallerIdentity, @@ -27,8 +28,9 @@ export async function assertExplicitWorkerTerminalUsable(args: { const targetPane = runtime.getTerminalPaneKey(terminal) const callerPane = coordinator?.paneKey ?? runtime.getTerminalPaneKey(from) // Structured coordinators may have no showable terminal; compare their handle/pane identity, or session address for handle-less callers. + // A paired Orca's coordinator has no terminal here either; its address is its handle. const coordinatorHandle = - coordinator?.terminalHandle === null + coordinator?.terminalHandle === null || isPeerCaller(coordinator) ? coordinator.address : isStructuredWorkerHandle(from) ? from diff --git a/src/main/runtime/rpc/methods/orchestration/worker/local-worker-start-dispatch.ts b/src/main/runtime/rpc/methods/orchestration/worker/local-worker-start-dispatch.ts index 5d26db76cb2..50ee585d311 100644 --- a/src/main/runtime/rpc/methods/orchestration/worker/local-worker-start-dispatch.ts +++ b/src/main/runtime/rpc/methods/orchestration/worker/local-worker-start-dispatch.ts @@ -64,6 +64,7 @@ export function createLocalWorkerStartDispatch( requiredCreatorDispatchId: helperCreator?.id, taskId: existingTask?.id, taskSpec: params.spec, + adoptTaskId: params.adoptTaskId, taskTitle: params.taskTitle, taskDeps, // A helper's Task sits under its creator's Task, so the Run's Task tree shows who started it. diff --git a/src/main/runtime/rpc/methods/orchestration/worker/local-worker-start.ts b/src/main/runtime/rpc/methods/orchestration/worker/local-worker-start.ts index 1af01cf6710..6d7446b10f6 100644 --- a/src/main/runtime/rpc/methods/orchestration/worker/local-worker-start.ts +++ b/src/main/runtime/rpc/methods/orchestration/worker/local-worker-start.ts @@ -11,7 +11,7 @@ import type { RunRow, TaskRow } from '../../../../orchestration/db/orchestration-records' -import type { OrchestrationSessionCaller } from '../../../../orchestration/addressing/orchestration-caller-identity' +import type { OrchestrationEntryCaller } from '../../../../orchestration/addressing/orchestration-caller-identity' import type { OrchestrationPartyIdentity as OrchestrationCallerIdentity } from '../../../../../../shared/orchestration/mailbox/orchestration-party-identity' import { resolveDispatchCallerWorktreeId } from '../orchestration-caller-workspace' import { resolveWorkerStartModeOnHost } from '../structured-workers/orchestration-worker-start-mode' @@ -48,7 +48,7 @@ export async function startLocalWorker(args: { bindRun: () => RunRow taskDeps: string[] | undefined coordinator: OrchestrationCallerIdentity | null - callerSession?: OrchestrationSessionCaller + callerSession?: OrchestrationEntryCaller existingTask?: TaskRow orchestrationMutation?: WorkerStartMutation /** Settings-driven; the executing host still gets to refuse below. */ diff --git a/src/main/runtime/rpc/methods/orchestration/worker/worker-list-method.ts b/src/main/runtime/rpc/methods/orchestration/worker/worker-list-method.ts index b506a17124f..c8083a27648 100644 --- a/src/main/runtime/rpc/methods/orchestration/worker/worker-list-method.ts +++ b/src/main/runtime/rpc/methods/orchestration/worker/worker-list-method.ts @@ -251,6 +251,7 @@ async function projectWorkerListPageWithFilteredSnapshot( dispatchStatus: row.dispatchStatus, agentTerminalHandle: row.agentTerminalHandle, terminalState: row.terminalState, + coordinatedFrom: row.coordinatedFrom, resource: row.resource ? exposeWorkerTerminalResource(row.resource) : null, // Emit only derived ownership; resource identity/release fields already live on the row. projection: { diff --git a/src/main/runtime/rpc/methods/orchestration/worker/worker-start-authority.ts b/src/main/runtime/rpc/methods/orchestration/worker/worker-start-authority.ts index 3df8bd1e22f..d54f92f4c16 100644 --- a/src/main/runtime/rpc/methods/orchestration/worker/worker-start-authority.ts +++ b/src/main/runtime/rpc/methods/orchestration/worker/worker-start-authority.ts @@ -4,7 +4,7 @@ import { liveDispatchCreatorEvaluation } from '../../../../orchestration/db/disp import { selectExistingWorkerStartRun } from './worker-start-run-authority' import type { OrchestrationDb } from '../../../../orchestration/db/orchestration-db' import { OrchestrationError } from '../../../../orchestration/orchestration-error' -import type { OrchestrationSessionCaller } from '../../../../orchestration/addressing/orchestration-caller-identity' +import type { OrchestrationEntryCaller } from '../../../../orchestration/addressing/orchestration-caller-identity' import type { OrchestrationPartyIdentity as OrchestrationCallerIdentity } from '../../../../../../shared/orchestration/mailbox/orchestration-party-identity' import type { DispatchContextRow, @@ -27,7 +27,7 @@ export function resolveWorkerStartRun( args: { coordinator: OrchestrationCallerIdentity | null from: string - callerSession: OrchestrationSessionCaller | undefined + callerSession: OrchestrationEntryCaller | undefined runId: string | undefined /** Objective for a Run this start may create; absent when it names an existing Task. */ objective: string | undefined @@ -120,7 +120,7 @@ export function qualifyLiveWorkerFollowUp( runtime: OrcaRuntimeService, coordinator: OrchestrationCallerIdentity | null, from: string, - session: OrchestrationSessionCaller | undefined, + session: OrchestrationEntryCaller | undefined, runId: string, followUp: Parameters>[1] ) { diff --git a/src/main/runtime/rpc/methods/orchestration/worker/workers.ts b/src/main/runtime/rpc/methods/orchestration/worker/workers.ts index dcf2e63ef94..2538b27521b 100644 --- a/src/main/runtime/rpc/methods/orchestration/worker/workers.ts +++ b/src/main/runtime/rpc/methods/orchestration/worker/workers.ts @@ -40,13 +40,15 @@ export const ORCHESTRATION_WORKER_START_METHODS = [ access: { kind: 'writes', caller: 'from', + server: 'on', targets: { task: 'task', parent: 'task', deps: 'task', run: 'run', retryOf: 'dispatch', - terminal: 'worker' + terminal: 'worker', + adoptTaskId: 'task' } }, requires: ['accounts'], @@ -81,6 +83,26 @@ export async function startWorker( { effectsApplied: false } ) } + if (params.adoptTaskId !== undefined && orchestrationCaller?.kind !== 'peer') { + throw new OrchestrationError( + 'invalid_argument', + 'Only the paired Orca coordinating a Run names its Task IDs. No effects were applied.', + { effectsApplied: false } + ) + } + const placement = params.worktree ?? 'current' + if ( + orchestrationCaller?.kind === 'peer' && + !followUp && + !params.terminal && + /^(current|new-child)$/.test(placement) + ) { + throw new OrchestrationError( + 'invalid_argument', + `--on requires an exact remote worktree selector or new-top-level: ${orchestrationCaller.peerRun.home_label} has no workspace on this server for --worktree ${placement}. No effects were applied.`, + { effectsApplied: false } + ) + } const readinessTimeoutMs = resolveWorkerStartReadinessTimeoutMs(params.timeoutMs) const db = runtime.getOrchestrationDb() const coordinator = resolveOrchestrationCaller(runtime, { diff --git a/src/main/runtime/rpc/orchestration-mutation-executor.test.ts b/src/main/runtime/rpc/orchestration-mutation-executor.test.ts index 2bda0a49813..c3e7a5466b8 100644 --- a/src/main/runtime/rpc/orchestration-mutation-executor.test.ts +++ b/src/main/runtime/rpc/orchestration-mutation-executor.test.ts @@ -50,6 +50,7 @@ function createHarness() { vi.spyOn(runtime, 'getTerminalPaneKey').mockReturnValue('window-1:leaf-prompt') return { db, + runtime, executor: new OrchestrationMutationExecutor(runtime), bindTerminal: (next: { generation: number; processIncarnation: string }) => { binding.mockReturnValue({ ptyId: 'pty-prompt', ...next }) @@ -236,3 +237,27 @@ describe('worker start mutation coalescing', () => { expect(invoke).toHaveBeenCalledOnce() }) }) + +describe('a stop or Run cancel interrupted by a restart', () => { + it.each(['orchestration.workerStop', 'orchestration.peerRunCancel'])( + '%s runs again on a retry with the same request ID instead of answering operation_unknown', + async (method) => { + const harness = createHarness() + const params = method === 'orchestration.workerStop' ? { dispatch: 'ctx_1' } : {} + // The first attempt's receipt is pending when this runtime goes away. + void harness.executor.run( + workerStartRequest(method, 'stop-1.1:ctx_1', params), + params, + () => new Promise(() => {}) + ) + const restarted = new OrchestrationMutationExecutor(harness.runtime) + + const invoke = vi.fn(async () => ({ remaining: 0 })) + await expect( + restarted.run(workerStartRequest(method, 'stop-1.1:ctx_1', params), params, invoke) + ).resolves.toMatchObject({ remaining: 0 }) + expect(invoke).toHaveBeenCalledOnce() + harness.db.close() + } + ) +}) diff --git a/src/main/runtime/rpc/orchestration-mutation-executor.ts b/src/main/runtime/rpc/orchestration-mutation-executor.ts index 2569a8d0e6e..a20faeb6649 100644 --- a/src/main/runtime/rpc/orchestration-mutation-executor.ts +++ b/src/main/runtime/rpc/orchestration-mutation-executor.ts @@ -3,7 +3,7 @@ import { isTerminalPromptMutation } from '../../../shared/orchestration/orchestration-rpc-contract' import type { OrcaRuntimeService } from '../orca-runtime' -import type { OrcaSessionId } from '../../../shared/orca-session-address' +import type { OrchestrationEntryCaller } from '../orchestration/addressing/orchestration-caller-identity' import { OrchestrationError } from '../orchestration/orchestration-error' import type { RpcRequest } from './core' import { @@ -32,6 +32,14 @@ export type DurableMutationInvocation = { replayedReceipt?: unknown } +/** Mutations whose pending receipt a restart re-enters, so a stop or cancel still finishes rather + * than answering operation_unknown: each re-runs its ordinary owner, which is safe to repeat. */ +const RESUMABLE_PENDING_METHODS: ReadonlySet = new Set([ + 'orchestration.workerRelease', + 'orchestration.workerStop', + 'orchestration.peerRunCancel' +]) + type InFlightMutation = { method: string payloadHash: string @@ -48,8 +56,8 @@ export class OrchestrationMutationExecutor { params: unknown, invoke: (mutation?: DurableMutationInvocation) => unknown, callerFingerprintOverride?: string, - /** The resolved session's Orca session id; it joins the payload so another caller cannot replay it. */ - callerOrcaSessionId?: OrcaSessionId + /** The resolved caller; its identity joins the payload so another caller cannot replay it. */ + caller?: OrchestrationEntryCaller ): Promise { const requestId = request.orchestrationRequestId if (!requestId || !isDurableMutation(request.method, params)) { @@ -57,12 +65,7 @@ export class OrchestrationMutationExecutor { } const callerFingerprint = callerFingerprintOverride ?? this.getLocalAuthenticatedCallerFingerprint() - const stableParams = replayStableCallerParams( - this.runtime, - params, - callerOrcaSessionId, - request.method - ) + const stableParams = replayStableCallerParams(this.runtime, params, caller, request.method) const basePayloadHash = hashCanonical({ method: request.method, params: stableParams }) const key = `${callerFingerprint}:${requestId}` const db = this.runtime.getOrchestrationDb() @@ -134,7 +137,7 @@ export class OrchestrationMutationExecutor { isResumablePendingWorkerDone(request.method, params, begun.row.receipt) const resumedPendingMutation = begun.disposition === 'pending' && - (request.method === 'orchestration.workerRelease' || resumedPendingWorkerDone) + (RESUMABLE_PENDING_METHODS.has(request.method) || resumedPendingWorkerDone) if (begun.disposition === 'completed') { const active = this.inFlight.get(key) @@ -191,7 +194,7 @@ export class OrchestrationMutationExecutor { { requestId } ) } - if (request.method !== 'orchestration.workerRelease' && !resumedPendingWorkerDone) { + if (!resumedPendingMutation) { const recovery = getPendingWorkerStartRecovery(request.method, begun.row.receipt) throw new OrchestrationError( 'operation_unknown', diff --git a/src/main/runtime/rpc/orchestration-mutation-receipt.ts b/src/main/runtime/rpc/orchestration-mutation-receipt.ts index 03cf9ebd9d7..ed20925ed9a 100644 --- a/src/main/runtime/rpc/orchestration-mutation-receipt.ts +++ b/src/main/runtime/rpc/orchestration-mutation-receipt.ts @@ -2,7 +2,7 @@ import { createHash } from 'node:crypto' import { isTerminalPromptMutation } from '../../../shared/orchestration/orchestration-rpc-contract' import { parsePaneKey } from '../../../shared/workspace-layout/stable-pane-id' import type { OrcaRuntimeService } from '../orca-runtime' -import type { OrcaSessionId } from '../../../shared/orca-session-address' +import type { OrchestrationEntryCaller } from '../orchestration/addressing/orchestration-caller-identity' export const EFFECT_FREE_WORKER_DONE_CHECKPOINT = JSON.stringify({ pending: { effectFree: 'worker_done' } @@ -15,11 +15,13 @@ export type MutationReplayNudge = | { kind: 'federation'; runId?: string } const CALLER_ORCA_SESSION_ID_KEY = '__orcaCallerOrcaSessionId' +// A paired Orca's address names its conversation, so one Run's receipt never answers another's. +const PEER_CALLER_KEY = '__orcaPeerCaller' export function replayStableCallerParams( runtime: OrcaRuntimeService, params: unknown, - callerOrcaSessionId?: OrcaSessionId, + caller?: OrchestrationEntryCaller, method?: string ): unknown { if (!params || typeof params !== 'object' || Array.isArray(params)) { @@ -27,9 +29,12 @@ export function replayStableCallerParams( } const source = params as Record // Absent for terminal callers, so their payload hashes are unchanged. - const result: Record = callerOrcaSessionId - ? { ...source, [CALLER_ORCA_SESSION_ID_KEY]: callerOrcaSessionId } - : { ...source } + const result: Record = + caller?.kind === 'peer' + ? { ...source, [PEER_CALLER_KEY]: caller.address } + : caller?.orcaSessionId + ? { ...source, [CALLER_ORCA_SESSION_ID_KEY]: caller.orcaSessionId } + : { ...source } if (method === 'orchestration.federationImport' && Array.isArray(result.items)) { result.items = result.items.map((item: Record) => { const { answerSenderReport: _answer, ...canonical } = item diff --git a/src/main/runtime/rpc/orchestration-peer-caller.ts b/src/main/runtime/rpc/orchestration-peer-caller.ts new file mode 100644 index 00000000000..f57053b9d88 --- /dev/null +++ b/src/main/runtime/rpc/orchestration-peer-caller.ts @@ -0,0 +1,72 @@ +import type { OrcaRuntimeService } from '../orca-runtime' +import type { RpcMethod, RpcRequest, RpcStreamingMethod } from './core' +import type { RpcDispatchStreamingOptions } from './dispatcher-stream-options' +import { OrchestrationError } from '../orchestration/orchestration-error' +import { isGeneratedId } from '../orchestration/db/generated-id' +import { RemoteOwnedPeerRun } from '../../../shared/orchestration/remote-owned-wire' +import { + peerCoordinatorCaller, + type OrchestrationPeerCaller +} from '../orchestration/addressing/orchestration-caller-identity' + +const NO_EFFECTS = { effectsApplied: false } as const + +/** + * A call a paired Orca makes as the coordinator of one of its Runs here. Admitted from the + * authenticated runtime pairing, never from a param, and synchronously: its Run is written in the + * frame's first turn, so a later frame of the same conversation (a cancel) always finds it. + * The declared caller field then names the peer, as a session's names the session. + */ +export function admitOrchestrationPeerCall( + runtime: OrcaRuntimeService, + request: RpcRequest, + method: RpcMethod | RpcStreamingMethod, + options: RpcDispatchStreamingOptions | undefined +): { request: RpcRequest; caller: OrchestrationPeerCaller } | undefined { + if (request.orchestrationPeerRun === undefined) { + return undefined + } + const access = method.orchestrationAccess + if (!access) { + throw new OrchestrationError( + 'invalid_argument', + `${request.method} is not an orchestration method, so it takes no peer Run. No effects were applied.`, + NO_EFFECTS + ) + } + const fingerprint = options?.authenticatedCallerFingerprint + if (options?.clientKind !== 'runtime' || options.pairedDeviceId === undefined || !fingerprint) { + throw new OrchestrationError( + 'mail_requires_server_pairing', + 'Only a paired computer can coordinate a Run on this server. No effects were applied.', + NO_EFFECTS + ) + } + const peerRun = RemoteOwnedPeerRun.safeParse(request.orchestrationPeerRun) + if (!peerRun.success || !isGeneratedId(peerRun.data.conversationId, 'peerconv')) { + throw new OrchestrationError( + 'invalid_argument', + 'A peer Run needs its Run, conversation ID and label. No effects were applied.', + NO_EFFECTS + ) + } + const caller = peerCoordinatorCaller( + runtime + .getOrchestrationDb() + .admitPeerRun({ peerFingerprint: fingerprint, peerRun: peerRun.data }) + ) + // Terminal attestation and pane keys name callers on the host that has them, never this one. + const peerRequest = { ...request, orchestrationCompatibilityEvidence: undefined } + const params: unknown = request.params + if (!params || typeof params !== 'object' || Array.isArray(params)) { + return { request: peerRequest, caller } + } + const bound: Record = { ...params } + if (access.callerPane) { + delete bound[access.callerPane] + } + if (access.caller) { + bound[access.caller] = caller.address + } + return { request: { ...peerRequest, params: bound }, caller } +} diff --git a/src/main/runtime/rpc/orchestration-session-caller.ts b/src/main/runtime/rpc/orchestration-session-caller.ts index 10a82436696..160cf758f1e 100644 --- a/src/main/runtime/rpc/orchestration-session-caller.ts +++ b/src/main/runtime/rpc/orchestration-session-caller.ts @@ -11,7 +11,10 @@ import { ORCA_SESSION_ADDRESS_PREFIX } from '../../../shared/orca-session-addres import { isOrcaSessionId, parseOrcaSessionAddress } from '../../../shared/orca-session-address' import { ORCHESTRATION_SESSION_CALLER_ERROR_CODES as CODES } from '../../../shared/orchestration/orchestration-session-caller-codes' import type { OrcaRuntimeService } from '../orca-runtime' -import type { OrchestrationSessionCaller } from '../orchestration/addressing/orchestration-caller-identity' +import type { + OrchestrationEntryCaller, + OrchestrationSessionCaller +} from '../orchestration/addressing/orchestration-caller-identity' import { OrchestrationError } from '../orchestration/orchestration-error' import { canonicalOrcaSessionId } from '../orchestration/addressing/session-lineage/canonical-orca-session-id' import type { OrchestrationDb } from '../orchestration/db/orchestration-db' @@ -36,7 +39,7 @@ export type OrchestrationRequestRoute = { export type ResolvedOrchestrationRequest = { /** The request with its declared caller bound to the session and its evidence reduced to it. */ request: RpcRequest - caller?: OrchestrationSessionCaller + caller?: OrchestrationEntryCaller } const NO_EFFECTS = { effectsApplied: false } as const diff --git a/src/main/runtime/rpc/rpc-request-admission-prologue.ts b/src/main/runtime/rpc/rpc-request-admission-prologue.ts index ee6560cea66..fa0deb52116 100644 --- a/src/main/runtime/rpc/rpc-request-admission-prologue.ts +++ b/src/main/runtime/rpc/rpc-request-admission-prologue.ts @@ -23,6 +23,7 @@ import { resolveOrchestrationSessionCaller, type ResolvedOrchestrationRequest } from './orchestration-session-caller' +import { admitOrchestrationPeerCall } from './orchestration-peer-caller' type RpcRequestAdmissionDeps = { runtime: OrcaRuntimeService @@ -59,6 +60,13 @@ export function admitRpcRequest( return reject(migrationFence) } + let peer: ReturnType + try { + peer = admitOrchestrationPeerCall(runtime, rawRequest, method, options) + } catch (error) { + return reject(mapDispatcherError(rawRequest, meta, error)) + } + const admitResolved = ({ request, caller }: ResolvedOrchestrationRequest) => { const parsedParams = parseRpcRequestParams(request, method, meta) if (parsedParams.error) { @@ -76,6 +84,9 @@ export function admitRpcRequest( } return { method, request, caller, params: parsedParams.value } } + if (peer) { + return admitResolved(peer) + } // Resolve once before parse and unary/streaming branching so both see the same caller. const callerField = method.orchestrationAccess?.caller return needsOrchestrationCallerResolution(rawRequest, callerField) diff --git a/src/main/runtime/rpc/server/runtime-rpc-mobile-method-routing.ts b/src/main/runtime/rpc/server/runtime-rpc-mobile-method-routing.ts index 937d3cf7482..aad41f99239 100644 --- a/src/main/runtime/rpc/server/runtime-rpc-mobile-method-routing.ts +++ b/src/main/runtime/rpc/server/runtime-rpc-mobile-method-routing.ts @@ -16,6 +16,12 @@ export const EXECUTION_HOST_METHODS = [ 'agentActivity.setRead', 'agentTeams.prepareLaunch', 'agentTeams.tmuxCompat', + // Transcripts live on the host that ran the agent, which is also where resume launches it. + 'aiVault.listSessions', + 'aiVault.prepareSessionResume', + 'aiVault.resolveSessionTitles', + 'aiVault.searchSessions', + 'aiVault.searchStatus', 'automation.list', 'automation.show', 'automation.create', diff --git a/src/main/runtime/rpc/server/runtime-rpc-mobile-paired-desktop-methods.ts b/src/main/runtime/rpc/server/runtime-rpc-mobile-paired-desktop-methods.ts index 945761935cd..12b4c117365 100644 --- a/src/main/runtime/rpc/server/runtime-rpc-mobile-paired-desktop-methods.ts +++ b/src/main/runtime/rpc/server/runtime-rpc-mobile-paired-desktop-methods.ts @@ -97,12 +97,6 @@ export const PAIRED_DESKTOP_METHODS = [ 'github.project.updatePullRequestBySlug', 'github.project.viewTable', 'github.project.workItemDetailsBySlug', - // Desktop main federates session history across hosts itself (executionHostId / scope params). - 'aiVault.listSessions', - 'aiVault.prepareSessionResume', - 'aiVault.resolveSessionTitles', - 'aiVault.searchSessions', - 'aiVault.searchStatus', // User preferences live on the Mac; the phone's settings screens mirror the desktop's. 'settings.get', 'settings.getTerminalQuickCommands', diff --git a/src/main/runtime/session-graph/session-window-graph.ts b/src/main/runtime/session-graph/session-window-graph.ts index 1b9eb188010..0b69ae28946 100644 --- a/src/main/runtime/session-graph/session-window-graph.ts +++ b/src/main/runtime/session-graph/session-window-graph.ts @@ -275,6 +275,9 @@ export abstract class OrcaRuntimeWithSyncWindowGraph extends OrcaRuntimeWithAdmi } for (const leaf of this.leaves.values()) { this.adoptPreAllocatedHandle(leaf) + if (leaf.ptyId && this._orchestrationDb?.hasAnyDispatchContexts()) { + this.issueHandle(leaf) + } const previousLeaf = previousLeaves.get(this.getLeafKey(leaf.tabId, leaf.leafId)) // A pane newly showing a terminal can bind it to the pane's Run or Dispatch mailbox. if ( diff --git a/src/main/runtime/terminal/identity/ordered-terminal-candidates.ts b/src/main/runtime/terminal/identity/ordered-terminal-candidates.ts new file mode 100644 index 00000000000..fadd064dd80 --- /dev/null +++ b/src/main/runtime/terminal/identity/ordered-terminal-candidates.ts @@ -0,0 +1,61 @@ +/** Ordered membership only; the canonical source still owns records and validation. */ +export class OrderedTerminalCandidates { + private readonly entries = new Map() + private readonly byKey = new Map() + private nextPosition = 0n + + first(handle: string): string | undefined { + return this.byKey.get(handle)?.[0] + } + + matching(keys: readonly string[]): string[] { + return [...new Set(keys.flatMap((key) => this.byKey.get(key) ?? []))].sort((a, b) => { + const left = this.entries.get(a)!.position + const right = this.entries.get(b)!.position + return left < right ? -1 : left > right ? 1 : 0 + }) + } + + set(id: string, key: string | readonly string[]): void { + const keys = typeof key === 'string' ? [key] : key + const previous = this.entries.get(id) + if ( + previous?.keys.length === keys.length && + previous.keys.every((value, index) => value === keys[index]) + ) { + return + } + const position = previous?.position ?? this.nextPosition++ + this.delete(id) + this.entries.set(id, { keys, position }) + for (const address of keys) { + const bucket = this.byKey.get(address) ?? [] + let index = bucket.length + while (index > 0 && this.entries.get(bucket[index - 1])!.position > position) { + index-- + } + bucket.splice(index, 0, id) + this.byKey.set(address, bucket) + } + } + + delete(id: string): void { + const previous = this.entries.get(id) + if (!previous) { + return + } + for (const key of previous.keys) { + const bucket = this.byKey.get(key)! + bucket.splice(bucket.indexOf(id), 1) + if (bucket.length === 0) { + this.byKey.delete(key) + } + } + this.entries.delete(id) + } + + clear(): void { + this.entries.clear() + this.byKey.clear() + } +} diff --git a/src/main/runtime/terminal/identity/terminal-identity-placement-schedules.test.ts b/src/main/runtime/terminal/identity/terminal-identity-placement-schedules.test.ts index d5d09002d70..07849a219f0 100644 --- a/src/main/runtime/terminal/identity/terminal-identity-placement-schedules.test.ts +++ b/src/main/runtime/terminal/identity/terminal-identity-placement-schedules.test.ts @@ -99,3 +99,30 @@ it('discovers the actual restored placement only after layout apply and re-reads watched.close() } }) + +it('keeps current pane selection ordered across rebinds and detached same-ID writes', () => { + const f = identityFixture() + const suffix = PANE.slice(PANE.indexOf(':')) + const otherPane = `tab-other${suffix}` + f.add('pty-first', 'term_first', otherPane, false) + f.add('pty-second', 'term_second', PANE, true) + const first = f.owner.ptysById.get('pty-first')! + const second = f.owner.ptysById.get('pty-second')! + expect(f.owner.getPtyRecordForPaneKey(PANE)).toBe(second) + f.owner.setPtyConnected(first, true) + expect(f.owner.getPtyRecordForPaneKey(PANE)).toBe(first) + f.owner.setPtyConnected(first, false) + f.owner.setPtyConnected(second, false) + expect(f.owner.getPtyRecordForPaneKey(PANE)).toBe(second) + + const movedPane = 'tab-moved:bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb' + f.owner.source.setRecordedSurface(second, 'tab-moved', movedPane, 1) + expect(f.owner.getPtyRecordForPaneKey(movedPane)).toBe(second) + expect(f.owner.getPtyRecordForPaneKey(PANE)).toBe(first) + const replacement = f.owner.source.createPty({ ...second, paneKey: PANE }) + f.owner.source.setRecordedSurface(second, 'tab-detached', movedPane, 2) + expect(f.owner.getPtyRecordForPaneKey(movedPane)).toBeNull() + expect(f.owner.getPtyRecordForPaneKey(PANE)).toBe(replacement) + f.owner.source.removePty('pty-second') + expect(f.owner.getPtyRecordForPaneKey(PANE)).toBe(first) +}) diff --git a/src/main/runtime/terminal/identity/terminal-identity-schedules.test.ts b/src/main/runtime/terminal/identity/terminal-identity-schedules.test.ts index e6727f0b341..814549959c6 100644 --- a/src/main/runtime/terminal/identity/terminal-identity-schedules.test.ts +++ b/src/main/runtime/terminal/identity/terminal-identity-schedules.test.ts @@ -1,6 +1,7 @@ import { expect, it } from 'vitest' import { identityFixture, identityGraph, LEAF, PANE } from '../query/terminal-identity.test-fixture' import { TEST_WORKTREE_ID } from '../../orca-runtime-tests/orca-runtime-test-fixtures.spec' +import { OrchestrationDb } from '../../orchestration/db/orchestration-db' it('retains pane-issued process identity across reload with exact first-match and SSH precedence in either context', () => { for (const captured of [false, true]) { @@ -83,3 +84,58 @@ it('retains pane-issued process identity across reload with exact first-match an } } }) + +it('keeps the displayed leaf worker ahead of retained PTYs after a dispatch refresh', () => { + const f = identityFixture() + const db = new OrchestrationDb(':memory:') + try { + f.add('retained', 'old-worker', PANE, false) + f.stamp('old-worker', 'retained') + f.runtime.registerPty('current', TEST_WORKTREE_ID, null, { + tabId: 'tab-original', + leafId: LEAF, + incarnationId: 'current' + }) + f.runtime.attachWindow(1) + f.runtime.syncWindowGraph(1, identityGraph('current')) + const current = f.runtime.getTerminalHandleForPaneKey(PANE)! + const run = db.createRun({ + objective: 'Displayed worker', + coordinatorHandle: null, + coordinatorPaneKey: null + }) + const retained = db.createDispatchContext({ + taskId: db.createTask({ runId: run.id, spec: 'Old worker' }).id, + assigneeHandle: 'old-worker', + assigneePaneKey: 'tab-retained:bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb', + creator: { kind: 'system' }, + maxDepth: 99 + }) + const displayed = db.createDispatchContext({ + taskId: db.createTask({ runId: run.id, spec: 'Current worker' }).id, + assigneeHandle: current, + assigneePaneKey: PANE, + creator: { kind: 'system' }, + maxDepth: 99 + }) + db.db + .prepare('UPDATE dispatch_contexts SET assignee_pane_key = ? WHERE id = ?') + .run(PANE, retained.id) + f.runtime.setOrchestrationDb(db) + expect( + f.runtime.syncWindowGraph(1, identityGraph('current')).agentOrchestrationByPaneKey?.[PANE] + ?.dispatchId + ).toBe(displayed.id) + f.owner.source.setPtyConnected(f.owner.ptysById.get('current')!, false) + db.db.prepare('UPDATE dispatch_contexts SET failure_count = 1 WHERE id = ?').run(retained.id) + expect( + f.runtime.syncWindowGraph(1, identityGraph('current')).agentOrchestrationByPaneKey?.[PANE] + ?.dispatchId + ).toBe(displayed.id) + expect(f.runtime.getAgentStatusOrchestrationContextForPaneKey(PANE)?.dispatchId).toBe( + displayed.id + ) + } finally { + db.close() + } +}) diff --git a/src/main/runtime/terminal/identity/terminal-identity-source.ts b/src/main/runtime/terminal/identity/terminal-identity-source.ts index dfcd5dcaf90..499245f4e37 100644 --- a/src/main/runtime/terminal/identity/terminal-identity-source.ts +++ b/src/main/runtime/terminal/identity/terminal-identity-source.ts @@ -5,7 +5,9 @@ import type { } from '../records/runtime-terminal-state-records' import type { TerminalHandleRecord, PtyIncarnationHandleRecord } from './terminal-handle-records' -import { TerminalIncarnationCandidates } from './terminal-incarnation-candidates' +import { OrderedTerminalCandidates } from './ordered-terminal-candidates' +import { TerminalIncarnationBindings } from './terminal-incarnation-bindings' +import { TerminalPaneCandidates } from './terminal-pane-candidates' import { retireReplacedLaunch } from '../launch/launch-evidence' type Mutable = { -readonly [K in keyof T]: T[K] } @@ -17,16 +19,13 @@ export class TerminalIdentitySource { private readonly handleRecords = new Map() private readonly ptyBindings = new Map() private readonly leafBindings = new Map() - private readonly incarnationBindings = new Map>() - private readonly incarnationCandidates = new TerminalIncarnationCandidates() + private readonly reverseCandidates = new OrderedTerminalCandidates() + private readonly incarnationSource = new TerminalIncarnationBindings(() => this.changed()) + readonly paneCandidates = new TerminalPaneCandidates() private readonly syntheticHandles = new Set() // Weak ownership links preserve detached canonical records without retaining their lifetime. private readonly ownedPtys = new WeakMap>() private readonly ownedLeaves = new WeakMap>() - private readonly ownedIncarnations = new WeakMap< - PtyIncarnationHandleRecord, - Mutable - >() private sequence = 0 private epoch = 0 @@ -42,7 +41,8 @@ export class TerminalIdentitySource { readonly handles: ReadonlyMap = this.handleRecords readonly reverse: ReadonlyMap = this.ptyBindings readonly leafHandles: ReadonlyMap = this.leafBindings - readonly incarnations: ReadonlyMap = this.incarnationBindings + readonly incarnations: ReadonlyMap = + this.incarnationSource.records readonly synthetic: ReadonlySet = this.syntheticHandles get graphSequence(): number { return this.sequence @@ -63,6 +63,7 @@ export class TerminalIdentitySource { const record = { ...input } this.ownedPtys.set(record, record) this.ptyRecords.set(record.ptyId, record) + this.paneCandidates.setPty(record) this.changed() return record } @@ -132,11 +133,15 @@ export class TerminalIdentitySource { owned.surfaceRecordedAtGraphSequence = standing } if (changed) { + if (this.ptyRecords.get(owned.ptyId) === owned) { + this.paneCandidates.setPty(owned) + } this.changed() } } removePty(id: string): boolean { + this.paneCandidates.removePty(id) return this.remove(this.ptyRecords, id) } @@ -145,10 +150,12 @@ export class TerminalIdentitySource { return } const next = new Map>() + this.paneCandidates.leaves.clear() for (const [key, input] of inputs) { const owned = this.ownedLeaves.get(input) ?? { ...input } this.ownedLeaves.set(owned, owned) next.set(key, owned) + this.paneCandidates.leaves.set(key, owned.leafId) } this.leafRecords = next this.changed() @@ -163,9 +170,11 @@ export class TerminalIdentitySource { } removeLeaf(key: string): boolean { + this.paneCandidates.leaves.delete(key) return this.remove(this.leafRecords, key) } clearLeaves(): void { + this.paneCandidates.leaves.clear() this.clear(this.leafRecords) } @@ -207,12 +216,18 @@ export class TerminalIdentitySource { } bindPty(id: string, handle: string): void { + this.reverseCandidates.set(id, handle) this.bind(this.ptyBindings, id, handle) } + firstReversePtyId(handle: string): string | undefined { + return this.reverseCandidates.first(handle) + } clearPtyBindings(): void { + this.reverseCandidates.clear() this.clear(this.ptyBindings) } unbindPty(id: string): boolean { + this.reverseCandidates.delete(id) return this.remove(this.ptyBindings, id) } bindLeaf(key: string, handle: string): void { @@ -226,44 +241,22 @@ export class TerminalIdentitySource { } setIncarnation(id: string, input: PtyIncarnationHandleRecord): void { - const previous = this.incarnationBindings.get(id) - const owned = { ...input } - this.ownedIncarnations.set(owned, owned) - this.incarnationBindings.set(id, owned) - this.incarnationCandidates.set(id, owned.handle) - if ( - !previous || - previous.handle !== owned.handle || - previous.incarnationId !== owned.incarnationId || - previous.leafKey !== owned.leafKey - ) { - this.changed() - } + this.incarnationSource.setIncarnation(id, input) } setIncarnationLeaf(record: PtyIncarnationHandleRecord, leafKey: string): void { - const owned = this.ownedIncarnations.get(record) - if (owned && owned.leafKey !== leafKey) { - owned.leafKey = leafKey - this.changed() - } + this.incarnationSource.setIncarnationLeaf(record, leafKey) } setIncarnationProcess(record: PtyIncarnationHandleRecord, incarnationId: string | null): void { - const owned = this.ownedIncarnations.get(record) - if (owned && owned.incarnationId !== incarnationId) { - owned.incarnationId = incarnationId - this.changed() - } + this.incarnationSource.setIncarnationProcess(record, incarnationId) } removeIncarnation(id: string): boolean { - this.incarnationCandidates.delete(id) - return this.remove(this.incarnationBindings, id) + return this.incarnationSource.removeIncarnation(id) } clearIncarnations(): void { - this.incarnationCandidates.clear() - this.clear(this.incarnationBindings) + this.incarnationSource.clearIncarnations() } firstIncarnationPtyId(handle: string): string | undefined { - return this.incarnationCandidates.first(handle) + return this.incarnationSource.firstIncarnationPtyId(handle) } addSynthetic(handle: string): void { diff --git a/src/main/runtime/terminal/identity/terminal-incarnation-bindings.ts b/src/main/runtime/terminal/identity/terminal-incarnation-bindings.ts new file mode 100644 index 00000000000..885169050a4 --- /dev/null +++ b/src/main/runtime/terminal/identity/terminal-incarnation-bindings.ts @@ -0,0 +1,60 @@ +import type { PtyIncarnationHandleRecord } from './terminal-handle-records' +import { OrderedTerminalCandidates } from './ordered-terminal-candidates' +type MutableIncarnation = { + -readonly [K in keyof PtyIncarnationHandleRecord]: PtyIncarnationHandleRecord[K] +} + +/** Ordered incarnation aliases and their canonical mutable records share one lifetime. */ +export class TerminalIncarnationBindings { + readonly records = new Map() + private readonly candidates = new OrderedTerminalCandidates() + private readonly ownedIncarnations = new WeakMap() + constructor(private readonly changed: () => void) {} + setIncarnation(id: string, input: PtyIncarnationHandleRecord): void { + const previous = this.records.get(id) + const owned = { ...input } + this.ownedIncarnations.set(owned, owned) + this.records.set(id, owned) + this.candidates.set(id, owned.handle) + if ( + !previous || + previous.handle !== owned.handle || + previous.incarnationId !== owned.incarnationId || + previous.leafKey !== owned.leafKey + ) { + this.changed() + } + } + setIncarnationLeaf(record: PtyIncarnationHandleRecord, leafKey: string): void { + const owned = this.ownedIncarnations.get(record) + if (owned && owned.leafKey !== leafKey) { + owned.leafKey = leafKey + this.changed() + } + } + setIncarnationProcess(record: PtyIncarnationHandleRecord, incarnationId: string | null): void { + const owned = this.ownedIncarnations.get(record) + if (owned && owned.incarnationId !== incarnationId) { + owned.incarnationId = incarnationId + this.changed() + } + } + removeIncarnation(id: string): boolean { + this.candidates.delete(id) + const removed = this.records.delete(id) + if (removed) { + this.changed() + } + return removed + } + clearIncarnations(): void { + this.candidates.clear() + if (this.records.size > 0) { + this.records.clear() + this.changed() + } + } + firstIncarnationPtyId(handle: string): string | undefined { + return this.candidates.first(handle) + } +} diff --git a/src/main/runtime/terminal/identity/terminal-incarnation-candidates.ts b/src/main/runtime/terminal/identity/terminal-incarnation-candidates.ts deleted file mode 100644 index b2168e0f92f..00000000000 --- a/src/main/runtime/terminal/identity/terminal-incarnation-candidates.ts +++ /dev/null @@ -1,45 +0,0 @@ -/** Ordered membership only; the canonical source still owns records and validation. */ -export class TerminalIncarnationCandidates { - private readonly entries = new Map() - private readonly byHandle = new Map() - private nextPosition = 0n - - first(handle: string): string | undefined { - return this.byHandle.get(handle)?.[0] - } - - set(id: string, handle: string): void { - const previous = this.entries.get(id) - if (previous?.handle === handle) { - return - } - const position = previous?.position ?? this.nextPosition++ - this.delete(id) - const bucket = this.byHandle.get(handle) ?? [] - let index = bucket.length - while (index > 0 && this.entries.get(bucket[index - 1])!.position > position) { - index-- - } - bucket.splice(index, 0, id) - this.entries.set(id, { handle, position }) - this.byHandle.set(handle, bucket) - } - - delete(id: string): void { - const previous = this.entries.get(id) - if (!previous) { - return - } - const bucket = this.byHandle.get(previous.handle)! - bucket.splice(bucket.indexOf(id), 1) - if (bucket.length === 0) { - this.byHandle.delete(previous.handle) - } - this.entries.delete(id) - } - - clear(): void { - this.entries.clear() - this.byHandle.clear() - } -} diff --git a/src/main/runtime/terminal/identity/terminal-pane-candidates.ts b/src/main/runtime/terminal/identity/terminal-pane-candidates.ts new file mode 100644 index 00000000000..f31952b7d86 --- /dev/null +++ b/src/main/runtime/terminal/identity/terminal-pane-candidates.ts @@ -0,0 +1,28 @@ +import { parsePaneKey } from '../../../../shared/workspace-layout/stable-pane-id' +import type { RuntimePtyWorktreeRecord } from '../records/runtime-terminal-state-records' +import { OrderedTerminalCandidates } from './ordered-terminal-candidates' + +/** Raw address membership; connectivity and pane authority remain read-time decisions. */ +export class TerminalPaneCandidates { + readonly leaves = new OrderedTerminalCandidates() + private readonly ptys = new OrderedTerminalCandidates() + + leavesForId(id: string): readonly string[] { + return this.leaves.matching([id]) + } + + ptysForPane(pane: string): readonly string[] { + const leaf = parsePaneKey(pane)?.leafId + return this.ptys.matching([`pane:${pane}`, ...(leaf ? [`leaf:${leaf}`] : [])]) + } + + setPty(record: RuntimePtyWorktreeRecord): void { + const pane = record.paneKey + const leaf = pane ? parsePaneKey(pane)?.leafId : null + this.ptys.set(record.ptyId, pane ? [`pane:${pane}`, ...(leaf ? [`leaf:${leaf}`] : [])] : []) + } + + removePty(id: string): void { + this.ptys.delete(id) + } +} diff --git a/src/main/runtime/terminal/input/terminal-send-stale-leaf-liveness.test.ts b/src/main/runtime/terminal/input/terminal-send-stale-leaf-liveness.test.ts index a567c6a4814..c9effa31366 100644 --- a/src/main/runtime/terminal/input/terminal-send-stale-leaf-liveness.test.ts +++ b/src/main/runtime/terminal/input/terminal-send-stale-leaf-liveness.test.ts @@ -336,6 +336,7 @@ function makeOrchestrationDbStub(toHandle: () => string) { }, db: { crewChanges: new CrewChanges(), + hasAnyDispatchContexts: () => false, listSessionDispatchesForPresentation: () => [], // Mirrors the real query: `read = 0 AND delivered_at IS NULL`. getUndeliveredUnreadMessages: (handle: string) => diff --git a/src/main/runtime/terminal/layout/agent-generated-tab-titles-runtime.ts b/src/main/runtime/terminal/layout/agent-generated-tab-titles-runtime.ts index afb982b09ac..e63c51a252e 100644 --- a/src/main/runtime/terminal/layout/agent-generated-tab-titles-runtime.ts +++ b/src/main/runtime/terminal/layout/agent-generated-tab-titles-runtime.ts @@ -15,7 +15,7 @@ export abstract class OrcaRuntimeWithAgentGeneratedTabTitles extends OrcaRuntime private readonly agentGeneratedTabTitles = new AgentGeneratedTabTitles({ enabled: () => this.store?.getSettings?.()?.tabAutoGenerateTitle === true, targetOf: (row) => this.generatedTitleTargetOf(row), - orchestrationByPaneKey: () => this.agentOrchestrationProjection.buildByPaneKey(), + orchestrationForPaneKey: (paneKey) => this.agentOrchestrationProjection.getForPaneKey(paneKey), apply: (command) => this.applyLayoutCommand(command) }) diff --git a/src/main/runtime/terminal/layout/agent-generated-tab-titles.test.ts b/src/main/runtime/terminal/layout/agent-generated-tab-titles.test.ts index 900c3c296dd..4727d394799 100644 --- a/src/main/runtime/terminal/layout/agent-generated-tab-titles.test.ts +++ b/src/main/runtime/terminal/layout/agent-generated-tab-titles.test.ts @@ -120,10 +120,10 @@ describe('main keeps the window’s generated-title rules', () => { ) { const host = await hostWith([GIT]) const reads = [labels].flat() - const read = vi.spyOn(host.runtime['agentOrchestrationProjection'], 'buildByPaneKey') - read.mockReturnValue(reads.at(-1)) + const read = vi.spyOn(host.runtime['agentOrchestrationProjection'], 'getForPaneKey') + read.mockImplementation((paneKey) => reads.at(-1)?.[paneKey]) for (const each of reads.slice(0, -1)) { - read.mockReturnValueOnce(each) + read.mockImplementationOnce((paneKey) => each[paneKey]) } for (const batch of statuses) { for (const row of batch) { diff --git a/src/main/runtime/terminal/layout/agent-generated-tab-titles.ts b/src/main/runtime/terminal/layout/agent-generated-tab-titles.ts index 5b9decf532c..1cb308727af 100644 --- a/src/main/runtime/terminal/layout/agent-generated-tab-titles.ts +++ b/src/main/runtime/terminal/layout/agent-generated-tab-titles.ts @@ -22,7 +22,7 @@ export type AgentGeneratedTabTitlesDeps = { enabled: () => boolean targetOf: (row: AgentStatusIpcPayload) => GeneratedTitleTarget | null /** Main's dispatch labels by pane key, which a worker's own status may lack. */ - orchestrationByPaneKey: () => Record | undefined + orchestrationForPaneKey: (paneKey: string) => AgentStatusOrchestrationContext | undefined apply: (command: RenameTabsCommand) => Promise } @@ -62,16 +62,15 @@ export class AgentGeneratedTabTitles { } // Later statuses in the batch must read earlier generated titles, matching window batching. const renames = new Map() - // Read once per batch, and only for a dispatch: it scans every dispatch record. - const orchestration = rows.some((row) => isOrcaDispatchPrompt(row.prompt)) - ? this.deps.orchestrationByPaneKey() - : undefined for (const row of rows) { const target = this.deps.targetOf(row) if (!target) { continue } - const labels = orchestration?.[row.paneKey] ?? row.orchestration + const labels = + (isOrcaDispatchPrompt(row.prompt) + ? this.deps.orchestrationForPaneKey(row.paneKey) + : undefined) ?? row.orchestration const key = `${target.workspace}\0${target.tabId}` const earlier = renames.get(key) const next = generatedTabTitleForStatus( diff --git a/src/main/runtime/terminal/query/pty-pane-record.ts b/src/main/runtime/terminal/query/pty-pane-record.ts new file mode 100644 index 00000000000..03c221349b7 --- /dev/null +++ b/src/main/runtime/terminal/query/pty-pane-record.ts @@ -0,0 +1,71 @@ +import type { + RuntimeLeafRecord, + RuntimePtyWorktreeRecord +} from '../records/runtime-terminal-state-records' +import { parsePaneKey } from '../../../../shared/workspace-layout/stable-pane-id' +import type { PtyPaneOf } from '../surface/pty-pane-query' +import type { TerminalIdentityReadContext } from './terminal-identity-read-context' + +export function ptyRecordForPaneKey( + paneKey: string, + source: { + leaves: ReadonlyMap + ptys: ReadonlyMap + leafKey: (tab: string, leaf: string) => string + capturePaneOf: () => PtyPaneOf + paneOf?: PtyPaneOf + leavesForId?: (id: string) => Iterable + ptysForPane?: (pane: string) => Iterable + }, + context?: TerminalIdentityReadContext +): RuntimePtyWorktreeRecord | null { + const parsed = parsePaneKey(paneKey) + let leafPty: RuntimePtyWorktreeRecord | null = null + if (parsed) { + const leaf = source.leaves.get(source.leafKey(parsed.tabId, parsed.leafId)) + const pty = leaf?.ptyId ? source.ptys.get(leaf.ptyId) : undefined + if (pty?.connected) { + return pty + } + leafPty = pty ?? null + const candidates = context + ? context.leavesForId(parsed.leafId) + : (source.leavesForId?.(parsed.leafId) ?? source.leaves.keys()) + for (const key of candidates) { + const candidate = source.leaves.get(key) + if (!candidate) { + continue + } + if (candidate.leafId !== parsed.leafId || !candidate.ptyId) { + continue + } + const remintedPty = source.ptys.get(candidate.ptyId) + if (remintedPty?.connected) { + return remintedPty + } + leafPty ??= remintedPty ?? null + } + } + let newestMatch: RuntimePtyWorktreeRecord | null = null + let paneOf: PtyPaneOf | undefined + const candidates = context + ? context.ptysForPane(paneKey) + : (source.ptysForPane?.(paneKey) ?? source.ptys.keys()) + for (const ptyId of candidates) { + const pty = source.ptys.get(ptyId) + if (!pty) { + continue + } + const recordedPaneKey = (paneOf ??= context?.paneOf ?? source.paneOf ?? source.capturePaneOf())( + pty + ).paneKey + const ptyPane = parsePaneKey(recordedPaneKey ?? '') + if (recordedPaneKey === paneKey || (parsed && ptyPane && parsed.leafId === ptyPane.leafId)) { + if (pty.connected) { + return pty + } + newestMatch = pty + } + } + return leafPty ?? newestMatch +} diff --git a/src/main/runtime/terminal/query/pty-terminal-summary.ts b/src/main/runtime/terminal/query/pty-terminal-summary.ts index 6946cd32092..5d49d792e0f 100644 --- a/src/main/runtime/terminal/query/pty-terminal-summary.ts +++ b/src/main/runtime/terminal/query/pty-terminal-summary.ts @@ -211,7 +211,7 @@ export abstract class OrcaRuntimeWithBuildPtyTerminalSummary extends OrcaRuntime if (!record) { const ptyId = context ? context.reversePtyIds(handle)[0] - : [...this.handleByPtyId.entries()].find(([, mappedHandle]) => mappedHandle === handle)?.[0] + : this.terminalIdentity.firstReversePtyId(handle) const pty = ptyId ? this.ptysById.get(ptyId) : null if (pty) { // Why: graph reload clears renderer handle records, but runtime-owned PTY handles remain the caller's control identity. diff --git a/src/main/runtime/terminal/query/terminal-identity-read-context.test.ts b/src/main/runtime/terminal/query/terminal-identity-read-context.test.ts index e8af70e3d38..174efc1112e 100644 --- a/src/main/runtime/terminal/query/terminal-identity-read-context.test.ts +++ b/src/main/runtime/terminal/query/terminal-identity-read-context.test.ts @@ -1,55 +1,15 @@ import { identityFixture as fixture, PANE } from './terminal-identity.test-fixture' -import { OrchestrationDb } from '../../orchestration/db/orchestration-db' import '../../orchestration/db/contract-constants' import '../../orchestration/db/messages/mailbox-routing-page' import '../../orchestration/db/dispatch-row-writer' import '../../orchestration/db/attempt-outcome-projection' -import { CrewReadModel } from '../../orchestration/crew/crew-read-model' -import { readCrewRuntimeInputs } from '../../orchestration/crew/crew-runtime-watch' import { expect, it, vi } from 'vitest' import '../../orca-runtime-tests/runtime-test-module-registration.spec' -import { TEST_WORKTREE_ID } from '../../orca-runtime-tests/orca-runtime-test-fixtures.spec' import '../../rpc/methods/orchestration/runs/runs' import '../../rpc/methods/orchestration/runs/run-scope' import '../../../../shared/orca-session-address' import '../../../../shared/orca-session-address-test-fixture' -function countIterations( - map: ReadonlyMap, - counts: { entries: number; get: number; set: number; delete: number } -) { - if (!(map instanceof Map)) { - throw new Error('Expected native map instrumentation') - } - const get = map.get.bind(map) - const set = map.set.bind(map) - const remove = map.delete.bind(map) - map.get = (key: K) => { - counts.get++ - return get(key) - } - map.set = (key: K, value: V) => { - counts.set++ - return set(key, value) - } - map.delete = (key: K) => { - counts.delete++ - return remove(key) - } - for (const method of ['entries', 'keys', 'values', Symbol.iterator] as const) { - const original = map[method].bind(map) - Object.defineProperty(map, method, { - configurable: true, - value: function* () { - for (const value of original()) { - counts.entries++ - yield value - } - } - }) - } -} - it('invalidates actual SSH-held facts on register and finally-release with equal and conflicting claims', async () => { const f = fixture() const wake = vi.fn() @@ -90,146 +50,3 @@ it('invalidates actual SSH-held facts on register and finally-release with equal expect(wake).toHaveBeenCalledTimes(6) stop() }) - -it('reuses raw inputs for new historical parties through the production Crew boundary and retires them on real owner writes', () => { - vi.useFakeTimers() - vi.setSystemTime('2026-10-28T20:00:00.000Z') - const measure = (population: number, captured: boolean) => { - const f = fixture() - const db = new OrchestrationDb(':memory:') - f.runtime.setOrchestrationDb(db) - f.add('coordinator', 'term_coord') - f.stamp('term_coord', 'coordinator') - for (let i = 0; i < population; i++) { - f.add(`unrelated-${i}`, `term_inventory_${i}`, `inventory-${i}`) - } - const counts = { entries: 0, get: 0, set: 0, delete: 0 } - countIterations(f.owner.handles, counts) - countIterations(f.owner.ptysById, counts) - countIterations(f.owner.handleByPtyId, counts) - const capture = vi.spyOn(f.runtime, 'createTerminalIdentityRawInputs') - const model = new CrewReadModel( - (previous) => { - const inputs = readCrewRuntimeInputs(f.owner.crewReaders, db, true, 'same-host', previous) - if (captured) { - return inputs - } - delete inputs.openIdentityRead - delete inputs.openRuntimeIdentityRead - return inputs - }, - (wake) => { - const stops = [f.owner.crewChanges.subscribe(wake), db.crewChanges.subscribe(wake)] - return () => stops.forEach((stop) => stop()) - } - ) - const wake = vi.fn() - const stop = model.subscribe(wake) - try { - expect(model.read('term_coord').sections.talkingWith).toEqual([]) - for (let i = 0; i < population; i++) { - db.insertMessage({ - from: `term_late_${i}`, - to: 'term_coord', - subject: 'Hello', - body: `message-${i}` - }) - } - db.db.prepare("UPDATE messages SET created_at = '2026-10-28 20:00:00'").run() - const output = model.read('term_coord') - expect(output.sections.talkingWith).toHaveLength(population) - const acquisition = { ...counts } - if (captured) { - const captures = capture.mock.calls.length - f.owner.crewChanges.notify(new Set(['status', 'names'])) - expect(model.read('term_coord')).toEqual(output) - expect(capture).toHaveBeenCalledTimes(captures) - expect(counts.entries).toBe(acquisition.entries) - // Register's actual controller handle, without another DB/status mutation, retires captured absence. - f.runtime.registerPty('late-pty', TEST_WORKTREE_ID, null, { - tabId: 'tab-late', - leafId: 'bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb', - terminalHandle: 'term_late_0' - }) - const installed = model - .read('term_coord') - .sections.talkingWith.find((row) => row.sendAddress === 'term_late_0') - expect(installed?.openTarget).toEqual({ kind: 'terminal', handle: 'term_late_0' }) - expect(capture.mock.calls.length).toBeGreaterThan(captures) - // Owner repair may dirty the generation once; the next read must settle, never feed a rebuild loop. - model.read('term_coord') - expect(capture.mock.calls.length).toBeLessThanOrEqual(captures + 2) - const afterInstallation = capture.mock.calls.length - f.owner.recordPtyWorktree('late-pty', TEST_WORKTREE_ID, { - lastOutputAt: 500, - preview: 'unconsumed output' - }) - model.read('term_coord') - expect(capture).toHaveBeenCalledTimes(afterInstallation) - const mutation = (write: () => unknown) => { - const before = capture.mock.calls.length - write() - model.read('term_coord') - expect(capture.mock.calls.length).toBeGreaterThan(before) - model.read('term_coord') - const settled = capture.mock.calls.length - model.read('term_coord') - expect(capture).toHaveBeenCalledTimes(settled) - } - const pty = f.owner.ptysById.get('late-pty')! - mutation(() => f.owner.setPtyConnected(pty, false)) - const disconnected = capture.mock.calls.length - f.owner.setPtyConnected(pty, false) - model.read('term_coord') - expect(capture).toHaveBeenCalledTimes(disconnected) - mutation(() => f.runtime.onPtyData('late-pty', 'resume', 500)) - const resumed = capture.mock.calls.length - const normalEntries = counts.entries - const normalWakes = wake.mock.calls.length - for (let i = 0; i < population; i++) { - f.runtime.onPtyData('late-pty', 'ordinary output', 501 + i) - model.read('term_coord') - } - expect(capture).toHaveBeenCalledTimes(resumed) - expect(counts.entries).toBe(normalEntries) - expect(wake).toHaveBeenCalledTimes(normalWakes) - mutation(() => f.owner.setPtyConnected(pty, false)) - mutation(() => f.runtime.onPtySpawned('late-pty', 'new-process')) - mutation(() => - f.owner.recordPtyWorktree('late-pty', TEST_WORKTREE_ID, { - paneKey: 'tab-moved:bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb' - }) - ) - f.runtime.attachWindow(1) - mutation(() => f.owner.beginGraphReload(1)) - mutation(() => f.owner.dropDisconnectedPtyRecord('late-pty')) - expect( - model - .read('term_coord') - .sections.talkingWith.find((row) => row.sendAddress === 'term_late_0')?.openTarget - ).toBeUndefined() - stop() - const beforeReenroll = capture.mock.calls.length - const release = model.subscribe(wake) - model.read('term_coord') - expect(capture).toHaveBeenCalledTimes(beforeReenroll + 1) - release() - } - return { output, acquisition } - } finally { - stop() - db.close() - } - } - try { - for (const population of [3, 30]) { - const baseline = measure(population, false) - const candidate = measure(population, true) - expect(candidate.output).toEqual(baseline.output) - expect(candidate.acquisition.entries).toBeLessThan(baseline.acquisition.entries) - expect(candidate.acquisition.entries).toBeLessThan(10 * (population + 1)) - } - } finally { - vi.useRealTimers() - } -}) diff --git a/src/main/runtime/terminal/query/terminal-identity-read-context.ts b/src/main/runtime/terminal/query/terminal-identity-read-context.ts index 2bf15877064..13e3090f68a 100644 --- a/src/main/runtime/terminal/query/terminal-identity-read-context.ts +++ b/src/main/runtime/terminal/query/terminal-identity-read-context.ts @@ -262,58 +262,3 @@ export class TerminalIdentityReadContext { return values } } - -export function ptyRecordForPaneKey( - paneKey: string, - source: { - leaves: ReadonlyMap - ptys: ReadonlyMap - leafKey: (tab: string, leaf: string) => string - capturePaneOf: () => PtyPaneOf - }, - context?: TerminalIdentityReadContext -): RuntimePtyWorktreeRecord | null { - const parsed = parsePaneKey(paneKey) - let leafPty: RuntimePtyWorktreeRecord | null = null - if (parsed) { - const leaf = source.leaves.get(source.leafKey(parsed.tabId, parsed.leafId)) - const pty = leaf?.ptyId ? source.ptys.get(leaf.ptyId) : undefined - if (pty?.connected) { - return pty - } - leafPty = pty ?? null - const candidates = context ? context.leavesForId(parsed.leafId) : source.leaves.keys() - for (const key of candidates) { - const candidate = source.leaves.get(key) - if (!candidate) { - continue - } - if (candidate.leafId !== parsed.leafId || !candidate.ptyId) { - continue - } - const remintedPty = source.ptys.get(candidate.ptyId) - if (remintedPty?.connected) { - return remintedPty - } - leafPty ??= remintedPty ?? null - } - } - let newestMatch: RuntimePtyWorktreeRecord | null = null - let paneOf: PtyPaneOf | undefined - const candidates = context ? context.ptysForPane(paneKey) : source.ptys.keys() - for (const ptyId of candidates) { - const pty = source.ptys.get(ptyId) - if (!pty) { - continue - } - const recordedPaneKey = (paneOf ??= context?.paneOf ?? source.capturePaneOf())(pty).paneKey - const ptyPane = parsePaneKey(recordedPaneKey ?? '') - if (recordedPaneKey === paneKey || (parsed && ptyPane && parsed.leafId === ptyPane.leafId)) { - if (pty.connected) { - return pty - } - newestMatch = pty - } - } - return leafPty ?? newestMatch -} diff --git a/src/main/runtime/workspaces/creation/created-worktree-approved-setup.test.ts b/src/main/runtime/workspaces/creation/created-worktree-approved-setup.test.ts index f9d48b5b9a5..00a59d16492 100644 --- a/src/main/runtime/workspaces/creation/created-worktree-approved-setup.test.ts +++ b/src/main/runtime/workspaces/creation/created-worktree-approved-setup.test.ts @@ -22,7 +22,12 @@ let repo: Repo const provisionManagedWorktreeTerminals = vi.fn() function runtimeFor() { - const worktree = { id: `repo::${worktreePath}`, repoId: 'repo', path: worktreePath } + const worktree = { + id: `repo::${worktreePath}`, + repoId: 'repo', + path: worktreePath, + displayName: 'w' + } return { showManagedWorktree: vi.fn(async () => worktree), requireStore: () => ({ diff --git a/src/main/runtime/workspaces/creation/created-worktree-approved-setup.ts b/src/main/runtime/workspaces/creation/created-worktree-approved-setup.ts index e8edb207a0c..7147cc3b6c3 100644 --- a/src/main/runtime/workspaces/creation/created-worktree-approved-setup.ts +++ b/src/main/runtime/workspaces/creation/created-worktree-approved-setup.ts @@ -1,4 +1,6 @@ import { isFolderRepo } from '../../../../shared/repo-kind' +import { isRepoOnCatalogHost } from '../../../../shared/execution-host' +import { scopeHooksToRepoKind } from '../../../../shared/folder-workspace-hooks' import { getSetupRunnerCommandPlatformForPath } from '../../../../shared/agent-launch/startup/setup-runner-command' import type { RunApprovedWorktreeSetupResult } from '../../../../shared/worktree/create-types' import { @@ -20,7 +22,9 @@ import type { RuntimeStore } from '../../construction/runtime-store-contract' import type { WorktreeTerminalProvisioningArgs } from '../startup/runtime-worktree-terminal-provisioning' type ApprovedSetupRuntime = { - showManagedWorktree: (selector: string) => Promise> + showManagedWorktree: ( + selector: string + ) => Promise> requireStore: () => Pick provisionManagedWorktreeTerminals: (args: WorktreeTerminalProvisioningArgs) => Promise } @@ -38,10 +42,10 @@ export async function runApprovedCreatedWorktreeSetup( const worktree = await runtime.showManagedWorktree(worktreeSelector) const store = runtime.requireStore() const repo = store.getRepo(worktree.repoId) - if (!repo || isFolderRepo(repo)) { + if (!repo || (isFolderRepo(repo) && !isRepoOnCatalogHost(repo))) { return { status: 'not_configured' } } - const yamlHooks = loadHooks(worktree.path) + const yamlHooks = scopeHooksToRepoKind(repo, loadHooks(worktree.path)) const mismatch = checkCreatedWorktreeSetupTrust(repo, yamlHooks, 'run', { approvedSetupHash }) if (mismatch) { return { status: 'mismatch', setupTrustMismatch: mismatch } @@ -54,7 +58,8 @@ export async function runApprovedCreatedWorktreeSetup( setupScript, getLocalProjectWorktreeGitOptions(store, repo), resolveSetupRunnerShell(store.getSettings()), - yamlHooks?.setupAgentStartupPolicy + yamlHooks?.setupAgentStartupPolicy, + { worktreeId: worktree.id, displayName: worktree.displayName } ) : undefined // The create already opened the command-less default tabs. diff --git a/src/main/runtime/workspaces/creation/runtime-folder-worktree-create.ts b/src/main/runtime/workspaces/creation/runtime-folder-worktree-create.ts index 7cf2c36ab43..1aecde1f210 100644 --- a/src/main/runtime/workspaces/creation/runtime-folder-worktree-create.ts +++ b/src/main/runtime/workspaces/creation/runtime-folder-worktree-create.ts @@ -7,7 +7,6 @@ import { shouldSeedWorktreePrimaryTerminal } from '../../../../shared/worktree-f import { randomUUID } from 'node:crypto' import { getProjectHostSetupWorktreeMeta } from '../../../../shared/project-host-setup-lookup' import { resolveWorktreeCreateDisplayNameRequest } from '../../../ipc/worktree-display-name' -import type { RuntimeTerminalCreate } from '../../../../shared/runtime-terminal-create-contract' import type { CreateWorktreeResult } from '../../../../shared/worktree/create-types' import type { Repo } from '../../../../shared/repo-types' import type { TuiAgent } from '../../../../shared/agent-launch/catalog/tui-agent' @@ -19,27 +18,24 @@ import { } from '../catalog/runtime-folder-workspace' import type { RuntimeManagedWorktreeCreateArgs } from './runtime-managed-worktree-create-types' import type { RuntimeStore } from '../../construction/runtime-store-contract' -import type { TerminalCreateOptions } from '../../terminal/launch/terminal-create-options' import type { WorktreeStartupDraftPaste, WorktreeStartupFollowup } from '../startup/runtime-worktree-agent-startup' import { hostWorktreeTargetForRepo } from '../../../persistence/host-qualified-worktree-meta' +import type { RuntimeLocalWorktreeTerminalPorts } from '../startup/runtime-local-worktree-terminal-startup' +import { + isPreparedFolderSetup, + prepareFolderWorktreeSetup, + startRuntimeFolderWorktreeSetupTerminals, + type RuntimeFolderWorktreeSetupDeps +} from './runtime-folder-worktree-setup' +import { buildRuntimeSetupReceipt } from './runtime-local-worktree-setup' type RuntimeFolderWorktreeCreateDeps = { store: RuntimeStore - ptySpawnAvailable: boolean - provisionInBackground?: () => boolean - createTerminal: ( - selector: string, - options: TerminalCreateOptions - ) => Promise - pasteDraft: (handle: string, draft: WorktreeStartupDraftPaste) => void - sendFollowup: ( - handle: string, - followup: WorktreeStartupFollowup, - terminal: RuntimeTerminalCreate - ) => void + /** The same terminal operations a worktree create uses; folder startup and setup share them. */ + terminals: RuntimeLocalWorktreeTerminalPorts invalidateResolvedWorktrees: () => void notifyWorktreesChanged: (repoId: string) => void emitCreated: (event: { @@ -55,6 +51,8 @@ type RuntimeFolderWorktreeCreateDeps = { startup?: WorktreeStartupLaunch, providesInitialSurface?: boolean ) => void + /** Absent where this host can't run the folder's setup script. */ + setup?: RuntimeFolderWorktreeSetupDeps } export async function createRuntimeFolderWorktree(args: { @@ -150,18 +148,47 @@ export async function createRuntimeFolderWorktree(args: { path: worktree.path, branch: worktree.branch }) + const setupResult = deps.setup + ? await prepareFolderWorktreeSetup({ + request, + repo, + worktree, + settings, + runtimeTarget: deps.setup.runtimeTarget, + shouldUseSetupRunner: deps.setup.shouldUseSetupRunner + }) + : undefined + const preparedSetup = isPreparedFolderSetup(setupResult) ? setupResult : undefined + if (preparedSetup?.setup && deps.setup) { + return { + worktree: folderCreateResultWorktree(worktree), + ...(await startRuntimeFolderWorktreeSetupTerminals({ + request, + repo, + worktree, + prepared: preparedSetup, + startup: args.startup, + startupFollowup: args.startupFollowup, + startupLaunchRuntime: args.startupLaunchRuntime, + createdWithAgent: args.createdWithAgent, + promisedAgentChat: args.promisedAgentChat, + draftPaste: args.draftPaste, + terminals: deps.terminals + })) + } + } const shouldActivate = request.activate === true || request.runHooks === true - let warning: string | undefined + let warning: string | undefined = setupResult?.warning let didSpawnStartup = false let startupTerminal: CreateWorktreeResult['startupTerminal'] // Main owns failed agent startup too, so its pane can show the reason without a terminal service. - if (args.startup && (deps.ptySpawnAvailable || ORCA_LAYOUT_OWNER_IS_MAIN)) { + if (args.startup && (deps.terminals.canSpawn || ORCA_LAYOUT_OWNER_IS_MAIN)) { try { const launchRuntime = args.startupLaunchRuntime if (launchRuntime instanceof Error && !ORCA_LAYOUT_OWNER_IS_MAIN) { throw launchRuntime } - const terminal = await deps.createTerminal(`id:${worktree.id}`, { + const terminal = await deps.terminals.createTerminal(`id:${worktree.id}`, { command: args.startup.command, ...(request.startupCwd ? { cwd: request.startupCwd } : {}), ...paneIdentity(request.startupPaneKey), @@ -182,10 +209,10 @@ export async function createRuntimeFolderWorktree(args: { }) request.onStartupTerminalCreated?.(terminal) if (args.draftPaste) { - deps.pasteDraft(terminal.handle, args.draftPaste) + deps.terminals.pasteDraft(terminal.handle, args.draftPaste) } if (args.startupFollowup) { - deps.sendFollowup(terminal.handle, args.startupFollowup, terminal) + deps.terminals.sendFollowup(terminal.handle, args.startupFollowup, terminal) } didSpawnStartup = true startupTerminal = { @@ -220,8 +247,8 @@ export async function createRuntimeFolderWorktree(args: { ) } if ( - (!shouldActivate || deps.provisionInBackground?.() === true) && - deps.ptySpawnAvailable && + (!shouldActivate || deps.terminals.provisionInBackground?.() === true) && + deps.terminals.canSpawn && shouldSeedWorktreePrimaryTerminal({ // Failed agents retain their panes; do not seed a shell beside them. hasPrimarySurface: didSpawnStartup || (ORCA_LAYOUT_OWNER_IS_MAIN && Boolean(args.startup)), @@ -230,7 +257,7 @@ export async function createRuntimeFolderWorktree(args: { }) ) { try { - await deps.createTerminal(`id:${worktree.id}`, { surfaceOwner: false }) + await deps.terminals.createTerminal(`id:${worktree.id}`, { surfaceOwner: false }) } catch (error) { const message = readableWslDistroHoldText( formatTerminalStartFailure(error) ?? @@ -244,20 +271,33 @@ export async function createRuntimeFolderWorktree(args: { } } return { - worktree: { - ...worktree, - parentWorktreeId: null, - childWorktreeIds: [], - lineage: null, - git: { - path: worktree.path, - head: worktree.head, - branch: worktree.branch, - isBare: worktree.isBare, - isMainWorktree: worktree.isMainWorktree - } - }, + worktree: folderCreateResultWorktree(worktree), ...(startupTerminal ? { startupTerminal } : {}), + ...(preparedSetup && request.awaitTerminalProvisioning + ? { setupReceipt: buildRuntimeSetupReceipt(preparedSetup, false, null) } + : {}), + // The window re-asks with this content, then runs the approved setup. + ...(preparedSetup?.setupTrustMismatch + ? { setupTrustMismatch: preparedSetup.setupTrustMismatch } + : {}), ...(warning ? { warning } : {}) } } + +function folderCreateResultWorktree( + worktree: ReturnType +): CreateWorktreeResult['worktree'] { + return { + ...worktree, + parentWorktreeId: null, + childWorktreeIds: [], + lineage: null, + git: { + path: worktree.path, + head: worktree.head, + branch: worktree.branch, + isBare: worktree.isBare, + isMainWorktree: worktree.isMainWorktree + } + } +} diff --git a/src/main/runtime/workspaces/creation/runtime-folder-worktree-setup.ts b/src/main/runtime/workspaces/creation/runtime-folder-worktree-setup.ts new file mode 100644 index 00000000000..7e1595156b6 --- /dev/null +++ b/src/main/runtime/workspaces/creation/runtime-folder-worktree-setup.ts @@ -0,0 +1,132 @@ +import { isRepoOnCatalogHost } from '../../../../shared/execution-host' +import type { Repo } from '../../../../shared/repo-types' +import type { TuiAgent } from '../../../../shared/agent-launch/catalog/tui-agent' +import type { AgentLaunchRuntime } from '../../../../shared/agent-launch/startup/agent-launch-runtime' +import type { CreateWorktreeResult } from '../../../../shared/worktree/create-types' +import type { Worktree } from '../../../../shared/worktree/types' +import type { WorktreeStartupLaunch } from '../../../../shared/worktree/launch-types' +import type { RuntimeStore } from '../../construction/runtime-store-contract' +import { + startRuntimeLocalWorktreeTerminals, + type RuntimeLocalWorktreeTerminalPorts +} from '../startup/runtime-local-worktree-terminal-startup' +import type { + WorktreeStartupDraftPaste, + WorktreeStartupFollowup +} from '../startup/runtime-worktree-agent-startup' +import type { RuntimeManagedWorktreeCreateArgs } from './runtime-managed-worktree-create-types' +import { + buildRuntimeSetupReceipt, + prepareRuntimeLocalWorktreeSetup, + resolveRuntimeSetupDecision +} from './runtime-local-worktree-setup' +import { blockedWslDistroForPath } from '../../../wsl/filesystem/wsl-unc-access-gate' + +export type RuntimeFolderWorktreeSetupDeps = { + runtimeTarget: () => { wslDistro?: string } | undefined + shouldUseSetupRunner: boolean +} + +type PreparedFolderSetup = Awaited> + +/** + * Only the host whose catalog holds the folder may read its orca.yaml or write runners there. + * The workspace already exists, so a setup problem becomes a warning, never a failed create. + */ +export async function prepareFolderWorktreeSetup(args: { + request: Parameters[0]['request'] & { + wslUserAct?: true + } + repo: Repo + worktree: Pick + settings: ReturnType + runtimeTarget: () => { wslDistro?: string } | undefined + shouldUseSetupRunner: boolean +}): Promise { + const { repo, worktree, request } = args + // A skipped setup needs no file access, so metadata-only creates stay metadata-only. + if (!isRepoOnCatalogHost(repo) || resolveRuntimeSetupDecision(request) === 'skip') { + return undefined + } + // Only a create someone started may start the folder's stopped WSL distro. + if (!request.wslUserAct && (await blockedWslDistroForPath(repo.path))) { + return { warning: "Setup did not run because the folder's WSL distro isn't running." } + } + try { + return await prepareRuntimeLocalWorktreeSetup({ + request: args.request, + repo, + worktreePath: worktree.path, + settings: args.settings, + runtimeTarget: args.runtimeTarget(), + shouldUseSetupRunner: args.shouldUseSetupRunner, + identity: { worktreeId: worktree.id, displayName: worktree.displayName } + }) + } catch (error) { + console.error(`[hooks] setup preparation failed for ${worktree.path}:`, error) + const message = error instanceof Error ? error.message : String(error) + return { warning: `Setup did not run for this folder workspace: ${message}` } + } +} + +export function isPreparedFolderSetup( + value: PreparedFolderSetup | { warning: string } | undefined +): value is PreparedFolderSetup { + return value !== undefined && 'effectiveDecision' in value +} + +/** Folder workspaces start setup and agents exactly as worktrees do, Setup-before-agent order included. */ +export async function startRuntimeFolderWorktreeSetupTerminals(args: { + request: RuntimeManagedWorktreeCreateArgs + repo: Repo + worktree: Worktree + prepared: PreparedFolderSetup + startup?: WorktreeStartupLaunch + startupFollowup?: WorktreeStartupFollowup + startupLaunchRuntime?: AgentLaunchRuntime | Error + createdWithAgent?: TuiAgent + promisedAgentChat?: boolean + draftPaste?: WorktreeStartupDraftPaste + terminals: RuntimeLocalWorktreeTerminalPorts +}): Promise> { + const { request, prepared } = args + const started = await startRuntimeLocalWorktreeTerminals({ + request, + repo: args.repo, + worktree: args.worktree, + setup: prepared.setup, + startup: args.startup, + startupFollowup: args.startupFollowup, + startupLaunchRuntime: args.startupLaunchRuntime, + createdWithAgent: args.createdWithAgent, + promisedAgentChat: args.promisedAgentChat, + draftPaste: args.draftPaste, + warning: prepared.warning, + ports: args.terminals + }) + return { + ...(started.returnedSetup ? { setup: started.returnedSetup } : {}), + ...(request.awaitTerminalProvisioning + ? { + setupReceipt: buildRuntimeSetupReceipt( + prepared, + started.didSpawnSetup, + started.setupTerminalHandle + ) + } + : {}), + ...(started.didSpawnStartup && started.startupTerminalHandle + ? { + startupTerminal: { + spawned: true, + handle: started.startupTerminalHandle, + ...(started.startupTerminalTabId ? { tabId: started.startupTerminalTabId } : {}), + ...(started.startupTerminalPaneKey ? { paneKey: started.startupTerminalPaneKey } : {}), + ...(started.startupTerminalPtyId ? { ptyId: started.startupTerminalPtyId } : {}), + surface: 'background' as const + } + } + : {}), + ...(started.warning ? { warning: started.warning } : {}) + } +} diff --git a/src/main/runtime/workspaces/creation/runtime-local-worktree-setup-trust.test.ts b/src/main/runtime/workspaces/creation/runtime-local-worktree-setup-trust.test.ts index fbc1ac7d2e7..97ce8e12fcb 100644 --- a/src/main/runtime/workspaces/creation/runtime-local-worktree-setup-trust.test.ts +++ b/src/main/runtime/workspaces/creation/runtime-local-worktree-setup-trust.test.ts @@ -21,8 +21,6 @@ const repo: Repo = { id: 'repo', path: '/primary', displayName: 'r', badgeColor: function prepare(approvedSetupHash?: string, approvedSetupHashes?: string[]) { return prepareRuntimeLocalWorktreeSetup({ request: { - repoSelector: 'id:repo', - name: 'w', setupDecision: 'run', ...(approvedSetupHash !== undefined ? { approvedSetupHash } : {}), ...(approvedSetupHashes ? { approvedSetupHashes } : {}) @@ -82,4 +80,42 @@ describe('created worktree setup trust', () => { expect(runner.createSetupRunnerScript).toHaveBeenCalledOnce() expect(result.setupTrustMismatch).toBeUndefined() }) + + describe('folder projects', () => { + const folderRepo: Repo = { ...repo, kind: 'folder' } + const identity = { worktreeId: 'repo::/acme::workspace:1', displayName: 'Fix login' } + const prepareFolder = (setupDecision: 'run' | 'inherit', approvedSetupHash?: string) => + prepareRuntimeLocalWorktreeSetup({ + request: { + setupDecision, + ...(approvedSetupHash !== undefined ? { approvedSetupHash } : {}) + }, + repo: folderRepo, + worktreePath, + settings: getDefaultSettings(tmpdir()), + runtimeTarget: undefined, + shouldUseSetupRunner: true, + identity + }) + + it('skips shared setup from an older client that sent no approval', async () => { + writeFileSync(join(worktreePath, 'orca.yaml'), 'scripts:\n setup: make bootstrap\n') + const result = await prepareFolder('inherit') + expect(runner.createSetupRunnerScript).not.toHaveBeenCalled() + expect(result.setup).toBeUndefined() + expect(result.warning).toContain('pass --setup run') + }) + + it('runs approved shared setup for the workspace, without default tabs', async () => { + writeFileSync( + join(worktreePath, 'orca.yaml'), + 'scripts:\n setup: make bootstrap\ndefaultTabs:\n - title: dev\n command: pnpm dev\n' + ) + const result = await prepareFolder('run', sha256('make bootstrap')) + expect(runner.createSetupRunnerScript).toHaveBeenCalledOnce() + expect(runner.createSetupRunnerScript.mock.calls[0][6]).toEqual(identity) + expect(result.defaultTabs).toBeUndefined() + expect(result.setupTrustMismatch).toBeUndefined() + }) + }) }) diff --git a/src/main/runtime/workspaces/creation/runtime-local-worktree-setup.ts b/src/main/runtime/workspaces/creation/runtime-local-worktree-setup.ts index 794d1b1de73..48ac76b6585 100644 --- a/src/main/runtime/workspaces/creation/runtime-local-worktree-setup.ts +++ b/src/main/runtime/workspaces/creation/runtime-local-worktree-setup.ts @@ -4,19 +4,24 @@ import type { SetupTrustMismatch } from '../../../../shared/worktree/create-types' import type { Repo } from '../../../../shared/repo-types' -import { getEffectiveHooks, loadHooks, runHook } from '../../../workspace-hooks/hooks' +import { loadHooks, runHook } from '../../../workspace-hooks/hooks' import { createSetupRunnerScript, resolveSetupRunnerShell } from '../../../workspace-hooks/worktree-runner-script' import { getDefaultTabsLaunch, + getEffectiveHooksFromConfig, shouldRunSetupForCreate } from '../../../workspace-hooks/effective-hook-config' import { checkCreatedWorktreeSetupTrust, - defaultTabsWithoutCommands + defaultTabsWithoutCommands, + folderSharedSetupLacksApproval } from '../../../workspace-hooks/created-worktree-setup-trust' +import type { HookWorkspaceIdentity } from '../../../workspace-hooks/setup-hook-env-vars' +import { scopeHooksToRepoKind } from '../../../../shared/folder-workspace-hooks' +import { isFolderRepo } from '../../../../shared/repo-kind' import type { RuntimeManagedWorktreeCreateArgs } from './runtime-managed-worktree-create-types' import type { RuntimeStore } from '../../construction/runtime-store-contract' @@ -28,13 +33,18 @@ export function resolveRuntimeSetupDecision( } export async function prepareRuntimeLocalWorktreeSetup(args: { - request: RuntimeManagedWorktreeCreateArgs + request: Pick< + RuntimeManagedWorktreeCreateArgs, + 'runHooks' | 'setupDecision' | 'approvedSetupHash' | 'approvedSetupHashes' + > repo: Repo worktreePath: string settings: ReturnType runtimeTarget: { wslDistro?: string } | undefined shouldUseSetupRunner: boolean warning?: string + /** Required for folder workspaces, whose shared directory can't name the workspace. */ + identity?: HookWorkspaceIdentity }): Promise<{ setup?: CreateWorktreeResult['setup'] defaultTabs?: CreateWorktreeResult['defaultTabs'] @@ -48,8 +58,9 @@ export async function prepareRuntimeLocalWorktreeSetup(args: { const { request, repo, worktreePath, settings } = args let warning = args.warning let setup: CreateWorktreeResult['setup'] - const yamlHooks = loadHooks(worktreePath) - const hooks = getEffectiveHooks(repo, worktreePath) + const yamlHooks = scopeHooksToRepoKind(repo, loadHooks(worktreePath)) + // One parse feeds both the trust check and the runner, so approved bytes are the bytes that run. + const hooks = getEffectiveHooksFromConfig(repo, yamlHooks) const effectiveDecision = resolveRuntimeSetupDecision(request) const setupTrustMismatch = checkCreatedWorktreeSetupTrust( repo, @@ -57,12 +68,20 @@ export async function prepareRuntimeLocalWorktreeSetup(args: { effectiveDecision, request ) + const lacksFolderApproval = + isFolderRepo(repo) && + folderSharedSetupLacksApproval(repo, yamlHooks, effectiveDecision, request) // Only the approved content may run; the client re-prompts with the branch's. - const runDecision = setupTrustMismatch ? 'skip' : effectiveDecision + const runDecision = setupTrustMismatch || lacksFolderApproval ? 'skip' : effectiveDecision if (setupTrustMismatch) { // Automations have no prompt to re-ask; the host log is their record of the skip. console.warn(`[hooks] setup skipped for ${worktreePath}: it differs from the approved content`) } + if (lacksFolderApproval) { + const skipped = + 'orca.yaml setup skipped for this folder workspace because it was not approved; pass --setup run to run it.' + warning = warning ? `${warning} Also ${skipped}` : skipped + } let defaultTabs: CreateWorktreeResult['defaultTabs'] try { const launch = getDefaultTabsLaunch(yamlHooks, repo, runDecision) @@ -92,14 +111,21 @@ export async function prepareRuntimeLocalWorktreeSetup(args: { hooks.scripts.setup, args.runtimeTarget, resolveSetupRunnerShell(settings), - yamlHooks?.setupAgentStartupPolicy + yamlHooks?.setupAgentStartupPolicy, + args.identity ) } catch (error) { console.error(`[hooks] Failed to prepare setup runner for ${worktreePath}:`, error) + if (isFolderRepo(repo)) { + const failed = `Setup did not run: Orca could not write its setup file in ${worktreePath}.` + warning = warning ? `${warning} Also ${failed}` : failed + } } } else { didStartInProcessSetupHook = true - void runHook('setup', worktreePath, repo, worktreePath, args.runtimeTarget).then((result) => { + void runHook('setup', worktreePath, repo, worktreePath, args.runtimeTarget, { + identity: args.identity + }).then((result) => { if (!result.success) { console.error(`[hooks] setup hook failed for ${worktreePath}:`, result.output) } diff --git a/src/main/runtime/workspaces/creation/workspace-creation.ts b/src/main/runtime/workspaces/creation/workspace-creation.ts index 6dea38dd8f6..c921f5bc2f5 100644 --- a/src/main/runtime/workspaces/creation/workspace-creation.ts +++ b/src/main/runtime/workspaces/creation/workspace-creation.ts @@ -15,6 +15,8 @@ import { resolveWorktreeCreateRoute } from '../../../workspaces/creation/worktre import { ExecutionHostNotDispatchableError } from '../../../providers/execution-host-provider-dispatch' import { SshHostNotServedError } from '../../../providers/ssh-host-not-served-error' import { createRuntimeFolderWorktree } from './runtime-folder-worktree-create' +import type { RuntimeNavigationTarget } from '../../../../shared/runtime-navigation' +import type { Worktree } from '../../../../shared/worktree/types' import { createRuntimeLocalManagedWorktree } from './runtime-local-worktree-create' import type { PreparationRearmHolder } from '../../../workspaces/creation/preparation/worktree-create-preparation' import { @@ -22,7 +24,10 @@ import { prepareRuntimeLocalWorktreeSetup } from './runtime-local-worktree-setup' import { invalidateAuthorizedRootsCacheForRepo } from '../../../ipc/worktrees/removal/registered-worktree-roots-scoped-invalidation' -import { startRuntimeLocalWorktreeTerminals } from '../startup/runtime-local-worktree-terminal-startup' +import { + startRuntimeLocalWorktreeTerminals, + type RuntimeLocalWorktreeTerminalPorts +} from '../startup/runtime-local-worktree-terminal-startup' import { trackRuntimeWorkspaceCreate } from '../../../workspaces/creation/workspace-create-telemetry' import type { RuntimeWorkspaceCreateEvents } from '../../../workspaces/creation/workspace-create-telemetry' import { @@ -128,17 +133,15 @@ export abstract class OrcaRuntimeWithCreateManagedWorktree extends OrcaRuntimeWi draftPaste: effectiveDraftPaste, deps: { store, - ptySpawnAvailable: Boolean(this.ptyController?.spawn), - provisionInBackground: () => this.shouldProvisionWorktreeInBackground(args.navigation), - createTerminal: (selector, options) => - this.createTerminal(selector, { ...options, ...wslUserAct(args) }), - pasteDraft: (handle, draft) => this.pasteStartupDraftWhenReady(handle, draft), - sendFollowup: (handle, followup, terminal) => - void this.deliverStartupFollowup(handle, followup, { terminalCreation: terminal }), + terminals: this.localWorktreeTerminalPorts(args, activationCallbacks.local), invalidateResolvedWorktrees: () => this.invalidateResolvedWorktreeCache(), notifyWorktreesChanged: (repoId) => this.notifyWorktreesChanged(repoId), emitCreated: (event) => this.emitWorktreeLifecycle(event), - activate: activationCallbacks.folder + activate: activationCallbacks.folder, + setup: { + runtimeTarget: () => this.getLocalGitExecutionOptionArgs(repo)[0], + shouldUseSetupRunner: this.canUseSetupRunner(effectiveStartup) + } } }) } @@ -195,10 +198,7 @@ export abstract class OrcaRuntimeWithCreateManagedWorktree extends OrcaRuntimeWi worktreePath, settings: createSettings, runtimeTarget: this.getLocalGitExecutionOptionArgs(repo)[0], - shouldUseSetupRunner: - this.authoritativeWindowId !== null || - Boolean(effectiveStartup) || - Boolean(this.ptyController?.spawn), + shouldUseSetupRunner: this.canUseSetupRunner(effectiveStartup), warning: [includeCopyWarning, addResult.upstreamWarning].filter(Boolean).join(' ') || undefined }) @@ -234,18 +234,7 @@ export abstract class OrcaRuntimeWithCreateManagedWorktree extends OrcaRuntimeWi promisedAgentChat: args.promisedAgentChat, draftPaste: effectiveDraftPaste, warning, - ports: { - canSpawn: Boolean(this.ptyController?.spawn), - provisionInBackground: () => this.shouldProvisionWorktreeInBackground(args.navigation), - createTerminal: (selector, options) => - this.createTerminal(selector, { ...options, ...wslUserAct(args) }, worktree), - pasteDraft: (handle, draft) => this.pasteStartupDraftWhenReady(handle, draft), - sendFollowup: (handle, followup, terminal) => - void this.deliverStartupFollowup(handle, followup, { terminalCreation: terminal }), - provision: (options) => - this.provisionManagedWorktreeTerminals({ ...options, ...wslUserAct(args) }, worktree), - activate: activationCallbacks.local - } + ports: this.localWorktreeTerminalPorts(args, activationCallbacks.local, worktree) }) warning = terminalWarning this.emitWorktreeLifecycle({ @@ -298,4 +287,32 @@ export abstract class OrcaRuntimeWithCreateManagedWorktree extends OrcaRuntimeWi : {}) } } + + // A window, an agent or a PTY host can show setup in a terminal; otherwise it runs in-process. + private canUseSetupRunner(startup: unknown): boolean { + return ( + this.authoritativeWindowId !== null || Boolean(startup) || Boolean(this.ptyController?.spawn) + ) + } + + private localWorktreeTerminalPorts( + args: { navigation?: RuntimeNavigationTarget; wslUserAct?: true }, + activate: RuntimeLocalWorktreeTerminalPorts['activate'], + worktree?: Worktree + ): RuntimeLocalWorktreeTerminalPorts { + return { + canSpawn: Boolean(this.ptyController?.spawn), + provisionInBackground: () => this.shouldProvisionWorktreeInBackground(args.navigation), + createTerminal: (selector, options) => + worktree + ? this.createTerminal(selector, { ...options, ...wslUserAct(args) }, worktree) + : this.createTerminal(selector, { ...options, ...wslUserAct(args) }), + pasteDraft: (handle, draft) => this.pasteStartupDraftWhenReady(handle, draft), + sendFollowup: (handle, followup, terminal) => + void this.deliverStartupFollowup(handle, followup, { terminalCreation: terminal }), + provision: (options) => + this.provisionManagedWorktreeTerminals({ ...options, ...wslUserAct(args) }, worktree), + activate + } + } } diff --git a/src/main/runtime/workspaces/process-listing/workspace-process-listing.ts b/src/main/runtime/workspaces/process-listing/workspace-process-listing.ts index 6f5424779f2..a133c8242db 100644 --- a/src/main/runtime/workspaces/process-listing/workspace-process-listing.ts +++ b/src/main/runtime/workspaces/process-listing/workspace-process-listing.ts @@ -298,8 +298,7 @@ export abstract class OrcaRuntimeWithGetWorktreePs extends RuntimeChatWorkerEven readStructuredAttentionWorkspaceLabels(this.requireStore(), scope), isWorkspaceMuted: (scope) => this.isWorkspaceNotificationMuted(scope.workspaceId), // The same contexts the session's chat row carries. - readOrchestration: (paneKey) => - this.agentOrchestrationProjection.buildByPaneKey()?.[paneKey], + readOrchestration: (paneKey) => this.agentOrchestrationProjection.getForPaneKey(paneKey), dispatch: (event) => this.mobileNotifications.dispatch(event), reconcile: (state) => this.mobileNotifications.reconcileStructuredPromptAttention(state), now: () => Date.now() diff --git a/src/main/runtime/workspaces/removal/runtime-registered-local-worktree-removal.ts b/src/main/runtime/workspaces/removal/runtime-registered-local-worktree-removal.ts index 3ef174772f6..cb942c3efbb 100644 --- a/src/main/runtime/workspaces/removal/runtime-registered-local-worktree-removal.ts +++ b/src/main/runtime/workspaces/removal/runtime-registered-local-worktree-removal.ts @@ -101,7 +101,8 @@ async function acceptRuntimeRegisteredLocalWorktreeRemoval(args: { canonicalPath, repo, undefined, - args.hasLocalOptions ? localOptions : undefined + args.hasLocalOptions ? localOptions : undefined, + { identity: { worktreeId: args.target.id } } ) archiveHookOverride = gateWorktreeRemovalOnArchiveHook({ worktreePath: canonicalPath, diff --git a/src/main/runtime/workspaces/removal/workspace-registration-removal.ts b/src/main/runtime/workspaces/removal/workspace-registration-removal.ts index f4f502f1233..2a8c12a6d04 100644 --- a/src/main/runtime/workspaces/removal/workspace-registration-removal.ts +++ b/src/main/runtime/workspaces/removal/workspace-registration-removal.ts @@ -5,7 +5,16 @@ import type { Repo } from '../../../../shared/repo-types' import type { ExecutionHostId } from '../../../../shared/execution-host' import type { WorktreeTeardownRuntime } from './worktree-teardown' import { splitWorktreeId, splitWorktreeIdForFilesystem } from '../../../../shared/worktree/id' -import { parseExecutionHostId } from '../../../../shared/execution-host' +import { isRepoOnCatalogHost, parseExecutionHostId } from '../../../../shared/execution-host' +import type { RemoveWorktreeResult } from '../../../../shared/worktree/create-types' +import { readWorktreeMetaForRepo } from '../../../persistence/host-qualified-worktree-meta' +import { getEffectiveHooks } from '../../../workspace-hooks/hooks' +import { blockedWslDistroForPath } from '../../../wsl/filesystem/wsl-unc-access-gate' +import { getLocalProjectWorktreeGitOptions } from '../../../workspaces/execution-host/project-runtime-git-options' +import { + gateFolderWorkspaceRemovalOnArchiveHook, + removeFolderWorkspaceRunnerFiles +} from '../../../workspaces/removal/folder-workspace-archive-hook' import { invalidateAuthorizedRootsCache } from '../../../ipc/worktrees/removal/registered-worktree-roots-cache' import { isFolderRepo } from '../../../../shared/repo-kind' import { getRuntimeFolderWorkspaceRootId } from '../catalog/runtime-folder-workspace' @@ -33,7 +42,8 @@ export async function removeOrphanOrFolderWorktree({ removalTarget, cleanupHostId, removalHostId, - repo + repo, + archive }: { runtime: WorkspaceRegistrationRemovalRuntime store: RuntimeStore @@ -41,7 +51,9 @@ export async function removeOrphanOrFolderWorktree({ cleanupHostId?: ExecutionHostId removalHostId?: ExecutionHostId repo?: Repo -}): Promise<{ warning?: string } | undefined> { + /** Same opt-in as worktree removal: archive runs only when the caller asked for hooks. */ + archive: { runHooks: boolean; allowFailedArchiveHook: boolean } +}): Promise<(RemoveWorktreeResult & { warning?: string }) | undefined> { if (!repo) { const orphanHost = parseExecutionHostId(store.getWorktreeMeta(removalTarget.id)?.hostId) if (cleanupHostId && orphanHost?.id !== cleanupHostId) { @@ -106,6 +118,25 @@ export async function removeOrphanOrFolderWorktree({ if (removalTarget.id === getRuntimeFolderWorkspaceRootId(repo)) { throw new Error('Cannot delete the project root workspace. Remove the folder project instead.') } + // Archive failure must refuse before watcher, PTY or metadata teardown (#19334). + const archiveHookOverride = await gateFolderWorkspaceRemovalOnArchiveHook({ + repo, + worktreeId: removalTarget.id, + displayName: + ( + readWorktreeMetaForRepo(store, removalTarget.id, repo) ?? + store.getWorktreeMeta(removalTarget.id) + )?.displayName ?? repo.displayName, + runArchive: archive.runHooks, + allowFailure: archive.allowFailedArchiveHook, + runtimeTarget: () => getLocalProjectWorktreeGitOptions(store, repo) + }) + // Without --run-hooks, look at the folder only to warn, and never start its stopped WSL distro for that. + const archiveSkipped = + !archive.runHooks && + isRepoOnCatalogHost(repo) && + !(await blockedWslDistroForPath(repo.path)) && + Boolean(getEffectiveHooks(repo)?.scripts.archive) // Use the resolved SSH owner, including executionHostId-only rows; runtime-nested targets belong to that environment's namespace. const folderHost = parseExecutionHostId(removalHostId) const folderConnectionId = folderHost?.kind === 'ssh' ? folderHost.targetId : null @@ -121,10 +152,19 @@ export async function removeOrphanOrFolderWorktree({ folderConnectionId ) await runtime.removeWorktreeMetadataAndHistory(store, removalTarget.id, removalHostId) + removeFolderWorkspaceRunnerFiles(repo, removalTarget.id) runtime.preservedBranchCleanup.delete(removalTarget.id, cleanupHostId) runtime.invalidateResolvedWorktreeCache() runtime.notifyWorktreesChanged(repo.id) - return {} + return { + ...(archiveHookOverride ? { archiveHookOverride } : {}), + ...(archiveSkipped + ? { + warning: + 'orca.yaml archive hook skipped for this folder workspace; pass --run-hooks to run it.' + } + : {}) + } } finally { await gate.finish(false) } diff --git a/src/main/runtime/workspaces/removal/workspace-removal.ts b/src/main/runtime/workspaces/removal/workspace-removal.ts index 110f3210a12..f4b8967642b 100644 --- a/src/main/runtime/workspaces/removal/workspace-removal.ts +++ b/src/main/runtime/workspaces/removal/workspace-removal.ts @@ -77,10 +77,7 @@ export abstract class OrcaRuntimeWithRemoveManagedWorktree extends RuntimeWorksp allowFailedArchiveHook = false, hostId } = options - if (!this.store) { - throw new Error('runtime_unavailable') - } - const store = this.store + const store = this.requireStore() const cleanupHostId = parseExecutionHostId(hostId)?.id const removalTarget = await this.resolveWorktreeRemovalTarget(worktreeSelector, cleanupHostId) // The repo row names the host; a caller may omit hostId for a worktree on another host. @@ -144,7 +141,8 @@ export abstract class OrcaRuntimeWithRemoveManagedWorktree extends RuntimeWorksp removalTarget, cleanupHostId, removalHostId, - repo + repo, + archive: { runHooks, allowFailedArchiveHook } }) if (orphanOrFolderResult) { return orphanOrFolderResult diff --git a/src/main/runtime/workspaces/startup/runtime-local-worktree-terminal-startup.ts b/src/main/runtime/workspaces/startup/runtime-local-worktree-terminal-startup.ts index 0e2ee76b7d1..dade1601abc 100644 --- a/src/main/runtime/workspaces/startup/runtime-local-worktree-terminal-startup.ts +++ b/src/main/runtime/workspaces/startup/runtime-local-worktree-terminal-startup.ts @@ -23,7 +23,7 @@ import type { WorktreeTerminalProvisioningArgs } from './runtime-worktree-terminal-provisioning' -type Ports = { +export type RuntimeLocalWorktreeTerminalPorts = { canSpawn: boolean provisionInBackground?: () => boolean createTerminal: ( @@ -76,7 +76,7 @@ export async function startRuntimeLocalWorktreeTerminals(args: { promisedAgentChat?: boolean draftPaste?: WorktreeStartupDraftPaste warning?: string - ports: Ports + ports: RuntimeLocalWorktreeTerminalPorts }): Promise { const { request, repo, worktree, defaultTabs, startup, ports } = args let { setup } = args diff --git a/src/main/sqlite/sync-database.ts b/src/main/sqlite/sync-database.ts index 19bb23352bd..152cf740043 100644 --- a/src/main/sqlite/sync-database.ts +++ b/src/main/sqlite/sync-database.ts @@ -91,6 +91,10 @@ class SyncDatabase { this.db.exec(sql) } + function(name: string, callback: Parameters[1]): void { + this.db.function(name, callback) + } + prepare(sql: string): SqliteStatement { const cached = this.statementCache.get(sql) if (cached) { diff --git a/src/main/window/renderer-publication-throttle-electron-fixture.ts b/src/main/window/renderer-publication-throttle-electron-fixture.ts index 9adaac8227b..3a417f1dc9f 100644 --- a/src/main/window/renderer-publication-throttle-electron-fixture.ts +++ b/src/main/window/renderer-publication-throttle-electron-fixture.ts @@ -47,6 +47,7 @@ async function run(): Promise { maxHeight: 480, everyNthFrame: 1, minFrameIntervalMs: 0, + holdPaint: () => () => {}, onFrame: () => { frames += 1 firstFrame() diff --git a/src/main/window/runtime-window-lifecycle.ts b/src/main/window/runtime-window-lifecycle.ts index 9af8fcb8048..b5d40e737b9 100644 --- a/src/main/window/runtime-window-lifecycle.ts +++ b/src/main/window/runtime-window-lifecycle.ts @@ -182,7 +182,8 @@ export function registerRuntimeWindowLifecycle( focusTerminal: (tabId, worktreeId, leafId) => send('ui:focusTerminal', { tabId, worktreeId, leafId }), revealTerminalPane: (target) => revealTerminalPaneInWindow(mainWindow, target), - focusEditorTab: (tabId, worktreeId) => send('ui:focusEditorTab', { tabId, worktreeId }), + focusEditorTab: (tabId, worktreeId, options) => + send('ui:focusEditorTab', { tabId, worktreeId, ...options }), closeSessionTab: (tabId, worktreeId) => requestSessionTabCloseFromRenderer(mainWindow, tabId, worktreeId), moveSessionTab: (worktreeId: string, move: RuntimeMobileSessionTabMove) => diff --git a/src/main/workspace-hooks/created-worktree-setup-trust.ts b/src/main/workspace-hooks/created-worktree-setup-trust.ts index 9cd6393cf5d..f9b4fdcd706 100644 --- a/src/main/workspace-hooks/created-worktree-setup-trust.ts +++ b/src/main/workspace-hooks/created-worktree-setup-trust.ts @@ -39,6 +39,28 @@ export function checkCreatedWorktreeSetupTrust( return matches ? undefined : { contentHash, scriptContent } } +/** + * Older clients send no approval hash. A folder's shared setup never ran before folder setup + * existed, so it needs an approval or an explicit run rather than starting unseen. + */ +export function folderSharedSetupLacksApproval( + repo: Repo, + createdYamlHooks: OrcaHooks | null, + decision: SetupDecision | undefined, + approved: ApprovedSetupHashes +): boolean { + if (approved.approvedSetupHash !== undefined || approved.approvedSetupHashes !== undefined) { + return false + } + if (decision === 'run') { + return false + } + const policy = resolveHookCommandSourcePolicy(repo.hookSettings?.commandSourcePolicy, { + hasLocalScript: Boolean(repo.hookSettings?.scripts.setup?.trim()) + }) + return policy !== 'local-only' && Boolean(getSetupTrustContent(createdYamlHooks)) +} + function wouldRunSetup(repo: Repo, decision: SetupDecision | undefined): boolean { try { return shouldRunSetupForCreate(repo, decision) diff --git a/src/main/workspace-hooks/folder-setup-runner-files.test.ts b/src/main/workspace-hooks/folder-setup-runner-files.test.ts new file mode 100644 index 00000000000..b022c63c532 --- /dev/null +++ b/src/main/workspace-hooks/folder-setup-runner-files.test.ts @@ -0,0 +1,46 @@ +import { mkdirSync, mkdtempSync, readdirSync, rmSync, writeFileSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { dirname, join } from 'node:path' +import { afterEach, beforeEach, describe, expect, it } from 'vitest' +import { newFolderSetupRunnerPath, removeFolderSetupRunnerFiles } from './folder-setup-runner-files' + +const WORKSPACE_A = 'repo::/acme::workspace:11111111-1111-4111-8111-111111111111' +const WORKSPACE_B = 'repo::/acme::workspace:22222222-2222-4222-8222-222222222222' + +let folder: string + +beforeEach(() => { + folder = mkdtempSync(join(tmpdir(), 'orca-folder-runner-')) +}) + +afterEach(() => { + rmSync(folder, { recursive: true, force: true }) +}) + +function writeRunner(worktreeId: string): string { + const path = newFolderSetupRunnerPath(folder, worktreeId, 'sh') + mkdirSync(dirname(path), { recursive: true }) + writeFileSync(path, 'echo setup\n') + return path +} + +describe('folder setup runner files', () => { + it('gives every launch its own file, so a later launch never rewrites a running script', () => { + const first = writeRunner(WORKSPACE_A) + const second = writeRunner(WORKSPACE_A) + expect(first).not.toBe(second) + expect(dirname(first)).toBe(dirname(second)) + }) + + it("removes only the removed workspace's runners", async () => { + writeRunner(WORKSPACE_A) + writeRunner(WORKSPACE_A) + const kept = writeRunner(WORKSPACE_B) + writeFileSync(join(folder, '.orca', 'issue-command'), 'claude') + await removeFolderSetupRunnerFiles(folder, WORKSPACE_A) + expect(readdirSync(join(folder, '.orca')).sort()).toEqual( + ['issue-command', dirname(kept).split(/[\\/]/).pop()!].sort() + ) + expect(readdirSync(dirname(kept))).toEqual([kept.split(/[\\/]/).pop()!]) + }) +}) diff --git a/src/main/workspace-hooks/folder-setup-runner-files.ts b/src/main/workspace-hooks/folder-setup-runner-files.ts new file mode 100644 index 00000000000..0986d8ed473 --- /dev/null +++ b/src/main/workspace-hooks/folder-setup-runner-files.ts @@ -0,0 +1,49 @@ +import { randomUUID } from 'node:crypto' +import { rm, writeFile } from 'node:fs/promises' +import { join } from 'node:path' +import { FOLDER_WORKSPACE_INSTANCE_SEPARATOR } from '../../shared/worktree/id' +import { windowsFsPath } from '../wsl/filesystem/wsl-unc-drive-fs-path' + +const FOLDER_RUNNER_DIR = '.orca' + +// One directory per workspace, so removal deletes it without listing its siblings' runners. +function runnerDirName(worktreeId: string): string { + const separatorIdx = worktreeId.lastIndexOf(FOLDER_WORKSPACE_INSTANCE_SEPARATOR) + const instance = + separatorIdx === -1 + ? 'root' + : worktreeId.slice(separatorIdx + FOLDER_WORKSPACE_INSTANCE_SEPARATOR.length) + return `setup-runner-${instance.replace(/[^A-Za-z0-9-]/g, '_')}` +} + +/** A fresh file per launch: workspaces share the folder, and bash/cmd re-read a runner by offset while it runs. */ +export function newFolderSetupRunnerPath( + folderPath: string, + worktreeId: string, + extension: 'sh' | 'cmd' +): string { + return join( + folderPath, + FOLDER_RUNNER_DIR, + runnerDirName(worktreeId), + `${randomUUID()}.${extension}` + ) +} + +/** A folder may itself be a Git checkout; keep its runners out of `git status` without editing its files. */ +export async function ignoreFolderSetupRunners(orcaDirFsPath: string): Promise { + await writeFile(join(orcaDirFsPath, '.gitignore'), 'setup-runner-*\n.gitignore\n', { + flag: 'wx' + }).catch(() => undefined) +} + +/** Call after the workspace's processes stopped, so no running script loses its file. */ +export async function removeFolderSetupRunnerFiles( + folderPath: string, + worktreeId: string +): Promise { + const dir = windowsFsPath(join(folderPath, FOLDER_RUNNER_DIR, runnerDirName(worktreeId))) + await rm(dir, { recursive: true, force: true }).catch((error: unknown) => { + console.warn(`[hooks] could not remove setup runners in ${dir}:`, error) + }) +} diff --git a/src/main/workspace-hooks/hook-archive-timeout-observation.test.ts b/src/main/workspace-hooks/hook-archive-timeout-observation.test.ts index 7a22d7f5c61..c81ae6d2897 100644 --- a/src/main/workspace-hooks/hook-archive-timeout-observation.test.ts +++ b/src/main/workspace-hooks/hook-archive-timeout-observation.test.ts @@ -15,7 +15,7 @@ async function runArchive(script: string, timeoutMs = 400) { const dir = mkdtempSync(join(tmpdir(), 'orca-hook-deadline-')) writeFileSync(join(dir, 'orca.yaml'), `scripts:\n archive: |\n ${script}\n`) try { - return await runHook('archive', dir, REPO, dir, undefined, timeoutMs) + return await runHook('archive', dir, REPO, dir, undefined, { timeoutMs }) } finally { rmSync(dir, { recursive: true, force: true }) } diff --git a/src/main/workspace-hooks/hook-orca-cli-env.ts b/src/main/workspace-hooks/hook-orca-cli-env.ts new file mode 100644 index 00000000000..503f1c84e36 --- /dev/null +++ b/src/main/workspace-hooks/hook-orca-cli-env.ts @@ -0,0 +1,72 @@ +import { getAppEnvironment, hasAppEnvironment } from '../../shared/app-environment' +import { toLinuxPath } from '../../shared/wsl-paths' +import { prependOrcaCliDirToChildPath } from '../cli/orca-cli-child-path' +import { getManagedWslCliDir, getWslCliCommandName } from '../cli/wsl-managed-cli' +import { WSL_MANAGED_CLI_PATH_RESTORE } from '../wsl/execution/wsl-managed-cli-path-restore' + +// A hook isn't a pane: an Orca started from an Orca terminal must not lend that pane's identity. +const INHERITED_PANE_IDENTITY_KEYS = [ + 'ORCA_TERMINAL_HANDLE', + 'ORCA_PANE_KEY', + 'ORCA_TAB_ID', + 'ORCA_AGENT_LAUNCH_TOKEN', + 'ORCA_WORKSPACE_ID', + 'ORCA_WORKTREE_ID' +] as const + +/** Give an in-process hook this app's `orca` CLI, as terminals get it. */ +export function applyHostHookOrcaCliEnv(env: Record): void { + for (const key of INHERITED_PANE_IDENTITY_KEYS) { + delete env[key] + } + if (!hasAppEnvironment()) { + return + } + const app = getAppEnvironment() + const userDataPath = app.getPath('userData') + const childEnv = Object.fromEntries( + Object.entries(env).filter((entry): entry is [string, string] => entry[1] !== undefined) + ) + childEnv.ORCA_USER_DATA_PATH = userDataPath + prependOrcaCliDirToChildPath(childEnv, { + isPackaged: app.isPackaged(), + userDataPath, + resourcesPath: process.resourcesPath ?? null + }) + for (const key of Object.keys(env)) { + if (!(key in childEnv)) { + delete env[key] + } + } + Object.assign(env, childEnv) +} + +/** + * The guest env and a script prefix that puts the managed WSL CLI first on PATH. Inherited pane + * identity is blanked, since wsl.exe would otherwise carry the host's values in through WSLENV. + */ +export function wslHookOrcaCliEnv(): { env: Record; scriptPrefix: string } { + const blankedIdentity = Object.fromEntries(INHERITED_PANE_IDENTITY_KEYS.map((key) => [key, ''])) + if (!hasAppEnvironment()) { + return { env: blankedIdentity, scriptPrefix: '' } + } + const app = getAppEnvironment() + const userDataPath = app.getPath('userData') + const managedCliDir = getManagedWslCliDir({ + isPackaged: app.isPackaged(), + userDataPath, + ...(process.resourcesPath ? { resourcesPath: process.resourcesPath } : {}) + }) + if (!managedCliDir) { + return { env: blankedIdentity, scriptPrefix: '' } + } + return { + env: { + ...blankedIdentity, + ORCA_WSL_CLI_DIR: toLinuxPath(managedCliDir), + ORCA_CLI_COMMAND: getWslCliCommandName(app.isPackaged()), + ORCA_USER_DATA_PATH: toLinuxPath(userDataPath) + }, + scriptPrefix: `${WSL_MANAGED_CLI_PATH_RESTORE}\n` + } +} diff --git a/src/main/workspace-hooks/hook-termination-real-process.test.ts b/src/main/workspace-hooks/hook-termination-real-process.test.ts index fc8d02cce38..fc4123fd6e5 100644 --- a/src/main/workspace-hooks/hook-termination-real-process.test.ts +++ b/src/main/workspace-hooks/hook-termination-real-process.test.ts @@ -27,7 +27,7 @@ async function survivorsAfterDeadline( ) let pids: number[] = [] try { - const result = await runHook('archive', dir, REPO, dir, undefined, 400) + const result = await runHook('archive', dir, REPO, dir, undefined, { timeoutMs: 400 }) expect(result.success).toBe(false) expect(existsSync(pidFile)).toBe(true) pids = readFileSync(pidFile, 'utf8').trim().split(/\s+/).map(Number) diff --git a/src/main/workspace-hooks/hooks.ts b/src/main/workspace-hooks/hooks.ts index 94a74cc949d..6194e841958 100644 --- a/src/main/workspace-hooks/hooks.ts +++ b/src/main/workspace-hooks/hooks.ts @@ -4,7 +4,8 @@ import { parseOrcaYaml } from '../../shared/orca-yaml' import { resolveHookCommandSourcePolicy } from '../../shared/hook-command-source-policy' import { getEffectiveHooksFromConfig } from './effective-hook-config' import { getHookRuntimeTarget, getHookWslContext } from './hook-runtime-target' -import { getSetupEnvVars } from './setup-hook-env-vars' +import { getSetupEnvVars, type HookWorkspaceIdentity } from './setup-hook-env-vars' +import { applyHostHookOrcaCliEnv, wslHookOrcaCliEnv } from './hook-orca-cli-env' import { iterateLfScriptLines } from './setup-runner-script-text' import { promptGuardShellEnv } from '../git/command-runner/git-process-env' import { dropIncoherentCondaActivationEnv } from '../pty/shell-startup/conda-activation-env' @@ -185,10 +186,12 @@ export function runHook( repo: Repo, hooksPath?: string, projectRuntime?: ProjectExecutionRuntimeResolution | HookRuntimeTarget, - timeoutMs: number = HOOK_TIMEOUT + options: { identity?: HookWorkspaceIdentity; timeoutMs?: number; hooks?: OrcaHooks } = {} // Failed hooks without an observed exit are unverifiable to the removal gate (#19334). ): Promise<{ success: boolean; output: string; exitCode?: number }> { - const hooks = getEffectiveHooks(repo, hooksPath) + const timeoutMs = options.timeoutMs ?? HOOK_TIMEOUT + // A caller that already resolved the hooks passes them, so orca.yaml is read once. + const hooks = options.hooks ?? getEffectiveHooks(repo, hooksPath) const script = hooks?.scripts[hookName] if (!script) { @@ -200,14 +203,15 @@ export function runHook( if (wslInfo) { // WSL hooks need Linux paths for ORCA_* values, including Windows UNC paths. - const envVars = getSetupEnvVars(repo, cwd) + const envVars = getSetupEnvVars(repo, cwd, options.identity) const wslEnv: Record = {} for (const [key, value] of Object.entries(envVars)) { wslEnv[key] = toLinuxPath(value) } // Forward unattended Git flags to WSL; keep host askpass out of the guest. const guardedEnv = promptGuardShellEnv(wslEnv) - const guestEnv: Record = { ...wslEnv } + const wslCli = wslHookOrcaCliEnv() + const guestEnv: Record = { ...wslCli.env, ...wslEnv } for (const [key, value] of Object.entries(guardedEnv)) { if (value !== undefined && (key === 'GIT_TERMINAL_PROMPT' || key === 'GCM_INTERACTIVE')) { guestEnv[key] = value @@ -217,7 +221,7 @@ export function runHook( return runWslProcess({ distro: wslInfo.distro ?? undefined, loginPath: 'preferred', - script, + script: `${wslCli.scriptPrefix}${script}`, // Match native Bash hook semantics; sh would reject Bash-only scripts inside WSL. shell: 'bash', cwd: wslInfo.linuxPath, @@ -228,7 +232,9 @@ export function runHook( .catch((error: unknown) => hookSpawnFailure(error, { hookName, cwd })) } - const shellHookEnv: NodeJS.ProcessEnv = { ...process.env, ...getSetupEnvVars(repo, cwd) } + const shellHookEnv: NodeJS.ProcessEnv = { ...process.env } + applyHostHookOrcaCliEnv(shellHookEnv) + Object.assign(shellHookEnv, getSetupEnvVars(repo, cwd, options.identity)) dropIncoherentCondaActivationEnv(shellHookEnv) return new Promise((resolve) => { diff --git a/src/main/workspace-hooks/setup-hook-env-vars.ts b/src/main/workspace-hooks/setup-hook-env-vars.ts index 337bdc20322..81211369da7 100644 --- a/src/main/workspace-hooks/setup-hook-env-vars.ts +++ b/src/main/workspace-hooks/setup-hook-env-vars.ts @@ -1,6 +1,14 @@ import { getRuntimePathBasename } from '../../shared/cross-platform-path' import { TERMINAL_GIT_CREDENTIAL_GUARD_POLICY_ENV } from '../../shared/shell/launch/terminal-git-credential-guard' import type { Repo } from '../../shared/repo-types' +import { isFolderRepo } from '../../shared/repo-kind' + +/** The workspace a hook runs for; folder workspaces share one directory, so the path can't name them. */ +export type HookWorkspaceIdentity = { + worktreeId: string + /** Names a folder workspace; a worktree's name is its directory's. */ + displayName?: string +} // Path-valued keys only, so WSL and posix-shell launches translate them; names are not paths. export const SETUP_RUNNER_PATH_ENV_KEYS = [ @@ -12,24 +20,37 @@ export const SETUP_RUNNER_PATH_ENV_KEYS = [ ] as const export function getSetupEnvVars( - repo: Pick, - worktreePath: string + repo: Pick, + worktreePath: string, + identity?: HookWorkspaceIdentity ): Record { + const workspaceName = + identity?.displayName && isFolderRepo(repo) + ? identity.displayName + : getRuntimePathBasename(worktreePath) return { ORCA_ROOT_PATH: repo.path, ORCA_WORKTREE_PATH: worktreePath, - ORCA_WORKSPACE_NAME: getRuntimePathBasename(worktreePath), + ORCA_WORKSPACE_NAME: workspaceName, + // Same values a pane sets, so `orca worktree create` in the hook attaches to this workspace. + ...(identity + ? { ORCA_WORKSPACE_ID: identity.worktreeId, ORCA_WORKTREE_ID: identity.worktreeId } + : {}), // Imported Conductor scripts read these names. CONDUCTOR_ROOT_PATH: repo.path, CONDUCTOR_WORKSPACE_PATH: worktreePath, - CONDUCTOR_WORKSPACE_NAME: getRuntimePathBasename(worktreePath), + CONDUCTOR_WORKSPACE_NAME: workspaceName, GHOSTX_ROOT_PATH: repo.path } } -export function getSetupRunnerEnvVars(repo: Repo, worktreePath: string): Record { +export function getSetupRunnerEnvVars( + repo: Repo, + worktreePath: string, + identity?: HookWorkspaceIdentity +): Record { return { - ...getSetupEnvVars(repo, worktreePath), + ...getSetupEnvVars(repo, worktreePath, identity), // Unattended setup always needs credential protection, regardless of user opt-out. [TERMINAL_GIT_CREDENTIAL_GUARD_POLICY_ENV]: 'guard' } diff --git a/src/main/workspace-hooks/worktree-runner-script.ts b/src/main/workspace-hooks/worktree-runner-script.ts index cc3ca4c067d..e7dd4ef7288 100644 --- a/src/main/workspace-hooks/worktree-runner-script.ts +++ b/src/main/workspace-hooks/worktree-runner-script.ts @@ -1,4 +1,4 @@ -import { mkdirSync, writeFileSync, chmodSync } from 'node:fs' +import { chmod, mkdir, writeFile } from 'node:fs/promises' import { dirname } from 'node:path' import { shouldWaitForSetupBeforeAgentStartup } from '../../shared/agent-launch/startup/setup-agent-startup-policy' import { @@ -14,13 +14,20 @@ import { readWorktreeGitPath } from '../git/worktrees/catalog/worktree-git-path' import { resolveWslWorktreeGitPath } from '../git/worktrees/catalog/wsl-worktree-git-path' import { knownWslAutomountRoots } from '../wsl/filesystem/wsl-automount-root' import { isWslPath } from '../wsl/filesystem/unc-path-access' +import { windowsFsPath } from '../wsl/filesystem/wsl-unc-drive-fs-path' import { toWindowsWslPath, toLinuxPath } from '../../shared/wsl-paths' import { getHookRuntimeTarget, getHookWslContext, type HookRuntimeTarget } from './hook-runtime-target' -import { SETUP_RUNNER_PATH_ENV_KEYS, getSetupRunnerEnvVars } from './setup-hook-env-vars' +import { + SETUP_RUNNER_PATH_ENV_KEYS, + getSetupRunnerEnvVars, + type HookWorkspaceIdentity +} from './setup-hook-env-vars' +import { ignoreFolderSetupRunners, newFolderSetupRunnerPath } from './folder-setup-runner-files' +import { isFolderRepo } from '../../shared/repo-kind' import { buildPosixRunnerScript, buildWindowsRunnerScript } from './setup-runner-script-text' import type { Repo } from '../../shared/repo-types' @@ -44,9 +51,11 @@ export async function createSetupRunnerScript( script: string, projectRuntime?: ProjectExecutionRuntimeResolution | HookRuntimeTarget, setupShell?: SetupRunnerShell, - projectStartupPolicy?: SetupAgentStartupPolicy + projectStartupPolicy?: SetupAgentStartupPolicy, + identity?: HookWorkspaceIdentity ): Promise { return createWorktreeRunnerScript({ + identity, repo, worktreePath, script, @@ -68,6 +77,7 @@ async function createWorktreeRunnerScript(args: { runtimeTarget?: HookRuntimeTarget waitForAgentStartup?: boolean setupShell?: SetupRunnerShell + identity?: HookWorkspaceIdentity }): Promise { const { repo, @@ -76,9 +86,10 @@ async function createWorktreeRunnerScript(args: { runnerBaseName, runtimeTarget, waitForAgentStartup, - setupShell + setupShell, + identity } = args - const envVars = getSetupRunnerEnvVars(repo, worktreePath) + const envVars = getSetupRunnerEnvVars(repo, worktreePath, identity) const wslWorktree = isWslPath(worktreePath) || Boolean(runtimeTarget?.wslDistro) const nativeWindowsWorktree = process.platform === 'win32' && !wslWorktree // Preserve existing Windows cmd script syntax; only a shebang opts into bash, regardless of terminal preference. @@ -93,34 +104,28 @@ async function createWorktreeRunnerScript(args: { : process.platform === 'win32' && runtimeTarget?.wslDistro ? { family: 'posix', executable: 'wsl.exe' } : undefined - // Linked worktrees have .git files; resolve the per-worktree gitdir through Git. const runnerExtension = runnerShell.family === 'cmd' ? 'cmd' : 'sh' - const gitRelPath = `orca/${runnerBaseName}.${runnerExtension}` - // Read the link with the D1c Git router (if WSL Git made the worktree, host Git can't). A worktree - // inside a distro never runs synchronous Git: that would be a synchronous wsl.exe on the main thread. - const fromLink = isWslPath(worktreePath) - ? await resolveWslWorktreeGitPath(worktreePath, gitRelPath) - : isLocalGitRuntimeRouterInstalled() - ? readWorktreeGitPath(worktreePath, gitRelPath, knownWslAutomountRoots()) - : null - let runnerScriptPath = fromLink ?? getGitPath(worktreePath, gitRelPath) + const runnerScriptPath = isFolderRepo(repo) + ? newFolderSetupRunnerPath( + worktreePath, + requireFolderIdentity(identity).worktreeId, + runnerExtension + ) + : await resolveGitRunnerScriptPath(worktreePath, runnerBaseName, runnerExtension, runtimeTarget) - // Convert WSL Git's Linux path to a path Windows filesystem calls can reach. - if (wslWorktree && !fromLink) { - const wslInfo = getHookWslContext(worktreePath, runtimeTarget) - if (wslInfo?.distro) { - runnerScriptPath = toWindowsWslPath(runnerScriptPath.trim(), wslInfo.distro) - } + // Write through the drive path when WSL refuses its drive mounts over UNC; launch keeps the UNC spelling. + const runnerFsPath = windowsFsPath(runnerScriptPath) + await mkdir(dirname(runnerFsPath), { recursive: true }) + if (isFolderRepo(repo)) { + await ignoreFolderSetupRunners(dirname(dirname(runnerFsPath))) } - mkdirSync(dirname(runnerScriptPath), { recursive: true }) - if (runnerShell.family === 'cmd') { - writeFileSync(runnerScriptPath, buildWindowsRunnerScript(script), 'utf-8') + await writeFile(runnerFsPath, buildWindowsRunnerScript(script), 'utf-8') } else { - writeFileSync(runnerScriptPath, buildPosixRunnerScript(script), 'utf-8') + await writeFile(runnerFsPath, buildPosixRunnerScript(script), 'utf-8') if (!nativeWindowsWorktree) { - chmodSync(runnerScriptPath, 0o755) + await chmod(runnerFsPath, 0o755) } } @@ -148,6 +153,41 @@ async function createWorktreeRunnerScript(args: { } } +function requireFolderIdentity(identity: HookWorkspaceIdentity | undefined): HookWorkspaceIdentity { + if (!identity) { + throw new Error('A folder workspace setup runner needs the workspace it runs for.') + } + return identity +} + +async function resolveGitRunnerScriptPath( + worktreePath: string, + runnerBaseName: 'setup-runner', + runnerExtension: 'sh' | 'cmd', + runtimeTarget: HookRuntimeTarget | undefined +): Promise { + const wslWorktree = isWslPath(worktreePath) || Boolean(runtimeTarget?.wslDistro) + // Linked worktrees have .git files; resolve the per-worktree gitdir through Git. + const gitRelPath = `orca/${runnerBaseName}.${runnerExtension}` + // Read the link with the D1c Git router (if WSL Git made the worktree, host Git can't). A worktree + // inside a distro never runs synchronous Git: that would be a synchronous wsl.exe on the main thread. + const fromLink = isWslPath(worktreePath) + ? await resolveWslWorktreeGitPath(worktreePath, gitRelPath) + : isLocalGitRuntimeRouterInstalled() + ? readWorktreeGitPath(worktreePath, gitRelPath, knownWslAutomountRoots()) + : null + let runnerScriptPath = fromLink ?? getGitPath(worktreePath, gitRelPath) + + // Convert WSL Git's Linux path to a path Windows filesystem calls can reach. + if (wslWorktree && !fromLink) { + const wslInfo = getHookWslContext(worktreePath, runtimeTarget) + if (wslInfo?.distro) { + runnerScriptPath = toWindowsWslPath(runnerScriptPath.trim(), wslInfo.distro) + } + } + return runnerScriptPath +} + export function resolveSetupRunnerShell( settings: SetupRunnerShellSettings, platform: NodeJS.Platform = process.platform, diff --git a/src/main/workspaces/removal/folder-workspace-archive-hook.ts b/src/main/workspaces/removal/folder-workspace-archive-hook.ts new file mode 100644 index 00000000000..987e1f89c56 --- /dev/null +++ b/src/main/workspaces/removal/folder-workspace-archive-hook.ts @@ -0,0 +1,52 @@ +import { isRepoOnCatalogHost } from '../../../shared/execution-host' +import type { Repo } from '../../../shared/repo-types' +import type { ArchiveHookOverride } from '../../../shared/worktree/archive-hook-removal-gate' +import { removeFolderSetupRunnerFiles } from '../../workspace-hooks/folder-setup-runner-files' +import { getEffectiveHooks, runHook } from '../../workspace-hooks/hooks' +import type { HookRuntimeTarget } from '../../workspace-hooks/hook-runtime-target' +import { gateWorktreeRemovalOnArchiveHook } from './worktree-archive-hook-gate' +import { blockedWslDistroForPath } from '../../wsl/filesystem/wsl-unc-access-gate' + +/** + * Run a folder workspace's archive script before anything is torn down, as worktree removal does. + * Only the host holding the folder runs it; others own no files there. + */ +export async function gateFolderWorkspaceRemovalOnArchiveHook(args: { + repo: Repo + worktreeId: string + displayName: string + runArchive: boolean + allowFailure: boolean + runtimeTarget: () => HookRuntimeTarget | undefined +}): Promise { + const { repo } = args + if (!args.runArchive || !isRepoOnCatalogHost(repo)) { + return undefined + } + const hooks = getEffectiveHooks(repo) + if (!hooks?.scripts.archive) { + return undefined + } + const result = await runHook('archive', repo.path, repo, repo.path, args.runtimeTarget(), { + identity: { worktreeId: args.worktreeId, displayName: args.displayName }, + hooks + }) + return gateWorktreeRemovalOnArchiveHook({ + worktreePath: repo.path, + result, + allowFailure: args.allowFailure + }) +} + +/** Runner files are per launch; drop this workspace's once its processes have stopped. */ +export function removeFolderWorkspaceRunnerFiles(repo: Repo, worktreeId: string): void { + if (!isRepoOnCatalogHost(repo)) { + return + } + // A stopped distro keeps its leftover runners rather than starting for cleanup. + void blockedWslDistroForPath(repo.path) + .then((blocked) => (blocked ? undefined : removeFolderSetupRunnerFiles(repo.path, worktreeId))) + .catch((error: unknown) => { + console.warn(`[hooks] could not clean setup runners in ${repo.path}:`, error) + }) +} diff --git a/src/renderer/src/app-shell/AppBackgroundServices.tsx b/src/renderer/src/app-shell/AppBackgroundServices.tsx index 3eef624b6ae..23c1a6a6bcc 100644 --- a/src/renderer/src/app-shell/AppBackgroundServices.tsx +++ b/src/renderer/src/app-shell/AppBackgroundServices.tsx @@ -1,5 +1,5 @@ import { Suspense } from 'react' -import { lazyWithRetry as lazy } from '@/lib/lazy-with-retry' +import { lazyWithRetry as lazy } from '@/app-shell/startup/lazy-with-retry' import { AgentHibernationGate } from '../components/AgentHibernationGate' import { AiVaultTabTitleSyncGate } from '../components/AiVaultTabTitleSyncGate' import { WorkspacePortScanner } from '../components/ports/WorkspacePortScanner' diff --git a/src/renderer/src/app-shell/AppNotificationCards.tsx b/src/renderer/src/app-shell/AppNotificationCards.tsx index ea36809b65e..cdaf8cbd54c 100644 --- a/src/renderer/src/app-shell/AppNotificationCards.tsx +++ b/src/renderer/src/app-shell/AppNotificationCards.tsx @@ -1,6 +1,6 @@ import { Suspense, type JSX } from 'react' import type { TopLevelView } from '../../../shared/ui-chrome-types' -import { lazyWithRetry as lazy } from '@/lib/lazy-with-retry' +import { lazyWithRetry as lazy } from '@/app-shell/startup/lazy-with-retry' import { CodexSharedSettingsNoticeCard } from '../components/CodexSharedSettingsNoticeCard' import { NotificationCardStack } from '../components/NotificationCardStack' import { StarNagCard } from '../components/StarNagCard' diff --git a/src/renderer/src/app-shell/AppRootSurfaces.tsx b/src/renderer/src/app-shell/AppRootSurfaces.tsx index 916fb186043..4e71408df47 100644 --- a/src/renderer/src/app-shell/AppRootSurfaces.tsx +++ b/src/renderer/src/app-shell/AppRootSurfaces.tsx @@ -4,7 +4,7 @@ import { OnboardingLanguageLoading } from '../components/onboarding/OnboardingLa import { useLanguageReadiness } from '../i18n/language-readiness' import { memo, Suspense } from 'react' import { createPortal } from 'react-dom' -import { lazyWithRetry as lazy } from '@/lib/lazy-with-retry' +import { lazyWithRetry as lazy } from '@/app-shell/startup/lazy-with-retry' import { useTranslate } from '@/i18n/use-translate' import { RecoverableRenderErrorBoundary } from '../components/error-boundaries/RecoverableRenderErrorBoundary' import NewWorkspaceComposerModal from '../components/NewWorkspaceComposerModal' @@ -20,7 +20,7 @@ import { ZoomOverlay } from '../components/ZoomOverlay' import { WslMoveDialogHost } from '../components/wsl-move/WslMoveDialog' import { MacosUpdateRequirementHost } from '../components/macos-update-requirement/MacosUpdateRequirementHost' import { shouldRenderPetOverlay } from '../components/pet/pet-overlay-visibility' -import { useAppStore } from '../store' +import { useAppStore } from '../store/index' import type { UpdateStatus } from '../../../shared/update-status-types' import { useLazyModalMounts } from './use-lazy-modal-mounts' import { AppNotificationCards } from './AppNotificationCards' diff --git a/src/renderer/src/app-shell/AppWorkspaceShell.tsx b/src/renderer/src/app-shell/AppWorkspaceShell.tsx index ac4293de10e..2e038a6e551 100644 --- a/src/renderer/src/app-shell/AppWorkspaceShell.tsx +++ b/src/renderer/src/app-shell/AppWorkspaceShell.tsx @@ -1,12 +1,12 @@ import { memo, Suspense, useCallback, useRef } from 'react' -import { lazyWithRetry as lazy } from '@/lib/lazy-with-retry' +import { lazyWithRetry as lazy } from '@/app-shell/startup/lazy-with-retry' import { useTranslate } from '@/i18n/use-translate' -import { useAppStore } from '@/store' +import { useAppStore } from '@/store/index' import { usePluginViewCaptureStore } from '@/store/plugins/capture/plugin-view-capture' import { pendingCreationOpensNativeChat } from '@/lib/workspace/creation/pending-worktree-creation' import { showsFloatingRightSidebarToggle } from '@/lib/right-sidebar-visibility' import Sidebar from '../components/Sidebar' -import RightSidebar from '../components/right-sidebar' +import RightSidebar from '../components/right-sidebar/index' import { RecoverableRenderErrorBoundary } from '../components/error-boundaries/RecoverableRenderErrorBoundary' import { FloatingTerminalToggleButton } from '../components/floating-terminal/FloatingTerminalToggleButton' import { TerminalWorkbenchContainer } from '../components/TerminalWorkbenchContainer' diff --git a/src/renderer/src/app-shell/app-command-handlers.ts b/src/renderer/src/app-shell/app-command-handlers.ts index f880e57a27b..22807ffc08f 100644 --- a/src/renderer/src/app-shell/app-command-handlers.ts +++ b/src/renderer/src/app-shell/app-command-handlers.ts @@ -16,10 +16,10 @@ import { deleteHoveredWorkspaceImmediately, resolveHoveredWorkspaceDeleteTarget } from '../components/sidebar/workspace-actions/deletion/hovered-workspace-delete' -import { useAppStore } from '../store' +import { useAppStore } from '../store/index' import type { usePluginCommands } from '@/store/plugins/catalog/plugin-contribution-catalog' import { isGitRepoKind } from '../../../shared/repo-kind' -import { openPluginsSettings } from '@/lib/open-plugins-settings' +import { openPluginsSettings } from '@/components/settings/navigation/open-plugins-settings' import { resolveActiveTabRenameTarget } from './active-tab-rename-target' import { createPluginsSettingsShortcutHandler } from './plugin-settings-shortcut-handler' import type { diff --git a/src/renderer/src/app-shell/appearance/window-material-runtime.ts b/src/renderer/src/app-shell/appearance/window-material-runtime.ts index c21e63fe549..26652aed987 100644 --- a/src/renderer/src/app-shell/appearance/window-material-runtime.ts +++ b/src/renderer/src/app-shell/appearance/window-material-runtime.ts @@ -1,5 +1,5 @@ import type { WindowMaterial, WindowMaterialHost } from '../../../../shared/window-material' -import { getRendererAppPlatform } from '../../lib/renderer-app-platform' +import { getRendererAppPlatform } from '../platform/renderer-app-platform' let material: WindowMaterial | undefined diff --git a/src/renderer/src/lib/client-environment-info.ts b/src/renderer/src/app-shell/platform/client-environment-info.ts similarity index 96% rename from src/renderer/src/lib/client-environment-info.ts rename to src/renderer/src/app-shell/platform/client-environment-info.ts index fda7a1a295b..3e4f5cef314 100644 --- a/src/renderer/src/lib/client-environment-info.ts +++ b/src/renderer/src/app-shell/platform/client-environment-info.ts @@ -1,7 +1,7 @@ import { formatClientEnvironmentFooter, type ClientEnvironmentInfo -} from '../../../shared/client-environment-info' +} from '../../../../shared/client-environment-info' import { getRendererAppPlatform } from './renderer-app-platform' export async function resolveClientEnvironmentInfo(): Promise { diff --git a/src/renderer/src/lib/ios-web-platform.ts b/src/renderer/src/app-shell/platform/ios-web-platform.ts similarity index 100% rename from src/renderer/src/lib/ios-web-platform.ts rename to src/renderer/src/app-shell/platform/ios-web-platform.ts diff --git a/src/renderer/src/lib/paired-web-client-host.ts b/src/renderer/src/app-shell/platform/paired-web-client-host.ts similarity index 91% rename from src/renderer/src/lib/paired-web-client-host.ts rename to src/renderer/src/app-shell/platform/paired-web-client-host.ts index 9b7a0bc8860..af617064ec0 100644 --- a/src/renderer/src/lib/paired-web-client-host.ts +++ b/src/renderer/src/app-shell/platform/paired-web-client-host.ts @@ -2,8 +2,8 @@ import { parseExecutionHostId, toRuntimeExecutionHostId, type ExecutionHostId -} from '../../../shared/execution-host' -import { isPairedWebClientWindow } from './desktop-window-chrome' +} from '../../../../shared/execution-host' +import { isPairedWebClientWindow } from '../../lib/desktop-window-chrome' type HostRouteState = { runtimeEnvironments?: readonly { id: string }[] } diff --git a/src/renderer/src/lib/passive-macos-app-data-access.ts b/src/renderer/src/app-shell/platform/passive-macos-app-data-access.ts similarity index 97% rename from src/renderer/src/lib/passive-macos-app-data-access.ts rename to src/renderer/src/app-shell/platform/passive-macos-app-data-access.ts index 03f636fbeec..5c0bf9dfa50 100644 --- a/src/renderer/src/lib/passive-macos-app-data-access.ts +++ b/src/renderer/src/app-shell/platform/passive-macos-app-data-access.ts @@ -1,7 +1,7 @@ import type { ActiveRightSidebarTab, RightSidebarExplorerView -} from '../../../shared/ui-chrome-types' +} from '../../../../shared/ui-chrome-types' import type { OpenFile } from '@/store/slices/editor/types/open-file' const MAC_APP_DATA_SEGMENT_RE = /(^|\/)Library\/(Containers|Group Containers)\// diff --git a/src/renderer/src/lib/renderer-app-platform.ts b/src/renderer/src/app-shell/platform/renderer-app-platform.ts similarity index 100% rename from src/renderer/src/lib/renderer-app-platform.ts rename to src/renderer/src/app-shell/platform/renderer-app-platform.ts diff --git a/src/renderer/src/lib/user-agent-platform.ts b/src/renderer/src/app-shell/platform/user-agent-platform.ts similarity index 100% rename from src/renderer/src/lib/user-agent-platform.ts rename to src/renderer/src/app-shell/platform/user-agent-platform.ts diff --git a/src/renderer/src/lib/web-client-location.ts b/src/renderer/src/app-shell/platform/web-client-location.ts similarity index 100% rename from src/renderer/src/lib/web-client-location.ts rename to src/renderer/src/app-shell/platform/web-client-location.ts diff --git a/src/renderer/src/app-shell/shutdown-checkpoint-persist.ts b/src/renderer/src/app-shell/shutdown-checkpoint-persist.ts index 7865c4ab8a9..fc68ea42f6f 100644 --- a/src/renderer/src/app-shell/shutdown-checkpoint-persist.ts +++ b/src/renderer/src/app-shell/shutdown-checkpoint-persist.ts @@ -1,7 +1,7 @@ import type { PersistedUIState } from '../../../shared/persisted-ui-state-types' import { formatShutdownCheckpointFailureReason } from '../../../shared/renderer-shutdown-events' import type { WorkspaceSessionHostSnapshot } from '../lib/workspace/persistence/workspace-session-host-persistence' -import { recordRendererCrashBreadcrumb } from '../lib/crash-breadcrumb-recorder' +import { recordRendererCrashBreadcrumb } from '../diagnostics/crash-reporting/crash-breadcrumb-recorder' export type ShutdownCheckpointStageArgs = { sessions: WorkspaceSessionHostSnapshot[] diff --git a/src/renderer/src/app-shell/shutdown-checkpoint-restart-lifecycle.test.ts b/src/renderer/src/app-shell/shutdown-checkpoint-restart-lifecycle.test.ts deleted file mode 100644 index 1632187546b..00000000000 --- a/src/renderer/src/app-shell/shutdown-checkpoint-restart-lifecycle.test.ts +++ /dev/null @@ -1,142 +0,0 @@ -// @vitest-environment happy-dom -import { afterEach, describe, expect, it, vi } from 'vitest' -import { - ORCA_APP_RESTART_ABORTED_EVENT, - ORCA_APP_RESTART_STARTED_EVENT, - ORCA_UPDATER_QUIT_AND_INSTALL_ABORTED_EVENT, - ORCA_UPDATER_QUIT_AND_INSTALL_STARTED_EVENT -} from '../../../shared/updater-renderer-events' -import { - ORCA_RENDERER_SHUTDOWN_CHECKPOINT_ABORTED_EVENT, - ORCA_RENDERER_UNLOAD_PREVENTED_EVENT -} from '../../../shared/renderer-shutdown-events' -import { prepareRendererForAppRestart } from '../../../shared/renderer-restart-preparation' -import { - createShutdownCheckpointBeforeUnloadHandler, - createShutdownCheckpointGuard -} from '../lib/shutdown-checkpoint-guard' -import { - isIntentionalAppRestartInProgress, - registerUpdaterBeforeUnloadBypass -} from '../lib/updater-beforeunload' -import { - createShutdownCheckpointPersist, - type ShutdownCheckpointPersistDeps -} from './shutdown-checkpoint-persist' - -type LifecycleHarness = { - cleanup: () => void - prepare: () => Promise - stageBeforeUnloadSync: ReturnType -} - -type LifecycleHarnessOverrides = Partial< - Pick -> - -function createLifecycleHarness( - startedEventName: string, - abortedEventName: string, - overrides: LifecycleHarnessOverrides = {} -): LifecycleHarness { - const stageBeforeUnloadSync = vi.fn((args: { sessions: unknown[] }) => { - if (args.sessions.length > 0) { - throw new Error('deterministic full-stage failure') - } - }) - const persist = createShutdownCheckpointPersist({ - shouldCaptureSession: () => true, - captureTerminalBuffers: vi.fn(), - captureSleepingAgentSessions: vi.fn(), - buildSessionSnapshots: () => [{ state: { activeTabId: 't1' } }] as never, - buildUiPatch: () => ({ activeView: 'workspace' }) as never, - hasDirtyOpenFiles: () => false, - isDegradableShutdownInProgress: isIntentionalAppRestartInProgress, - stageBeforeUnloadSync, - ...overrides - }) - const guard = createShutdownCheckpointGuard(persist.run, persist.abandonAttempt) - const checkpoint = createShutdownCheckpointBeforeUnloadHandler(guard) - const cleanupRestartTracking = registerUpdaterBeforeUnloadBypass() - window.addEventListener('beforeunload', checkpoint) - window.addEventListener( - ORCA_RENDERER_SHUTDOWN_CHECKPOINT_ABORTED_EVENT, - guard.abortAfterCheckpointFailure - ) - window.addEventListener(abortedEventName, guard.abandonAttempt) - window.addEventListener(ORCA_RENDERER_UNLOAD_PREVENTED_EVENT, guard.abandonAttempt) - return { - stageBeforeUnloadSync, - prepare: () => - prepareRendererForAppRestart(window, { - startedEventName, - abortedEventName, - awaitCheckpoint: () => Promise.resolve() - }), - cleanup: () => { - cleanupRestartTracking() - window.removeEventListener('beforeunload', checkpoint) - window.removeEventListener( - ORCA_RENDERER_SHUTDOWN_CHECKPOINT_ABORTED_EVENT, - guard.abortAfterCheckpointFailure - ) - window.removeEventListener(abortedEventName, guard.abandonAttempt) - window.removeEventListener(ORCA_RENDERER_UNLOAD_PREVENTED_EVENT, guard.abandonAttempt) - } - } -} - -describe('shutdown checkpoint restart lifecycle', () => { - const cleanupFns: (() => void)[] = [] - - afterEach(() => { - cleanupFns.splice(0).forEach((cleanup) => cleanup()) - vi.restoreAllMocks() - }) - - it.each([ - { - lifecycle: 'app restart', - startedEventName: ORCA_APP_RESTART_STARTED_EVENT, - abortedEventName: ORCA_APP_RESTART_ABORTED_EVENT - }, - { - lifecycle: 'updater install', - startedEventName: ORCA_UPDATER_QUIT_AND_INSTALL_STARTED_EVENT, - abortedEventName: ORCA_UPDATER_QUIT_AND_INSTALL_ABORTED_EVENT - } - ])( - 'preserves retry-then-degrade across a checkpoint-caused $lifecycle abort', - async ({ startedEventName, abortedEventName }) => { - vi.spyOn(console, 'error').mockImplementation(() => {}) - const harness = createLifecycleHarness(startedEventName, abortedEventName) - cleanupFns.push(harness.cleanup) - - await expect(harness.prepare()).rejects.toThrow('deterministic full-stage failure') - expect(isIntentionalAppRestartInProgress()).toBe(false) - await expect(harness.prepare()).resolves.toBeUndefined() - - expect(harness.stageBeforeUnloadSync).toHaveBeenCalledTimes(3) - expect(harness.stageBeforeUnloadSync).toHaveBeenLastCalledWith({ - sessions: [], - ui: { activeView: 'workspace' } - }) - } - ) - - it('abandons retry state when a later restart attempt is independently canceled', async () => { - vi.spyOn(console, 'error').mockImplementation(() => {}) - const harness = createLifecycleHarness( - ORCA_APP_RESTART_STARTED_EVENT, - ORCA_APP_RESTART_ABORTED_EVENT - ) - cleanupFns.push(harness.cleanup) - - await expect(harness.prepare()).rejects.toThrow('deterministic full-stage failure') - window.dispatchEvent(new Event(ORCA_APP_RESTART_STARTED_EVENT)) - window.dispatchEvent(new Event(ORCA_APP_RESTART_ABORTED_EVENT)) - await expect(harness.prepare()).rejects.toThrow('deterministic full-stage failure') - - expect(harness.stageBeforeUnloadSync).toHaveBeenCalledTimes(2) - }) -}) diff --git a/src/renderer/src/lib/shutdown-checkpoint-failure-toast.ts b/src/renderer/src/app-shell/shutdown/shutdown-checkpoint-failure-toast.ts similarity index 95% rename from src/renderer/src/lib/shutdown-checkpoint-failure-toast.ts rename to src/renderer/src/app-shell/shutdown/shutdown-checkpoint-failure-toast.ts index 155389f7b4e..8f08f58b14d 100644 --- a/src/renderer/src/lib/shutdown-checkpoint-failure-toast.ts +++ b/src/renderer/src/app-shell/shutdown/shutdown-checkpoint-failure-toast.ts @@ -1,6 +1,6 @@ import { toast } from 'sonner' import { translate } from '@/i18n/i18n' -import { consumeShutdownCheckpointFailureReason } from '../../../shared/renderer-shutdown-events' +import { consumeShutdownCheckpointFailureReason } from '../../../../shared/renderer-shutdown-events' export function showShutdownCheckpointFailureToast( canceledAction: 'quit' | 'reload' = 'quit' diff --git a/src/renderer/src/lib/shutdown-checkpoint-guard.ts b/src/renderer/src/app-shell/shutdown/shutdown-checkpoint-guard.ts similarity index 93% rename from src/renderer/src/lib/shutdown-checkpoint-guard.ts rename to src/renderer/src/app-shell/shutdown/shutdown-checkpoint-guard.ts index 74c7be22ce3..37eff4da062 100644 --- a/src/renderer/src/lib/shutdown-checkpoint-guard.ts +++ b/src/renderer/src/app-shell/shutdown/shutdown-checkpoint-guard.ts @@ -4,8 +4,8 @@ import { ORCA_RENDERER_SHUTDOWN_CHECKPOINT_FAILED_EVENT, ORCA_RENDERER_UNLOAD_PREVENTED_EVENT, publishShutdownCheckpointFailureReason -} from '../../../shared/renderer-shutdown-events' -import { recordRendererCrashBreadcrumb } from './crash-breadcrumb-recorder' +} from '../../../../shared/renderer-shutdown-events' +import { recordRendererCrashBreadcrumb } from '../../diagnostics/crash-reporting/crash-breadcrumb-recorder' export type ShutdownCheckpointGuard = { persistOnce: () => boolean diff --git a/src/renderer/src/lib/active-view-persist.ts b/src/renderer/src/app-shell/startup/active-view-persist.ts similarity index 69% rename from src/renderer/src/lib/active-view-persist.ts rename to src/renderer/src/app-shell/startup/active-view-persist.ts index 3b2b4a4d349..75c86f571ce 100644 --- a/src/renderer/src/lib/active-view-persist.ts +++ b/src/renderer/src/app-shell/startup/active-view-persist.ts @@ -1,5 +1,5 @@ -import type { PersistedUIState } from '../../../shared/persisted-ui-state-types' -import type { TopLevelView } from '../../../shared/ui-chrome-types' +import type { PersistedUIState } from '../../../../shared/persisted-ui-state-types' +import type { TopLevelView } from '../../../../shared/ui-chrome-types' type ActiveViewUnloadState = { activeView: TopLevelView diff --git a/src/renderer/src/lib/e2e-config.ts b/src/renderer/src/app-shell/startup/e2e-config.ts similarity index 94% rename from src/renderer/src/lib/e2e-config.ts rename to src/renderer/src/app-shell/startup/e2e-config.ts index 15d19bbced2..fd0b1769bba 100644 --- a/src/renderer/src/lib/e2e-config.ts +++ b/src/renderer/src/app-shell/startup/e2e-config.ts @@ -1,4 +1,4 @@ -import { createE2EConfig } from '../../../shared/e2e-config' +import { createE2EConfig } from '../../../../shared/e2e-config' const rendererE2EExposeStore = String(import.meta.env.VITE_EXPOSE_STORE) === 'true' // The paired API installs after module initialization; read the build-gated test URL before caching configuration. diff --git a/src/renderer/src/lib/lazy-chunk-recovery-reload.ts b/src/renderer/src/app-shell/startup/lazy-chunk-recovery-reload.ts similarity index 91% rename from src/renderer/src/lib/lazy-chunk-recovery-reload.ts rename to src/renderer/src/app-shell/startup/lazy-chunk-recovery-reload.ts index 64e78fc283a..52984e70057 100644 --- a/src/renderer/src/lib/lazy-chunk-recovery-reload.ts +++ b/src/renderer/src/app-shell/startup/lazy-chunk-recovery-reload.ts @@ -1,9 +1,9 @@ -import { prepareRendererForAppRestart } from '../../../shared/renderer-restart-preparation' -import { ORCA_RENDERER_UNLOAD_PREVENTED_EVENT } from '../../../shared/renderer-shutdown-events' +import { prepareRendererForAppRestart } from '../../../../shared/renderer-restart-preparation' +import { ORCA_RENDERER_UNLOAD_PREVENTED_EVENT } from '../../../../shared/renderer-shutdown-events' import { ORCA_APP_RESTART_ABORTED_EVENT, ORCA_APP_RESTART_STARTED_EVENT -} from '../../../shared/updater-renderer-events' +} from '../../../../shared/updater-renderer-events' // Bare reloads are vetoed by dirty tabs; restart preparation backs them up first. diff --git a/src/renderer/src/lib/lazy-with-retry.never-landed-reload.test.ts b/src/renderer/src/app-shell/startup/lazy-with-retry.never-landed-reload.test.ts similarity index 100% rename from src/renderer/src/lib/lazy-with-retry.never-landed-reload.test.ts rename to src/renderer/src/app-shell/startup/lazy-with-retry.never-landed-reload.test.ts diff --git a/src/renderer/src/lib/lazy-with-retry.ts b/src/renderer/src/app-shell/startup/lazy-with-retry.ts similarity index 100% rename from src/renderer/src/lib/lazy-with-retry.ts rename to src/renderer/src/app-shell/startup/lazy-with-retry.ts diff --git a/src/renderer/src/lib/react-renderer-root.ts b/src/renderer/src/app-shell/startup/react-renderer-root.ts similarity index 100% rename from src/renderer/src/lib/react-renderer-root.ts rename to src/renderer/src/app-shell/startup/react-renderer-root.ts diff --git a/src/renderer/src/lib/startup-ui-hydration.ts b/src/renderer/src/app-shell/startup/startup-ui-hydration.ts similarity index 94% rename from src/renderer/src/lib/startup-ui-hydration.ts rename to src/renderer/src/app-shell/startup/startup-ui-hydration.ts index 894ab91c162..624fefeba59 100644 --- a/src/renderer/src/lib/startup-ui-hydration.ts +++ b/src/renderer/src/app-shell/startup/startup-ui-hydration.ts @@ -5,8 +5,8 @@ import { DEFAULT_SHOW_SLEEPING_WORKSPACES, DEFAULT_STATUS_BAR_ITEMS, DEFAULT_WORKTREE_CARD_PROPERTIES -} from '../../../shared/constants' -import type { PersistedUIState } from '../../../shared/persisted-ui-state-types' +} from '../../../../shared/constants' +import type { PersistedUIState } from '../../../../shared/persisted-ui-state-types' export function hydratePersistedUIAfterStartupRead({ persistedUI, diff --git a/src/renderer/src/lib/update-check-click-options.ts b/src/renderer/src/app-shell/updates/update-check-click-options.ts similarity index 85% rename from src/renderer/src/lib/update-check-click-options.ts rename to src/renderer/src/app-shell/updates/update-check-click-options.ts index 59869b1de96..282e004346b 100644 --- a/src/renderer/src/lib/update-check-click-options.ts +++ b/src/renderer/src/app-shell/updates/update-check-click-options.ts @@ -1,5 +1,5 @@ -import type { UpdateCheckOptions } from '../../../shared/update-status-types' -import { getShortcutPlatform } from './keyboard/shortcut-platform' +import type { UpdateCheckOptions } from '../../../../shared/update-status-types' +import { getShortcutPlatform } from '../../lib/keyboard/shortcut-platform' type UpdateCheckClickEvent = Pick diff --git a/src/renderer/src/lib/updater-beforeunload.ts b/src/renderer/src/app-shell/updates/updater-beforeunload.ts similarity index 89% rename from src/renderer/src/lib/updater-beforeunload.ts rename to src/renderer/src/app-shell/updates/updater-beforeunload.ts index 42f3e72587b..d728bf22506 100644 --- a/src/renderer/src/lib/updater-beforeunload.ts +++ b/src/renderer/src/app-shell/updates/updater-beforeunload.ts @@ -3,15 +3,11 @@ import { ORCA_APP_RESTART_STARTED_EVENT, ORCA_UPDATER_QUIT_AND_INSTALL_ABORTED_EVENT, ORCA_UPDATER_QUIT_AND_INSTALL_STARTED_EVENT -} from '../../../shared/updater-renderer-events' -import { ORCA_RENDERER_SHUTDOWN_CHECKPOINT_ABORTED_EVENT } from '../../../shared/renderer-shutdown-events' +} from '../../../../shared/updater-renderer-events' +import { ORCA_RENDERER_SHUTDOWN_CHECKPOINT_ABORTED_EVENT } from '../../../../shared/renderer-shutdown-events' let intentionalAppRestartInProgress = false -export function isUpdaterQuitAndInstallInProgress(): boolean { - return isIntentionalAppRestartInProgress() -} - export function isIntentionalAppRestartInProgress(): boolean { return intentionalAppRestartInProgress } diff --git a/src/renderer/src/lib/updater-message-copy.ts b/src/renderer/src/app-shell/updates/updater-message-copy.ts similarity index 53% rename from src/renderer/src/lib/updater-message-copy.ts rename to src/renderer/src/app-shell/updates/updater-message-copy.ts index 76a90f2745f..7d1cca61568 100644 --- a/src/renderer/src/lib/updater-message-copy.ts +++ b/src/renderer/src/app-shell/updates/updater-message-copy.ts @@ -1,99 +1,163 @@ import { translate } from '@/i18n/i18n' -import type { LinuxPackageCommandUnavailableReason } from '../../../shared/update-status-types' +import type { LinuxPackageCommandUnavailableReason } from '../../../../shared/update-status-types' import { - UPDATER_FAILURE_COPY as EN, + UPDATER_FAILURE_COPY, type UpdaterFailureCode -} from '../../../shared/updater-failure-copy' +} from '../../../../shared/updater-failure-copy' type Param = (name: string) => string | null type CountParam = (name: string) => number | null // null = required params missing; caller shows the host's English message. const COPY: Record string | null> = { - releaseNotReady: () => translate('updates.failure.releaseNotReady', EN.releaseNotReady), + releaseNotReady: () => + translate('updates.failure.releaseNotReady', UPDATER_FAILURE_COPY.releaseNotReady), updateServerUnreachable: () => - translate('updates.failure.updateServerUnreachable', EN.updateServerUnreachable), + translate( + 'updates.failure.updateServerUnreachable', + UPDATER_FAILURE_COPY.updateServerUnreachable + ), channelUnsupportedPlatform: (param) => { const channel = param('channel') return channel === null ? null - : translate('updates.failure.channelUnsupportedPlatform', EN.channelUnsupportedPlatform, { - channel - }) + : translate( + 'updates.failure.channelUnsupportedPlatform', + UPDATER_FAILURE_COPY.channelUnsupportedPlatform, + { + channel + } + ) }, unsignedDevChannel: (param) => { const channel = param('channel') return channel === null ? null - : translate('updates.failure.unsignedDevChannel', EN.unsignedDevChannel, { channel }) + : translate('updates.failure.unsignedDevChannel', UPDATER_FAILURE_COPY.unsignedDevChannel, { + channel + }) }, linuxPackageMissing: () => - translate('updates.failure.linuxPackageMissing', EN.linuxPackageMissing), + translate('updates.failure.linuxPackageMissing', UPDATER_FAILURE_COPY.linuxPackageMissing), linuxPackageNotRegular: () => - translate('updates.failure.linuxPackageNotRegular', EN.linuxPackageNotRegular), + translate( + 'updates.failure.linuxPackageNotRegular', + UPDATER_FAILURE_COPY.linuxPackageNotRegular + ), linuxPackageHashMismatch: () => - translate('updates.failure.linuxPackageHashMismatch', EN.linuxPackageHashMismatch), + translate( + 'updates.failure.linuxPackageHashMismatch', + UPDATER_FAILURE_COPY.linuxPackageHashMismatch + ), linuxPackageReadFailed: () => - translate('updates.failure.linuxPackageReadFailed', EN.linuxPackageReadFailed), - linuxPackageNoSudo: () => translate('updates.failure.linuxPackageNoSudo', EN.linuxPackageNoSudo), + translate( + 'updates.failure.linuxPackageReadFailed', + UPDATER_FAILURE_COPY.linuxPackageReadFailed + ), + linuxPackageNoSudo: () => + translate('updates.failure.linuxPackageNoSudo', UPDATER_FAILURE_COPY.linuxPackageNoSudo), linuxPackageNoPackageManager: () => - translate('updates.failure.linuxPackageNoPackageManager', EN.linuxPackageNoPackageManager), + translate( + 'updates.failure.linuxPackageNoPackageManager', + UPDATER_FAILURE_COPY.linuxPackageNoPackageManager + ), linuxPackageInvalidPath: () => - translate('updates.failure.linuxPackageInvalidPath', EN.linuxPackageInvalidPath), + translate( + 'updates.failure.linuxPackageInvalidPath', + UPDATER_FAILURE_COPY.linuxPackageInvalidPath + ), linuxPackageMarkerUnusable: () => - translate('updates.failure.linuxPackageMarkerUnusable', EN.linuxPackageMarkerUnusable), + translate( + 'updates.failure.linuxPackageMarkerUnusable', + UPDATER_FAILURE_COPY.linuxPackageMarkerUnusable + ), linuxPackageExternallyManaged: () => - translate('updates.failure.linuxPackageExternallyManaged', EN.linuxPackageExternallyManaged), + translate( + 'updates.failure.linuxPackageExternallyManaged', + UPDATER_FAILURE_COPY.linuxPackageExternallyManaged + ), linuxPackageManualInstall: () => - translate('updates.failure.linuxPackageManualInstall', EN.linuxPackageManualInstall), + translate( + 'updates.failure.linuxPackageManualInstall', + UPDATER_FAILURE_COPY.linuxPackageManualInstall + ), linuxPackageMetadataUnusable: () => - translate('updates.failure.linuxPackageMetadataUnusable', EN.linuxPackageMetadataUnusable), + translate( + 'updates.failure.linuxPackageMetadataUnusable', + UPDATER_FAILURE_COPY.linuxPackageMetadataUnusable + ), unknownReleaseChannel: (param) => { const channel = param('channel') return channel === null ? null - : translate('updates.failure.unknownReleaseChannel', EN.unknownReleaseChannel, { channel }) + : translate( + 'updates.failure.unknownReleaseChannel', + UPDATER_FAILURE_COPY.unknownReleaseChannel, + { channel } + ) }, invalidReleaseTag: (param) => { const tag = param('tag') return tag === null ? null - : translate('updates.failure.invalidReleaseTag', EN.invalidReleaseTag, { tag }) + : translate('updates.failure.invalidReleaseTag', UPDATER_FAILURE_COPY.invalidReleaseTag, { + tag + }) }, releaseRepoNotFound: (param) => { const repo = param('repo') return repo === null ? null - : translate('updates.failure.releaseRepoNotFound', EN.releaseRepoNotFound, { repo }) + : translate('updates.failure.releaseRepoNotFound', UPDATER_FAILURE_COPY.releaseRepoNotFound, { + repo + }) }, releaseListFailed: (param, count) => { const channel = param('channel') const status = count('status') return channel === null || status === null ? null - : translate('updates.failure.releaseListFailed', EN.releaseListFailed, { channel, status }) + : translate('updates.failure.releaseListFailed', UPDATER_FAILURE_COPY.releaseListFailed, { + channel, + status + }) }, releaseListUnreadable: (param) => { const channel = param('channel') return channel === null ? null - : translate('updates.failure.releaseListUnreadable', EN.releaseListUnreadable, { channel }) + : translate( + 'updates.failure.releaseListUnreadable', + UPDATER_FAILURE_COPY.releaseListUnreadable, + { channel } + ) }, - rateLimitedSoon: () => translate('updates.failure.rateLimitedSoon', EN.rateLimitedSoon), + rateLimitedSoon: () => + translate('updates.failure.rateLimitedSoon', UPDATER_FAILURE_COPY.rateLimitedSoon), rateLimitedSoonSignedOut: () => - translate('updates.failure.rateLimitedSoonSignedOut', EN.rateLimitedSoonSignedOut), + translate( + 'updates.failure.rateLimitedSoonSignedOut', + UPDATER_FAILURE_COPY.rateLimitedSoonSignedOut + ), rateLimitedInMinute: () => - translate('updates.failure.rateLimitedInMinute', EN.rateLimitedInMinute), + translate('updates.failure.rateLimitedInMinute', UPDATER_FAILURE_COPY.rateLimitedInMinute), rateLimitedInMinuteSignedOut: () => - translate('updates.failure.rateLimitedInMinuteSignedOut', EN.rateLimitedInMinuteSignedOut), + translate( + 'updates.failure.rateLimitedInMinuteSignedOut', + UPDATER_FAILURE_COPY.rateLimitedInMinuteSignedOut + ), rateLimitedInMinutes: (_param, count) => { const minutes = count('count') return minutes === null ? null - : translate('updates.failure.rateLimitedInMinutes', EN.rateLimitedInMinutes, { - count: minutes, - defaultValue_one: 'GitHub rate limit reached. Try again in about {{count}} minute.' - }) + : translate( + 'updates.failure.rateLimitedInMinutes', + UPDATER_FAILURE_COPY.rateLimitedInMinutes, + { + count: minutes, + defaultValue_one: 'GitHub rate limit reached. Try again in about {{count}} minute.' + } + ) }, rateLimitedInMinutesSignedOut: (_param, count) => { const minutes = count('count') @@ -101,7 +165,7 @@ const COPY: Record stri ? null : translate( 'updates.failure.rateLimitedInMinutesSignedOut', - EN.rateLimitedInMinutesSignedOut, + UPDATER_FAILURE_COPY.rateLimitedInMinutesSignedOut, { count: minutes, defaultValue_one: diff --git a/src/renderer/src/app-shell/use-app-session-persistence.ts b/src/renderer/src/app-shell/use-app-session-persistence.ts index d420f4a0093..9fca4439f46 100644 --- a/src/renderer/src/app-shell/use-app-session-persistence.ts +++ b/src/renderer/src/app-shell/use-app-session-persistence.ts @@ -1,12 +1,12 @@ import { useEffect } from 'react' -import { useAppStore } from '../store' +import { useAppStore } from '../store/index' import { ORCA_LAYOUT_OWNER_IS_MAIN } from '../../../shared/layout-owner-switch' import { createSessionWriteSubscriber } from '../lib/workspace/persistence/session-write-subscriber' -import { buildActiveViewUnloadPatch } from '../lib/active-view-persist' +import { buildActiveViewUnloadPatch } from './startup/active-view-persist' import { isIntentionalAppRestartInProgress, registerUpdaterBeforeUnloadBypass -} from '../lib/updater-beforeunload' +} from './updates/updater-beforeunload' import { buildWorkspaceSessionPayload, shouldPersistWorkspaceSession @@ -18,8 +18,8 @@ import { import { createShutdownCheckpointBeforeUnloadHandler, createShutdownCheckpointGuard -} from '../lib/shutdown-checkpoint-guard' -import { showShutdownCheckpointFailureToast } from '../lib/shutdown-checkpoint-failure-toast' +} from './shutdown/shutdown-checkpoint-guard' +import { showShutdownCheckpointFailureToast } from './shutdown/shutdown-checkpoint-failure-toast' import { isPairedWebClientWindow } from '../lib/desktop-window-chrome' import { createShutdownCheckpointPersist } from './shutdown-checkpoint-persist' import { shutdownBufferCaptures } from '../components/terminal-pane/snapshots/shutdown-buffer-captures' diff --git a/src/renderer/src/app-shell/use-app-startup-hydration.ts b/src/renderer/src/app-shell/use-app-startup-hydration.ts index a8c203d9de5..f8aa1abb34d 100644 --- a/src/renderer/src/app-shell/use-app-startup-hydration.ts +++ b/src/renderer/src/app-shell/use-app-startup-hydration.ts @@ -3,7 +3,7 @@ import { useEffect, useRef } from 'react' import { restoreLocalStructuredChatsAtStartup } from '@/runtime/native-chat/local-sessions/local-structured-chats' import { syncZoomCSSVar } from '@/lib/ui-zoom' import { installCodexDetachedPaneRestartExecutor } from '@/components/terminal-pane/account-restart/detached/codex-detached-pane-restart-scheduler' -import { useAppStore } from '../store' +import { useAppStore } from '../store/index' import { reconcileHydratedWorkspaceTabModels } from './reconcile-hydrated-workspace-tab-models' import { useStartupActions } from './use-app-startup-actions' import { waitForNativeChatDraftsAtStartup } from './native-chat-draft-startup' @@ -14,7 +14,7 @@ import { collectFolderWorkspaceKeysFromSession, collectWorktreeHydrationRepoIdsFromSession } from '../lib/workspace/persistence/workspace-session-hydration-keys' -import { hydratePersistedUIAfterStartupRead } from '../lib/startup-ui-hydration' +import { hydratePersistedUIAfterStartupRead } from './startup/startup-ui-hydration' import { logRendererStartupDiagnostic, timeRendererStartupStep, diff --git a/src/renderer/src/app-shell/use-onboarding-and-feature-tips.ts b/src/renderer/src/app-shell/use-onboarding-and-feature-tips.ts index 3394b68510b..7f8ef1f0d9d 100644 --- a/src/renderer/src/app-shell/use-onboarding-and-feature-tips.ts +++ b/src/renderer/src/app-shell/use-onboarding-and-feature-tips.ts @@ -13,8 +13,8 @@ import { trackCmdJPaletteFeatureTipShown, trackOrcaCliFeatureTipShown } from '../components/feature-tips/feature-tip-telemetry' -import { useAppStore } from '../store' -import { isWebClientLocation } from '../lib/web-client-location' +import { useAppStore } from '../store/index' +import { isWebClientLocation } from './platform/web-client-location' import type { OnboardingState } from '../../../shared/onboarding-state-types' export type OnboardingGate = ReturnType diff --git a/src/renderer/src/app-shell/use-visible-hosted-review-refresh.test.tsx b/src/renderer/src/app-shell/use-visible-hosted-review-refresh.test.tsx deleted file mode 100644 index 65ddda49d3d..00000000000 --- a/src/renderer/src/app-shell/use-visible-hosted-review-refresh.test.tsx +++ /dev/null @@ -1,54 +0,0 @@ -// @vitest-environment happy-dom -import { cleanup, renderHook } from '@testing-library/react' -import { afterEach, expect, it, vi } from 'vitest' -import { useVisibleHostedReviewRefresh } from './use-visible-hosted-review-refresh' - -const mocks = vi.hoisted(() => ({ - refresh: vi.fn(async () => true), - getState: vi.fn(() => ({})), - subscribe: vi.fn(() => vi.fn()), - web: vi.fn(() => false) -})) -vi.mock('@/store', () => ({ - useAppStore: { getState: mocks.getState, subscribe: mocks.subscribe } -})) -vi.mock('@/lib/web-client-location', () => ({ isWebClientLocation: mocks.web })) -vi.mock('@/store/slices/hosted-review/refresh/visible-hosted-review-refresh-targets', () => ({ - visibleHostedReviewRefreshInputsChanged: () => true, - getVisibleHostedReviewWorkspaces: () => [], - getVisibleHostedReviewRefreshTargets: () => [ - { - key: 'review', - revision: 'head', - selected: true, - intervalMs: 60_000, - fetchedAt: null, - refresh: mocks.refresh - } - ] -})) -afterEach(() => { - cleanup() - vi.useRealTimers() - vi.restoreAllMocks() -}) - -it('waits for workspace readiness and stops timers/subscription when disabled', async () => { - vi.useFakeTimers() - vi.spyOn(document, 'visibilityState', 'get').mockReturnValue('visible') - const hook = renderHook(({ enabled }) => useVisibleHostedReviewRefresh({ enabled }), { - initialProps: { enabled: false } - }) - await vi.advanceTimersByTimeAsync(600_000) - expect(mocks.refresh).not.toHaveBeenCalled() - expect(mocks.subscribe).not.toHaveBeenCalled() - hook.rerender({ enabled: true }) - await vi.advanceTimersByTimeAsync(0) - expect(mocks.refresh).toHaveBeenCalledOnce() - const unsubscribe = mocks.subscribe.mock.results[0].value - hook.rerender({ enabled: false }) - expect(unsubscribe).toHaveBeenCalledOnce() - expect(vi.getTimerCount()).toBe(0) - await vi.advanceTimersByTimeAsync(600_000) - expect(mocks.refresh).toHaveBeenCalledOnce() -}) diff --git a/src/renderer/src/app-shell/use-visible-hosted-review-refresh.ts b/src/renderer/src/app-shell/use-visible-hosted-review-refresh.ts index 2ebfa9857ac..01a33014bd2 100644 --- a/src/renderer/src/app-shell/use-visible-hosted-review-refresh.ts +++ b/src/renderer/src/app-shell/use-visible-hosted-review-refresh.ts @@ -1,7 +1,7 @@ import { useEffect } from 'react' -import { useAppStore } from '@/store' -import { isWindowVisible } from '@/lib/window-visibility-interval' -import { isWebClientLocation } from '@/lib/web-client-location' +import { useAppStore } from '@/store/index' +import { isWindowVisible } from '@/lib/window-activity/window-visibility-interval' +import { isWebClientLocation } from '@/app-shell/platform/web-client-location' import { createVisibleHostedReviewRefreshScheduler } from '@/store/slices/hosted-review/refresh/visible-hosted-review-refresh-scheduler' import { getWorkspaceReferenceRefreshTargets } from '@/components/sidebar/workspace-card/review/workspace-reference-refresh-targets' import { diff --git a/src/renderer/src/app-shell/worktree-jump-palette-preload.ts b/src/renderer/src/app-shell/worktree-jump-palette-preload.ts index c1438604988..cc058334e79 100644 --- a/src/renderer/src/app-shell/worktree-jump-palette-preload.ts +++ b/src/renderer/src/app-shell/worktree-jump-palette-preload.ts @@ -1,6 +1,6 @@ import { useEffect } from 'react' -import { scheduleAfterInputQuiet } from '@/lib/input-quiet-scheduler' -import { lazyWithPreload } from '@/lib/lazy-with-retry' +import { scheduleAfterInputQuiet } from '@/lib/window-activity/input-quiet-scheduler' +import { lazyWithPreload } from '@/app-shell/startup/lazy-with-retry' export const WorktreeJumpPalette = lazyWithPreload( () => import('../components/worktree-jump/WorktreeJumpPalette') diff --git a/src/renderer/src/attention/agent-finish-drop-breadcrumb.ts b/src/renderer/src/attention/agent-finish-drop-breadcrumb.ts index 9c42d0049e4..195a5672a3a 100644 --- a/src/renderer/src/attention/agent-finish-drop-breadcrumb.ts +++ b/src/renderer/src/attention/agent-finish-drop-breadcrumb.ts @@ -1,4 +1,4 @@ -import { recordRendererCrashBreadcrumb } from '@/lib/crash-breadcrumb-recorder' +import { recordRendererCrashBreadcrumb } from '@/diagnostics/crash-reporting/crash-breadcrumb-recorder' /** Why a finished agent turn did not mark its workspace unread. */ export type AgentFinishDropCause = diff --git a/src/renderer/src/components/AgentProgressRing.tsx b/src/renderer/src/components/AgentProgressRing.tsx index 51becb59da2..07c6e6b297f 100644 --- a/src/renderer/src/components/AgentProgressRing.tsx +++ b/src/renderer/src/components/AgentProgressRing.tsx @@ -1,5 +1,5 @@ import React from 'react' -import { cn } from '@/lib/utils' +import { cn } from '@/lib/class-names' export type AgentProgressRingTone = 'working' | 'attention' diff --git a/src/renderer/src/components/AgentQuestionIcon.tsx b/src/renderer/src/components/AgentQuestionIcon.tsx index 880fd6dcb55..2da63e9823f 100644 --- a/src/renderer/src/components/AgentQuestionIcon.tsx +++ b/src/renderer/src/components/AgentQuestionIcon.tsx @@ -1,6 +1,6 @@ import React from 'react' import { MessageCircleQuestion } from 'lucide-react' -import { cn } from '@/lib/utils' +import { cn } from '@/lib/class-names' // Share the question glyph and --agent-question token across sidebar, tabs, dashboard and kanban; callers choose size. diff --git a/src/renderer/src/components/AgentStateDot.tsx b/src/renderer/src/components/AgentStateDot.tsx index f9449bdfb64..3772ef44f3a 100644 --- a/src/renderer/src/components/AgentStateDot.tsx +++ b/src/renderer/src/components/AgentStateDot.tsx @@ -1,6 +1,6 @@ import React from 'react' import { Activity, CircleCheck, CircleDashed } from 'lucide-react' -import { cn } from '@/lib/utils' +import { cn } from '@/lib/class-names' import { translate } from '@/i18n/i18n' import { useUiLanguageRevision } from '@/i18n/use-ui-language-revision' import { AgentQuestionIcon } from '@/components/AgentQuestionIcon' diff --git a/src/renderer/src/components/AgentWorkingSpinner.tsx b/src/renderer/src/components/AgentWorkingSpinner.tsx index 763380067a4..56ce94ad0e5 100644 --- a/src/renderer/src/components/AgentWorkingSpinner.tsx +++ b/src/renderer/src/components/AgentWorkingSpinner.tsx @@ -1,6 +1,6 @@ import React from 'react' -import { cn } from '@/lib/utils' -import { observeOffscreenAnimation } from '@/lib/offscreen-animation-pause' +import { cn } from '@/lib/class-names' +import { observeOffscreenAnimation } from '@/lib/window-activity/offscreen-animation-pause' const SPINNER_ANIMATION_NAME = 'agent-spinner-rotate' diff --git a/src/renderer/src/components/AiVaultTabTitleSyncGate.tsx b/src/renderer/src/components/AiVaultTabTitleSyncGate.tsx index e69b4864d11..edfd0f50901 100644 --- a/src/renderer/src/components/AiVaultTabTitleSyncGate.tsx +++ b/src/renderer/src/components/AiVaultTabTitleSyncGate.tsx @@ -1,7 +1,7 @@ import { useEffect } from 'react' import { startAiVaultTabTitleSync } from '@/lib/agent-session/history/title-sync/ai-vault-tab-title-sync' -import { scheduleAfterInputQuiet } from '@/lib/input-quiet-scheduler' -import { useAppStore } from '@/store' +import { scheduleAfterInputQuiet } from '@/lib/window-activity/input-quiet-scheduler' +import { useAppStore } from '@/store/index' const TITLE_SYNC_DELAY_MS = 1_000 const TITLE_SYNC_QUIET_MS = 1_500 diff --git a/src/renderer/src/components/DetachedHeadBadge.tsx b/src/renderer/src/components/DetachedHeadBadge.tsx index 6671735514d..4f834cdc32e 100644 --- a/src/renderer/src/components/DetachedHeadBadge.tsx +++ b/src/renderer/src/components/DetachedHeadBadge.tsx @@ -2,7 +2,7 @@ import React from 'react' import { GitCommitHorizontal } from 'lucide-react' import { Badge } from '@/components/ui/badge' import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip' -import { cn } from '@/lib/utils' +import { cn } from '@/lib/class-names' import type { WorktreeGitIdentityDisplay } from '../../../shared/worktree/git-identity-display' type DetachedHeadDisplay = Extract diff --git a/src/renderer/src/components/FirstLaunchBanner.tsx b/src/renderer/src/components/FirstLaunchBanner.tsx index 1a40a437175..17fbc55609a 100644 --- a/src/renderer/src/components/FirstLaunchBanner.tsx +++ b/src/renderer/src/components/FirstLaunchBanner.tsx @@ -4,7 +4,11 @@ import { useState } from 'react' import { X } from 'lucide-react' import { Button } from './ui/button' -import { acknowledgeBanner, PRIVACY_URL, setOptIn as telemetrySetOptIn } from '../lib/telemetry' +import { + acknowledgeBanner, + PRIVACY_URL, + setOptIn as telemetrySetOptIn +} from '../diagnostics/telemetry/telemetry' import { useMountedRef } from '@/hooks/useMountedRef' import { useTranslate } from '@/i18n/use-translate' import { openAppHttpLink } from '@/lib/browser/navigation/app-http-link-open' diff --git a/src/renderer/src/components/Landing.tsx b/src/renderer/src/components/Landing.tsx index c2d660f3f17..f3b1c67e35d 100644 --- a/src/renderer/src/components/Landing.tsx +++ b/src/renderer/src/components/Landing.tsx @@ -1,7 +1,7 @@ import { useEffect, useEffectEvent, useMemo, useRef, useState } from 'react' import { AlertTriangle, ExternalLink, FolderPlus, GitBranchPlus, Star, X } from 'lucide-react' -import { cn } from '../lib/utils' -import { useAppStore } from '../store' +import { cn } from '../lib/class-names' +import { useAppStore } from '../store/index' import { isGitRepoKind } from '../../../shared/repo-kind' import type { Repo } from '../../../shared/repo-types' import { diff --git a/src/renderer/src/components/LinearIssueMarkdownDescriptionEditor.tsx b/src/renderer/src/components/LinearIssueMarkdownDescriptionEditor.tsx index 438a3d7681e..c041cf0be09 100644 --- a/src/renderer/src/components/LinearIssueMarkdownDescriptionEditor.tsx +++ b/src/renderer/src/components/LinearIssueMarkdownDescriptionEditor.tsx @@ -14,11 +14,11 @@ import { } from '@/components/editor/rich-markdown/document/rich-markdown-source-transport' import { LinearIssueMarkdownToolbar } from '@/components/LinearIssueMarkdownToolbar' import { RichMarkdownTableControls } from '@/components/editor/rich-markdown/tables/RichMarkdownTableControls' -import { isScreenSubmitShortcut } from '@/lib/screen-submit-shortcut' -import { cn } from '@/lib/utils' +import { isScreenSubmitShortcut } from '@/lib/keyboard/screen-submit-shortcut' +import { cn } from '@/lib/class-names' import { translate } from '@/i18n/i18n' import { useTranslate } from '@/i18n/use-translate' -import { useAppStore } from '@/store' +import { useAppStore } from '@/store/index' import { getRichMarkdownSpellcheckAttribute, useRichMarkdownSpellcheckAttribute diff --git a/src/renderer/src/components/LinearIssueMarkdownToolbar.tsx b/src/renderer/src/components/LinearIssueMarkdownToolbar.tsx index 16e6a84229f..973a1b7e4f7 100644 --- a/src/renderer/src/components/LinearIssueMarkdownToolbar.tsx +++ b/src/renderer/src/components/LinearIssueMarkdownToolbar.tsx @@ -17,7 +17,7 @@ import { } from 'lucide-react' import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip' -import { cn } from '@/lib/utils' +import { cn } from '@/lib/class-names' import { translate } from '@/i18n/i18n' import { useTranslate } from '@/i18n/use-translate' diff --git a/src/renderer/src/components/LinearIssueTextEditor.tsx b/src/renderer/src/components/LinearIssueTextEditor.tsx index 110eb89794b..1a8aa83266b 100644 --- a/src/renderer/src/components/LinearIssueTextEditor.tsx +++ b/src/renderer/src/components/LinearIssueTextEditor.tsx @@ -7,9 +7,12 @@ import { toast } from 'sonner' import { LinearIssueMarkdownDescriptionEditor } from '@/components/LinearIssueMarkdownDescriptionEditor' import { useMountedRef } from '@/hooks/useMountedRef' -import { cn } from '@/lib/utils' -import { useAppStore } from '@/store' -import { getScreenSubmitShortcutLabel, isScreenSubmitShortcut } from '@/lib/screen-submit-shortcut' +import { cn } from '@/lib/class-names' +import { useAppStore } from '@/store/index' +import { + getScreenSubmitShortcutLabel, + isScreenSubmitShortcut +} from '@/lib/keyboard/screen-submit-shortcut' import { linearUpdateIssue } from '@/runtime/linear/runtime-linear-issue-client' import type { LinearIssue } from '../../../shared/linear/issue-types' import type { TaskSourceContext } from '../../../shared/work-items/task-source-context' diff --git a/src/renderer/src/components/LinuxPackageInstallRecoveryCard.tsx b/src/renderer/src/components/LinuxPackageInstallRecoveryCard.tsx index 3c4d9686999..978cd18b89b 100644 --- a/src/renderer/src/components/LinuxPackageInstallRecoveryCard.tsx +++ b/src/renderer/src/components/LinuxPackageInstallRecoveryCard.tsx @@ -7,7 +7,7 @@ import type { import { UpdateErrorCardContent } from './UpdateErrorCardContent' import { translate } from '@/i18n/i18n' import { useTranslate } from '@/i18n/use-translate' -import { linuxPackageCommandUnavailableText } from '@/lib/updater-message-copy' +import { linuxPackageCommandUnavailableText } from '@/app-shell/updates/updater-message-copy' import { useMountedRef } from '@/hooks/useMountedRef' function copiedNote(packageFileName: string): string { diff --git a/src/renderer/src/components/LoadingSpinner.tsx b/src/renderer/src/components/LoadingSpinner.tsx index 0b91dd04be6..40e0dcaceab 100644 --- a/src/renderer/src/components/LoadingSpinner.tsx +++ b/src/renderer/src/components/LoadingSpinner.tsx @@ -1,6 +1,6 @@ import React from 'react' import { Hourglass, Loader2 } from 'lucide-react' -import { cn } from '@/lib/utils' +import { cn } from '@/lib/class-names' // Reduced motion uses an hourglass rather than a stuck spinner. Hide it only when motion is allowed; hidden plus motion-reduce:block left it hidden. export function LoadingSpinner({ className }: { className?: string }): React.JSX.Element { diff --git a/src/renderer/src/components/NewWorkspaceComposerCard.tsx b/src/renderer/src/components/NewWorkspaceComposerCard.tsx index 3a898de67f3..fc28448d151 100644 --- a/src/renderer/src/components/NewWorkspaceComposerCard.tsx +++ b/src/renderer/src/components/NewWorkspaceComposerCard.tsx @@ -1,17 +1,17 @@ import React from 'react' import { useTranslation } from 'react-i18next' import { toast } from 'sonner' -import { useAppStore } from '@/store' -import { cn } from '@/lib/utils' +import { useAppStore } from '@/store/index' +import { cn } from '@/lib/class-names' import { getAgentCatalog } from '@/lib/agent-catalog/agent-catalog' -import { getScreenSubmitModifierLabel } from '@/lib/screen-submit-shortcut' +import { getScreenSubmitModifierLabel } from '@/lib/keyboard/screen-submit-shortcut' import { resolveProjectCloneUrlPrefill } from '@/lib/workspace/creation/project-clone-url-prefill' import { useContextualTour } from '@/components/contextual-tours/use-contextual-tour' import { AddRemoteHostDialog, type AddRemoteHostMode } from '@/components/sidebar/host-admission/ssh/AddRemoteHostDialog' -import { lazyWithRetry } from '@/lib/lazy-with-retry' +import { lazyWithRetry } from '@/app-shell/startup/lazy-with-retry' import type * as SetProjectLocationDialogModule from '@/components/new-workspace/SetProjectLocationDialog' import { unwrapRuntimeRpcResult } from '@/runtime/rpc/calls/runtime-rpc-result' import { withUiConnectTimeout } from '@/ssh/ssh-connect-ui-timeout' diff --git a/src/renderer/src/components/NewWorkspaceComposerModal.tsx b/src/renderer/src/components/NewWorkspaceComposerModal.tsx index c0a27c4122c..d36e3994a86 100644 --- a/src/renderer/src/components/NewWorkspaceComposerModal.tsx +++ b/src/renderer/src/components/NewWorkspaceComposerModal.tsx @@ -13,7 +13,7 @@ import { agentChoicePending } from '@/lib/agent-session/launch/inventory/host-ch import type { AgentLaunchSurface } from '@/lib/agent-session/launch/routing/agent-session-launch-plan' import React, { Suspense, useCallback, useEffect, useMemo, useRef, useState } from 'react' import { useAppStore } from '@/store/index' -import { lazyWithRetry } from '@/lib/lazy-with-retry' +import { lazyWithRetry } from '@/app-shell/startup/lazy-with-retry' import { Dialog, DialogContent, @@ -35,7 +35,7 @@ import { } from '@/lib/workspace/creation/quick-workspace-agent-selection' import { useAgentsOfferedForLaunch } from '@/lib/agent-session/launch/inventory/host-chat-program-acquisition' import { shouldAllowComposerEnterSubmitTarget } from '@/lib/workspace/creation/new-workspace-enter-guard' -import { isScreenSubmitShortcut } from '@/lib/screen-submit-shortcut' +import { isScreenSubmitShortcut } from '@/lib/keyboard/screen-submit-shortcut' import type { TuiAgent } from '../../../shared/agent-launch/catalog/tui-agent' import { translate } from '@/i18n/i18n' import { useTranslate } from '@/i18n/use-translate' diff --git a/src/renderer/src/components/OrcaSignInProgress.tsx b/src/renderer/src/components/OrcaSignInProgress.tsx index 10caa6e6dae..371b9a585f5 100644 --- a/src/renderer/src/components/OrcaSignInProgress.tsx +++ b/src/renderer/src/components/OrcaSignInProgress.tsx @@ -3,8 +3,8 @@ import { toast } from 'sonner' import { Button } from './ui/button' import { translate } from '@/i18n/i18n' import { useTranslate } from '@/i18n/use-translate' -import { cn } from '@/lib/utils' -import { useAppStore } from '../store' +import { cn } from '@/lib/class-names' +import { useAppStore } from '../store/index' async function copySignInLink(link: string): Promise { try { diff --git a/src/renderer/src/components/ShortcutKeyCombo.tsx b/src/renderer/src/components/ShortcutKeyCombo.tsx index 396680ad38b..c9696840ea9 100644 --- a/src/renderer/src/components/ShortcutKeyCombo.tsx +++ b/src/renderer/src/components/ShortcutKeyCombo.tsx @@ -1,5 +1,5 @@ import React from 'react' -import { cn } from '@/lib/utils' +import { cn } from '@/lib/class-names' import { useTranslate } from '@/i18n/use-translate' function KeyCap({ diff --git a/src/renderer/src/components/TerminalLegacyEditorSurface.tsx b/src/renderer/src/components/TerminalLegacyEditorSurface.tsx index 33fcd96dd30..25a906a1fec 100644 --- a/src/renderer/src/components/TerminalLegacyEditorSurface.tsx +++ b/src/renderer/src/components/TerminalLegacyEditorSurface.tsx @@ -1,5 +1,5 @@ import { Suspense } from 'react' -import { lazyWithRetry as lazy } from '@/lib/lazy-with-retry' +import { lazyWithRetry as lazy } from '@/app-shell/startup/lazy-with-retry' import { useTranslate } from '@/i18n/use-translate' import type { TerminalController } from './use-terminal-controller' diff --git a/src/renderer/src/components/UnexpectedSignoutCard.tsx b/src/renderer/src/components/UnexpectedSignoutCard.tsx index 6526bbab29b..86dc10bc0f8 100644 --- a/src/renderer/src/components/UnexpectedSignoutCard.tsx +++ b/src/renderer/src/components/UnexpectedSignoutCard.tsx @@ -1,8 +1,8 @@ import { useEffect, useState } from 'react' import { BookOpen, ChevronDown, CircleUserRound, Files, Smartphone, X } from 'lucide-react' -import { useAppStore } from '../store' +import { useAppStore } from '../store/index' import { useTranslate } from '@/i18n/use-translate' -import { cn } from '@/lib/utils' +import { cn } from '@/lib/class-names' import { Button } from './ui/button' import { Card } from './ui/card' import { Collapsible, CollapsibleContent, CollapsibleTrigger } from './ui/collapsible' diff --git a/src/renderer/src/components/UpdateCard.tsx b/src/renderer/src/components/UpdateCard.tsx index 95105a3408b..f32f72c6e5d 100644 --- a/src/renderer/src/components/UpdateCard.tsx +++ b/src/renderer/src/components/UpdateCard.tsx @@ -2,11 +2,11 @@ import { useCallback, useEffect, useRef, useState } from 'react' import { X } from 'lucide-react' import type { ChangelogData } from '../../../shared/update-status-types' import { usePrefersReducedMotion } from '@/hooks/usePrefersReducedMotion' -import { useAppStore } from '../store' +import { useAppStore } from '../store/index' import { Card } from './ui/card' import { Button } from './ui/button' import { useTranslate } from '@/i18n/use-translate' -import { updaterMessageText } from '@/lib/updater-message-copy' +import { updaterMessageText } from '@/app-shell/updates/updater-message-copy' import { UpdateCardStateContent } from './maintenance/update-card/UpdateCardStateContent' import { buildUpdateCardErrorModel } from './maintenance/update-card/update-card-error-model' import { diff --git a/src/renderer/src/components/activity/activity-thread-context-menu.tsx b/src/renderer/src/components/activity/activity-thread-context-menu.tsx index 725fceb20b7..9bfb38d71ae 100644 --- a/src/renderer/src/components/activity/activity-thread-context-menu.tsx +++ b/src/renderer/src/components/activity/activity-thread-context-menu.tsx @@ -10,10 +10,10 @@ import { } from '@/components/ui/context-menu' import { translate } from '@/i18n/i18n' import { useTranslate, type Translate } from '@/i18n/use-translate' -import { CLOSE_ALL_CONTEXT_MENUS_EVENT } from '@/lib/close-all-context-menus' +import { CLOSE_ALL_CONTEXT_MENUS_EVENT } from '@/lib/overlay-interaction/close-all-context-menus' import { formatClipboardFilePath } from '@/lib/clipboard/clipboard-file-path' import { getWorktreeRowLocalPathOpenOwner } from '@/lib/workspace/ownership/worktree-row-open-in-owner' -import { useAppStore } from '@/store' +import { useAppStore } from '@/store/index' import { clearActivityThread, clearCompletedActivity, diff --git a/src/renderer/src/components/activity/activity-thread-controls.tsx b/src/renderer/src/components/activity/activity-thread-controls.tsx index d9520854b5f..f90a355788e 100644 --- a/src/renderer/src/components/activity/activity-thread-controls.tsx +++ b/src/renderer/src/components/activity/activity-thread-controls.tsx @@ -3,7 +3,7 @@ import { ChevronDown } from 'lucide-react' import { AgentStateDot } from '@/components/AgentStateDot' import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip' import { useNow } from '@/hooks/use-now' -import { cn } from '@/lib/utils' +import { cn } from '@/lib/class-names' import { formatShortTimeAgo } from '@/lib/short-time-ago' import { RepoBadgeMark } from '@/components/repo/RepoBadgeLabel' import type { Repo } from '../../../../shared/repo-types' diff --git a/src/renderer/src/components/activity/activity-thread-detail-pane.tsx b/src/renderer/src/components/activity/activity-thread-detail-pane.tsx index db2fab50f99..171c7e448fa 100644 --- a/src/renderer/src/components/activity/activity-thread-detail-pane.tsx +++ b/src/renderer/src/components/activity/activity-thread-detail-pane.tsx @@ -1,7 +1,7 @@ import React from 'react' import { MessageSquareText, TerminalSquare } from 'lucide-react' import { AgentTypeIcon } from '@/components/agent/icons/agent-type-icon' -import { cn } from '@/lib/utils' +import { cn } from '@/lib/class-names' import { useTranslate } from '@/i18n/use-translate' import { EventRepoBadge, ThreadAgentStateIndicator } from './activity-thread-controls' import type { ActivityTerminalPortalSlotId, AgentPaneThread } from './activity-thread-types' diff --git a/src/renderer/src/components/activity/activity-thread-hover-card-summary.tsx b/src/renderer/src/components/activity/activity-thread-hover-card-summary.tsx index 663bc53bed5..0d02ee03145 100644 --- a/src/renderer/src/components/activity/activity-thread-hover-card-summary.tsx +++ b/src/renderer/src/components/activity/activity-thread-hover-card-summary.tsx @@ -1,7 +1,7 @@ import React, { useCallback, useMemo } from 'react' import { Cloud, Copy, FolderGit2, GitBranch, Laptop, LocateFixed, Server } from 'lucide-react' import { toast } from 'sonner' -import { useAppStore } from '@/store' +import { useAppStore } from '@/store/index' import { RepoBadgeMark } from '@/components/repo/RepoBadgeLabel' import { AgentTypeIcon } from '@/components/agent/icons/agent-type-icon' import { formatAgentTypeLabel } from '../../../../shared/agent-status/presentation/agent-type-label' @@ -11,7 +11,7 @@ import { translate } from '@/i18n/i18n' import { useTranslate } from '@/i18n/use-translate' import { formatClipboardFilePath } from '@/lib/clipboard/clipboard-file-path' import { getWorktreeRowLocalPathOpenOwner } from '@/lib/workspace/ownership/worktree-row-open-in-owner' -import { cn } from '@/lib/utils' +import { cn } from '@/lib/class-names' import { getExecutionHostLabel, getWorktreeExecutionHostId, diff --git a/src/renderer/src/components/activity/activity-thread-list-pane.tsx b/src/renderer/src/components/activity/activity-thread-list-pane.tsx index 473f72e8d3a..13168f4f233 100644 --- a/src/renderer/src/components/activity/activity-thread-list-pane.tsx +++ b/src/renderer/src/components/activity/activity-thread-list-pane.tsx @@ -6,7 +6,7 @@ import { useVirtualizer, type Range } from '@tanstack/react-virtual' -import { cn } from '@/lib/utils' +import { cn } from '@/lib/class-names' import { useTranslate } from '@/i18n/use-translate' import { ActivityThreadListToolbar } from './activity-thread-list-toolbar' import { diff --git a/src/renderer/src/components/activity/activity-thread-list-resize-handle.tsx b/src/renderer/src/components/activity/activity-thread-list-resize-handle.tsx index 810a2b47853..65f1c34e455 100644 --- a/src/renderer/src/components/activity/activity-thread-list-resize-handle.tsx +++ b/src/renderer/src/components/activity/activity-thread-list-resize-handle.tsx @@ -1,5 +1,5 @@ import type React from 'react' -import { cn } from '@/lib/utils' +import { cn } from '@/lib/class-names' import { useTranslate } from '@/i18n/use-translate' export function ActivityThreadListResizeHandle({ diff --git a/src/renderer/src/components/activity/activity-thread-list-toolbar.tsx b/src/renderer/src/components/activity/activity-thread-list-toolbar.tsx index 49bf1348cc2..80e9cdd09d6 100644 --- a/src/renderer/src/components/activity/activity-thread-list-toolbar.tsx +++ b/src/renderer/src/components/activity/activity-thread-list-toolbar.tsx @@ -11,7 +11,7 @@ import { } from '@/components/ui/select' import { Toggle } from '@/components/ui/toggle' import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip' -import { cn } from '@/lib/utils' +import { cn } from '@/lib/class-names' import { useTranslate } from '@/i18n/use-translate' import { ActivityThreadOptionsMenu } from './activity-thread-controls' import type { diff --git a/src/renderer/src/components/activity/activity-thread-row.tsx b/src/renderer/src/components/activity/activity-thread-row.tsx index ef6e21f58fa..e1f43c68f97 100644 --- a/src/renderer/src/components/activity/activity-thread-row.tsx +++ b/src/renderer/src/components/activity/activity-thread-row.tsx @@ -4,7 +4,7 @@ import { AgentTypeIcon } from '@/components/agent/icons/agent-type-icon' import { formatAgentTypeLabel } from '../../../../shared/agent-status/presentation/agent-type-label' import { Button } from '@/components/ui/button' import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@/components/ui/tooltip' -import { cn } from '@/lib/utils' +import { cn } from '@/lib/class-names' import { useTranslate } from '@/i18n/use-translate' import { useUiLanguageRevision } from '@/i18n/use-ui-language-revision' import '../sidebar/workspace-card/activity/worktree-card-empty-inputs' diff --git a/src/renderer/src/components/agent/AgentCombobox.tsx b/src/renderer/src/components/agent/AgentCombobox.tsx index a91dbaf4751..ca201f1ae47 100644 --- a/src/renderer/src/components/agent/AgentCombobox.tsx +++ b/src/renderer/src/components/agent/AgentCombobox.tsx @@ -11,7 +11,7 @@ import { getAgentPickerCommandValue, searchAgentPickerEntries } from '@/lib/agent-catalog/agent-picker-search' -import { cn } from '@/lib/utils' +import { cn } from '@/lib/class-names' import type { TuiAgent } from '../../../../shared/agent-launch/catalog/tui-agent' import * as state from './agent-combobox-command-state' import { diff --git a/src/renderer/src/components/agent/AgentLaunchSetupFooter.tsx b/src/renderer/src/components/agent/AgentLaunchSetupFooter.tsx index 82edb8b3792..c716668ece6 100644 --- a/src/renderer/src/components/agent/AgentLaunchSetupFooter.tsx +++ b/src/renderer/src/components/agent/AgentLaunchSetupFooter.tsx @@ -2,7 +2,7 @@ import { terminalPendingLabel } from '../tab-bar/new-tab-agent-menu-model' import { useImperativeHandle, useRef, type Ref } from 'react' import { CornerDownLeft, MessageSquare, SquareTerminal } from 'lucide-react' import { Button } from '@/components/ui/button' -import { cn } from '@/lib/utils' +import { cn } from '@/lib/class-names' import { ShortcutKeyCombo } from '@/components/ShortcutKeyCombo' import { translate } from '@/i18n/i18n' import { useTranslate, type Translate } from '@/i18n/use-translate' diff --git a/src/renderer/src/components/agent/AgentLaunchSetupPanel.tsx b/src/renderer/src/components/agent/AgentLaunchSetupPanel.tsx index e3bcdbd25d0..e72c21251f4 100644 --- a/src/renderer/src/components/agent/AgentLaunchSetupPanel.tsx +++ b/src/renderer/src/components/agent/AgentLaunchSetupPanel.tsx @@ -21,7 +21,7 @@ import { } from '@/components/ui/command' import { useTranslate } from '@/i18n/use-translate' import { agentModelChoiceChips } from './launch-settings/agent-model-choice-chips' -import { isScreenSubmitShortcut } from '@/lib/screen-submit-shortcut' +import { isScreenSubmitShortcut } from '@/lib/keyboard/screen-submit-shortcut' import { isImeOwnedKeyboardEvent } from '@/lib/text-input/ime/ime-composition-keyboard-event' import { AgentDefaultArgsInput } from './launch-settings/AgentLaunchDefaultsEditor' import { NativeChatSessionOptionRows } from '../native-chat/session/options/controls/NativeChatSessionOptionRows' diff --git a/src/renderer/src/components/agent/AgentSettingsDialog.tsx b/src/renderer/src/components/agent/AgentSettingsDialog.tsx index 415ba2ff320..a7e10158096 100644 --- a/src/renderer/src/components/agent/AgentSettingsDialog.tsx +++ b/src/renderer/src/components/agent/AgentSettingsDialog.tsx @@ -1,7 +1,10 @@ import { useAppStateValue, useAppStateViewActive } from '@/store/retained-views/app-state-view' import React, { useCallback } from 'react' -import { useAppStore } from '@/store' -import { getOverlayFocusOwners, overlayFocusContains } from '@/lib/overlay-focus-ownership' +import { useAppStore } from '@/store/index' +import { + getOverlayFocusOwners, + overlayFocusContains +} from '@/lib/overlay-interaction/overlay-focus-ownership' import { Dialog, DialogContent, @@ -15,7 +18,7 @@ import { isWindowsTerminalCapabilityHost, useLocalWindowsTerminalCapabilities } from '@/runtime/hosts/capabilities/windows-terminal-capabilities' -import { isWebClientLocation } from '@/lib/web-client-location' +import { isWebClientLocation } from '@/app-shell/platform/web-client-location' import { useWindowsTerminalCapabilityOwnerKey } from '@/hooks/useWindowsTerminalCapabilityOwnerKey' import { resolveSettingsHostScope } from '@/components/settings/host-scope/settings-host-scope' diff --git a/src/renderer/src/components/agent/AgentSurfaceLaunchButton.tsx b/src/renderer/src/components/agent/AgentSurfaceLaunchButton.tsx index 100dc494258..cc260ec60a0 100644 --- a/src/renderer/src/components/agent/AgentSurfaceLaunchButton.tsx +++ b/src/renderer/src/components/agent/AgentSurfaceLaunchButton.tsx @@ -1,6 +1,6 @@ import React from 'react' import { MessageSquare, SquareTerminal } from 'lucide-react' -import { cn } from '@/lib/utils' +import { cn } from '@/lib/class-names' type AgentSurfaceLaunchButtonProps = Omit, 'children' | 'title'> & { title: string diff --git a/src/renderer/src/components/agent/agent-combobox-items.tsx b/src/renderer/src/components/agent/agent-combobox-items.tsx index 347adbf7da6..0d18046c13a 100644 --- a/src/renderer/src/components/agent/agent-combobox-items.tsx +++ b/src/renderer/src/components/agent/agent-combobox-items.tsx @@ -7,7 +7,7 @@ import { ContextMenuItem, ContextMenuTrigger } from '@/components/ui/context-menu' -import { cn } from '@/lib/utils' +import { cn } from '@/lib/class-names' import { useTranslate } from '@/i18n/use-translate' type ItemRenderArgs = { diff --git a/src/renderer/src/components/agent/agent-combobox-surface-items.tsx b/src/renderer/src/components/agent/agent-combobox-surface-items.tsx index 0749ff09194..b9f66b0cb67 100644 --- a/src/renderer/src/components/agent/agent-combobox-surface-items.tsx +++ b/src/renderer/src/components/agent/agent-combobox-surface-items.tsx @@ -13,7 +13,7 @@ import { rowLabel, rowTitle } from '@/components/tab-bar/tab-agent-row-presentation' -import { cn } from '@/lib/utils' +import { cn } from '@/lib/class-names' import { translate } from '@/i18n/i18n' import { useTranslate, type Translate } from '@/i18n/use-translate' import type { TuiAgent } from '../../../../shared/agent-launch/catalog/tui-agent' diff --git a/src/renderer/src/components/agent/icons/agent-icon-glyphs.tsx b/src/renderer/src/components/agent/icons/agent-icon-glyphs.tsx index be70a55196e..2cc72aa94f0 100644 --- a/src/renderer/src/components/agent/icons/agent-icon-glyphs.tsx +++ b/src/renderer/src/components/agent/icons/agent-icon-glyphs.tsx @@ -1,5 +1,5 @@ import React from 'react' -import { cn } from '../../../lib/utils' +import { cn } from '../../../lib/class-names' export function PiIcon({ size = 14, diff --git a/src/renderer/src/components/agent/launch-settings/AgentDefaultSurfacePreviews.tsx b/src/renderer/src/components/agent/launch-settings/AgentDefaultSurfacePreviews.tsx index 64e73ff1657..aa9c0a5cf9a 100644 --- a/src/renderer/src/components/agent/launch-settings/AgentDefaultSurfacePreviews.tsx +++ b/src/renderer/src/components/agent/launch-settings/AgentDefaultSurfacePreviews.tsx @@ -19,7 +19,7 @@ import { useIntlLocale, useTranslate } from '@/i18n/use-translate' import { AgentIcon } from '@/components/agent/icons/AgentIcon' import { buildFontFamily } from '../../../../../shared/monospace-font-family' import { resolveEffectiveTerminalAppearance } from '@/lib/terminal-theme' -import { cn } from '@/lib/utils' +import { cn } from '@/lib/class-names' // The tip's chat miniature, finished and denser so it fits a tile; nothing here animates. const CHAT_SCALE: CSSProperties & { '--chat-font-size': string } = { '--chat-font-size': '10px' } diff --git a/src/renderer/src/components/agent/launch-settings/AgentPermissionMenu.tsx b/src/renderer/src/components/agent/launch-settings/AgentPermissionMenu.tsx index 5755c37a089..cbce5d28108 100644 --- a/src/renderer/src/components/agent/launch-settings/AgentPermissionMenu.tsx +++ b/src/renderer/src/components/agent/launch-settings/AgentPermissionMenu.tsx @@ -1,5 +1,5 @@ import { useTranslate } from '../../../i18n/use-translate' -import { cn } from '../../../lib/utils' +import { cn } from '../../../lib/class-names' import { ChevronDown } from 'lucide-react' import { Button } from '../../ui/button' import { Label } from '../../ui/label' diff --git a/src/renderer/src/components/artifacts/ArtifactCollection.tsx b/src/renderer/src/components/artifacts/ArtifactCollection.tsx index 08663157396..564400b5542 100644 --- a/src/renderer/src/components/artifacts/ArtifactCollection.tsx +++ b/src/renderer/src/components/artifacts/ArtifactCollection.tsx @@ -3,12 +3,12 @@ import { Loader2 } from 'lucide-react' import type { ArtifactListItem } from '../../../../shared/artifacts/artifacts' import { Button } from '@/components/ui/button' import { useTranslate } from '@/i18n/use-translate' -import { cn } from '@/lib/utils' +import { cn } from '@/lib/class-names' import { clampArtifactListSearchQuery, filterArtifactsBySearchQuery } from './artifact-list-search' import { ArtifactListRows } from './ArtifactListRows' import { ArtifactListTableHeader } from './ArtifactListTableHeader' import { ArtifactListToolbar } from './ArtifactListToolbar' -import { LIST_TABLE_CONTAINER_CLASS } from '@/lib/list-table-layout' +import { LIST_TABLE_CONTAINER_CLASS } from '@/lib/list-interaction/list-table-layout' export function ArtifactCollection({ artifacts, diff --git a/src/renderer/src/components/artifacts/ArtifactListRow.tsx b/src/renderer/src/components/artifacts/ArtifactListRow.tsx index 47e63f1b3eb..c1088a175fe 100644 --- a/src/renderer/src/components/artifacts/ArtifactListRow.tsx +++ b/src/renderer/src/components/artifacts/ArtifactListRow.tsx @@ -19,8 +19,11 @@ import { } from '@/components/ui/dropdown-menu' import { translate } from '@/i18n/i18n' import { useIntlLocale, useTranslate, type Translate } from '@/i18n/use-translate' -import { cn } from '@/lib/utils' -import { isPortaledRowMenuClick, isRowActivationKey } from '@/lib/list-row-interaction' +import { cn } from '@/lib/class-names' +import { + isPortaledRowMenuClick, + isRowActivationKey +} from '@/lib/list-interaction/list-row-interaction' import { artifactName, artifactTypeLabel, @@ -34,7 +37,7 @@ import { LIST_TABLE_ROW_CLASS, LIST_TABLE_ROW_DIVIDER_CLASS, LIST_TABLE_ROW_SELECTED_CLASS -} from '@/lib/list-table-layout' +} from '@/lib/list-interaction/list-table-layout' type ArtifactRowAction = { key: string diff --git a/src/renderer/src/components/artifacts/ArtifactListSearchField.tsx b/src/renderer/src/components/artifacts/ArtifactListSearchField.tsx index f33d9200119..05c54d1787f 100644 --- a/src/renderer/src/components/artifacts/ArtifactListSearchField.tsx +++ b/src/renderer/src/components/artifacts/ArtifactListSearchField.tsx @@ -3,7 +3,7 @@ import { Search, X } from 'lucide-react' import { Button } from '@/components/ui/button' import { Input } from '@/components/ui/input' import { useTranslate } from '@/i18n/use-translate' -import { cn } from '@/lib/utils' +import { cn } from '@/lib/class-names' export function ArtifactListSearchField({ query, diff --git a/src/renderer/src/components/artifacts/ArtifactListTableHeader.tsx b/src/renderer/src/components/artifacts/ArtifactListTableHeader.tsx index 4033ff8921b..7b91c07ec6a 100644 --- a/src/renderer/src/components/artifacts/ArtifactListTableHeader.tsx +++ b/src/renderer/src/components/artifacts/ArtifactListTableHeader.tsx @@ -1,7 +1,7 @@ -import { cn } from '@/lib/utils' +import { cn } from '@/lib/class-names' import { useTranslate } from '@/i18n/use-translate' import { ARTIFACTS_TABLE_GRID_CLASS } from './artifacts-table-layout' -import { LIST_TABLE_HEADER_CLASS } from '@/lib/list-table-layout' +import { LIST_TABLE_HEADER_CLASS } from '@/lib/list-interaction/list-table-layout' export function ArtifactListTableHeader(): React.JSX.Element { const t = useTranslate() diff --git a/src/renderer/src/components/artifacts/ArtifactListToolbar.tsx b/src/renderer/src/components/artifacts/ArtifactListToolbar.tsx index 2c3272773f8..85680aac4ff 100644 --- a/src/renderer/src/components/artifacts/ArtifactListToolbar.tsx +++ b/src/renderer/src/components/artifacts/ArtifactListToolbar.tsx @@ -2,7 +2,7 @@ import { RefreshCw } from 'lucide-react' import { Button } from '@/components/ui/button' import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip' import { useTranslate } from '@/i18n/use-translate' -import { cn } from '@/lib/utils' +import { cn } from '@/lib/class-names' import { ArtifactListSearchField } from './ArtifactListSearchField' export function ArtifactListToolbar({ diff --git a/src/renderer/src/components/artifacts/ArtifactPublishButton.tsx b/src/renderer/src/components/artifacts/ArtifactPublishButton.tsx index d75832498cc..2d3d3b3f7e0 100644 --- a/src/renderer/src/components/artifacts/ArtifactPublishButton.tsx +++ b/src/renderer/src/components/artifacts/ArtifactPublishButton.tsx @@ -5,8 +5,8 @@ import { Button } from '@/components/ui/button' import { Popover, PopoverAnchor, PopoverContent, PopoverTrigger } from '@/components/ui/popover' import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip' import { useTranslate } from '@/i18n/use-translate' -import { cn } from '@/lib/utils' -import { useAppStore } from '@/store' +import { cn } from '@/lib/class-names' +import { useAppStore } from '@/store/index' import { ArtifactPublishedLinkPanel } from './ArtifactPublishedLinkPanel' import { getPublishedArtifactLink } from './artifact-published-link-client' import { publishArtifactFromSurface } from './artifact-publish-flow' diff --git a/src/renderer/src/components/artifacts/ArtifactPublishedLinkPanel.tsx b/src/renderer/src/components/artifacts/ArtifactPublishedLinkPanel.tsx index ff9d79009a2..a37b18b1aa3 100644 --- a/src/renderer/src/components/artifacts/ArtifactPublishedLinkPanel.tsx +++ b/src/renderer/src/components/artifacts/ArtifactPublishedLinkPanel.tsx @@ -3,7 +3,7 @@ import { Check, Copy, ExternalLink, Loader2, RefreshCw } from 'lucide-react' import { Button } from '@/components/ui/button' import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip' import { useTranslate } from '@/i18n/use-translate' -import { cn } from '@/lib/utils' +import { cn } from '@/lib/class-names' import { copyArtifactLink, openArtifactInBrowser } from './artifact-link-actions' export function ArtifactPublishedLinkPanel({ diff --git a/src/renderer/src/components/artifacts/ArtifactsPageSkeleton.tsx b/src/renderer/src/components/artifacts/ArtifactsPageSkeleton.tsx index 919799b700d..663f3299a9a 100644 --- a/src/renderer/src/components/artifacts/ArtifactsPageSkeleton.tsx +++ b/src/renderer/src/components/artifacts/ArtifactsPageSkeleton.tsx @@ -1,7 +1,10 @@ -import { cn } from '@/lib/utils' +import { cn } from '@/lib/class-names' import { useTranslate } from '@/i18n/use-translate' import { ARTIFACTS_TABLE_GRID_CLASS } from './artifacts-table-layout' -import { LIST_TABLE_CONTAINER_CLASS, LIST_TABLE_HEADER_CLASS } from '@/lib/list-table-layout' +import { + LIST_TABLE_CONTAINER_CLASS, + LIST_TABLE_HEADER_CLASS +} from '@/lib/list-interaction/list-table-layout' function SkeletonBar({ className }: { className?: string }): React.JSX.Element { return

diff --git a/src/renderer/src/components/automations/AutomationsPageSkeleton.tsx b/src/renderer/src/components/automations/AutomationsPageSkeleton.tsx index 10c081c2a23..360169b3a9d 100644 --- a/src/renderer/src/components/automations/AutomationsPageSkeleton.tsx +++ b/src/renderer/src/components/automations/AutomationsPageSkeleton.tsx @@ -1,12 +1,12 @@ import React from 'react' -import { cn } from '@/lib/utils' +import { cn } from '@/lib/class-names' import { AUTOMATIONS_TABLE_GRID_CLASS } from './listing/automations-table-layout' import { LIST_TABLE_CONTAINER_CLASS, LIST_TABLE_HEADER_CLASS, LIST_TABLE_STICKY_HEADER_CELL_CLASS, LIST_TABLE_STICKY_ROW_CELL_CLASS -} from '@/lib/list-table-layout' +} from '@/lib/list-interaction/list-table-layout' import { useTranslate } from '@/i18n/use-translate' function SkeletonBar({ className }: { className?: string }): React.JSX.Element { diff --git a/src/renderer/src/components/automations/authoring/AutomationCustomCronPanel.tsx b/src/renderer/src/components/automations/authoring/AutomationCustomCronPanel.tsx index 99451dab731..af8dadf7ccb 100644 --- a/src/renderer/src/components/automations/authoring/AutomationCustomCronPanel.tsx +++ b/src/renderer/src/components/automations/authoring/AutomationCustomCronPanel.tsx @@ -1,7 +1,7 @@ import React from 'react' import { CheckCircle2, CircleAlert } from 'lucide-react' import { Input } from '@/components/ui/input' -import { cn } from '@/lib/utils' +import { cn } from '@/lib/class-names' import { describeAutomationSchedule } from '../../../../../shared/automations/scheduling/automation-schedules' import { getAutomationCronExpressionFields } from '../../../../../shared/automations/scheduling/automation-schedule-parsing' import { formatUiAutomationScheduleDescriptor } from '../details/automation-schedule-label' diff --git a/src/renderer/src/components/automations/authoring/AutomationEditorPromptEditor.tsx b/src/renderer/src/components/automations/authoring/AutomationEditorPromptEditor.tsx index 15bf790323d..242b01c70a0 100644 --- a/src/renderer/src/components/automations/authoring/AutomationEditorPromptEditor.tsx +++ b/src/renderer/src/components/automations/authoring/AutomationEditorPromptEditor.tsx @@ -7,7 +7,7 @@ import { isMonacoFindWidgetOpen } from '@/components/editor/monaco-find-widget' import { monacoTypographyOptions } from '@/lib/editor/appearance/editor-typography' import { useEditorTypography } from '@/hooks/use-editor-typography' import '@/lib/editor/monaco/monaco-setup' -import { cn } from '@/lib/utils' +import { cn } from '@/lib/class-names' import { buildAutomationPromptEditorOptions } from './automation-editor-prompt-options' import { useMonacoTheme } from '@/hooks/use-monaco-theme' diff --git a/src/renderer/src/components/automations/authoring/AutomationProjectCombobox.tsx b/src/renderer/src/components/automations/authoring/AutomationProjectCombobox.tsx index 490c23c1751..0c25f2bfcbe 100644 --- a/src/renderer/src/components/automations/authoring/AutomationProjectCombobox.tsx +++ b/src/renderer/src/components/automations/authoring/AutomationProjectCombobox.tsx @@ -8,7 +8,7 @@ import { useAppStore } from '@/store/index' import { isGitRepoKind } from '../../../../../shared/repo-kind' import { getRepoExecutionHostId } from '../../../../../shared/execution-host' import { isRepoSearchQueryTooLarge, searchRepos } from '@/lib/repo-search' -import { cn } from '@/lib/utils' +import { cn } from '@/lib/class-names' import { useMountedRef } from '@/hooks/useMountedRef' import { useTranslate } from '@/i18n/use-translate' import { projectHostCountLabel } from '@/components/project-host-count-label' diff --git a/src/renderer/src/components/automations/authoring/AutomationSchedulePicker.tsx b/src/renderer/src/components/automations/authoring/AutomationSchedulePicker.tsx index 7a8147234fc..1b1657dd4a1 100644 --- a/src/renderer/src/components/automations/authoring/AutomationSchedulePicker.tsx +++ b/src/renderer/src/components/automations/authoring/AutomationSchedulePicker.tsx @@ -1,4 +1,4 @@ -import { cn } from '@/lib/utils' +import { cn } from '@/lib/class-names' import { Select, SelectContent, diff --git a/src/renderer/src/components/automations/authoring/AutomationSetupDecisionField.tsx b/src/renderer/src/components/automations/authoring/AutomationSetupDecisionField.tsx index a4ff868a06c..cd07c430940 100644 --- a/src/renderer/src/components/automations/authoring/AutomationSetupDecisionField.tsx +++ b/src/renderer/src/components/automations/authoring/AutomationSetupDecisionField.tsx @@ -1,7 +1,7 @@ import React from 'react' import { Check, ChevronDown } from 'lucide-react' import { Button } from '@/components/ui/button' -import { cn } from '@/lib/utils' +import { cn } from '@/lib/class-names' import { useTranslate } from '@/i18n/use-translate' import { getVisibleAutomationSetupDecision } from './automation-setup-decision' import type { AutomationDraft } from './AutomationEditorDialog' diff --git a/src/renderer/src/components/automations/authoring/AutomationTimeField.tsx b/src/renderer/src/components/automations/authoring/AutomationTimeField.tsx index 68e4a13cadd..b347cc49d7e 100644 --- a/src/renderer/src/components/automations/authoring/AutomationTimeField.tsx +++ b/src/renderer/src/components/automations/authoring/AutomationTimeField.tsx @@ -1,7 +1,7 @@ import { ImeInput } from '@/lib/text-input/ime/ime-text-field' import React from 'react' import { Clock } from 'lucide-react' -import { cn } from '@/lib/utils' +import { cn } from '@/lib/class-names' import { useTranslate } from '@/i18n/use-translate' const TIME_SHELL_CLASS = diff --git a/src/renderer/src/components/automations/authoring/WorkspaceCombobox.tsx b/src/renderer/src/components/automations/authoring/WorkspaceCombobox.tsx index a262dfe5940..a6126592095 100644 --- a/src/renderer/src/components/automations/authoring/WorkspaceCombobox.tsx +++ b/src/renderer/src/components/automations/authoring/WorkspaceCombobox.tsx @@ -9,7 +9,7 @@ import { CommandList } from '@/components/ui/command' import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover' -import { cn } from '@/lib/utils' +import { cn } from '@/lib/class-names' import type { Worktree } from '../../../../../shared/worktree/types' import { useTranslate } from '@/i18n/use-translate' diff --git a/src/renderer/src/components/automations/automation-page-parts.tsx b/src/renderer/src/components/automations/automation-page-parts.tsx index 6019c4fe14a..297865a0052 100644 --- a/src/renderer/src/components/automations/automation-page-parts.tsx +++ b/src/renderer/src/components/automations/automation-page-parts.tsx @@ -1,7 +1,7 @@ import React from 'react' import type { Badge } from '@/components/ui/badge' import { Button } from '@/components/ui/button' -import { cn } from '@/lib/utils' +import { cn } from '@/lib/class-names' import type { AutomationRun } from '../../../../shared/automations/history/automation-run' import type { PendingAutomationSetupReview } from './authoring/automation-setup-review' import { translate } from '@/i18n/i18n' diff --git a/src/renderer/src/components/automations/automations-page-test-harness.tsx b/src/renderer/src/components/automations/automations-page-test-harness.tsx index cab3577d27c..1dbb50644f4 100644 --- a/src/renderer/src/components/automations/automations-page-test-harness.tsx +++ b/src/renderer/src/components/automations/automations-page-test-harness.tsx @@ -94,7 +94,7 @@ vi.mock('sonner', () => ({ } })) -vi.mock('@/lib/window-visibility-interval', () => ({ +vi.mock('@/lib/window-activity/window-visibility-interval', () => ({ installWindowVisibilityInterval: () => () => undefined })) diff --git a/src/renderer/src/components/automations/details/AutomationPromptDisclosure.tsx b/src/renderer/src/components/automations/details/AutomationPromptDisclosure.tsx index 6e8814d380e..92e384bb1be 100644 --- a/src/renderer/src/components/automations/details/AutomationPromptDisclosure.tsx +++ b/src/renderer/src/components/automations/details/AutomationPromptDisclosure.tsx @@ -1,6 +1,6 @@ import React, { useCallback, useEffect, useId, useRef, useState } from 'react' import { Button } from '@/components/ui/button' -import { cn } from '@/lib/utils' +import { cn } from '@/lib/class-names' import { useTranslate } from '@/i18n/use-translate' export function AutomationPromptDisclosure({ prompt }: { prompt: string }): React.JSX.Element { diff --git a/src/renderer/src/components/automations/hosts/AutomationHostBadges.tsx b/src/renderer/src/components/automations/hosts/AutomationHostBadges.tsx index 3b84f10f631..c2be0482feb 100644 --- a/src/renderer/src/components/automations/hosts/AutomationHostBadges.tsx +++ b/src/renderer/src/components/automations/hosts/AutomationHostBadges.tsx @@ -2,7 +2,7 @@ import React from 'react' import RepoBadgeLabel from '@/components/repo/RepoBadgeLabel' import { Badge } from '@/components/ui/badge' import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip' -import { cn } from '@/lib/utils' +import { cn } from '@/lib/class-names' import type { AutomationHostCatalogEntry } from './automation-host-catalog-types' import { hostScopeDescriptor } from './automation-host-scope-descriptors' import { diff --git a/src/renderer/src/components/automations/hosts/AutomationHostFilterNotice.tsx b/src/renderer/src/components/automations/hosts/AutomationHostFilterNotice.tsx index 22e30e7ae75..329ef4b219a 100644 --- a/src/renderer/src/components/automations/hosts/AutomationHostFilterNotice.tsx +++ b/src/renderer/src/components/automations/hosts/AutomationHostFilterNotice.tsx @@ -3,7 +3,7 @@ import { Loader2, TriangleAlert } from 'lucide-react' import { Button } from '@/components/ui/button' import { translate } from '@/i18n/i18n' import { useTranslate, type Translate } from '@/i18n/use-translate' -import { cn } from '@/lib/utils' +import { cn } from '@/lib/class-names' import { AutomationHostStatusBadges } from './AutomationHostBadges' import type { AutomationHostFilterResolution } from './automation-host-filter-resolution' import { diff --git a/src/renderer/src/components/automations/hosts/AutomationOwnerConflictNotice.tsx b/src/renderer/src/components/automations/hosts/AutomationOwnerConflictNotice.tsx index 66d36784651..86037da11a0 100644 --- a/src/renderer/src/components/automations/hosts/AutomationOwnerConflictNotice.tsx +++ b/src/renderer/src/components/automations/hosts/AutomationOwnerConflictNotice.tsx @@ -1,7 +1,7 @@ import React from 'react' import { TriangleAlert } from 'lucide-react' import { Button } from '@/components/ui/button' -import { cn } from '@/lib/utils' +import { cn } from '@/lib/class-names' import { useTranslate } from '@/i18n/use-translate' import { recoveryActionLabel, diff --git a/src/renderer/src/components/automations/hosts/automation-host-client.ts b/src/renderer/src/components/automations/hosts/automation-host-client.ts index ccc395d8126..5c26da354ee 100644 --- a/src/renderer/src/components/automations/hosts/automation-host-client.ts +++ b/src/renderer/src/components/automations/hosts/automation-host-client.ts @@ -1,5 +1,5 @@ import { callRuntimeRpc } from '@/runtime/rpc/calls/runtime-rpc-call' -import { getPairedWebClientEnvironmentId } from '@/lib/paired-web-client-host' +import { getPairedWebClientEnvironmentId } from '@/app-shell/platform/paired-web-client-host' import { prepareAutomationLaunchSetup } from './automation-capability-probe' import type { Automation, diff --git a/src/renderer/src/components/automations/hosts/automation-host-recovery.ts b/src/renderer/src/components/automations/hosts/automation-host-recovery.ts index d88e3fd9714..85ce009ae60 100644 --- a/src/renderer/src/components/automations/hosts/automation-host-recovery.ts +++ b/src/renderer/src/components/automations/hosts/automation-host-recovery.ts @@ -1,6 +1,6 @@ /** Use descriptor recovery verbs; reconnect the failed runtime or SSH target, and route Update server to version management. */ -import type { SettingsNavigationTarget } from '@/lib/settings-navigation-types' +import type { SettingsNavigationTarget } from '@/components/settings/navigation/settings-navigation-types' import type { AutomationHostCatalogEntry } from './automation-host-catalog-types' import type { AutomationHostRecoveryAction } from './automation-host-status-descriptors' diff --git a/src/renderer/src/components/automations/hosts/use-automation-host-catalog-source-state.ts b/src/renderer/src/components/automations/hosts/use-automation-host-catalog-source-state.ts index 8c7195f1a25..d6417c6a75a 100644 --- a/src/renderer/src/components/automations/hosts/use-automation-host-catalog-source-state.ts +++ b/src/renderer/src/components/automations/hosts/use-automation-host-catalog-source-state.ts @@ -1,6 +1,6 @@ import { useMemo } from 'react' import { useAppStore } from '@/store/index' -import { getPairedWebClientEnvironmentId } from '@/lib/paired-web-client-host' +import { getPairedWebClientEnvironmentId } from '@/app-shell/platform/paired-web-client-host' import type { PublicKnownRuntimeEnvironment } from '../../../../../shared/remote-runtime/host-catalog/runtime-environments' import { getManagedOrcadSshTargetId } from '../../../../../shared/execution-host/managed-orcad-execution-host' import type { diff --git a/src/renderer/src/components/automations/listing/AutomationListEmptyView.tsx b/src/renderer/src/components/automations/listing/AutomationListEmptyView.tsx index 0b888cb16a7..9f3a330ca63 100644 --- a/src/renderer/src/components/automations/listing/AutomationListEmptyView.tsx +++ b/src/renderer/src/components/automations/listing/AutomationListEmptyView.tsx @@ -1,6 +1,6 @@ import React from 'react' import { Button } from '@/components/ui/button' -import { cn } from '@/lib/utils' +import { cn } from '@/lib/class-names' import { resolveAutomationListEmptyState, type AutomationListEmptyStateInput diff --git a/src/renderer/src/components/automations/listing/AutomationListExternalRow.tsx b/src/renderer/src/components/automations/listing/AutomationListExternalRow.tsx index b802be4ba44..d3e1f56aef4 100644 --- a/src/renderer/src/components/automations/listing/AutomationListExternalRow.tsx +++ b/src/renderer/src/components/automations/listing/AutomationListExternalRow.tsx @@ -15,7 +15,7 @@ import { DropdownMenuTrigger } from '@/components/ui/dropdown-menu' import { Button } from '@/components/ui/button' -import { cn } from '@/lib/utils' +import { cn } from '@/lib/class-names' import type { ExternalAutomationAction, ExternalAutomationJob, @@ -36,8 +36,11 @@ import { LIST_TABLE_ROW_CLASS, LIST_TABLE_ROW_SELECTED_CLASS, LIST_TABLE_STICKY_ROW_CELL_CLASS -} from '@/lib/list-table-layout' -import { isPortaledRowMenuClick, isRowActivationKey } from '@/lib/list-row-interaction' +} from '@/lib/list-interaction/list-table-layout' +import { + isPortaledRowMenuClick, + isRowActivationKey +} from '@/lib/list-interaction/list-row-interaction' import { getExternalAutomationLastRunSnapshot } from './automation-list-last-run' import { AutomationListLastRunCell } from './AutomationListLastRunCell' import { AutomationListStatusCell } from './AutomationListStatusCell' diff --git a/src/renderer/src/components/automations/listing/AutomationListLastRunCell.tsx b/src/renderer/src/components/automations/listing/AutomationListLastRunCell.tsx index e51e9743a24..d9809d2fe52 100644 --- a/src/renderer/src/components/automations/listing/AutomationListLastRunCell.tsx +++ b/src/renderer/src/components/automations/listing/AutomationListLastRunCell.tsx @@ -1,5 +1,5 @@ import React from 'react' -import { cn } from '@/lib/utils' +import { cn } from '@/lib/class-names' import { formatAutomationLastRunCell, type AutomationLastRunSnapshot diff --git a/src/renderer/src/components/automations/listing/AutomationListLocalRow.tsx b/src/renderer/src/components/automations/listing/AutomationListLocalRow.tsx index 85c2ec0f2b3..7d39557aca1 100644 --- a/src/renderer/src/components/automations/listing/AutomationListLocalRow.tsx +++ b/src/renderer/src/components/automations/listing/AutomationListLocalRow.tsx @@ -20,7 +20,7 @@ import { import { Button } from '@/components/ui/button' import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip' import { AgentIcon } from '@/components/agent/icons/AgentIcon' -import { cn } from '@/lib/utils' +import { cn } from '@/lib/class-names' import type { AutomationRun } from '../../../../../shared/automations/history/automation-run' import { getAutomationRunRepoId } from '../../../../../shared/automations/history/automation-run-identity' import { formatUiAutomationSchedule } from '../details/automation-schedule-label' @@ -50,8 +50,11 @@ import { LIST_TABLE_ROW_CLASS, LIST_TABLE_ROW_SELECTED_CLASS, LIST_TABLE_STICKY_ROW_CELL_CLASS -} from '@/lib/list-table-layout' -import { isPortaledRowMenuClick, isRowActivationKey } from '@/lib/list-row-interaction' +} from '@/lib/list-interaction/list-table-layout' +import { + isPortaledRowMenuClick, + isRowActivationKey +} from '@/lib/list-interaction/list-row-interaction' import { AutomationListStatusCell } from './AutomationListStatusCell' import { useIntlLocale, useTranslate } from '@/i18n/use-translate' import { useAppStore } from '@/store/index' diff --git a/src/renderer/src/components/automations/listing/AutomationListSearchField.tsx b/src/renderer/src/components/automations/listing/AutomationListSearchField.tsx index 9b6d5199bae..b393a320673 100644 --- a/src/renderer/src/components/automations/listing/AutomationListSearchField.tsx +++ b/src/renderer/src/components/automations/listing/AutomationListSearchField.tsx @@ -3,7 +3,7 @@ import { Search, X } from 'lucide-react' import { Button } from '@/components/ui/button' import { Input } from '@/components/ui/input' import { useTranslate } from '@/i18n/use-translate' -import { cn } from '@/lib/utils' +import { cn } from '@/lib/class-names' import { isAutomationListArrowKey, shouldHandleAutomationListSearchArrowKey, diff --git a/src/renderer/src/components/automations/listing/AutomationListSortHeader.tsx b/src/renderer/src/components/automations/listing/AutomationListSortHeader.tsx index e1f39ee2683..6762b3598b8 100644 --- a/src/renderer/src/components/automations/listing/AutomationListSortHeader.tsx +++ b/src/renderer/src/components/automations/listing/AutomationListSortHeader.tsx @@ -1,6 +1,6 @@ import React from 'react' import { ArrowDown, ArrowUp } from 'lucide-react' -import { cn } from '@/lib/utils' +import { cn } from '@/lib/class-names' import { useTranslate } from '@/i18n/use-translate' import type { AutomationListSort, AutomationListSortField } from './automation-list-view' diff --git a/src/renderer/src/components/automations/listing/AutomationListTableHeader.tsx b/src/renderer/src/components/automations/listing/AutomationListTableHeader.tsx index 69c261f30d9..76366e3b95a 100644 --- a/src/renderer/src/components/automations/listing/AutomationListTableHeader.tsx +++ b/src/renderer/src/components/automations/listing/AutomationListTableHeader.tsx @@ -4,7 +4,7 @@ import { AUTOMATIONS_TABLE_GRID_CLASS } from './automations-table-layout' import { LIST_TABLE_HEADER_CLASS, LIST_TABLE_STICKY_HEADER_CELL_CLASS -} from '@/lib/list-table-layout' +} from '@/lib/list-interaction/list-table-layout' import { AutomationListSortHeader } from './AutomationListSortHeader' import type { AutomationListSort, AutomationListSortField } from './automation-list-view' diff --git a/src/renderer/src/components/automations/listing/AutomationListToolbar.tsx b/src/renderer/src/components/automations/listing/AutomationListToolbar.tsx index bbe24069a21..5c2e5252711 100644 --- a/src/renderer/src/components/automations/listing/AutomationListToolbar.tsx +++ b/src/renderer/src/components/automations/listing/AutomationListToolbar.tsx @@ -3,7 +3,7 @@ import { History, Plus, RefreshCw } from 'lucide-react' import { Button } from '@/components/ui/button' import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip' import { useTranslate } from '@/i18n/use-translate' -import { cn } from '@/lib/utils' +import { cn } from '@/lib/class-names' import type { AutomationHostCatalogEntry } from '../hosts/automation-host-catalog-types' import type { AutomationListArrowKey } from './automation-list-keyboard-navigation' import { clampAutomationListSearchQueryInput } from './automation-list-search-query' diff --git a/src/renderer/src/components/automations/listing/AutomationsListPanel.tsx b/src/renderer/src/components/automations/listing/AutomationsListPanel.tsx index ac96f41f002..9fbf5b2bd28 100644 --- a/src/renderer/src/components/automations/listing/AutomationsListPanel.tsx +++ b/src/renderer/src/components/automations/listing/AutomationsListPanel.tsx @@ -1,7 +1,7 @@ import type { SetupTrustMismatch } from '../../../../../shared/worktree/create-types' import type { RuntimeEnvironmentSshBucket } from '../../../store/slices/ssh/runtime-environment-ssh' import React, { useRef } from 'react' -import { cn } from '@/lib/utils' +import { cn } from '@/lib/class-names' import type { AutomationRun } from '../../../../../shared/automations/history/automation-run' import type { ExternalAutomationAction, @@ -51,7 +51,7 @@ import type { AutomationHostCatalogView } from '../hosts/use-automation-host-cat import type { AutomationHostRecoveryAction } from '../hosts/automation-host-status-descriptors' import type { AutomationHostCatalogEntry } from '../hosts/automation-host-catalog-types' import { useAutomationListFocusRecovery } from './use-automation-list-focus-recovery' -import { LIST_TABLE_CONTAINER_CLASS } from '@/lib/list-table-layout' +import { LIST_TABLE_CONTAINER_CLASS } from '@/lib/list-interaction/list-table-layout' import { useTranslate } from '@/i18n/use-translate' import { AutomationTemplateEmptyState } from '../authoring/AutomationTemplateEmptyState' import { AutomationListTableHeader } from './AutomationListTableHeader' diff --git a/src/renderer/src/components/automations/runs/AutomationRunDetailsPage.tsx b/src/renderer/src/components/automations/runs/AutomationRunDetailsPage.tsx index c393904acd9..6e6a91bce2b 100644 --- a/src/renderer/src/components/automations/runs/AutomationRunDetailsPage.tsx +++ b/src/renderer/src/components/automations/runs/AutomationRunDetailsPage.tsx @@ -2,7 +2,7 @@ import React from 'react' import { Eye, RefreshCw } from 'lucide-react' import { Button } from '@/components/ui/button' import CommentMarkdown from '@/components/sidebar/CommentMarkdown' -import { cn } from '@/lib/utils' +import { cn } from '@/lib/class-names' import { useIntlLocale, useTranslate } from '@/i18n/use-translate' import type { Automation } from '../../../../../shared/automations/automation-definition' import type { AutomationRun } from '../../../../../shared/automations/history/automation-run' diff --git a/src/renderer/src/components/automations/runs/AutomationRunHistory.tsx b/src/renderer/src/components/automations/runs/AutomationRunHistory.tsx index 6fe9129addd..235f8c57bf8 100644 --- a/src/renderer/src/components/automations/runs/AutomationRunHistory.tsx +++ b/src/renderer/src/components/automations/runs/AutomationRunHistory.tsx @@ -1,7 +1,7 @@ import React, { useCallback, useLayoutEffect, useMemo, useRef, useState } from 'react' import { useVirtualizer } from '@tanstack/react-virtual' import { Badge } from '@/components/ui/badge' -import { cn } from '@/lib/utils' +import { cn } from '@/lib/class-names' import type { AutomationRun } from '../../../../../shared/automations/history/automation-run' import type { Worktree } from '../../../../../shared/worktree/types' import { diff --git a/src/renderer/src/components/automations/use-automations-page-refresh.ts b/src/renderer/src/components/automations/use-automations-page-refresh.ts index d79192d22aa..9a9742d8172 100644 --- a/src/renderer/src/components/automations/use-automations-page-refresh.ts +++ b/src/renderer/src/components/automations/use-automations-page-refresh.ts @@ -1,5 +1,5 @@ import { useCallback, useEffect, useRef } from 'react' -import { installWindowVisibilityInterval } from '@/lib/window-visibility-interval' +import { installWindowVisibilityInterval } from '@/lib/window-activity/window-visibility-interval' import { useAppStore } from '@/store/index' import { AUTOMATIONS_CHANGED_EVENT } from '@/lib/automations-changed-window-event' import { diff --git a/src/renderer/src/components/browser-favicon.tsx b/src/renderer/src/components/browser-favicon.tsx index 86e1ba67c31..383a3ca1266 100644 --- a/src/renderer/src/components/browser-favicon.tsx +++ b/src/renderer/src/components/browser-favicon.tsx @@ -1,6 +1,6 @@ import { useState } from 'react' import { Globe, Loader2 } from 'lucide-react' -import { cn } from '@/lib/utils' +import { cn } from '@/lib/class-names' import { displayableFaviconUrl } from '../../../shared/browser/browser-favicon-url' export function BrowserFavicon({ diff --git a/src/renderer/src/components/browser-pane/ClientHostedBrowserPagePane.dead-guest.test.tsx b/src/renderer/src/components/browser-pane/ClientHostedBrowserPagePane.dead-guest.test.tsx deleted file mode 100644 index 30b1f23b1c6..00000000000 --- a/src/renderer/src/components/browser-pane/ClientHostedBrowserPagePane.dead-guest.test.tsx +++ /dev/null @@ -1,255 +0,0 @@ -// @vitest-environment happy-dom -import { act, cleanup, render, screen } from '@testing-library/react' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import type { BrowserPage } from '../../../../shared/browser-workspace-types' - -const mocks = vi.hoisted(() => ({ - attach: vi.fn(), - detach: vi.fn(), - recordBreadcrumb: vi.fn() -})) - -vi.mock('./browser-client-page-renderer-installation', () => ({ - attachBrowserClientPageToViewport: mocks.attach -})) -vi.mock('@/lib/crash-breadcrumb-recorder', () => ({ - recordRendererCrashBreadcrumb: mocks.recordBreadcrumb -})) -vi.mock('sonner', () => ({ - toast: { error: vi.fn(), success: vi.fn(), loading: vi.fn(), message: vi.fn() } -})) - -import { TooltipProvider } from '@/components/ui/tooltip' -import { installClientHostedPaneApi } from './client-hosted-browser-pane-test-rig' -import { ClientHostedBrowserPagePane } from './ClientHostedBrowserPagePane' - -const PLACEMENT = { - kind: 'client' as const, - browserHostClientId: 'host-a', - browserHostGeneration: 3, - pageHostGeneration: 7 -} - -/** Verbatim from Electron 43.4.1: main destroyed the guest, the tag still holds its id. */ -function invalidGuestInstanceId(): Error { - return new Error('Invalid guestInstanceId: 7') -} - -/** Verbatim from Electron 43.4.1: focus() after the retained tag left the DOM. */ -function nullContentWindowFocus(): TypeError { - return new TypeError("Cannot read properties of null (reading 'focus')") -} - -function pageNavigationStart(): Event { - return Object.assign(new Event('did-start-navigation'), { - isMainFrame: true, - isInPlace: false, - url: 'https://example.com/next' - }) -} - -function page(overrides?: Partial): BrowserPage { - return { - id: 'page-a', - workspaceId: 'workspace-a', - worktreeId: 'worktree-a', - url: 'https://example.internal/', - title: 'Example', - loading: false, - faviconUrl: null, - canGoBack: false, - canGoForward: false, - loadError: null, - createdAt: 1, - ...overrides - } -} - -function createGuest(): Electron.WebviewTag & { - getURL: ReturnType - reload: ReturnType -} { - const webview = document.createElement('webview') as Electron.WebviewTag & { - getURL: ReturnType - reload: ReturnType - } - Object.assign(webview, { - // An attached guest has a WebContents id; focus waits for one. - getWebContentsId: vi.fn(() => 7), - getURL: vi.fn(() => 'https://example.internal/'), - getTitle: vi.fn(() => 'Example'), - isLoading: vi.fn(() => false), - canGoBack: vi.fn(() => false), - canGoForward: vi.fn(() => false), - focus: vi.fn(), - blur: vi.fn(), - goBack: vi.fn(), - goForward: vi.fn(), - reload: vi.fn(), - loadURL: vi.fn(async () => {}) - }) - mocks.attach.mockReturnValue({ - webview, - detach: mocks.detach, - nextMetadataRevision: vi.fn(() => 1) - }) - return webview -} - -function paneElement( - isActive: boolean, - options?: { browserTab?: BrowserPage; onUpdatePageState?: (id: string, state: unknown) => void } -): React.JSX.Element { - return ( - - - - ) -} - -let webview: ReturnType - -beforeEach(() => { - mocks.attach.mockReset() - mocks.detach.mockReset() - mocks.recordBreadcrumb.mockReset() - installClientHostedPaneApi() - webview = createGuest() -}) - -afterEach(() => { - cleanup() - vi.clearAllMocks() -}) - -describe('client-hosted browser pane over a dead guest', () => { - it('degrades to the unavailable notice when the guest was destroyed in main', () => { - webview.getURL.mockImplementation(() => { - throw invalidGuestInstanceId() - }) - - expect(() => render(paneElement(true))).not.toThrow() - expect(screen.getByText('Client-hosted browser unavailable')).toBeTruthy() - expect(mocks.detach).toHaveBeenCalled() - expect(mocks.recordBreadcrumb).toHaveBeenCalledWith('browser_client_page_guest_unavailable', { - browserPageId: 'page-a', - pageHostGeneration: PLACEMENT.pageHostGeneration, - reason: 'unreadable', - tagConnected: false - }) - // Why: the catch is total, so the swallowed error must stay visible to diagnostics. - expect(mocks.recordBreadcrumb).toHaveBeenCalledWith('browser_client_page_guest_read_failed', { - errorName: 'Error', - errorMessage: 'Invalid guestInstanceId: 7' - }) - }) - - it('flips to the unavailable notice when the guest renderer goes away after attach', () => { - const onUpdatePageState = vi.fn() - render(paneElement(true, { browserTab: page({ loading: true }), onUpdatePageState })) - expect(screen.queryByText('Client-hosted browser unavailable')).toBeNull() - onUpdatePageState.mockClear() - - // The registry pulls the tag out of the DOM on this event without telling the pane. - webview.remove() - act(() => { - webview.dispatchEvent(new Event('render-process-gone')) - }) - - expect(screen.getByText('Client-hosted browser unavailable')).toBeTruthy() - expect(mocks.detach).toHaveBeenCalled() - expect(onUpdatePageState).toHaveBeenCalledWith('page-a', { loading: false }) - expect(mocks.recordBreadcrumb).toHaveBeenCalledWith('browser_client_page_guest_unavailable', { - browserPageId: 'page-a', - pageHostGeneration: PLACEMENT.pageHostGeneration, - reason: 'render-process-gone', - tagConnected: false - }) - }) - - it('flips to the unavailable notice when main destroys the guest after attach', () => { - render(paneElement(true)) - - act(() => { - webview.dispatchEvent(new Event('destroyed')) - }) - - expect(screen.getByText('Client-hosted browser unavailable')).toBeTruthy() - expect(mocks.recordBreadcrumb).toHaveBeenCalledWith( - 'browser_client_page_guest_unavailable', - expect.objectContaining({ reason: 'destroyed' }) - ) - // The chrome must not keep driving the dead tag: Reload routes to the notice, not a throw. - webview.reload.mockImplementation(() => { - throw invalidGuestInstanceId() - }) - expect(() => act(() => screen.getByRole('button', { name: 'Reload' }).click())).not.toThrow() - expect(webview.reload).not.toHaveBeenCalled() - }) - - it('stops the spinner when the guest dies as a load starts', () => { - const onUpdatePageState = vi.fn() - render(paneElement(true, { onUpdatePageState })) - onUpdatePageState.mockClear() - webview.getURL.mockImplementation(() => { - throw invalidGuestInstanceId() - }) - - act(() => { - webview.dispatchEvent(pageNavigationStart()) - }) - - expect(screen.getByText('Client-hosted browser unavailable')).toBeTruthy() - // The navigation start writes loading:true first; the loss must be the last word. - expect(onUpdatePageState.mock.calls.at(-1)).toEqual(['page-a', { loading: false }]) - }) - - it('ignores queued load events after guest loss', () => { - const onUpdatePageState = vi.fn() - render(paneElement(true, { onUpdatePageState })) - act(() => webview.dispatchEvent(new Event('destroyed'))) - onUpdatePageState.mockClear() - - act(() => webview.dispatchEvent(pageNavigationStart())) - - expect(onUpdatePageState).not.toHaveBeenCalled() - expect(screen.getByText('Client-hosted browser unavailable')).toBeTruthy() - }) - - it('stops listening for guest loss once the pane lets go of the tag', () => { - const onUpdatePageState = vi.fn() - const view = render(paneElement(true, { onUpdatePageState })) - view.unmount() - onUpdatePageState.mockClear() - mocks.recordBreadcrumb.mockClear() - - webview.dispatchEvent(new Event('destroyed')) - - expect(onUpdatePageState).not.toHaveBeenCalled() - expect(mocks.recordBreadcrumb).not.toHaveBeenCalled() - }) - - it('survives activation focus after the retained tag left the DOM', () => { - const view = render(paneElement(false)) - webview.focus = vi.fn(() => { - throw nullContentWindowFocus() - }) - - expect(() => - act(() => { - view.rerender(paneElement(true)) - }) - ).not.toThrow() - expect(webview.focus).toHaveBeenCalled() - }) -}) diff --git a/src/renderer/src/components/browser-pane/ReopenBrowserPageOnServerButton.tsx b/src/renderer/src/components/browser-pane/ReopenBrowserPageOnServerButton.tsx index 044c72e5339..207a94ae24c 100644 --- a/src/renderer/src/components/browser-pane/ReopenBrowserPageOnServerButton.tsx +++ b/src/renderer/src/components/browser-pane/ReopenBrowserPageOnServerButton.tsx @@ -4,7 +4,7 @@ import { toast } from 'sonner' import { Button } from '@/components/ui/button' import { translate } from '@/i18n/i18n' import { useTranslate, type Translate } from '@/i18n/use-translate' -import { cn } from '@/lib/utils' +import { cn } from '@/lib/class-names' import { reopenBrowserPageOnServer } from './browser-reopen-on-server' /** Deferred so a fast local round-trip never flashes a spinner. */ diff --git a/src/renderer/src/components/browser-pane/annotate/MarkupDrawButton.tsx b/src/renderer/src/components/browser-pane/annotate/MarkupDrawButton.tsx index 3f4879b56ba..7b560e7c9b3 100644 --- a/src/renderer/src/components/browser-pane/annotate/MarkupDrawButton.tsx +++ b/src/renderer/src/components/browser-pane/annotate/MarkupDrawButton.tsx @@ -2,7 +2,7 @@ import React from 'react' import { PenTool } from 'lucide-react' import { Button } from '@/components/ui/button' import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip' -import { cn } from '@/lib/utils' +import { cn } from '@/lib/class-names' import { useTranslate } from '@/i18n/use-translate' import { MarkupDrawHintPopover, useMarkupDrawHintState } from './markup-draw-hint-popover' diff --git a/src/renderer/src/components/browser-pane/annotate/MarkupOverlay.tsx b/src/renderer/src/components/browser-pane/annotate/MarkupOverlay.tsx index 73c73aac099..b41fa518dea 100644 --- a/src/renderer/src/components/browser-pane/annotate/MarkupOverlay.tsx +++ b/src/renderer/src/components/browser-pane/annotate/MarkupOverlay.tsx @@ -3,7 +3,7 @@ import React, { useCallback, useRef, useState } from 'react' import { createPortal } from 'react-dom' import { Check, X } from 'lucide-react' import { Button } from '@/components/ui/button' -import { cn } from '@/lib/utils' +import { cn } from '@/lib/class-names' import { useTranslate } from '@/i18n/use-translate' import { MarkupToolbar } from './MarkupToolbar' import type { MarkupBaseImage } from './markup-base-image' diff --git a/src/renderer/src/components/browser-pane/annotate/MarkupToolbar.tsx b/src/renderer/src/components/browser-pane/annotate/MarkupToolbar.tsx index aaa1dc4cc09..6ff31b2cd0f 100644 --- a/src/renderer/src/components/browser-pane/annotate/MarkupToolbar.tsx +++ b/src/renderer/src/components/browser-pane/annotate/MarkupToolbar.tsx @@ -14,7 +14,7 @@ import { import { Button } from '@/components/ui/button' import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@/components/ui/tooltip' import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover' -import { cn } from '@/lib/utils' +import { cn } from '@/lib/class-names' import { translate } from '@/i18n/i18n' import { useTranslate, type Translate } from '@/i18n/use-translate' import { useUiLanguageRevision } from '@/i18n/use-ui-language-revision' diff --git a/src/renderer/src/components/browser-pane/annotate/browser-page-annotation-tray.tsx b/src/renderer/src/components/browser-pane/annotate/browser-page-annotation-tray.tsx index 46c1fbb77b4..0c85bbe7caf 100644 --- a/src/renderer/src/components/browser-pane/annotate/browser-page-annotation-tray.tsx +++ b/src/renderer/src/components/browser-pane/annotate/browser-page-annotation-tray.tsx @@ -19,7 +19,7 @@ import { } from '@/components/ui/dropdown-menu' import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip' import { ToggleGroup, ToggleGroupItem } from '@/components/ui/toggle-group' -import { isScreenSubmitShortcut } from '@/lib/screen-submit-shortcut' +import { isScreenSubmitShortcut } from '@/lib/keyboard/screen-submit-shortcut' import { useTranslate } from '@/i18n/use-translate' import { GRAB_BUDGET, diff --git a/src/renderer/src/components/browser-pane/annotate/pending-browser-annotation-card.tsx b/src/renderer/src/components/browser-pane/annotate/pending-browser-annotation-card.tsx index 7da77dff10c..2734c73fa9b 100644 --- a/src/renderer/src/components/browser-pane/annotate/pending-browser-annotation-card.tsx +++ b/src/renderer/src/components/browser-pane/annotate/pending-browser-annotation-card.tsx @@ -5,7 +5,10 @@ import { Button } from '@/components/ui/button' import { ToggleGroup, ToggleGroupItem } from '@/components/ui/toggle-group' import { Label } from '@/components/ui/label' import { Popover, PopoverAnchor, PopoverContent } from '@/components/ui/popover' -import { getScreenSubmitModifierLabel, isScreenSubmitShortcut } from '@/lib/screen-submit-shortcut' +import { + getScreenSubmitModifierLabel, + isScreenSubmitShortcut +} from '@/lib/keyboard/screen-submit-shortcut' import { GRAB_BUDGET, type BrowserAnnotationIntent, diff --git a/src/renderer/src/components/browser-pane/assemble-chrome/BrowserAddressBar.tsx b/src/renderer/src/components/browser-pane/assemble-chrome/BrowserAddressBar.tsx index 06fe9192e0d..27d7677b619 100644 --- a/src/renderer/src/components/browser-pane/assemble-chrome/BrowserAddressBar.tsx +++ b/src/renderer/src/components/browser-pane/assemble-chrome/BrowserAddressBar.tsx @@ -2,9 +2,9 @@ import { useCallback, useEffect, useMemo, useRef, useState } from 'react' import { Globe } from 'lucide-react' import { Input } from '@/components/ui/input' import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover' -import { cn } from '@/lib/utils' +import { cn } from '@/lib/class-names' import { useTranslate } from '@/i18n/use-translate' -import { useAppStore } from '@/store' +import { useAppStore } from '@/store/index' import { findPage } from '@/store/slices/browser/pages/browser-page-records' import { DEFAULT_SEARCH_ENGINE, type SearchEngine } from '../../../../../shared/browser-url' import type { BrowserPageDocLocation } from '../../../../../shared/browser-workspace-types' diff --git a/src/renderer/src/components/browser-pane/assemble-chrome/BrowserImportHintButton.tsx b/src/renderer/src/components/browser-pane/assemble-chrome/BrowserImportHintButton.tsx index 58bda179f1c..56a905e92ea 100644 --- a/src/renderer/src/components/browser-pane/assemble-chrome/BrowserImportHintButton.tsx +++ b/src/renderer/src/components/browser-pane/assemble-chrome/BrowserImportHintButton.tsx @@ -17,8 +17,8 @@ import { DropdownMenuTrigger } from '@/components/ui/dropdown-menu' import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover' -import { useAppStore } from '@/store' -import { isLinuxUserAgent, isMacUserAgent } from '@/lib/user-agent-platform' +import { useAppStore } from '@/store/index' +import { isLinuxUserAgent, isMacUserAgent } from '@/app-shell/platform/user-agent-platform' import { getBrowserCookieImportSourceLabels } from '../../../../../shared/browser-cookie-import-sources' import { shouldShowBrowserImportHint } from './browser-import-hint-visibility' import { formatBrowserImportSummary } from './browser-detected-browsers-summary' diff --git a/src/renderer/src/components/browser-pane/assemble-chrome/BrowserMobileDriverOverlay.tsx b/src/renderer/src/components/browser-pane/assemble-chrome/BrowserMobileDriverOverlay.tsx index 6767e8140bb..b6c7dc55355 100644 --- a/src/renderer/src/components/browser-pane/assemble-chrome/BrowserMobileDriverOverlay.tsx +++ b/src/renderer/src/components/browser-pane/assemble-chrome/BrowserMobileDriverOverlay.tsx @@ -1,6 +1,6 @@ import { useCallback, useRef, useState, type ReactElement } from 'react' import { Button } from '@/components/ui/button' -import { cn } from '@/lib/utils' +import { cn } from '@/lib/class-names' import type { RuntimeTerminalDriverState } from '../../../../../shared/runtime-session-contracts' import { useTranslate } from '@/i18n/use-translate' diff --git a/src/renderer/src/components/browser-pane/assemble-chrome/browser-annotate-split-button.tsx b/src/renderer/src/components/browser-pane/assemble-chrome/browser-annotate-split-button.tsx index d10eb448d1b..db953c79880 100644 --- a/src/renderer/src/components/browser-pane/assemble-chrome/browser-annotate-split-button.tsx +++ b/src/renderer/src/components/browser-pane/assemble-chrome/browser-annotate-split-button.tsx @@ -20,7 +20,7 @@ import { } from '@/components/ui/dropdown-menu' import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip' import { useTranslate } from '@/i18n/use-translate' -import { cn } from '@/lib/utils' +import { cn } from '@/lib/class-names' import type { GrabIntent } from '../../../../../shared/browser/element-grab/browser-grab-types' import { MarkupDrawHintPopover, useMarkupDrawHintState } from '../annotate/markup-draw-hint-popover' diff --git a/src/renderer/src/components/browser-pane/assemble-chrome/browser-egress-indicator.tsx b/src/renderer/src/components/browser-pane/assemble-chrome/browser-egress-indicator.tsx index caac19220bd..fd2141b18b4 100644 --- a/src/renderer/src/components/browser-pane/assemble-chrome/browser-egress-indicator.tsx +++ b/src/renderer/src/components/browser-pane/assemble-chrome/browser-egress-indicator.tsx @@ -1,14 +1,14 @@ import { useState } from 'react' import { Globe, Monitor, Server } from 'lucide-react' import { useTranslate } from '@/i18n/use-translate' -import { useAppStore } from '@/store' +import { useAppStore } from '@/store/index' import { Button } from '@/components/ui/button' import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover' import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip' import { BROWSER_CLIENT_HOSTED_REMOTE_SETTINGS_TARGET_ID, BROWSER_SSH_WORKSPACE_ROUTING_SETTINGS_TARGET_ID -} from '@/lib/settings-navigation-types' +} from '@/components/settings/navigation/settings-navigation-types' import { toRuntimeExecutionHostId, toSshExecutionHostId diff --git a/src/renderer/src/components/browser-pane/assemble-chrome/browser-extension-action-menu.tsx b/src/renderer/src/components/browser-pane/assemble-chrome/browser-extension-action-menu.tsx index dac44cfa2c2..65524ac57b4 100644 --- a/src/renderer/src/components/browser-pane/assemble-chrome/browser-extension-action-menu.tsx +++ b/src/renderer/src/components/browser-pane/assemble-chrome/browser-extension-action-menu.tsx @@ -18,7 +18,7 @@ import { import { useConfirmationDialog } from '@/components/confirmation-dialog-context' import { browserExtensionRemovalDescription } from '@/components/browser-extension-removal-description' import { useTranslate } from '@/i18n/use-translate' -import { cn } from '@/lib/utils' +import { cn } from '@/lib/class-names' import type { BrowserExtensionContextMenuItem } from '../../../../../shared/browser/extensions/browser-extension-context-menu-types' import type { BrowserExtensionActionResult } from '../../../../../shared/browser/extensions/browser-extension-types' import type { BrowserExtensionToolbarAction } from '../../../../../shared/browser/extensions/browser-extension-toolbar-types' diff --git a/src/renderer/src/components/browser-pane/assemble-chrome/browser-extension-toolbar.tsx b/src/renderer/src/components/browser-pane/assemble-chrome/browser-extension-toolbar.tsx index e87d5d6e89c..60ec2f415da 100644 --- a/src/renderer/src/components/browser-pane/assemble-chrome/browser-extension-toolbar.tsx +++ b/src/renderer/src/components/browser-pane/assemble-chrome/browser-extension-toolbar.tsx @@ -12,8 +12,8 @@ import { } from '@/components/ui/dropdown-menu' import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip' import { useTranslate } from '@/i18n/use-translate' -import { cn } from '@/lib/utils' -import { useAppStore } from '@/store' +import { cn } from '@/lib/class-names' +import { useAppStore } from '@/store/index' import type { BrowserExtensionToolbarAction, BrowserExtensionToolbarState diff --git a/src/renderer/src/components/browser-pane/assemble-chrome/browser-link-status-bubble.tsx b/src/renderer/src/components/browser-pane/assemble-chrome/browser-link-status-bubble.tsx index 9c1cc7ecd22..8b3c067ddcf 100644 --- a/src/renderer/src/components/browser-pane/assemble-chrome/browser-link-status-bubble.tsx +++ b/src/renderer/src/components/browser-pane/assemble-chrome/browser-link-status-bubble.tsx @@ -1,5 +1,5 @@ import { useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react' -import { cn } from '@/lib/utils' +import { cn } from '@/lib/class-names' import { windowDipToCssPx } from '@/lib/ui-zoom' import { toDisplayUrl } from '../describe-page/browser-page-url-display' diff --git a/src/renderer/src/components/browser-pane/assemble-chrome/browser-navigation-control-row.tsx b/src/renderer/src/components/browser-pane/assemble-chrome/browser-navigation-control-row.tsx index 36de7804a45..31a33b7c25c 100644 --- a/src/renderer/src/components/browser-pane/assemble-chrome/browser-navigation-control-row.tsx +++ b/src/renderer/src/components/browser-pane/assemble-chrome/browser-navigation-control-row.tsx @@ -1,7 +1,7 @@ import { ArrowLeft, ArrowRight, RefreshCw, X } from 'lucide-react' import { Button } from '@/components/ui/button' import { useTranslate } from '@/i18n/use-translate' -import { cn } from '@/lib/utils' +import { cn } from '@/lib/class-names' import { BROWSER_CHROME_ADDRESS_SLOT_ATTRIBUTE, BROWSER_CHROME_ADDRESS_SLOT_HEIGHT_CLASS diff --git a/src/renderer/src/components/browser-pane/assemble-chrome/browser-page-chrome-banners.tsx b/src/renderer/src/components/browser-pane/assemble-chrome/browser-page-chrome-banners.tsx index 4e346034015..4ce988d5d15 100644 --- a/src/renderer/src/components/browser-pane/assemble-chrome/browser-page-chrome-banners.tsx +++ b/src/renderer/src/components/browser-pane/assemble-chrome/browser-page-chrome-banners.tsx @@ -1,5 +1,5 @@ import type { Dispatch, SetStateAction } from 'react' -import { cn } from '@/lib/utils' +import { cn } from '@/lib/class-names' import { CircleCheck, Copy, Crosshair, Send, Trash2 } from 'lucide-react' import { Button } from '@/components/ui/button' import { diff --git a/src/renderer/src/components/browser-pane/assemble-chrome/browser-page-extension-menu-items.tsx b/src/renderer/src/components/browser-pane/assemble-chrome/browser-page-extension-menu-items.tsx index 2906b0b8ba2..97b17cf8a5b 100644 --- a/src/renderer/src/components/browser-pane/assemble-chrome/browser-page-extension-menu-items.tsx +++ b/src/renderer/src/components/browser-pane/assemble-chrome/browser-page-extension-menu-items.tsx @@ -1,6 +1,6 @@ import { useState } from 'react' import { Check, ChevronRight } from 'lucide-react' -import { cn } from '@/lib/utils' +import { cn } from '@/lib/class-names' import type { BrowserExtensionContextMenuItem, BrowserExtensionContextMenuPayload diff --git a/src/renderer/src/components/browser-pane/assemble-chrome/browser-page-feedback-badge.tsx b/src/renderer/src/components/browser-pane/assemble-chrome/browser-page-feedback-badge.tsx index 29c4a2e144f..c645530c5d8 100644 --- a/src/renderer/src/components/browser-pane/assemble-chrome/browser-page-feedback-badge.tsx +++ b/src/renderer/src/components/browser-pane/assemble-chrome/browser-page-feedback-badge.tsx @@ -1,5 +1,5 @@ import { useEffect, useImperativeHandle, useRef, useState, type Ref } from 'react' -import { cn } from '@/lib/utils' +import { cn } from '@/lib/class-names' import { BROWSER_PAGE_ZOOM_FEEDBACK_MS } from '../describe-page/browser-annotation-geometry' export type BrowserPageFeedbackBadgeHandle = { diff --git a/src/renderer/src/components/browser-pane/assemble-chrome/browser-page-pane.tsx b/src/renderer/src/components/browser-pane/assemble-chrome/browser-page-pane.tsx index 015330ae64e..ca2157b01bf 100644 --- a/src/renderer/src/components/browser-pane/assemble-chrome/browser-page-pane.tsx +++ b/src/renderer/src/components/browser-pane/assemble-chrome/browser-page-pane.tsx @@ -1,9 +1,9 @@ import { useEffect, useLayoutEffect, useRef, useState } from 'react' import { createPortal } from 'react-dom' -import { cn } from '@/lib/utils' +import { cn } from '@/lib/class-names' import '@/lib/workspace/ownership/connection-context' import { getConnectionIdFromState } from '@/lib/workspace/ownership/connection-owner-resolution' -import { useAppStore } from '@/store' +import { useAppStore } from '@/store/index' import { useShortcutLabel } from '@/hooks/useShortcutLabel' import '../../../../../shared/constants' import { ORCA_BROWSER_BLANK_URL } from '../../../../../shared/browser/browser-blank-page' diff --git a/src/renderer/src/components/browser-pane/browser-client-page-guest-metadata.ts b/src/renderer/src/components/browser-pane/browser-client-page-guest-metadata.ts index aaafcd0c845..18c78708b2d 100644 --- a/src/renderer/src/components/browser-pane/browser-client-page-guest-metadata.ts +++ b/src/renderer/src/components/browser-pane/browser-client-page-guest-metadata.ts @@ -1,7 +1,7 @@ import type { BrowserLoadError } from '../../../../shared/browser-workspace-types' import type { BrowserPageFailLoadEvent } from './describe-page/browser-page-types' import { resolveBrowserWebviewLoadFailure } from './navigate/browser-webview-load-failure' -import { recordRendererCrashBreadcrumb } from '@/lib/crash-breadcrumb-recorder' +import { recordRendererCrashBreadcrumb } from '@/diagnostics/crash-reporting/crash-breadcrumb-recorder' import { redactKagiSessionToken } from '../../../../shared/browser-url' import type { BrowserClientPageMetadataSnapshot } from './browser-client-page-metadata-publisher' diff --git a/src/renderer/src/components/browser-pane/browser-client-page-metadata-publish-e2e-fault.ts b/src/renderer/src/components/browser-pane/browser-client-page-metadata-publish-e2e-fault.ts index 0b1d8b2cdf8..ab2a022f805 100644 --- a/src/renderer/src/components/browser-pane/browser-client-page-metadata-publish-e2e-fault.ts +++ b/src/renderer/src/components/browser-pane/browser-client-page-metadata-publish-e2e-fault.ts @@ -1,4 +1,4 @@ -import { e2eConfig } from '@/lib/e2e-config' +import { e2eConfig } from '@/app-shell/startup/e2e-config' /** Hold runtime metadata stale deterministically; normal publish lag is sub-second, and snapshot waits would miss both that window and outright failure. */ type MetadataPublishFaultApi = { diff --git a/src/renderer/src/components/browser-pane/browser-user-agent-migration-notice.ts b/src/renderer/src/components/browser-pane/browser-user-agent-migration-notice.ts index b618a4ea366..8932b5baba9 100644 --- a/src/renderer/src/components/browser-pane/browser-user-agent-migration-notice.ts +++ b/src/renderer/src/components/browser-pane/browser-user-agent-migration-notice.ts @@ -1,8 +1,8 @@ import { useEffect } from 'react' import { toast } from 'sonner' import { translate } from '@/i18n/i18n' -import { useAppStore } from '@/store' -import { BROWSER_USER_AGENT_SETTINGS_TARGET_ID } from '@/lib/settings-navigation-types' +import { useAppStore } from '@/store/index' +import { BROWSER_USER_AGENT_SETTINGS_TARGET_ID } from '@/components/settings/navigation/settings-navigation-types' export function useBrowserIdentityMigrationNotice(): void { useEffect(() => { diff --git a/src/renderer/src/components/browser-pane/host-guest/browser-client-page-guest-loss.ts b/src/renderer/src/components/browser-pane/host-guest/browser-client-page-guest-loss.ts index b9e2f6a21f6..baeab47a922 100644 --- a/src/renderer/src/components/browser-pane/host-guest/browser-client-page-guest-loss.ts +++ b/src/renderer/src/components/browser-pane/host-guest/browser-client-page-guest-loss.ts @@ -1,5 +1,5 @@ import type { MutableRefObject } from 'react' -import { recordRendererCrashBreadcrumb } from '@/lib/crash-breadcrumb-recorder' +import { recordRendererCrashBreadcrumb } from '@/diagnostics/crash-reporting/crash-breadcrumb-recorder' export type BrowserClientPageGuestLossReason = 'unreadable' | 'destroyed' | 'render-process-gone' diff --git a/src/renderer/src/components/browser-pane/navigate/browser-load-failure-auto-retry.tsx b/src/renderer/src/components/browser-pane/navigate/browser-load-failure-auto-retry.tsx index fe2ca83ab47..d29aceaa5fb 100644 --- a/src/renderer/src/components/browser-pane/navigate/browser-load-failure-auto-retry.tsx +++ b/src/renderer/src/components/browser-pane/navigate/browser-load-failure-auto-retry.tsx @@ -3,7 +3,7 @@ import type { BrowserLoadFailureDescription, BrowserLoadFailureRecovery } from '../../../../../shared/browser-load-failure' -import { isWindowVisible } from '@/lib/window-visibility-interval' +import { isWindowVisible } from '@/lib/window-activity/window-visibility-interval' import { translateLoadFailurePiece } from './browser-notices' export type BrowserLoadFailureAutoRetry = { diff --git a/src/renderer/src/components/browser-pane/navigate/use-browser-page-webview-url-sync.ts b/src/renderer/src/components/browser-pane/navigate/use-browser-page-webview-url-sync.ts index e75edf5a5fa..8e0ad0bcd32 100644 --- a/src/renderer/src/components/browser-pane/navigate/use-browser-page-webview-url-sync.ts +++ b/src/renderer/src/components/browser-pane/navigate/use-browser-page-webview-url-sync.ts @@ -11,7 +11,7 @@ import { applyBrowserPageViewportLayout, syncBrowserPageChromeInset } from '../host-guest/browser-page-viewport' -import { installWindowVisibilityInterval } from '@/lib/window-visibility-interval' +import { installWindowVisibilityInterval } from '@/lib/window-activity/window-visibility-interval' import { shouldPollChromiumErrorPage } from './chromium-error-page-polling' import { isChromiumErrorPage } from '../describe-page/browser-page-url-display' import type { BrowserTabPageState } from '../describe-page/browser-page-types' diff --git a/src/renderer/src/components/browser-pane/new-tab/browser-new-tab-workspace-card.tsx b/src/renderer/src/components/browser-pane/new-tab/browser-new-tab-workspace-card.tsx index 8db21bb677a..783e4e55f28 100644 --- a/src/renderer/src/components/browser-pane/new-tab/browser-new-tab-workspace-card.tsx +++ b/src/renderer/src/components/browser-pane/new-tab/browser-new-tab-workspace-card.tsx @@ -6,7 +6,7 @@ import { useState } from 'react' import { ChevronRight, CircleDot, GitMerge, GitPullRequest } from 'lucide-react' import { translate } from '@/i18n/i18n' import { useTranslate, type Translate } from '@/i18n/use-translate' -import { cn } from '@/lib/utils' +import { cn } from '@/lib/class-names' import { LinearIcon } from '@/components/icons/LinearIcon' import { JiraIcon } from '@/components/icons/JiraIcon' import { getReviewStateTone } from '@/components/github/review-state-presentation' diff --git a/src/renderer/src/components/browser-pane/stream-remote/remote-browser-screencast-subscription.ts b/src/renderer/src/components/browser-pane/stream-remote/remote-browser-screencast-subscription.ts index d1eb1ab666b..1611e8172dd 100644 --- a/src/renderer/src/components/browser-pane/stream-remote/remote-browser-screencast-subscription.ts +++ b/src/renderer/src/components/browser-pane/stream-remote/remote-browser-screencast-subscription.ts @@ -4,7 +4,7 @@ import type { BrowserScreencastResult } from '../../../../../shared/browser/runtime/runtime-browser-contracts' import { withBrowserPaneUiRuntimeRpcSource } from '../../../../../shared/runtime-rpc-feature-interaction-source' -import { e2eConfig } from '@/lib/e2e-config' +import { e2eConfig } from '@/app-shell/startup/e2e-config' import { isRemoteBrowserPageMissingCode } from './remote-browser-stream-errors' import type { RemoteBrowserViewportSize } from './remote-browser-stream-tokens' diff --git a/src/renderer/src/components/cmd-j/PaletteFilterFieldOptions.tsx b/src/renderer/src/components/cmd-j/PaletteFilterFieldOptions.tsx index f3af842801a..5280b21ba45 100644 --- a/src/renderer/src/components/cmd-j/PaletteFilterFieldOptions.tsx +++ b/src/renderer/src/components/cmd-j/PaletteFilterFieldOptions.tsx @@ -2,7 +2,7 @@ import { ImeInput } from '@/lib/text-input/ime/ime-text-field' import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react' import { useVirtualizer } from '@tanstack/react-virtual' import { Check, ChevronLeft, SearchIcon } from 'lucide-react' -import { cn } from '@/lib/utils' +import { cn } from '@/lib/class-names' import { useTranslate } from '@/i18n/use-translate' import type { PaletteFilterOption } from './palette-filter-options' import type { PaletteFilterField } from './palette-filter' diff --git a/src/renderer/src/components/cmd-j/palette-results.ts b/src/renderer/src/components/cmd-j/palette-results.ts index 2b98f6e08bd..082d5233a1b 100644 --- a/src/renderer/src/components/cmd-j/palette-results.ts +++ b/src/renderer/src/components/cmd-j/palette-results.ts @@ -1,6 +1,9 @@ import { translate } from '@/i18n/i18n' import type { Translate } from '@/i18n/use-translate' -import type { SettingsNavIcon, SettingsNavSection } from '@/lib/settings-navigation-types' +import type { + SettingsNavIcon, + SettingsNavSection +} from '@/components/settings/navigation/settings-navigation-types' import type { CmdJQuickAction } from './quick-actions' import { isClipboardTextByteLengthOverLimit } from '../../../../shared/clipboard-text' import { diff --git a/src/renderer/src/components/confirmation-dialog.tsx b/src/renderer/src/components/confirmation-dialog.tsx index 05dc78a514e..c760ead49f8 100644 --- a/src/renderer/src/components/confirmation-dialog.tsx +++ b/src/renderer/src/components/confirmation-dialog.tsx @@ -17,9 +17,9 @@ import { type ConfirmationDialogContextValue, type ConfirmationDialogOptions } from '@/components/confirmation-dialog-context' -import { useAppStore } from '@/store' +import { useAppStore } from '@/store/index' import { useTranslate } from '@/i18n/use-translate' -import { cn } from '@/lib/utils' +import { cn } from '@/lib/class-names' type ConfirmationDialogRequest = { id: number diff --git a/src/renderer/src/components/confirmation-skip-preference.ts b/src/renderer/src/components/confirmation-skip-preference.ts index c7eea096fd4..302d9701347 100644 --- a/src/renderer/src/components/confirmation-skip-preference.ts +++ b/src/renderer/src/components/confirmation-skip-preference.ts @@ -1,6 +1,6 @@ import { toast } from 'sonner' import { translate } from '@/i18n/i18n' -import type { SettingsNavTarget } from '@/lib/settings-navigation-types' +import type { SettingsNavTarget } from '@/components/settings/navigation/settings-navigation-types' import type { GlobalSettings } from '../../../shared/global-settings-types' /** Persists the preference and keeps its reversal one click away. */ diff --git a/src/renderer/src/components/contextual-tours/ContextualTourOverlay.tsx b/src/renderer/src/components/contextual-tours/ContextualTourOverlay.tsx index 73eb03b8bb4..7b1ba7bb562 100644 --- a/src/renderer/src/components/contextual-tours/ContextualTourOverlay.tsx +++ b/src/renderer/src/components/contextual-tours/ContextualTourOverlay.tsx @@ -1,6 +1,6 @@ import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState, type JSX } from 'react' import { hasUndoneContextualTourAction } from '../../../../shared/contextual-tour-action-steps' -import { useAppStore } from '@/store' +import { useAppStore } from '@/store/index' import { runActiveNativeChatSplit } from '@/components/native-chat/pane/routing/native-chat-layout-actions' import { getContextualTour, @@ -11,7 +11,7 @@ import type { ContextualTourOutcome } from '../../../../shared/feature-education import { trackContextualTourOutcome, trackContextualTourShown -} from '@/lib/feature-education-telemetry' +} from '@/diagnostics/telemetry/feature-education-telemetry' import { isContextualTourAllowedForModal } from './contextual-tour-gate' import { areContextualTourRenderStatesEqual, @@ -25,12 +25,12 @@ import { handleContextualTourOverlayKeyDown, type ActiveTourRenderState } from './ContextualTourOverlaySurface' -import { installWindowVisibilityInterval } from '@/lib/window-visibility-interval' +import { installWindowVisibilityInterval } from '@/lib/window-activity/window-visibility-interval' import { requestActiveTerminalPaneSplit } from '@/components/tab-bar/request-active-terminal-pane-split' import { performContextualTourStepAction } from './contextual-tour-step-actions' import { useContextualTourFocus } from './use-contextual-tour-focus' import { openWorkspaceCreationComposerWithTourHandoff } from './workspace-creation-tour-handoff' -import { BROWSER_CLIENT_HOSTED_REMOTE_SETTINGS_TARGET_ID } from '@/lib/settings-navigation-types' +import { BROWSER_CLIENT_HOSTED_REMOTE_SETTINGS_TARGET_ID } from '@/components/settings/navigation/settings-navigation-types' export function ContextualTourOverlay(): JSX.Element | null { const activeTourId = useAppStore((s) => s.activeContextualTourId) diff --git a/src/renderer/src/components/contextual-tours/ContextualTourOverlaySurface.tsx b/src/renderer/src/components/contextual-tours/ContextualTourOverlaySurface.tsx index e4184bb60b3..87ee6953377 100644 --- a/src/renderer/src/components/contextual-tours/ContextualTourOverlaySurface.tsx +++ b/src/renderer/src/components/contextual-tours/ContextualTourOverlaySurface.tsx @@ -11,8 +11,8 @@ import { import { ArrowLeft, ArrowRight, X } from 'lucide-react' import { Badge } from '@/components/ui/badge' import { Button } from '@/components/ui/button' -import { cn } from '@/lib/utils' -import { useAppStore } from '@/store' +import { cn } from '@/lib/class-names' +import { useAppStore } from '@/store/index' import { getContextualTour, type ContextualTourId, diff --git a/src/renderer/src/components/contextual-tours/ContextualTourProgressDots.tsx b/src/renderer/src/components/contextual-tours/ContextualTourProgressDots.tsx index 302f4094562..dc784398dc7 100644 --- a/src/renderer/src/components/contextual-tours/ContextualTourProgressDots.tsx +++ b/src/renderer/src/components/contextual-tours/ContextualTourProgressDots.tsx @@ -1,5 +1,5 @@ import type { JSX } from 'react' -import { cn } from '@/lib/utils' +import { cn } from '@/lib/class-names' import { useTranslate } from '@/i18n/use-translate' export function ContextualTourProgressDots({ diff --git a/src/renderer/src/components/crash-report/CrashReportDialog.tsx b/src/renderer/src/components/crash-report/CrashReportDialog.tsx index f28ef34dd3a..ecd1d071327 100644 --- a/src/renderer/src/components/crash-report/CrashReportDialog.tsx +++ b/src/renderer/src/components/crash-report/CrashReportDialog.tsx @@ -1,10 +1,10 @@ import { Suspense, useCallback, useEffect, useRef, useState } from 'react' -import { lazyWithRetry as lazy } from '@/lib/lazy-with-retry' +import { lazyWithRetry as lazy } from '@/app-shell/startup/lazy-with-retry' import { useMountedRef } from '@/hooks/useMountedRef' import { REACT_ERROR_BOUNDARY_REPORT_AVAILABLE_EVENT, takePendingReactErrorBoundaryReport -} from '@/lib/react-error-boundary-reporting' +} from '@/diagnostics/crash-reporting/react-error-boundary-reporting' import type { CrashReportRecord } from '../../../../shared/crash-reporting' const CrashReportDialogSurface = lazy(() => diff --git a/src/renderer/src/components/dashboard-popout/AgentCardLastMessages.tsx b/src/renderer/src/components/dashboard-popout/AgentCardLastMessages.tsx index d5b6be31ec1..61680753967 100644 --- a/src/renderer/src/components/dashboard-popout/AgentCardLastMessages.tsx +++ b/src/renderer/src/components/dashboard-popout/AgentCardLastMessages.tsx @@ -1,7 +1,7 @@ import { formatAgentTypeLabel } from '../../../../shared/agent-status/presentation/agent-type-label' import type { DashboardCard } from '../../../../shared/dashboard-snapshot' import { useTranslate } from '@/i18n/use-translate' -import { cn } from '@/lib/utils' +import { cn } from '@/lib/class-names' export function hasAgentCardLastMessages(card: DashboardCard): boolean { return Boolean(card.lastUserMessage || card.lastAgentMessage) diff --git a/src/renderer/src/components/dashboard-popout/AgentDashboardToolbar.tsx b/src/renderer/src/components/dashboard-popout/AgentDashboardToolbar.tsx index d5b393f270a..f225ad2fd67 100644 --- a/src/renderer/src/components/dashboard-popout/AgentDashboardToolbar.tsx +++ b/src/renderer/src/components/dashboard-popout/AgentDashboardToolbar.tsx @@ -11,7 +11,7 @@ import { } from '@/components/ui/dropdown-menu' import { Input } from '@/components/ui/input' import { useTranslate } from '@/i18n/use-translate' -import { cn } from '@/lib/utils' +import { cn } from '@/lib/class-names' import { getWorkspaceStatusVisualMeta } from '../sidebar/workspace-status/presentation/workspace-status' import type { DashboardCard, DashboardFilterOptions } from '../../../../shared/dashboard-snapshot' import { diff --git a/src/renderer/src/components/dashboard-popout/AgentKanbanBoard.tsx b/src/renderer/src/components/dashboard-popout/AgentKanbanBoard.tsx index 65a1b766bf4..3982f058d2a 100644 --- a/src/renderer/src/components/dashboard-popout/AgentKanbanBoard.tsx +++ b/src/renderer/src/components/dashboard-popout/AgentKanbanBoard.tsx @@ -7,9 +7,9 @@ import { type DashboardSnapshot } from '../../../../shared/dashboard-snapshot' import type { RepoIcon } from '../../../../shared/repo-icon' -import { cn } from '@/lib/utils' +import { cn } from '@/lib/class-names' import { TooltipProvider } from '@/components/ui/tooltip' -import { installWindowVisibilityInterval } from '@/lib/window-visibility-interval' +import { installWindowVisibilityInterval } from '@/lib/window-activity/window-visibility-interval' import { AgentKanbanCard } from './AgentKanbanCard' import { AgentDashboardToolbar } from './AgentDashboardToolbar' import { AgentTerminalDialog, type AgentRevealArgs } from './AgentTerminalDialog' diff --git a/src/renderer/src/components/dashboard-popout/AgentKanbanCard.tsx b/src/renderer/src/components/dashboard-popout/AgentKanbanCard.tsx index dc46ed8d2d5..3cd6f0788d7 100644 --- a/src/renderer/src/components/dashboard-popout/AgentKanbanCard.tsx +++ b/src/renderer/src/components/dashboard-popout/AgentKanbanCard.tsx @@ -12,7 +12,7 @@ import { AgentQuestionIcon } from '@/components/AgentQuestionIcon' import { AgentStateDot } from '@/components/AgentStateDot' import { RepoIconGlyph } from '@/components/repo/repo-icon' import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip' -import { cn } from '@/lib/utils' +import { cn } from '@/lib/class-names' import { dashboardCardDisplayState, type DashboardCard diff --git a/src/renderer/src/components/dashboard-popout/AgentTerminalDialog.tsx b/src/renderer/src/components/dashboard-popout/AgentTerminalDialog.tsx index 560c0e3459a..47ae4dff869 100644 --- a/src/renderer/src/components/dashboard-popout/AgentTerminalDialog.tsx +++ b/src/renderer/src/components/dashboard-popout/AgentTerminalDialog.tsx @@ -14,7 +14,7 @@ import { AgentTerminalPreview } from './AgentTerminalPreview' import { AgentCardLastMessages, hasAgentCardLastMessages } from './AgentCardLastMessages' import { terminalPreviewUnavailableMessage } from './terminal-preview-unavailable-message' import { useTranslate } from '@/i18n/use-translate' -import { cn } from '@/lib/utils' +import { cn } from '@/lib/class-names' /** Routing payload for focusing an agent's pane in the main window. */ export type AgentRevealArgs = DashboardRevealAgentArgs diff --git a/src/renderer/src/components/dashboard-popout/AgentTerminalPreview.tsx b/src/renderer/src/components/dashboard-popout/AgentTerminalPreview.tsx index 9ef12243799..f5ced3a45ee 100644 --- a/src/renderer/src/components/dashboard-popout/AgentTerminalPreview.tsx +++ b/src/renderer/src/components/dashboard-popout/AgentTerminalPreview.tsx @@ -16,8 +16,8 @@ import { syncPreviewTerminalLigatures } from './preview-terminal-ligatures' import type { DashboardCardTerminalInput } from '../../../../shared/dashboard-snapshot' import { terminalPreviewUnavailableMessage } from './terminal-preview-unavailable-message' import { resolveEffectiveTerminalAppearance } from '@/lib/terminal-theme' -import { cn } from '@/lib/utils' -import { useAppStore } from '@/store' +import { cn } from '@/lib/class-names' +import { useAppStore } from '@/store/index' import { usePluginFontReady } from '@/store/plugins/appearance/plugin-fonts' import { createPreviewGridClaim } from './preview-grid-claim' import { createPreviewBoxFit } from './preview-terminal-box-fit' diff --git a/src/renderer/src/components/dashboard-popout/DashboardHostBadge.tsx b/src/renderer/src/components/dashboard-popout/DashboardHostBadge.tsx index cd8557f37f8..0e95bb2ee15 100644 --- a/src/renderer/src/components/dashboard-popout/DashboardHostBadge.tsx +++ b/src/renderer/src/components/dashboard-popout/DashboardHostBadge.tsx @@ -2,7 +2,7 @@ import { Server } from 'lucide-react' import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip' import { translate } from '@/i18n/i18n' import { useTranslate, type Translate } from '@/i18n/use-translate' -import { cn } from '@/lib/utils' +import { cn } from '@/lib/class-names' import type { DashboardCardHostKind } from '../../../../shared/dashboard-snapshot' import { parseExecutionHostId, type ExecutionHostId } from '../../../../shared/execution-host' diff --git a/src/renderer/src/components/dashboard-popout/dashboard-preview-link-interaction.ts b/src/renderer/src/components/dashboard-popout/dashboard-preview-link-interaction.ts index afa28feafba..a75ae43fad9 100644 --- a/src/renderer/src/components/dashboard-popout/dashboard-preview-link-interaction.ts +++ b/src/renderer/src/components/dashboard-popout/dashboard-preview-link-interaction.ts @@ -14,7 +14,7 @@ import { getTerminalBufferPositionForMouseEvent } from '@/components/terminal-pa import { findHttpLinkAtTerminalMouseEvent } from '@/components/terminal-pane/links/http/terminal-url-link-hit-testing' import { findTerminalHttpLinkAtBufferPosition } from '../../../../shared/terminal/links/terminal-link-buffer-hit-testing' import { httpLinkDirectClickDestination } from '@/lib/browser/navigation/http-link-destinations' -import { isWindowsUserAgent } from '@/lib/user-agent-platform' +import { isWindowsUserAgent } from '@/app-shell/platform/user-agent-platform' import type { GlobalSettings } from '../../../../shared/global-settings-types' import { dashboardPreviewHttpActions, diff --git a/src/renderer/src/components/dashboard-popout/use-agent-dashboard-telemetry.test.ts b/src/renderer/src/components/dashboard-popout/use-agent-dashboard-telemetry.test.ts deleted file mode 100644 index 5b351691f32..00000000000 --- a/src/renderer/src/components/dashboard-popout/use-agent-dashboard-telemetry.test.ts +++ /dev/null @@ -1,120 +0,0 @@ -// @vitest-environment happy-dom - -import { act, cleanup, renderHook } from '@testing-library/react' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { getDefaultSettings } from '../../../../shared/constants' -import type { TelemetryConsentState } from '../../../../shared/telemetry-consent-types' -import { useAppStore } from '@/store' - -const { track, getConsentState } = vi.hoisted(() => ({ - track: vi.fn(), - getConsentState: vi.fn() -})) -vi.mock('@/lib/telemetry', () => ({ track, trackWithResult: track, getConsentState })) - -import { useAgentDashboardTelemetry } from './use-agent-dashboard-telemetry' - -const initialState = useAppStore.getInitialState() - -async function flushConsent(): Promise { - await act(async () => { - await Promise.resolve() - }) -} - -function publishSavedConsent(optedIn: boolean | null): void { - useAppStore.setState((state) => ({ - settings: { - ...(state.settings ?? getDefaultSettings(process.cwd())), - telemetry: { optedIn, installId: 'test-install', existedBeforeTelemetryRelease: false } - } - })) -} - -describe('dashboard visible-use telemetry', () => { - let visibility: DocumentVisibilityState - - beforeEach(() => { - vi.useFakeTimers({ now: new Date('2026-10-22T12:00:00Z') }) - track.mockReset().mockResolvedValue(true) - getConsentState.mockReset().mockResolvedValue({ effective: 'enabled' }) - useAppStore.setState({ - settings: { - ...getDefaultSettings(process.cwd()), - telemetry: { - optedIn: true, - installId: 'test-install', - existedBeforeTelemetryRelease: false - } - } - }) - visibility = 'visible' - vi.spyOn(document, 'visibilityState', 'get').mockImplementation(() => visibility) - }) - - afterEach(() => { - cleanup() - useAppStore.setState(initialState, true) - vi.useRealTimers() - vi.restoreAllMocks() - }) - - it.each(['pending_banner', 'user_opt_out', 'do_not_track', 'orca_disabled', 'ci'] as const)( - 'creates no timer or daily-use attempts while blocked by %s', - async (reason) => { - getConsentState.mockResolvedValue( - reason === 'pending_banner' - ? { effective: 'pending_banner' } - : { effective: 'disabled', reason } - ) - renderHook(() => useAgentDashboardTelemetry('popout')) - await flushConsent() - - act(() => vi.advanceTimersByTime(24 * 60 * 60_000)) - - expect(vi.getTimerCount()).toBe(0) - expect(track.mock.calls).toEqual([['agent_dashboard_opened', { surface: 'popout' }]]) - } - ) - - it('starts and stops observing on consent broadcasts without counting a new opening', async () => { - publishSavedConsent(null) - getConsentState.mockResolvedValue({ effective: 'pending_banner' }) - renderHook(() => useAgentDashboardTelemetry('popout')) - await flushConsent() - expect(vi.getTimerCount()).toBe(0) - - getConsentState.mockResolvedValue({ effective: 'enabled' }) - act(() => { - publishSavedConsent(true) - }) - await flushConsent() - expect(vi.getTimerCount()).toBe(1) - expect(track.mock.calls.filter(([event]) => event === 'agent_dashboard_active')).toHaveLength(1) - - getConsentState.mockResolvedValue({ effective: 'disabled', reason: 'user_opt_out' }) - act(() => { - publishSavedConsent(false) - }) - await flushConsent() - expect(vi.getTimerCount()).toBe(0) - expect(track.mock.calls.filter(([event]) => event === 'agent_dashboard_opened')).toHaveLength(1) - }) - - it('does not install an observer after closing before the consent read finishes', async () => { - let resolveConsent: ((value: TelemetryConsentState) => void) | undefined - getConsentState.mockReturnValue( - new Promise((resolve) => { - resolveConsent = resolve - }) - ) - const { unmount } = renderHook(() => useAgentDashboardTelemetry('popout')) - unmount() - - resolveConsent?.({ effective: 'enabled' }) - await flushConsent() - - expect(vi.getTimerCount()).toBe(0) - expect(track.mock.calls).toEqual([['agent_dashboard_opened', { surface: 'popout' }]]) - }) -}) diff --git a/src/renderer/src/components/dashboard-popout/use-agent-dashboard-telemetry.ts b/src/renderer/src/components/dashboard-popout/use-agent-dashboard-telemetry.ts index 9f353179124..9fd788ea8cc 100644 --- a/src/renderer/src/components/dashboard-popout/use-agent-dashboard-telemetry.ts +++ b/src/renderer/src/components/dashboard-popout/use-agent-dashboard-telemetry.ts @@ -1,8 +1,8 @@ import { useEffect } from 'react' import type { AgentDashboardSurface } from '../../../../shared/telemetry-agent-dashboard-event-schemas' -import { getConsentState, track, trackWithResult } from '@/lib/telemetry' -import { installWindowVisibilityInterval } from '@/lib/window-visibility-interval' -import { useAppStore } from '@/store' +import { getConsentState, track, trackWithResult } from '@/diagnostics/telemetry/telemetry' +import { installWindowVisibilityInterval } from '@/lib/window-activity/window-visibility-interval' +import { useAppStore } from '@/store/index' export function useAgentDashboardTelemetry(surface: AgentDashboardSurface): void { const optedIn = useAppStore((state) => state.settings?.telemetry?.optedIn) diff --git a/src/renderer/src/components/dashboard/DashboardAgentChildDisclosure.tsx b/src/renderer/src/components/dashboard/DashboardAgentChildDisclosure.tsx index 44842099050..e9de1e7fa30 100644 --- a/src/renderer/src/components/dashboard/DashboardAgentChildDisclosure.tsx +++ b/src/renderer/src/components/dashboard/DashboardAgentChildDisclosure.tsx @@ -1,6 +1,6 @@ import React, { useCallback } from 'react' import { ChevronDown } from 'lucide-react' -import { cn } from '@/lib/utils' +import { cn } from '@/lib/class-names' import { Button } from '@/components/ui/button' import { useTranslate } from '@/i18n/use-translate' diff --git a/src/renderer/src/components/dashboard/DashboardAgentRow.tsx b/src/renderer/src/components/dashboard/DashboardAgentRow.tsx index 7d676e65533..a67e05ec0e3 100644 --- a/src/renderer/src/components/dashboard/DashboardAgentRow.tsx +++ b/src/renderer/src/components/dashboard/DashboardAgentRow.tsx @@ -1,5 +1,5 @@ import React, { useState, useCallback } from 'react' -import { cn } from '@/lib/utils' +import { cn } from '@/lib/class-names' import { opensClaudeParentConversation, viewClaudeAgentFromRow diff --git a/src/renderer/src/components/dashboard/DashboardAgentRowMessage.tsx b/src/renderer/src/components/dashboard/DashboardAgentRowMessage.tsx index 5ad38208446..2024cc53425 100644 --- a/src/renderer/src/components/dashboard/DashboardAgentRowMessage.tsx +++ b/src/renderer/src/components/dashboard/DashboardAgentRowMessage.tsx @@ -1,5 +1,5 @@ import { useEffect } from 'react' -import { cn } from '@/lib/utils' +import { cn } from '@/lib/class-names' import { CommentMarkdownAsync, preloadCommentMarkdown diff --git a/src/renderer/src/components/dashboard/DashboardAgentRowToolStep.tsx b/src/renderer/src/components/dashboard/DashboardAgentRowToolStep.tsx index e96843bd814..6ae783f9df5 100644 --- a/src/renderer/src/components/dashboard/DashboardAgentRowToolStep.tsx +++ b/src/renderer/src/components/dashboard/DashboardAgentRowToolStep.tsx @@ -1,5 +1,5 @@ import { Wrench } from 'lucide-react' -import { cn } from '@/lib/utils' +import { cn } from '@/lib/class-names' type DashboardAgentRowToolStepProps = { expanded: boolean diff --git a/src/renderer/src/components/dashboard/DashboardAgentRowTrailingControls.tsx b/src/renderer/src/components/dashboard/DashboardAgentRowTrailingControls.tsx index 07d1a10179d..28b90b79c86 100644 --- a/src/renderer/src/components/dashboard/DashboardAgentRowTrailingControls.tsx +++ b/src/renderer/src/components/dashboard/DashboardAgentRowTrailingControls.tsx @@ -1,7 +1,7 @@ import React, { useCallback } from 'react' import { ChevronDown, Send, X } from 'lucide-react' import { useTranslate } from '@/i18n/use-translate' -import { cn } from '@/lib/utils' +import { cn } from '@/lib/class-names' import { DashboardAgentChildDisclosure } from './DashboardAgentChildDisclosure' type DashboardAgentRowTrailingControlsProps = { diff --git a/src/renderer/src/components/dashboard/build-dashboard-snapshot.ts b/src/renderer/src/components/dashboard/build-dashboard-snapshot.ts index 6289fdafc09..958b30dc3ad 100644 --- a/src/renderer/src/components/dashboard/build-dashboard-snapshot.ts +++ b/src/renderer/src/components/dashboard/build-dashboard-snapshot.ts @@ -1,6 +1,5 @@ import { agentVerdictDisplayMark } from '../../../../shared/agent-status/lifecycle/agent-main-agent-verdict' import type { StructuredChatTabNames } from '@/runtime/native-chat/naming/structured-chat-tab-name' -import type { AgentLaunchRouteView } from '@/lib/agent-session/launch/routing/agent-launch-route-input' import type { AppState } from '@/store/types' import { DASHBOARD_MAX_MAP_WORKSPACES, @@ -42,10 +41,6 @@ import { rowConversationName, rowTask } from './dashboard-card-labels' -import { - buildDashboardWorktreeLaunchOptions, - type DashboardLaunchDetectionState -} from './dashboard-worktree-launch-options' import { buildDashboardSnapshotFilterOptions } from './dashboard-snapshot-filter-options' import { groupSubagentsByParentPaneKey } from './dashboard-subagent-cards' import { selectDashboardOrchestration } from './dashboard-orchestration-selection' @@ -70,7 +65,6 @@ export type DashboardSnapshotState = Pick< DashboardCardContextState & Partial< DashboardCardTerminalInputState & - DashboardLaunchDetectionState & Pick< AppState, | 'runtimeEnvironments' @@ -88,7 +82,6 @@ export function buildDashboardSnapshot( state: DashboardSnapshotInput, now: number, options: { - launchRouteStore?: AgentLaunchRouteView includeCardDetails?: boolean includeFilterOptions?: boolean /** Cache only row derivation; review/host/status inputs still require fresh card assembly. */ @@ -273,17 +266,6 @@ export function buildDashboardSnapshot( ...(workspaces ? { workspaces } : {}), showIdle, filterOptions, - // Count-only callers offer no launcher; skip host-detection lookups for sidebar rebuilds. - ...(includeCardDetails - ? { - launchableAgentsByWorktreeId: buildDashboardWorktreeLaunchOptions( - state, - cards, - workspaces, - options.launchRouteStore - ) - } - : {}), repoIconsByRepoId } } diff --git a/src/renderer/src/components/dashboard/dashboard-chat-program-acquisition.ts b/src/renderer/src/components/dashboard/dashboard-chat-program-acquisition.ts deleted file mode 100644 index a6f29976a82..00000000000 --- a/src/renderer/src/components/dashboard/dashboard-chat-program-acquisition.ts +++ /dev/null @@ -1,41 +0,0 @@ -import type { AppState } from '@/store/types' -import { holdChatProgramFacts } from '@/lib/agent-session/launch/inventory/host-chat-program-acquisition' -import { resolveChatProgramContext } from '@/lib/agent-session/launch/inventory/host-chat-program' -import { - selectAgentLaunchRouteView, - worktreeLaunchWorkspace -} from '@/lib/agent-session/launch/routing/agent-launch-route-input' -import { DASHBOARD_MAX_LAUNCH_WORKTREES } from '../../../../shared/dashboard-snapshot' -import { collectActiveDashboardWorkspaces } from './dashboard-snapshot-workspaces' - -/** Publishers reconcile one hold per represented execution resource before building payloads. */ -export function createDashboardChatProgramHolds() { - const held = new Map void>() - return { - reconcile(state: AppState): void { - const next = new Set() - const routeStore = selectAgentLaunchRouteView(state) - const shown = collectActiveDashboardWorkspaces(state, false) - for (const { worktree } of shown.slice(0, DASHBOARD_MAX_LAUNCH_WORKTREES)) { - const context = resolveChatProgramContext(routeStore, worktreeLaunchWorkspace(worktree.id)) - const key = context.revision - next.add(key) - if (!held.has(key)) { - // A new hold can notify synchronously and re-enter this reconcile: reserve its key first. - held.set(key, () => {}) - held.set(key, holdChatProgramFacts(context).release) - } - } - for (const [key, release] of held) { - if (!next.has(key)) { - release() - held.delete(key) - } - } - }, - release(): void { - held.forEach((release) => release()) - held.clear() - } - } -} diff --git a/src/renderer/src/components/dashboard/dashboard-worktree-launch-options.ts b/src/renderer/src/components/dashboard/dashboard-worktree-launch-options.ts deleted file mode 100644 index 7e6e7dab48b..00000000000 --- a/src/renderer/src/components/dashboard/dashboard-worktree-launch-options.ts +++ /dev/null @@ -1,151 +0,0 @@ -import type { AppState } from '@/store/types' -import { parseExecutionHostId } from '../../../../shared/execution-host' -import { - DASHBOARD_MAX_LAUNCH_WORKTREES, - type DashboardCard, - type DashboardWorkspace -} from '../../../../shared/dashboard-snapshot' -import { isTuiAgent } from '../../../../shared/agent-launch/catalog/tui-agent-config' -import { - filterEnabledTuiAgents, - TUI_AGENT_AUTO_PICK_ORDER -} from '../../../../shared/agent-launch/catalog/tui-agent-selection' -import type { TuiAgent } from '../../../../shared/agent-launch/catalog/tui-agent' -import { parseWorkspaceKey } from '../../../../shared/workspace-scope' -import { getRuntimeAgentInventoryKey } from '@/store/slices/agent-inventory/runtime-agent-inventory-key' -import { - worktreeLaunchWorkspace, - type AgentLaunchRouteView -} from '@/lib/agent-session/launch/routing/agent-launch-route-input' -import { agentsOfferedForLaunch } from '@/lib/agent-session/launch/inventory/host-chat-program' -import { selectWorktreesByRepo } from '@/store/workspaces/catalog/workspace-record-fields' - -export type DashboardLaunchDetectionState = Pick< - AppState, - | 'detectedAgentIds' - | 'folderWorkspaces' - | 'projectGroups' - | 'remoteDetectedAgentIds' - | 'runtimeDetectedAgentIds' -> - -type DashboardLaunchOptionState = Pick & - Partial - -type DashboardLaunchCatalog = { - foldersById: Map - groupsById: Map - reposById: Map - worktreesByRepoAndId: Map> -} - -function buildDashboardLaunchCatalog(state: DashboardLaunchOptionState): DashboardLaunchCatalog { - return { - foldersById: new Map((state.folderWorkspaces ?? []).map((folder) => [folder.id, folder])), - groupsById: new Map((state.projectGroups ?? []).map((group) => [group.id, group])), - reposById: new Map((state.repos ?? []).map((repo) => [repo.id, repo])), - worktreesByRepoAndId: new Map( - Object.entries(selectWorktreesByRepo(state) ?? {}).map(([repoId, worktrees]) => [ - repoId, - new Map(worktrees.map((worktree) => [worktree.id, worktree])) - ]) - ) - } -} - -// Why the host-default fallback: a card can render before any launch surface probed its workspace. -function runtimeAgentsForWorkspace( - state: DashboardLaunchOptionState, - environmentId: string, - worktreeId: string -): readonly TuiAgent[] { - const agents = state.runtimeDetectedAgentIds - return ( - agents?.[getRuntimeAgentInventoryKey(environmentId, worktreeId)] ?? - agents?.[environmentId] ?? - [] - ) -} - -function detectedAgentsForWorktree( - state: DashboardLaunchOptionState, - worktreeId: string, - repoId: string, - catalog: DashboardLaunchCatalog -): readonly TuiAgent[] { - const workspaceScope = parseWorkspaceKey(worktreeId) - if (workspaceScope?.type === 'folder') { - const folder = catalog.foldersById.get(workspaceScope.folderWorkspaceId) - const group = folder ? catalog.groupsById.get(folder.projectGroupId) : undefined - const host = parseExecutionHostId(group?.executionHostId) - if (host?.kind === 'runtime') { - return runtimeAgentsForWorkspace(state, host.environmentId, worktreeId) - } - const connectionId = folder?.connectionId ?? group?.connectionId - return connectionId ? (state.remoteDetectedAgentIds?.[connectionId] ?? []) : [] - } - - const worktree = catalog.worktreesByRepoAndId.get(repoId)?.get(worktreeId) - const repo = catalog.reposById.get(worktree?.repoId ?? repoId) - const host = parseExecutionHostId(worktree?.hostId ?? repo?.executionHostId) - if (host?.kind === 'runtime') { - return runtimeAgentsForWorkspace(state, host.environmentId, worktreeId) - } - const connectionId = host?.kind === 'ssh' ? host.targetId : repo?.connectionId - return connectionId - ? (state.remoteDetectedAgentIds?.[connectionId] ?? []) - : (state.detectedAgentIds ?? []) -} - -/** Host-detected choices, agents that open as a chat there, and providers proven to run there. */ -export function buildDashboardWorktreeLaunchOptions( - state: DashboardLaunchOptionState, - cards: readonly DashboardCard[], - workspaces: readonly DashboardWorkspace[] = [], - launchRouteStore?: AgentLaunchRouteView -): Record { - const catalog = buildDashboardLaunchCatalog(state) - const cardsByWorktreeId = new Map() - const repoIdByWorktreeId = new Map( - workspaces.map((workspace) => [workspace.worktreeId, workspace.repoId]) - ) - for (const card of cards) { - repoIdByWorktreeId.set(card.worktreeId, card.repoId) - const existing = cardsByWorktreeId.get(card.worktreeId) - if (existing) { - existing.push(card) - } else { - cardsByWorktreeId.set(card.worktreeId, [card]) - } - } - - const result: Record = {} - for (const [worktreeId, repoId] of repoIdByWorktreeId) { - // Bound launch options before validation would reject the entire snapshot. - if (Object.keys(result).length >= DASHBOARD_MAX_LAUNCH_WORKTREES) { - break - } - const worktreeCards = cardsByWorktreeId.get(worktreeId) ?? [] - const detected = detectedAgentsForWorktree(state, worktreeId, repoId, catalog) - const available = new Set( - launchRouteStore - ? agentsOfferedForLaunch(launchRouteStore, worktreeLaunchWorkspace(worktreeId), detected) - : detected - ) - for (const card of worktreeCards) { - if (isTuiAgent(card.agentType)) { - available.add(card.agentType) - } - } - const enabled = filterEnabledTuiAgents( - TUI_AGENT_AUTO_PICK_ORDER.filter((agent) => available.has(agent)), - state.settings?.disabledTuiAgents - ) - const preferred = state.settings?.defaultTuiAgent - result[worktreeId] = - preferred && preferred !== 'blank' && enabled.includes(preferred) - ? [preferred, ...enabled.filter((agent) => agent !== preferred)] - : enabled - } - return result -} diff --git a/src/renderer/src/components/dashboard/useDashboardPopoutBridge.ts b/src/renderer/src/components/dashboard/useDashboardPopoutBridge.ts index 01f3cb3711d..5c30bc7fbc0 100644 --- a/src/renderer/src/components/dashboard/useDashboardPopoutBridge.ts +++ b/src/renderer/src/components/dashboard/useDashboardPopoutBridge.ts @@ -1,4 +1,3 @@ -import { createDashboardChatProgramHolds } from './dashboard-chat-program-acquisition' import { useEffect } from 'react' import { useAppStore } from '@/store' import type { AppState } from '@/store/types' @@ -6,12 +5,6 @@ import { subscribeStructuredChatTabNames, getStructuredChatTabNames } from '@/runtime/native-chat/naming/structured-chat-name-observation' -import { subscribeChatProgramFacts } from '@/lib/agent-session/launch/inventory/host-chat-program' -import { - type AgentLaunchRouteView, - agentLaunchRouteInputsChanged, - selectAgentLaunchRouteView -} from '@/lib/agent-session/launch/routing/agent-launch-route-input' import { revealDashboardAgent } from './reveal-dashboard-agent' import type { RepoIcon } from '../../../../shared/repo-icon' import { buildDashboardSnapshot, type DashboardSnapshotState } from './build-dashboard-snapshot' @@ -36,16 +29,15 @@ export function repoIconsUnchanged( return nextIds.every((id) => id in previous && next[id] === previous[id]) } -type DashboardSnapshotWatchState = DashboardSnapshotState & - Pick & - AgentLaunchRouteView +type DashboardSnapshotWatchState = DashboardSnapshotState & Pick export function dashboardSnapshotInputsChanged( state: DashboardSnapshotWatchState, previousState: DashboardSnapshotWatchState ): boolean { return ( - agentLaunchRouteInputsChanged(state, previousState) || + state.activeWorktreeId !== previousState.activeWorktreeId || + state.activeWorkspaceExecutionHostId !== previousState.activeWorkspaceExecutionHostId || state.repos !== previousState.repos || selectWorktreesByRepo(state) !== selectWorktreesByRepo(previousState) || state.tabsByWorktree !== previousState.tabsByWorktree || @@ -61,9 +53,6 @@ export function dashboardSnapshotInputsChanged( // Why: settings controls idle visibility and generated conversation names. state.settings !== previousState.settings || state.workspaceStatuses !== previousState.workspaceStatuses || - state.detectedAgentIds !== previousState.detectedAgentIds || - state.remoteDetectedAgentIds !== previousState.remoteDetectedAgentIds || - state.runtimeDetectedAgentIds !== previousState.runtimeDetectedAgentIds || // Relay live hooks directly; rebuild snapshots for host-profile changes too, since idle boards may have no later event to correct stale byte routing. state.sshConnectionStates !== previousState.sshConnectionStates || state.sshStateByEnvironment !== previousState.sshStateByEnvironment || @@ -91,12 +80,9 @@ export function watchSnapshotInputs(onChanged: () => void): () => void { onChanged() } }) - // Launch options also read host chat facts held outside the store. - const unsubscribeChatFacts = subscribeChatProgramFacts(onChanged) return () => { stopNames() unsubscribeStore() - unsubscribeChatFacts() } } @@ -127,7 +113,6 @@ export function useDashboardPopoutBridge(enabled: boolean): void { } let open = false let disposed = false - const chatOwners = createDashboardChatProgramHolds() let unsubscribeStore: (() => void) | null = null let trailingTimer: ReturnType | null = null let lastPublishAt = 0 @@ -138,12 +123,10 @@ export function useDashboardPopoutBridge(enabled: boolean): void { const publishNow = (withIcons: boolean): void => { lastPublishAt = Date.now() const state = useAppStore.getState() - chatOwners.reconcile(state) const snapshot = buildDashboardSnapshot( { ...state, chatNames: getStructuredChatTabNames() }, lastPublishAt, { - launchRouteStore: selectAgentLaunchRouteView(state), rowsCache, rowsGeneration: state.agentStatusEpoch } @@ -209,7 +192,6 @@ export function useDashboardPopoutBridge(enabled: boolean): void { } publishNow(true) } else { - chatOwners.release() unsubscribeStore?.() unsubscribeStore = null if (trailingTimer) { @@ -235,7 +217,6 @@ export function useDashboardPopoutBridge(enabled: boolean): void { return () => { disposed = true - chatOwners.release() offOpenChanged?.() offRequested?.() unsubscribeStore?.() diff --git a/src/renderer/src/components/dashboard/useLiveDashboardSnapshot.ts b/src/renderer/src/components/dashboard/useLiveDashboardSnapshot.ts index a47736c057a..bcb2e7a6f54 100644 --- a/src/renderer/src/components/dashboard/useLiveDashboardSnapshot.ts +++ b/src/renderer/src/components/dashboard/useLiveDashboardSnapshot.ts @@ -1,13 +1,9 @@ -import { watchSnapshotInputs } from './useDashboardPopoutBridge' -import { createDashboardChatProgramHolds } from './dashboard-chat-program-acquisition' -import { useEffect, useMemo, useRef } from 'react' +import { useMemo, useRef } from 'react' import { useAppStore } from '@/store' import { useStructuredChatTabNames } from '@/runtime/native-chat/naming/structured-chat-name-observation' import type { DashboardSnapshot } from '../../../../shared/dashboard-snapshot' import { buildDashboardSnapshot } from './build-dashboard-snapshot' -import { useChatProgramFactsVersion } from '@/lib/agent-session/launch/inventory/host-chat-program-acquisition' import { createWorktreeAgentRowsCache } from './worktree-agent-rows-cache' -import { selectAgentLaunchRouteView } from '@/lib/agent-session/launch/routing/agent-launch-route-input' import { selectDetectedWorktreesByRepo, selectFolderWorkspaces, @@ -52,25 +48,11 @@ export function useLiveDashboardSnapshot(): DashboardSnapshot { const runtimeEnvironmentCatalogHydrated = useAppStore((s) => s.runtimeEnvironmentCatalogHydrated) const removedRuntimeEnvironmentIds = useAppStore((s) => s.removedRuntimeEnvironmentIds) const paneForegroundAgentByPaneKey = useAppStore((s) => s.paneForegroundAgentByPaneKey) - const detectedAgentIds = useAppStore((s) => s.detectedAgentIds) - const remoteDetectedAgentIds = useAppStore((s) => s.remoteDetectedAgentIds) - const runtimeDetectedAgentIds = useAppStore((s) => s.runtimeDetectedAgentIds) // Freshness can change buckets without map writes; the epoch invalidates stale-decay memos. const agentStatusEpoch = useAppStore((s) => s.agentStatusEpoch) const chatNames = useStructuredChatTabNames() - // Why: launch options read only this view, so any route input change rebuilds them. - const launchRouteStore = useAppStore(selectAgentLaunchRouteView) - useEffect(() => { - const holds = createDashboardChatProgramHolds() - const reconcile = (): void => holds.reconcile(useAppStore.getState()) - const stopWatching = watchSnapshotInputs(reconcile) - reconcile() - return () => { - stopWatching() - holds.release() - } - }, []) - const chatProgramFactsVersion = useChatProgramFactsVersion() + const activeWorktreeId = useAppStore((s) => s.activeWorktreeId) + const activeWorkspaceExecutionHostId = useAppStore((s) => s.activeWorkspaceExecutionHostId) return useMemo( // Read the clock when the freshness epoch invalidates this memo, matching row derivation. @@ -78,8 +60,8 @@ export function useLiveDashboardSnapshot(): DashboardSnapshot { buildDashboardSnapshot( { chatNames, - activeWorktreeId: launchRouteStore.activeWorktreeId, - activeWorkspaceExecutionHostId: launchRouteStore.activeWorkspaceExecutionHostId, + activeWorktreeId, + activeWorkspaceExecutionHostId, repos, worktreesByRepo, tabsByWorktree, @@ -107,15 +89,12 @@ export function useLiveDashboardSnapshot(): DashboardSnapshot { runtimeEnvironmentCatalogHydrated, removedRuntimeEnvironmentIds, paneForegroundAgentByPaneKey, - detectedAgentIds, - remoteDetectedAgentIds, - runtimeDetectedAgentIds, // Read launch identity non-reactively because Shift+Enter routing does not depend on it; match the bridge gate. agentLaunchConfigByPaneKey: useAppStore.getState().agentLaunchConfigByPaneKey }, Date.now(), // Reuse unchanged worktree rows while assembling cards fresh from current review/host/status slices. - { rowsCache: rowsCacheRef.current, rowsGeneration: agentStatusEpoch, launchRouteStore } + { rowsCache: rowsCacheRef.current, rowsGeneration: agentStatusEpoch } ), // eslint-disable-next-line react-hooks/exhaustive-deps [ @@ -146,12 +125,9 @@ export function useLiveDashboardSnapshot(): DashboardSnapshot { runtimeEnvironmentCatalogHydrated, removedRuntimeEnvironmentIds, paneForegroundAgentByPaneKey, - detectedAgentIds, - remoteDetectedAgentIds, - runtimeDetectedAgentIds, chatNames, - chatProgramFactsVersion, - launchRouteStore, + activeWorktreeId, + activeWorkspaceExecutionHostId, agentStatusEpoch ] ) diff --git a/src/renderer/src/components/dictation/DictationGrapes.tsx b/src/renderer/src/components/dictation/DictationGrapes.tsx index 8b80331c9b0..7b80ed415a1 100644 --- a/src/renderer/src/components/dictation/DictationGrapes.tsx +++ b/src/renderer/src/components/dictation/DictationGrapes.tsx @@ -1,4 +1,4 @@ -import { cn } from '@/lib/utils' +import { cn } from '@/lib/class-names' import { DICTATION_GRAPES } from '../../../../shared/dictation-audio-meter' type DictationGrapesProps = { diff --git a/src/renderer/src/components/dictation/DictationIndicator.tsx b/src/renderer/src/components/dictation/DictationIndicator.tsx index 43b0969d090..28121e94e28 100644 --- a/src/renderer/src/components/dictation/DictationIndicator.tsx +++ b/src/renderer/src/components/dictation/DictationIndicator.tsx @@ -4,9 +4,9 @@ import { Button } from '@/components/ui/button' import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip' import { useShortcutKeyDetails } from '@/hooks/useShortcutLabel' import { useTranslate } from '@/i18n/use-translate' -import { installWindowVisibilityInterval } from '@/lib/window-visibility-interval' -import { cn } from '@/lib/utils' -import { useAppStore } from '@/store' +import { installWindowVisibilityInterval } from '@/lib/window-activity/window-visibility-interval' +import { cn } from '@/lib/class-names' +import { useAppStore } from '@/store/index' import { ArrowUp, Check, CornerDownLeft, Loader2 } from 'lucide-react' import { isDictationPillShown } from '../../../../shared/dictation-session-machine' import { dictationSeparators } from '../../../../shared/dictation-transcript-spacing' diff --git a/src/renderer/src/components/dictation/DictationPillShell.tsx b/src/renderer/src/components/dictation/DictationPillShell.tsx index dbfea6fc954..5cffcfac656 100644 --- a/src/renderer/src/components/dictation/DictationPillShell.tsx +++ b/src/renderer/src/components/dictation/DictationPillShell.tsx @@ -1,5 +1,5 @@ -import { KEEPS_FOCUS_ATTRIBUTE } from '@/lib/focus-keeping-press' -import { cn } from '@/lib/utils' +import { KEEPS_FOCUS_ATTRIBUTE } from '@/lib/overlay-interaction/focus-keeping-press' +import { cn } from '@/lib/class-names' import { useDictationPillBox, type DictationPillAnchor } from './dictation-pill-anchor' // Presses on the pill keep focus where the words are going. diff --git a/src/renderer/src/components/dictation/dictation-meter-store.ts b/src/renderer/src/components/dictation/dictation-meter-store.ts index 57b771190ff..0799072b952 100644 --- a/src/renderer/src/components/dictation/dictation-meter-store.ts +++ b/src/renderer/src/components/dictation/dictation-meter-store.ts @@ -1,4 +1,4 @@ -import { e2eConfig } from '@/lib/e2e-config' +import { e2eConfig } from '@/app-shell/startup/e2e-config' import { useStore } from 'zustand' import { createStore } from 'zustand/vanilla' import { diff --git a/src/renderer/src/components/dictation/dictation-toasts.ts b/src/renderer/src/components/dictation/dictation-toasts.ts index 4d16b528431..cf9145f7593 100644 --- a/src/renderer/src/components/dictation/dictation-toasts.ts +++ b/src/renderer/src/components/dictation/dictation-toasts.ts @@ -1,7 +1,7 @@ import { toast } from 'sonner' -import { useAppStore } from '@/store' +import { useAppStore } from '@/store/index' import { translate } from '@/i18n/i18n' -import { compactIpcErrorMessage } from '@/lib/ipc-error' +import { compactIpcErrorMessage } from '@/runtime/errors/ipc-error' import { hostDictationErrorMessage } from '../../../../shared/host-dictation-error-messages' import { SPEECH_MODEL_NEEDS_UPDATE_ERROR } from '../../../../shared/speech-model-retirement' diff --git a/src/renderer/src/components/dismiss/EyeOffDismissButton.tsx b/src/renderer/src/components/dismiss/EyeOffDismissButton.tsx index ddee49616c1..6c6949d80ca 100644 --- a/src/renderer/src/components/dismiss/EyeOffDismissButton.tsx +++ b/src/renderer/src/components/dismiss/EyeOffDismissButton.tsx @@ -1,6 +1,6 @@ import { EyeOff } from 'lucide-react' import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip' -import { cn } from '@/lib/utils' +import { cn } from '@/lib/class-names' /** The eye-slash control that hides a teaching or info surface; its label names what goes away. */ export function EyeOffDismissButton({ diff --git a/src/renderer/src/components/editor/ChangesModeView.tsx b/src/renderer/src/components/editor/ChangesModeView.tsx index c24703feaac..0d6343d37a4 100644 --- a/src/renderer/src/components/editor/ChangesModeView.tsx +++ b/src/renderer/src/components/editor/ChangesModeView.tsx @@ -1,5 +1,5 @@ import React from 'react' -import { lazyWithRetry as lazy } from '@/lib/lazy-with-retry' +import { lazyWithRetry as lazy } from '@/app-shell/startup/lazy-with-retry' import type { OpenFile } from '@/store/slices/editor/types/open-file' import type { GitDiffResult } from '../../../../shared/git/diff/git-diff-compare-types' import type { GitStatusEntry } from '../../../../shared/git/status/git-status-types' diff --git a/src/renderer/src/components/editor/ConflictComponents.tsx b/src/renderer/src/components/editor/ConflictComponents.tsx index bc1eeeede53..a33ca8dda8b 100644 --- a/src/renderer/src/components/editor/ConflictComponents.tsx +++ b/src/renderer/src/components/editor/ConflictComponents.tsx @@ -11,7 +11,7 @@ import { } from 'lucide-react' import { Button } from '@/components/ui/button' import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip' -import { cn } from '@/lib/utils' +import { cn } from '@/lib/class-names' import type { ConflictReviewEntry } from '../../../../shared/editor-tab-view-types' import type { OpenFile } from '@/store/slices/editor/types/open-file' import type { diff --git a/src/renderer/src/components/editor/ConflictReviewFileTree.tsx b/src/renderer/src/components/editor/ConflictReviewFileTree.tsx index 9b68aa734a9..77647f54081 100644 --- a/src/renderer/src/components/editor/ConflictReviewFileTree.tsx +++ b/src/renderer/src/components/editor/ConflictReviewFileTree.tsx @@ -2,7 +2,7 @@ import React from 'react' import { ChevronDown, PanelLeftClose } from 'lucide-react' import { Button } from '@/components/ui/button' import { FileTypeIcon, FolderIcon } from '@/components/FileTypeIcon' -import { cn } from '@/lib/utils' +import { cn } from '@/lib/class-names' import { buildSourceControlTree, compactSourceControlTree, diff --git a/src/renderer/src/components/editor/EditorContent.monaco-lifecycle.test.tsx b/src/renderer/src/components/editor/EditorContent.monaco-lifecycle.test.tsx deleted file mode 100644 index a9890849ccc..00000000000 --- a/src/renderer/src/components/editor/EditorContent.monaco-lifecycle.test.tsx +++ /dev/null @@ -1,282 +0,0 @@ -// @vitest-environment happy-dom -import { cleanup, render } from '@testing-library/react' -import { afterEach, describe, expect, it, vi } from 'vitest' -import type { OpenFile } from '@/store/slices/editor/types/open-file' - -const lifecycle = vi.hoisted(() => ({ - events: [] as string[], - diffModelKeys: [] as string[], - viewStateKeys: new Array(), - models: new Map(), - notebookProps: [] as { - fileId: string - filePath: string - worktreeId: string - scrollCacheKey: string - onContentChange: (content: string) => void - onSave: (content: string) => Promise - }[], - richMarkdownProps: [] as { - externalSshTargetId?: string - runtimeEnvironmentId?: string - worktreeId: string - }[], - mountedProps: [] as { - filePath: string - readOnly?: boolean - liveTail?: boolean - viewStateId?: string - }[] -})) - -vi.mock('@/lib/lazy-with-retry', async () => { - const React = await import('react') - const { syncContentOnMount } = await import('./monaco-content-sync') - return { - lazyWithRetry: (factory: () => Promise) => { - if (factory.toString().includes('/DiffViewer.tsx')) { - return function MockDiffViewer(props: { filePath: string; modifiedModelKey?: string }) { - lifecycle.diffModelKeys.push(props.modifiedModelKey ?? '') - /* oxlint-disable react-hooks/exhaustive-deps -- Mount-only by design: a prop-effect would hide a missing outer React remount. */ - React.useEffect(() => { - lifecycle.events.push(`mount-diff:${props.filePath}`) - return () => { - lifecycle.events.push(`unmount-diff:${props.filePath}`) - } - }, []) - /* oxlint-enable react-hooks/exhaustive-deps */ - return null - } - } - if (factory.toString().includes('/IpynbViewer.tsx')) { - return function MockIpynbViewer(props: (typeof lifecycle.notebookProps)[number]) { - lifecycle.notebookProps.push(props) - return null - } - } - if (factory.toString().includes('/RichMarkdownEditor.tsx')) { - return function MockRichMarkdownEditor( - props: (typeof lifecycle.richMarkdownProps)[number] - ) { - lifecycle.richMarkdownProps.push(props) - return null - } - } - if (!factory.toString().includes('/MonacoEditor.tsx')) { - return () => null - } - return function MockRetainedMonaco(props: { - filePath: string - content: string - readOnly?: boolean - liveTail?: boolean - viewStateId?: string - viewStateKey: string - }) { - lifecycle.viewStateKeys.push(props.viewStateKey) - /* oxlint-disable react-hooks/exhaustive-deps -- Mount-only by design: a prop-effect would hide a missing outer React remount. */ - React.useEffect(() => { - lifecycle.events.push(`mount:${props.filePath}`) - lifecycle.mountedProps.push({ - filePath: props.filePath, - readOnly: props.readOnly, - liveTail: props.liveTail, - viewStateId: props.viewStateId - }) - const retained = lifecycle.models.get(props.filePath) ?? { content: '', undo: [] } - const model = { - getValue: () => retained.content, - getEOL: () => '\n', - getFullModelRange: () => ({ - startLineNumber: 1, - startColumn: 1, - endLineNumber: 1, - endColumn: retained.content.length + 1 - }), - pushEditOperations: (_selections: unknown[], operations: { text: string }[]) => { - retained.content = operations[0]?.text ?? retained.content - } - } - // Use the real mount reconciler to observe key ordering with retained-model behavior intact. - syncContentOnMount( - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: content sync calls only the editor methods stubbed here. - { - getModel: () => model, - saveViewState: () => null, - restoreViewState: () => {}, - pushUndoStop: () => { - retained.undo.push('unexpected undo stop') - return true - } - } as never, - props.content - ) - lifecycle.models.set(props.filePath, retained) - return () => { - lifecycle.events.push(`unmount:${props.filePath}`) - } - }, []) - /* oxlint-enable react-hooks/exhaustive-deps */ - return null - } - } - } -}) -vi.mock('@/store', () => ({ - useAppStore: Object.assign( - (selector: (state: Record) => unknown) => - selector({ - worktreesByRepo: {}, - settings: {}, - markdownRichModeSizeOverride: {}, - setMarkdownRichModeSizeOverride: vi.fn(), - openFile: vi.fn(), - openMarkdownPreview: vi.fn(), - openConflictReviewFile: vi.fn(), - openConflictReview: vi.fn(), - closeFile: vi.fn(), - setRightSidebarTab: vi.fn(), - setPendingEditorReveal: vi.fn(), - reloadOpenCheckRunDetailsTab: vi.fn() - }), - { - getState: () => ({ - folderWorkspaces: [], - projectGroups: [], - repos: [], - settings: {}, - worktreesByRepo: {}, - openFile: vi.fn(), - openMarkdownPreview: vi.fn(), - openConflictReviewFile: vi.fn(), - openConflictReview: vi.fn(), - closeFile: vi.fn(), - setRightSidebarTab: vi.fn(), - setPendingEditorReveal: vi.fn(), - reloadOpenCheckRunDetailsTab: vi.fn() - }) - } - ) -})) - -import { EditorContent } from './EditorContent' - -function file(filePath: string, overrides: Partial = {}): OpenFile { - return { - id: filePath, - filePath, - relativePath: filePath.split('/').at(-1) ?? filePath, - worktreeId: 'repo::/repo', - language: 'typescript', - isDirty: false, - mode: 'edit', - ...overrides - } -} - -function props(activeFile: OpenFile, content: string) { - return { - activeFile, - viewStateScopeId: 'same-pane', - fileContents: { [activeFile.id]: { content, isBinary: false } }, - diffContents: {}, - editBuffers: {}, - openFiles: [activeFile], - worktreeEntries: [], - resolvedLanguage: 'typescript', - isMarkdown: false, - isMermaid: false, - isCsv: false, - isNotebook: false, - mdViewMode: 'rich' as const, - inlineMarkdownRenderState: null, - isChangesMode: false, - sideBySide: false, - pendingEditorReveal: null, - handleContentChange: vi.fn(), - handleContentChangeForFile: vi.fn(), - handleDirtyStateHint: vi.fn(), - handleSave: vi.fn(), - handleSaveForFile: vi.fn(), - reloadContent: vi.fn() - } -} - -function diffProps(activeFile: OpenFile, modifiedContent: string) { - return { - ...props(activeFile, ''), - diffContents: { - [activeFile.id]: { - kind: 'text' as const, - originalContent: '', - modifiedContent, - originalIsBinary: false as const, - modifiedIsBinary: false as const - } - } - } -} - -afterEach(() => { - cleanup() - lifecycle.events.length = 0 - lifecycle.diffModelKeys.length = 0 - lifecycle.viewStateKeys.length = 0 - lifecycle.models.clear() - lifecycle.mountedProps.length = 0 - lifecycle.notebookProps.length = 0 - lifecycle.richMarkdownProps.length = 0 -}) - -describe('EditorContent Monaco lifecycle boundary', () => { - it('unmounts the prior path before reconciling a stale retained target model', () => { - const first = file('/repo/first.ts') - const second = file('/repo/second.ts') - lifecycle.models.set(first.filePath, { content: 'first with edits', undo: ['first undo'] }) - lifecycle.models.set(second.filePath, { content: 'stale second', undo: ['second undo'] }) - const view = render() - - view.rerender() - - expect(lifecycle.events).toEqual([ - 'mount:/repo/first.ts', - 'unmount:/repo/first.ts', - 'mount:/repo/second.ts' - ]) - expect(lifecycle.models.get(second.filePath)).toEqual({ - content: 'fresh second', - undo: ['second undo'] - }) - expect(lifecycle.models.get(first.filePath)).toEqual({ - content: 'first with edits', - undo: ['first undo'] - }) - }) - - it('keeps the diff editor mounted when a save updates the modified content', () => { - // Saves refresh retained models without remounting the widget and flashing its loading placeholder. - const diff = file('/repo/notes.ts', { mode: 'diff', diffSource: 'unstaged' }) - - const view = render() - view.rerender() - - expect(lifecycle.events).toEqual(['mount-diff:/repo/notes.ts']) - expect(lifecycle.diffModelKeys).toHaveLength(2) - expect(lifecycle.diffModelKeys[1]).not.toBe(lifecycle.diffModelKeys[0]) - }) - - it('still remounts the diff editor for an explicit reload request', () => { - const diff = file('/repo/notes.ts', { mode: 'diff', diffSource: 'unstaged' }) - const view = render() - - view.rerender( - - ) - - expect(lifecycle.events).toEqual([ - 'mount-diff:/repo/notes.ts', - 'unmount-diff:/repo/notes.ts', - 'mount-diff:/repo/notes.ts' - ]) - }) -}) diff --git a/src/renderer/src/components/editor/EditorFileLoadErrorView.tsx b/src/renderer/src/components/editor/EditorFileLoadErrorView.tsx index 88632ff7709..613b8c3146f 100644 --- a/src/renderer/src/components/editor/EditorFileLoadErrorView.tsx +++ b/src/renderer/src/components/editor/EditorFileLoadErrorView.tsx @@ -2,7 +2,7 @@ import { AlertCircle, RefreshCw } from 'lucide-react' import { Button } from '@/components/ui/button' import { translate } from '@/i18n/i18n' import { useTranslate, type Translate } from '@/i18n/use-translate' -import { displayIpcErrorMessage } from '@/lib/ipc-error' +import { displayIpcErrorMessage } from '@/runtime/errors/ipc-error' import { isFileTooLargeCodeMessage } from '../../../../shared/file-write/file-write-disk-precondition' import { WORKTREE_HOST_UNRESOLVED_CODE } from './editor-panel-content-types' import { useStoppedWslHost } from '../wsl-host-stopped/use-stopped-wsl-host' diff --git a/src/renderer/src/components/editor/EditorPanelHeaderPath.tsx b/src/renderer/src/components/editor/EditorPanelHeaderPath.tsx index 9db39932b01..10f0f1f0765 100644 --- a/src/renderer/src/components/editor/EditorPanelHeaderPath.tsx +++ b/src/renderer/src/components/editor/EditorPanelHeaderPath.tsx @@ -14,7 +14,7 @@ import { isImeCompositionKeyDown } from '@/lib/text-input/ime/ime-composition-ke import { useTranslate } from '@/i18n/use-translate' import type { OpenFile } from '@/store/slices/editor/types/open-file' import { isVirtualEditorFile } from '@/store/slices/editor/tabs/editor-tab-content-type' -import { CLOSE_ALL_CONTEXT_MENUS_EVENT } from '@/lib/close-all-context-menus' +import { CLOSE_ALL_CONTEXT_MENUS_EVENT } from '@/lib/overlay-interaction/close-all-context-menus' import { useEditorHeaderFileRename } from './editor-header-file-rename' import { getEditorHeaderCopyState } from './editor-header' import { splitPathForDisplay } from './editor-path-display' diff --git a/src/renderer/src/components/editor/ImageViewer.tsx b/src/renderer/src/components/editor/ImageViewer.tsx index 1fbb791e991..df016270be5 100644 --- a/src/renderer/src/components/editor/ImageViewer.tsx +++ b/src/renderer/src/components/editor/ImageViewer.tsx @@ -1,6 +1,6 @@ import { Image as ImageIcon, Maximize2, RotateCcw, ZoomIn, ZoomOut } from 'lucide-react' import { type JSX, type SyntheticEvent, useMemo, useState } from 'react' -import { cn } from '@/lib/utils' +import { cn } from '@/lib/class-names' import PdfViewer from './PdfViewer' import { IMAGE_VIEWER_ZOOM_STEP } from './image-viewer-zoom' import type { PanZoomSize } from '../../../../shared/pan-zoom-view' diff --git a/src/renderer/src/components/editor/MediaViewer.test.tsx b/src/renderer/src/components/editor/MediaViewer.test.tsx index 2e82cec6d80..3aaaba95902 100644 --- a/src/renderer/src/components/editor/MediaViewer.test.tsx +++ b/src/renderer/src/components/editor/MediaViewer.test.tsx @@ -3,7 +3,7 @@ import { StrictMode, act } from 'react' import { createRoot, type Root } from 'react-dom/client' import { afterEach, describe, expect, it, vi } from 'vitest' -import { mediaPlaybackPositionCache } from '@/lib/scroll-cache' +import { mediaPlaybackPositionCache } from '@/components/editor/model-lifetime/retention/editor-view-state-cache' import MediaViewer from './MediaViewer' vi.mock('@/i18n/i18n', () => ({ translate: (_key: string, fallback: string) => fallback })) @@ -41,36 +41,6 @@ describe('MediaViewer', () => { return { root, video } } - it('keeps its source through Strict Mode setup and stops playback on unmount', async () => { - const pause = vi.spyOn(HTMLMediaElement.prototype, 'pause').mockImplementation(() => {}) - const load = vi.spyOn(HTMLMediaElement.prototype, 'load').mockImplementation(() => {}) - const container = document.createElement('div') - const root = createRoot(container) - await act(async () => - root.render( - - - - ) - ) - const video = container.querySelector('video') - expect(video?.getAttribute('src')).toBe('orca-media://file/token') - expect(video?.controls).toBe(true) - expect(video?.autoplay).toBe(false) - expect(video?.preload).toBe('metadata') - pause.mockClear() - load.mockClear() - await act(async () => root.unmount()) - expect(pause).toHaveBeenCalledTimes(1) - expect(load).toHaveBeenCalledTimes(1) - expect(video?.getAttribute('src')).toBeNull() - }) - it('retains the position when leaving before metadata and clamps it when the file shrinks', async () => { vi.spyOn(HTMLMediaElement.prototype, 'pause').mockImplementation(() => {}) vi.spyOn(HTMLMediaElement.prototype, 'load').mockImplementation(() => {}) diff --git a/src/renderer/src/components/editor/MediaViewer.tsx b/src/renderer/src/components/editor/MediaViewer.tsx index 12df5319be0..7878b63ede4 100644 --- a/src/renderer/src/components/editor/MediaViewer.tsx +++ b/src/renderer/src/components/editor/MediaViewer.tsx @@ -2,7 +2,10 @@ import { LOCAL_EXECUTION_HOST_ID } from '../../../../shared/execution-host' import { useEffect, useRef, useState } from 'react' import { useTranslate } from '@/i18n/use-translate' import { Button } from '@/components/ui/button' -import { mediaPlaybackPositionCache, setWithLRU } from '@/lib/scroll-cache' +import { + mediaPlaybackPositionCache, + setWithLRU +} from '@/components/editor/model-lifetime/retention/editor-view-state-cache' export default function MediaViewer({ src, diff --git a/src/renderer/src/components/editor/MermaidViewer.test.tsx b/src/renderer/src/components/editor/MermaidViewer.test.tsx deleted file mode 100644 index b5af2054e3c..00000000000 --- a/src/renderer/src/components/editor/MermaidViewer.test.tsx +++ /dev/null @@ -1,124 +0,0 @@ -// @vitest-environment happy-dom -import { act, cleanup, render, waitFor } from '@testing-library/react' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { scrollTopCache } from '@/lib/scroll-cache' - -const mermaid = vi.hoisted(() => ({ - initialize: vi.fn(), - render: vi.fn<(id: string, content: string) => Promise<{ svg: string }>>() -})) -vi.mock('mermaid', () => ({ default: mermaid })) -vi.mock('dompurify', () => ({ default: { sanitize: (svg: string) => svg } })) - -import MermaidViewer from './MermaidViewer' - -const frames = new Map() -const resizes = new Set<() => void>() -let nextFrame = 0 - -beforeEach(() => { - scrollTopCache.clear() - frames.clear() - resizes.clear() - mermaid.render.mockReset() - vi.stubGlobal('requestAnimationFrame', (callback: FrameRequestCallback) => { - const id = ++nextFrame - frames.set(id, callback) - return id - }) - vi.stubGlobal('cancelAnimationFrame', (id: number) => frames.delete(id)) - vi.stubGlobal( - 'ResizeObserver', - class { - constructor(private callback: () => void) {} - observe(): void { - resizes.add(this.callback) - } - disconnect(): void { - resizes.delete(this.callback) - } - } - ) -}) - -afterEach(() => { - cleanup() - vi.unstubAllGlobals() - scrollTopCache.clear() -}) - -function diagramViewport( - container: HTMLElement, - renderedHeight = 1200, - visible = () => true -): HTMLElement { - const viewer = container.querySelector('.mermaid-viewer') - if (!(viewer instanceof HTMLElement)) { - throw new Error('Missing diagram viewport') - } - let scrollTop = 0 - Object.defineProperties(viewer, { - clientHeight: { get: () => (visible() ? 100 : 0) }, - scrollHeight: { - get: () => - !visible() - ? 0 - : viewer.querySelector('.mermaid-block')?.hasChildNodes() - ? renderedHeight - : 100 - }, - scrollTop: { - get: () => scrollTop, - set: (value: number) => { - scrollTop = Math.max(0, Math.min(value, viewer.scrollHeight - viewer.clientHeight)) - } - } - }) - return viewer -} - -function advanceFrames(count: number): void { - for (let index = 0; index < count; index += 1) { - const scheduled = [...frames.values()] - frames.clear() - scheduled.forEach((callback) => callback(index * 16)) - } -} - -describe('Mermaid diagram scroll restoration', () => { - it('restores the cached position when rendering finishes after the old retry window', async () => { - const pending = Promise.withResolvers<{ svg: string }>() - mermaid.render.mockReturnValueOnce(pending.promise) - scrollTopCache.set('/diagram.mmd:mermaid-diagram', 600) - const { container } = render( - - ) - const viewer = diagramViewport(container) - await waitFor(() => expect(mermaid.render).toHaveBeenCalledTimes(1)) - act(() => advanceFrames(40)) - expect(viewer.scrollTop).toBe(0) - - await act(async () => pending.resolve({ svg: 'Diagram' })) - - expect(viewer.scrollTop).toBe(600) - }) - - it('waits for a hidden workspace to become measurable after rendering completes', async () => { - const pending = Promise.withResolvers<{ svg: string }>() - mermaid.render.mockReturnValueOnce(pending.promise) - scrollTopCache.set('/diagram.mmd:mermaid-diagram', 600) - const { container } = render( - - ) - let visible = false - const viewer = diagramViewport(container, 1200, () => visible) - await waitFor(() => expect(mermaid.render).toHaveBeenCalledTimes(1)) - await act(async () => pending.resolve({ svg: 'Diagram' })) - expect(viewer.scrollTop).toBe(0) - - visible = true - act(() => resizes.forEach((callback) => callback())) - - expect(viewer.scrollTop).toBe(600) - }) -}) diff --git a/src/renderer/src/components/editor/MermaidViewer.tsx b/src/renderer/src/components/editor/MermaidViewer.tsx index f9f9d07ffad..3212b019124 100644 --- a/src/renderer/src/components/editor/MermaidViewer.tsx +++ b/src/renderer/src/components/editor/MermaidViewer.tsx @@ -1,5 +1,8 @@ import React, { useCallback, useLayoutEffect, useRef } from 'react' -import { scrollTopCache, setWithLRU } from '@/lib/scroll-cache' +import { + scrollTopCache, + setWithLRU +} from '@/components/editor/model-lifetime/retention/editor-view-state-cache' import MermaidBlock from './MermaidBlock' import { useMermaidDiagramExpand } from './use-mermaid-diagram-expand' import { useDocumentDarkTheme } from '@/hooks/use-document-dark-theme' diff --git a/src/renderer/src/components/editor/MonacoCodeExcerpt.tsx b/src/renderer/src/components/editor/MonacoCodeExcerpt.tsx index 17ea73dd547..902d112d28d 100644 --- a/src/renderer/src/components/editor/MonacoCodeExcerpt.tsx +++ b/src/renderer/src/components/editor/MonacoCodeExcerpt.tsx @@ -5,7 +5,7 @@ import { editorTypographyTextStyle } from '@/lib/editor/appearance/editor-typography' import { useEditorTypography } from '@/hooks/use-editor-typography' -import { cn } from '@/lib/utils' +import { cn } from '@/lib/class-names' import { useMonacoTheme } from '@/hooks/use-monaco-theme' let pythonLanguageRegistrationPromise: Promise | null = null diff --git a/src/renderer/src/components/editor/MonacoEditor.owner-view-state.test.tsx b/src/renderer/src/components/editor/MonacoEditor.owner-view-state.test.tsx deleted file mode 100644 index 5fe29c1c11c..00000000000 --- a/src/renderer/src/components/editor/MonacoEditor.owner-view-state.test.tsx +++ /dev/null @@ -1,177 +0,0 @@ -// @vitest-environment happy-dom -import { act, cleanup, render, waitFor } from '@testing-library/react' -import * as monaco from 'monaco-editor/esm/vs/editor/editor.api.js' -import { afterEach, expect, it, vi } from 'vitest' -import type { AppState } from '@/store/types' -import { useStore } from 'zustand' -import { createEditorStore } from '@/store/slices/editor/editor-slice-test-harness' -import { makeWorktree } from '@/store/slices/worktrees/worktree.test-fixture' -import type { OpenFile } from '@/store/slices/editor/types/open-file' -import { editorSelectionCache, editorViewStateCache, scrollTopCache } from '@/lib/scroll-cache' -import { getDefaultSettings } from '../../../../shared/constants' - -const testState = vi.hoisted(() => { - const state: { store: ReturnType | null } = { store: null } - return state -}) - -vi.mock('@/store', () => { - const getStore = () => { - if (!testState.store) { - throw new Error('Missing test store') - } - return testState.store - } - return { - useAppStore: Object.assign( - (selector: (state: AppState) => unknown) => useStore(getStore(), selector), - { - getState: () => getStore().getState() - } - ) - } -}) -vi.mock('@/lib/editor/monaco/monaco-setup', async () => { - const { loader } = await import('@monaco-editor/react') - // Why: the real setup installs this guard; without it a disposed editor's pending word - // highlight rejects with Monaco's "Canceled" and the run reports unhandled errors. - const { installMonacoDelayerCancellationGuard } = - await import('@/lib/editor/monaco/monaco-delayer-cancellation-guard') - installMonacoDelayerCancellationGuard() - loader.config({ monaco }) - return {} -}) -vi.mock('./useContextualCopySetup', () => ({ - useContextualCopySetup: () => ({ setupCopy: vi.fn(), toastNode: null }) -})) -vi.mock('../diff-comments/useDiffCommentDecorator', () => ({ - useDiffCommentDecorator: vi.fn() -})) -vi.mock('sonner', () => ({ - toast: { info: vi.fn(), error: vi.fn(), success: vi.fn() } -})) - -import MonacoEditor from './MonacoEditor' - -const originalGetContext = HTMLCanvasElement.prototype.getContext -let creationListener: monaco.IDisposable | null = null - -afterEach(() => { - cleanup() - creationListener?.dispose() - creationListener = null - for (const model of monaco.editor.getModels()) { - model.dispose() - } - editorSelectionCache.clear() - editorViewStateCache.clear() - scrollTopCache.clear() - Reflect.set(HTMLCanvasElement.prototype, 'getContext', originalGetContext) - testState.store = null -}) - -it('preserves a draft, selected range and scroll when the same tab gains a known owner', async () => { - // Only text metrics are needed; this test does not inspect canvas painting. - Reflect.set(HTMLCanvasElement.prototype, 'getContext', () => ({ - webkitBackingStorePixelRatio: 1, - measureText: (value: string) => ({ width: value.length * 8 }), - fillRect: () => {}, - clearRect: () => {}, - fillText: () => {}, - setTransform: () => {}, - save: () => {}, - restore: () => {}, - beginPath: () => {}, - moveTo: () => {}, - lineTo: () => {}, - stroke: () => {}, - createImageData: (width: number, height: number) => ({ - data: new Uint8ClampedArray(width * height * 4) - }), - getImageData: (width: number, height: number) => ({ - data: new Uint8ClampedArray(width * height * 4) - }), - putImageData: () => {} - })) - const store = createEditorStore() - testState.store = store - const file: OpenFile = { - id: 'restored-file', - worktreeId: 'pending-workspace', - filePath: '/repo/restored.txt', - relativePath: 'restored.txt', - mode: 'edit', - language: 'plaintext', - isDirty: true - } - store.setState({ - openFiles: [file], - activeWorktreeId: null, - activeWorkspaceExecutionHostId: null, - runtimeEnvironments: [], - editorFontZoomLevel: 0, - editorDrafts: { [file.id]: 'unsaved draft' }, - repos: [], - worktreesByRepo: {}, - detectedWorktreesByRepo: {}, - settings: { ...getDefaultSettings('/fixture'), theme: 'dark', editorWordWrap: false } - }) - const widgets: monaco.editor.ICodeEditor[] = [] - creationListener = monaco.editor.onDidCreateEditor((instance) => widgets.push(instance)) - const props = { - fileId: file.id, - filePath: file.filePath, - viewStateKey: 'pane:restored-file', - relativePath: file.relativePath, - language: file.language, - content: Array.from({ length: 300 }, (_, index) => `line ${index + 1}`).join('\n'), - onContentChange: vi.fn(), - onSave: vi.fn() - } - const rendered = render() - await waitFor(() => expect(widgets).toHaveLength(1)) - const before = widgets[0] - if (!before) { - throw new Error('Missing initial editor') - } - const originalModel = before.getModel() - if (!originalModel) { - throw new Error('Missing original model') - } - const draft = `${props.content}\nunsaved draft` - rendered.rerender() - expect(originalModel.getValue()).toBe(draft) - expect(originalModel.canUndo()).toBe(true) - before.layout({ width: 600, height: 300 }) - const selection = new monaco.Selection(80, 2, 82, 5) - before.setSelection(selection) - before.setScrollTop(1500) - expect(before.getScrollTop()).toBe(1500) - - const openFiles = store.getState().openFiles - act(() => { - store.setState({ - worktreesByRepo: { - repo: [ - makeWorktree({ id: file.worktreeId, repoId: 'repo', path: '/repo', hostId: 'local' }) - ] - } - }) - }) - expect(store.getState().openFiles).toBe(openFiles) - await waitFor(() => expect(widgets).toHaveLength(2)) - const after = widgets[1] - if (!after) { - throw new Error('Missing resolved editor') - } - expect(after.getModel()).not.toBe(originalModel) - expect(after.getModel()?.getValue()).toBe(draft) - expect(after.getModel()?.canUndo()).toBe(false) - await waitFor(() => expect(after.getSelection()?.toString()).toBe(selection.toString())) - expect(after.getScrollTop()).toBe(1500) - expect(props.onContentChange).not.toHaveBeenCalled() - act(() => { - after.executeEdits('user-edit', [{ range: new monaco.Range(301, 14, 301, 14), text: '!' }]) - }) - expect(props.onContentChange).toHaveBeenCalledExactlyOnceWith(`${draft}!`) -}) diff --git a/src/renderer/src/components/editor/MonacoEditor.tsx b/src/renderer/src/components/editor/MonacoEditor.tsx index 90684d7bfb8..36f00cbb099 100644 --- a/src/renderer/src/components/editor/MonacoEditor.tsx +++ b/src/renderer/src/components/editor/MonacoEditor.tsx @@ -8,7 +8,7 @@ import { monacoTypographyOptions } from '@/lib/editor/appearance/editor-typograp import { useEditorTypography } from '@/hooks/use-editor-typography' import { useContextualCopySetup } from './useContextualCopySetup' import { MonacoGutterContextMenu } from './MonacoGutterContextMenu' -import { isLinuxUserAgent } from '../../lib/user-agent-platform' +import { isLinuxUserAgent } from '../../app-shell/platform/user-agent-platform' import { MAX_TOKENIZATION_LINE_LENGTH } from '@/lib/monaco-languages/monarch-embed-entry-budget' import { buildFileEditorWordWrapOptions } from './file-editor-word-wrap-options' import { resolveFileEditorMinimapEnabled } from '../../../../shared/editor/editor-typography' diff --git a/src/renderer/src/components/editor/PanZoomImageSurface.tsx b/src/renderer/src/components/editor/PanZoomImageSurface.tsx index cfb7b833ed6..a1c6c57ca87 100644 --- a/src/renderer/src/components/editor/PanZoomImageSurface.tsx +++ b/src/renderer/src/components/editor/PanZoomImageSurface.tsx @@ -1,5 +1,5 @@ import type React from 'react' -import { cn } from '@/lib/utils' +import { cn } from '@/lib/class-names' import type { PanZoomSize } from '../../../../shared/pan-zoom-view' import type { PanZoomViewport } from './use-pan-zoom-viewport' diff --git a/src/renderer/src/components/editor/PluginEditorNeedsDesktopNotice.tsx b/src/renderer/src/components/editor/PluginEditorNeedsDesktopNotice.tsx index 40c70adcb98..d7cda76d857 100644 --- a/src/renderer/src/components/editor/PluginEditorNeedsDesktopNotice.tsx +++ b/src/renderer/src/components/editor/PluginEditorNeedsDesktopNotice.tsx @@ -2,7 +2,7 @@ import { Monitor } from 'lucide-react' import { Button } from '@/components/ui/button' import { translate } from '@/i18n/i18n' import { useTranslate, type Translate } from '@/i18n/use-translate' -import { isWebClientLocation } from '@/lib/web-client-location' +import { isWebClientLocation } from '@/app-shell/platform/web-client-location' import { useFileCustomEditors } from '@/store/plugins/file-editors/plugin-custom-editors' function detail(title: string, t: Translate = translate): string { diff --git a/src/renderer/src/components/editor/check-details/panel/CheckRunCopyButton.tsx b/src/renderer/src/components/editor/check-details/panel/CheckRunCopyButton.tsx index 88711bbd39f..51ea88ef36c 100644 --- a/src/renderer/src/components/editor/check-details/panel/CheckRunCopyButton.tsx +++ b/src/renderer/src/components/editor/check-details/panel/CheckRunCopyButton.tsx @@ -2,7 +2,7 @@ import React from 'react' import { Check, Copy } from 'lucide-react' import { useClipboardTextCopyFeedback } from '@/hooks/clipboard/use-clipboard-text-copy-feedback' import { useTranslate } from '@/i18n/use-translate' -import { cn } from '@/lib/utils' +import { cn } from '@/lib/class-names' import { Button } from '@/components/ui/button' import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip' diff --git a/src/renderer/src/components/editor/check-details/panel/CheckRunDetailsPanel.captured-failure.test.tsx b/src/renderer/src/components/editor/check-details/panel/CheckRunDetailsPanel.captured-failure.test.tsx deleted file mode 100644 index cfc76c8a7fb..00000000000 --- a/src/renderer/src/components/editor/check-details/panel/CheckRunDetailsPanel.captured-failure.test.tsx +++ /dev/null @@ -1,164 +0,0 @@ -// @vitest-environment happy-dom -import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { TooltipProvider } from '@/components/ui/tooltip' -import { useAppStore } from '@/store/index' -import { createEditorTabsStore } from '@/store/slices/editor/editor-slice-test-harness' -import { scrollTopCache } from '@/lib/scroll-cache' -import { CheckRunDetailsPanel } from './CheckRunDetailsPanel' -import { readingCheck, readingDetails } from '../reading/check-details-reading-fixture' -import { - capturedCheckLogExcerpt, - capturedCheckLogFailure -} from '../../../right-sidebar/checks-panel/logs/check-job-log-captured-fixture' - -vi.mock('@/i18n/i18n', () => ({ - i18n: { language: 'en' }, - getIntlLocale: () => 'en', - translate: (_key: string, fallback: string, values?: Record) => - fallback.replace(/{{(\w+)}}/g, (_match, key) => String(values?.[key] ?? '')) -})) -vi.mock('@/components/sidebar/CommentMarkdown', () => ({ - default: ({ content }: { content: string }) => content -})) -vi.mock('@/components/right-sidebar/source-control/panel/source-control-fix-split-button', () => ({ - SourceControlFixSplitButton: () => null -})) -vi.mock('../actions/check-run-details-fix-with-ai', () => ({ - useCheckRunDetailsFixWithAI: () => ({ - canFixWithAI: false, - disabledReason: null, - isFixing: false, - fixPrompt: '', - repoId: null, - connectionId: null, - launchPlatform: null, - savedAgentId: null, - savedCommandInputTemplate: null, - savedAgentArgs: [], - saveLaunchActionDefault: vi.fn(), - openSourceControlAiSettings: vi.fn(), - fixWithAI: vi.fn() - }) -})) - -const original = useAppStore.getState() -const writeClipboardText = vi.fn<(text: string) => Promise>() -const fetchDetails = vi.fn() - -beforeEach(() => { - writeClipboardText.mockReset().mockResolvedValue(undefined) - fetchDetails.mockReset() - Object.assign(window, { api: { ui: { writeClipboardText } } }) - const fixture = createEditorTabsStore().getState() - useAppStore.setState({ - openFiles: [], - repos: fixture.repos, - worktreesByRepo: fixture.worktreesByRepo, - fetchPRCheckDetails: fetchDetails - }) -}) -afterEach(() => { - cleanup() - useAppStore.setState(original, true) - scrollTopCache.clear() -}) - -describe('captured failure output in the details panel', () => { - it('keeps failure context first, successes collapsed, and Copy literal without another request', async () => { - const base = readingDetails(capturedCheckLogExcerpt, 'available') - const check = { ...readingCheck, url: 'https://github.com/acme/widgets/actions/runs/1/job/42' } - const details = { - ...base, - title: 'Provider title', - summary: 'Provider-written output', - annotations: [ - { - path: 'src/example.ts', - startLine: 1, - endLine: 1, - annotationLevel: 'failure', - title: null, - message: 'Provider annotation', - rawDetails: null - } - ], - jobs: [ - { - ...base.jobs[0], - name: 'Failed fixture job', - steps: [ - { - name: 'Test shard', - status: 'completed', - conclusion: 'failure', - startedAt: null, - completedAt: null - }, - { - name: 'Setup', - status: 'completed', - conclusion: 'success', - startedAt: null, - completedAt: null - } - ] - } - ] - } - useAppStore.getState().openCheckRunDetails('wt-1', 'captured', check, { - details, - loading: false, - error: null - }) - const { container } = render( - - - - ) - const text = container.textContent ?? '' - const parts = [ - 'Failed fixture job', - 'Test shard', - 'Log excerpt', - capturedCheckLogFailure.expectedDiagnostic, - '1 succeeded', - 'Output', - 'Provider-written output', - 'Annotations', - 'Provider annotation' - ] - const positions = parts.map((part) => text.indexOf(part)) - expect( - positions.every( - (position, index) => position >= 0 && (index === 0 || position > positions[index - 1]) - ) - ).toBe(true) - const pre = container.querySelector('pre') - expect(pre?.textContent).toBe(capturedCheckLogExcerpt) - expect(pre?.childNodes).toHaveLength(1) - const disclosure = screen.getByRole('button', { name: '1 succeeded' }) - expect(disclosure.getAttribute('aria-expanded')).toBe('false') - expect(screen.queryByText('Setup')).toBeNull() - expect(screen.getByRole('button', { name: 'Open details' })).toBeTruthy() - expect(fetchDetails).not.toHaveBeenCalled() - fireEvent.click(screen.getByRole('button', { name: 'Copy log excerpt' })) - await waitFor(() => - expect(writeClipboardText).toHaveBeenCalledExactlyOnceWith(capturedCheckLogExcerpt) - ) - fireEvent.click(disclosure) - expect(screen.getByText('Setup')).toBeTruthy() - expect(container.querySelector('pre')).toBe(pre) - expect(fetchDetails).not.toHaveBeenCalled() - }) -}) diff --git a/src/renderer/src/components/editor/check-details/panel/CheckRunDetailsPanel.log-outcomes.test.tsx b/src/renderer/src/components/editor/check-details/panel/CheckRunDetailsPanel.log-outcomes.test.tsx deleted file mode 100644 index 97036bb23ed..00000000000 --- a/src/renderer/src/components/editor/check-details/panel/CheckRunDetailsPanel.log-outcomes.test.tsx +++ /dev/null @@ -1,337 +0,0 @@ -// @vitest-environment happy-dom -import { StrictMode } from 'react' -import { act, cleanup, fireEvent, render, screen, within } from '@testing-library/react' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { TooltipProvider } from '@/components/ui/tooltip' -import { useAppStore } from '@/store/index' -import { createEditorTabsStore } from '@/store/slices/editor/editor-slice-test-harness' -import type { PRCheckRunDetails } from '../../../../../../shared/github/check-types' -import { readingCheck, readingDetails } from '../reading/check-details-reading-fixture' -import { CheckRunDetailsPanel } from './CheckRunDetailsPanel' -import { CheckRunDetails } from '@/components/right-sidebar/checks-panel/presentation/check-run-details' -import { scrollTopCache, setWithLRU } from '@/lib/scroll-cache' -import { - checkDetailsReadingKey, - checkJobIdentities, - checkReadingIntentKey -} from '../reading/check-details-reading-cache' -import * as diagnosticPosition from '@/components/right-sidebar/checks-panel/logs/check-log-initial-diagnostic-position' - -vi.mock('@/i18n/i18n', () => ({ - getIntlLocale: () => 'en', - i18n: { language: 'en' }, - translate: (_key: string, fallback: string, values?: Record) => - fallback.replace(/{{(\w+)}}/g, (_match, key) => String(values?.[key] ?? '')) -})) -vi.mock('@/components/sidebar/CommentMarkdown', () => ({ - default: ({ content }: { content: string }) => content -})) -vi.mock('../actions/check-run-details-fix-with-ai', () => ({ - useCheckRunDetailsFixWithAI: () => ({ canFixWithAI: false }) -})) -const original = useAppStore.getState() -const id = 'wt-1::check-details::check-run:42' -const context = 'outcome-context' -const check = { ...readingCheck, url: 'https://provider.test/job/7', workflowRunId: 55 } -const retry = vi.fn() -const copy = vi.fn().mockResolvedValue(undefined) - -function StoredPanel({ scope = 'outcome-pane' }: { scope?: string }) { - const file = useAppStore((state) => state.openFiles.find((tab) => tab.id === id)) - const state = file?.checkRunDetails - return state && file ? ( -
- { - void useAppStore.getState().reloadOpenCheckRunDetailsTab(file.id) - }} - /> -
- ) : null -} -function payload(text: string | null = null, logState: 'error' | 'available' = 'error') { - const value = readingDetails(text, logState) - return { - ...value, - startedAt: '2026-10-10T12:00:00Z', - completedAt: '2026-10-10T12:05:00Z', - jobs: [ - { - ...value.jobs[0], - startedAt: '2026-10-10T12:00:00Z', - completedAt: '2026-10-10T12:05:00Z', - steps: [ - { - name: 'setup', - status: 'completed', - conclusion: 'success', - startedAt: null, - completedAt: null - } - ] - } - ] - } -} -function open(details: PRCheckRunDetails, requestId = 0) { - useAppStore.getState().openCheckRunDetails('wt-1', context, check, { - requestId, - details, - loading: false, - error: null - }) -} -function gate() { - let resolve: (details: PRCheckRunDetails | null) => void = () => {} - let reject: (reason: Error) => void = () => {} - const promise = new Promise((done, fail) => { - resolve = done - reject = fail - }) - return { promise, resolve, reject } -} -beforeEach(() => { - const fixture = createEditorTabsStore().getState() - useAppStore.setState({ - openFiles: [], - repos: fixture.repos, - worktreesByRepo: fixture.worktreesByRepo, - fetchPRCheckDetails: vi.fn() - }) - retry.mockReset() - copy.mockClear() - scrollTopCache.clear() - Object.assign(window, { api: { ui: { writeClipboardText: copy }, shell: { openUrl: vi.fn() } } }) - vi.spyOn(HTMLElement.prototype, 'clientWidth', 'get').mockReturnValue(400) - vi.spyOn(HTMLElement.prototype, 'clientHeight', 'get').mockReturnValue(200) - vi.spyOn(HTMLElement.prototype, 'scrollHeight', 'get').mockReturnValue(2000) - vi.spyOn(HTMLElement.prototype, 'getBoundingClientRect').mockReturnValue( - new DOMRect(0, 0, 400, 200) - ) -}) -afterEach(() => { - cleanup() - useAppStore.setState(original, true) - scrollTopCache.clear() - vi.restoreAllMocks() -}) - -describe('synthetic outcome payloads through real sidebar and header actions', () => { - it.each([false, true])( - 'retries one combined request with unchanged identities, already open=%s', - async (alreadyOpen) => { - const first = payload() - first.jobs.push({ - ...first.jobs[0], - id: 8, - name: 'retained', - logState: 'available', - logTail: 'Error: retained synthetic excerpt' - }) - const next = { - ...first, - jobs: first.jobs.map((job) => ({ - ...job, - logState: 'available' as const, - logTail: job.logTail ?? 'Error: recovered synthetic excerpt' - })) - } - const pending = gate() - const fetch = vi.fn(() => pending.promise) - useAppStore.setState({ fetchPRCheckDetails: fetch }) - if (alreadyOpen) { - open(first) - } - render( - - - - - ) - expect( - screen.getByText("Couldn't load logs. Open View full details, then use Refresh to retry.") - ).toBeTruthy() - expect(screen.queryByRole('button', { name: 'Retry' })).toBeNull() - fireEvent.click(screen.getByRole('button', { name: 'View full details' })) - expect(useAppStore.getState().openFiles[0].checkRunDetails?.details).toBe(first) - expect(fetch).not.toHaveBeenCalled() - const panel = screen.getByTestId('outcome-pane') - const pre = panel.querySelector('pre') - const outer = panel.querySelector('[aria-busy].overflow-y-auto') - if (!(pre instanceof HTMLPreElement) || !(outer instanceof HTMLDivElement)) { - throw new Error('Missing retained reading nodes') - } - fireEvent.wheel(pre) - pre.scrollTop = 180 - fireEvent.scroll(pre) - outer.scrollTop = 320 - fireEvent.scroll(outer) - const geometry = { excerpt: pre.getBoundingClientRect().top, height: outer.clientHeight } - await act(async () => { - fireEvent.click(within(panel).getByRole('button', { name: 'Copy log excerpt' })) - }) - expect(copy).toHaveBeenCalledExactlyOnceWith(first.jobs[1].logTail) - expect(fetch).not.toHaveBeenCalled() - fireEvent.click(within(panel).getByRole('button', { name: 'Refresh' })) - expect(fetch).toHaveBeenCalledTimes(1) - expect(fetch).toHaveBeenCalledWith( - '/repo', - { checkRunId: 42, workflowRunId: 55, checkName: 'verify', url: check.url, prRepo: null }, - { repoId: 'repo-1', repoOwnerExecutionHostId: 'local' } - ) - const during = useAppStore.getState().openFiles[0].checkRunDetails - const positions = [...scrollTopCache] - fireEvent.click(screen.getByRole('button', { name: 'View full details' })) - act(() => { - useAppStore.getState().patchOpenCheckRunDetails('wt-1', context, check, { - requestId: 0, - details: first, - loading: false, - error: null - }) - }) - expect(useAppStore.getState().openFiles[0].checkRunDetails).toBe(during) - expect([...scrollTopCache]).toEqual(positions) - expect(panel.querySelector('pre')).toBe(pre) - expect(pre.scrollTop).toBe(180) - expect(outer.scrollTop).toBe(320) - expect(within(panel).getByText("Couldn't load logs. Use Refresh to retry.")).toBeTruthy() - await act(async () => pending.resolve(next)) - expect(useAppStore.getState().openFiles[0].checkRunDetails?.details).toBe(next) - expect(panel.querySelectorAll('pre')[1]).toBe(pre) - expect(pre.scrollTop).toBe(180) - expect(outer.scrollTop).toBe(320) - expect({ excerpt: pre.getBoundingClientRect().top, height: outer.clientHeight }).toEqual( - geometry - ) - expect(within(panel).queryByText("Couldn't load logs. Use Refresh to retry.")).toBeNull() - expect(within(panel).getByRole('button', { name: 'Open details' })).toBeTruthy() - const accepted = useAppStore.getState().openFiles[0].checkRunDetails - const saved = [...scrollTopCache] - fireEvent.click(screen.getByRole('button', { name: 'View full details' })) - expect(useAppStore.getState().openFiles[0].checkRunDetails).toBe(accepted) - expect([...scrollTopCache]).toEqual(saved) - expect(fetch).toHaveBeenCalledTimes(1) - expect(retry).not.toHaveBeenCalled() - expect(next.jobs.map(({ logState: _state, logTail: _tail, ...job }) => job)).toEqual( - first.jobs.map(({ logState: _state, logTail: _tail, ...job }) => job) - ) - } - ) - - it.each(['untouched', 'outer wheel', 'outer scroll', 'steps', 'evicted'])( - 'allows error-only first text exactly once when intent survives %s', - async (interaction) => { - const first = payload() - const next = payload( - 'prefix\nError: recovered synthetic diagnostic\n at synthetic.ts:1:2', - 'available' - ) - const pending = gate() - const fetch = vi.fn(() => pending.promise) - useAppStore.setState({ fetchPRCheckDetails: fetch }) - open(first) - const marker = vi.spyOn(diagnosticPosition, 'findInitialCheckLogDiagnostic') - const measure = vi - .spyOn(diagnosticPosition, 'measureInitialCheckLogScrollTop') - .mockReturnValue(600) - const { unmount } = render( - - - - - - ) - const panel = screen.getByTestId('outcome-pane') - const outer = panel.querySelector('[aria-busy].overflow-y-auto') - if (!(outer instanceof HTMLDivElement)) { - throw new Error('Missing outer scroller') - } - const identity = checkJobIdentities(first.jobs)[0].identity - const owner = checkDetailsReadingKey(id, 'outcome-pane', context) - expect(scrollTopCache.get(checkReadingIntentKey(owner, identity))).toBe(-1) - expect( - scrollTopCache.has( - checkReadingIntentKey(checkDetailsReadingKey(id, null, context), identity) - ) - ).toBe(false) - if (interaction === 'outer wheel') { - fireEvent.wheel(outer) - } - if (interaction === 'outer scroll') { - outer.scrollTop = 320 - fireEvent.scroll(outer) - } - if (interaction === 'steps') { - fireEvent.click(within(panel).getByRole('button', { name: '1 succeeded' })) - } - if (interaction === 'evicted') { - for (let index = 0; index < 21; index++) { - setWithLRU(scrollTopCache, `ordinary-${index}`, index) - } - } - fireEvent.click(within(panel).getByRole('button', { name: 'Refresh' })) - expect(panel.querySelector('pre')).toBeNull() - await act(async () => pending.resolve(next)) - expect(marker).toHaveBeenCalledTimes(interaction === 'untouched' ? 1 : 0) - expect(measure).toHaveBeenCalledTimes(interaction === 'untouched' ? 1 : 0) - expect(panel.querySelector('pre')?.scrollTop).toBe(interaction === 'untouched' ? 600 : 0) - expect(fetch).toHaveBeenCalledTimes(1) - unmount() - render( - - - - ) - expect(marker).toHaveBeenCalledTimes(interaction === 'untouched' ? 1 : 0) - expect(fetch).toHaveBeenCalledTimes(1) - } - ) - - it('claims an error-only intent in one pane and cancels only the interacted job', async () => { - const first = payload() - first.jobs.push({ ...first.jobs[0], id: 8, name: 'other-error' }) - const pending = gate() - useAppStore.setState({ fetchPRCheckDetails: vi.fn(() => pending.promise) }) - open(first) - const marker = vi.spyOn(diagnosticPosition, 'findInitialCheckLogDiagnostic') - vi.spyOn(diagnosticPosition, 'measureInitialCheckLogScrollTop').mockReturnValue(600) - render( - - - - - ) - const left = screen.getByTestId('left') - const right = screen.getByTestId('right') - fireEvent.click(within(left).getAllByRole('button', { name: '1 succeeded' })[0]) - fireEvent.click(within(right).getByRole('button', { name: 'Refresh' })) - const next = { - ...first, - jobs: first.jobs.map((job) => ({ - ...job, - logState: 'available' as const, - logTail: `Error: synthetic ${job.name}` - })) - } - await act(async () => pending.resolve(next)) - expect(marker).toHaveBeenCalledTimes(1) - expect([...left.querySelectorAll('pre')].map((pre) => pre.scrollTop)).toEqual([0, 600]) - expect([...right.querySelectorAll('pre')].map((pre) => pre.scrollTop)).toEqual([0, 0]) - }) -}) diff --git a/src/renderer/src/components/editor/check-details/panel/CheckRunJobs.tsx b/src/renderer/src/components/editor/check-details/panel/CheckRunJobs.tsx index 92094b986ab..dabe9cce32e 100644 --- a/src/renderer/src/components/editor/check-details/panel/CheckRunJobs.tsx +++ b/src/renderer/src/components/editor/check-details/panel/CheckRunJobs.tsx @@ -11,7 +11,7 @@ import { isGitLabAllowedFailureJob } from '@/components/github/pr-check-presenta import { CHECK_COLOR } from '@/components/right-sidebar/checks-panel/presentation/check-presentation' import { CheckJobLogTail } from '@/components/right-sidebar/checks-panel/logs/check-job-log-tail' import { useTranslate } from '@/i18n/use-translate' -import { cn } from '@/lib/utils' +import { cn } from '@/lib/class-names' import type { PRCheckDetail, PRCheckJob, @@ -27,7 +27,10 @@ import { CheckRunCopyButton } from './CheckRunCopyButton' import { Badge } from '@/components/ui/badge' import { Button } from '@/components/ui/button' import { Collapsible, CollapsibleContent, CollapsibleTrigger } from '@/components/ui/collapsible' -import { scrollTopCache, setWithLRU } from '@/lib/scroll-cache' +import { + scrollTopCache, + setWithLRU +} from '@/components/editor/model-lifetime/retention/editor-view-state-cache' import { checkJobIdentities, checkReadingStepsKey } from '../reading/check-details-reading-cache' import type { CheckDetailsReadingOwner } from '../reading/check-details-reading-owner' diff --git a/src/renderer/src/components/editor/check-details/reading/check-details-reading-cache.ts b/src/renderer/src/components/editor/check-details/reading/check-details-reading-cache.ts index 67a3d62dcdf..7d66f3b1106 100644 --- a/src/renderer/src/components/editor/check-details/reading/check-details-reading-cache.ts +++ b/src/renderer/src/components/editor/check-details/reading/check-details-reading-cache.ts @@ -1,6 +1,9 @@ import type { PRCheckJob, PRCheckRunDetails } from '../../../../../../shared/github/check-types' import type { OpenCheckRunDetailsState } from '../../../../../../shared/editor-tab-view-types' -import { scrollTopCache, setWithLRU } from '@/lib/scroll-cache' +import { + scrollTopCache, + setWithLRU +} from '@/components/editor/model-lifetime/retention/editor-view-state-cache' import { sha256 } from '../../../../../../shared/sha256' import { resolveStepOutcome } from '../../../../../../shared/source-control/checks/pr-check-step-status' diff --git a/src/renderer/src/components/editor/check-details/reading/check-details-reading-owner.ts b/src/renderer/src/components/editor/check-details/reading/check-details-reading-owner.ts index 4dd3ddd9326..040c5a226a7 100644 --- a/src/renderer/src/components/editor/check-details/reading/check-details-reading-owner.ts +++ b/src/renderer/src/components/editor/check-details/reading/check-details-reading-owner.ts @@ -1,6 +1,9 @@ import type { OpenFile } from '@/store/slices/editor/types/open-file' import { resolveStepOutcome } from '../../../../../../shared/source-control/checks/pr-check-step-status' -import { scrollTopCache, setWithLRU } from '@/lib/scroll-cache' +import { + scrollTopCache, + setWithLRU +} from '@/components/editor/model-lifetime/retention/editor-view-state-cache' import { cancelCheckReadingIntents, checkDetailsReadingKey, diff --git a/src/renderer/src/components/editor/check-details/reading/check-details-reading-viewport.test.ts b/src/renderer/src/components/editor/check-details/reading/check-details-reading-viewport.test.ts deleted file mode 100644 index 40013f2e4b2..00000000000 --- a/src/renderer/src/components/editor/check-details/reading/check-details-reading-viewport.test.ts +++ /dev/null @@ -1,193 +0,0 @@ -// @vitest-environment happy-dom -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { scrollTopCache, setWithLRU } from '@/lib/scroll-cache' -import { - checkLogDigest, - checkReadingLogKey, - checkReadingOuterKey -} from './check-details-reading-cache' - -import { attachCheckReadingViewport } from './check-details-reading-viewport' -import { - measuredReadingNode, - readingDetails, - readingFixture -} from './check-details-reading-fixture' -import * as digest from '../../../../../../shared/sha256' - -const frames = new Map() -let nextFrame = 0 -beforeEach(() => { - scrollTopCache.clear() - nextFrame = 0 - vi.stubGlobal( - 'requestAnimationFrame', - vi.fn((callback: FrameRequestCallback) => { - frames.set(++nextFrame, callback) - return nextFrame - }) - ) - vi.stubGlobal( - 'cancelAnimationFrame', - vi.fn((id: number) => frames.delete(id)) - ) -}) -afterEach(() => { - frames.clear() - document.body.replaceChildren() - vi.restoreAllMocks() - vi.unstubAllGlobals() -}) -function flushFrames(): void { - const pending = [...frames.values()] - frames.clear() - for (const callback of pending) { - callback(0) - } -} - -describe('owned reading positions', () => { - it('retirement cancels a pending frame and rejects a captured callback after close and reopen', () => { - const { owner, store, file, logKey, text, identity } = readingFixture() - const node = measuredReadingNode(text, 0) - setWithLRU(scrollTopCache, logKey, 180) - const detachOwner = owner.attach() - const detach = attachCheckReadingViewport({ - node, - owner, - cacheKey: logKey, - job: identity, - text - }) - const callback = [...frames.values()][0] - store.setState({ openFiles: [] }) - expect(frames.size).toBe(0) - scrollTopCache.delete(logKey) - store.setState({ openFiles: [file] }) - Object.defineProperty(node, 'clientHeight', { configurable: true, value: 200 }) - callback(0) - node.dispatchEvent(new Event('scroll')) - detach() - detachOwner() - expect(scrollTopCache.has(logKey)).toBe(false) - }) - it.each(['outer', 'inner'])( - 'preserves retained %s target through zero layout and a real remount', - (kind) => { - const { owner, logKey, text, identity } = readingFixture() - const key = kind === 'outer' ? checkReadingOuterKey(owner.key) : logKey - const node = measuredReadingNode(kind === 'outer' ? '' : text) - Object.defineProperty(node, 'clientHeight', { configurable: true, value: 0 }) - setWithLRU(scrollTopCache, key, 320) - const detachOwner = owner.attach() - const options = { - node, - owner, - cacheKey: key, - ...(kind === 'inner' ? { job: identity, text } : {}) - } - const detach = attachCheckReadingViewport(options) - flushFrames() - Object.defineProperty(node, 'clientHeight', { configurable: true, value: 200 }) - node.dispatchEvent(new Event('scroll')) - detach() - expect(scrollTopCache.get(key)).toBe(320) - const remount = attachCheckReadingViewport(options) - expect(node.scrollTop).toBe(320) - remount() - detachOwner() - } - ) - - it('fences callbacks published before the observer and never rewinds on a reentrant notification', () => { - const { owner, store, file, logKey, text, identity } = readingFixture() - const node = measuredReadingNode(text) - let nested = false - const before = store.subscribe(() => { - node.scrollTop = 999 - node.dispatchEvent(new Event('scroll')) - if (!nested) { - nested = true - store.setState({ openFiles: [] }) - } - }) - const detachOwner = owner.attach() - const detach = attachCheckReadingViewport({ - node, - owner, - cacheKey: logKey, - job: identity, - text - }) - const writes = vi.spyOn(scrollTopCache, 'set') - store.setState({ openFiles: [{ ...file, isDirty: true }] }) - expect(writes).not.toHaveBeenCalled() - before() - scrollTopCache.delete(logKey) - store.setState({ openFiles: [file] }) - node.dispatchEvent(new Event('scroll')) - detach() - expect(scrollTopCache.has(logKey)).toBe(false) - detachOwner() - }) - - it('retires a changed digest before handoff and prevents queued old callbacks from recreating it', () => { - const { owner, store, file, logKey, text, identity } = readingFixture() - const node = measuredReadingNode(text) - const detachOwner = owner.attach() - const detach = attachCheckReadingViewport({ - node, - owner, - cacheKey: logKey, - job: identity, - text - }) - node.scrollTop = 180 - node.dispatchEvent(new Event('scroll')) - const details = readingDetails('Error: accepted new text') - const next = { ...file.checkRunDetails!, details } - store.setState({ openFiles: [{ ...file, checkRunDetails: next }] }) - const destination = checkReadingLogKey( - owner.key, - identity, - checkLogDigest(details.jobs[0].logTail ?? '') - ) - expect(scrollTopCache.get(destination)).toBe(180) - node.scrollTop = 900 - node.dispatchEvent(new Event('scroll')) - detach() - flushFrames() - expect(scrollTopCache.has(logKey)).toBe(false) - expect(scrollTopCache.get(destination)).toBe(180) - detachOwner() - }) - - it('does no hashing, marker work, Range work or frame scheduling during 100 scroll/unrelated notifications', () => { - const { owner, store, logKey, text, identity } = readingFixture() - const node = measuredReadingNode(text) - const add = vi.spyOn(node, 'addEventListener') - const remove = vi.spyOn(node, 'removeEventListener') - const detachOwner = owner.attach() - const detach = attachCheckReadingViewport({ - node, - owner, - cacheKey: logKey, - job: identity, - text - }) - const hash = vi.spyOn(digest, 'sha256') - const range = vi.spyOn(document, 'createRange') - for (let index = 1; index <= 100; index++) { - node.scrollTop = index - node.dispatchEvent(new Event('scroll')) - store.setState({ unrelated: index }) - } - expect(scrollTopCache.get(logKey)).toBe(100) - expect(hash).not.toHaveBeenCalled() - expect(range).not.toHaveBeenCalled() - expect(requestAnimationFrame).not.toHaveBeenCalled() - detach() - detachOwner() - expect(remove.mock.calls.map(([name]) => name)).toEqual(add.mock.calls.map(([name]) => name)) - }) -}) diff --git a/src/renderer/src/components/editor/check-details/reading/check-details-reading-viewport.ts b/src/renderer/src/components/editor/check-details/reading/check-details-reading-viewport.ts index 0b7c84b7b72..7c4d436c785 100644 --- a/src/renderer/src/components/editor/check-details/reading/check-details-reading-viewport.ts +++ b/src/renderer/src/components/editor/check-details/reading/check-details-reading-viewport.ts @@ -1,4 +1,7 @@ -import { scrollTopCache, setWithLRU } from '@/lib/scroll-cache' +import { + scrollTopCache, + setWithLRU +} from '@/components/editor/model-lifetime/retention/editor-view-state-cache' import { hasCheckReadingLayout } from '@/components/right-sidebar/checks-panel/logs/check-log-initial-diagnostic-position' import type { CheckDetailsReadingOwner } from './check-details-reading-owner' diff --git a/src/renderer/src/components/editor/combined-diff/browse-files/combined-diff-file-tree-row.tsx b/src/renderer/src/components/editor/combined-diff/browse-files/combined-diff-file-tree-row.tsx index e82211d0a6c..8a21ac07e1a 100644 --- a/src/renderer/src/components/editor/combined-diff/browse-files/combined-diff-file-tree-row.tsx +++ b/src/renderer/src/components/editor/combined-diff/browse-files/combined-diff-file-tree-row.tsx @@ -5,7 +5,7 @@ import { STATUS_LABELS } from '../../../../../../shared/git/status/git-status-la import type { SourceControlTreeNode } from '../../../../../../shared/source-control/listing/source-control-tree' import { FileTypeIcon, FolderIcon } from '@/components/FileTypeIcon' import { basename, dirname, joinPath } from '@/lib/path' -import { cn } from '@/lib/utils' +import { cn } from '@/lib/class-names' import { WORKSPACE_FILE_PATH_MIME } from '@/lib/files/drop/workspace-file-drag' import { writeWorkspaceFileDragSourceForWorkspace } from '@/lib/files/drop/workspace-file-drag-source' import type { GitBranchChangeEntry } from '../../../../../../shared/git/diff/git-diff-compare-types' diff --git a/src/renderer/src/components/editor/combined-diff/browse-files/combined-diff-file-tree.tsx b/src/renderer/src/components/editor/combined-diff/browse-files/combined-diff-file-tree.tsx index 83c825bbe3d..5786cde7e40 100644 --- a/src/renderer/src/components/editor/combined-diff/browse-files/combined-diff-file-tree.tsx +++ b/src/renderer/src/components/editor/combined-diff/browse-files/combined-diff-file-tree.tsx @@ -1,6 +1,6 @@ import React from 'react' import { Check, Filter, PanelLeftClose, Search } from 'lucide-react' -import { cn } from '@/lib/utils' +import { cn } from '@/lib/class-names' import { Button } from '@/components/ui/button' import { Input } from '@/components/ui/input' import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover' diff --git a/src/renderer/src/components/editor/diff/large-files/ImageDiffViewer.tsx b/src/renderer/src/components/editor/diff/large-files/ImageDiffViewer.tsx index 22d3f54e690..9029cc1154a 100644 --- a/src/renderer/src/components/editor/diff/large-files/ImageDiffViewer.tsx +++ b/src/renderer/src/components/editor/diff/large-files/ImageDiffViewer.tsx @@ -1,5 +1,5 @@ import type { JSX } from 'react' -import { cn } from '@/lib/utils' +import { cn } from '@/lib/class-names' import ImageViewer from '../../ImageViewer' import { useTranslate } from '@/i18n/use-translate' diff --git a/src/renderer/src/components/editor/diff/monaco-view/DiffViewer.tsx b/src/renderer/src/components/editor/diff/monaco-view/DiffViewer.tsx index 9fb9bf3ab77..9af43207c3e 100644 --- a/src/renderer/src/components/editor/diff/monaco-view/DiffViewer.tsx +++ b/src/renderer/src/components/editor/diff/monaco-view/DiffViewer.tsx @@ -4,7 +4,10 @@ import React, { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useSta import { DiffEditor, type DiffOnMount } from '@monaco-editor/react' import type { editor } from 'monaco-editor' import { useAppStore } from '@/store/index' -import { diffViewStateCache, setWithLRU } from '@/lib/scroll-cache' +import { + diffViewStateCache, + setWithLRU +} from '@/components/editor/model-lifetime/retention/editor-view-state-cache' import { monacoTypographyOptions } from '@/lib/editor/appearance/editor-typography' import { useEditorTypography } from '@/hooks/use-editor-typography' import { useContextualCopySetup } from '../../useContextualCopySetup' @@ -38,7 +41,7 @@ import { applyModelLanguage } from '@/lib/monaco-languages/plugin-syntax-editor-options' import { useMonacoTheme } from '@/hooks/use-monaco-theme' -import { cn } from '@/lib/utils' +import { cn } from '@/lib/class-names' import { wholeFileDiffTintClass } from './whole-file-diff-tint' export default function DiffViewer({ diff --git a/src/renderer/src/components/editor/diff/monaco-view/useDiffViewerFirstChangeAutoScroll.ts b/src/renderer/src/components/editor/diff/monaco-view/useDiffViewerFirstChangeAutoScroll.ts index 4fcb253b8dc..daae50f4837 100644 --- a/src/renderer/src/components/editor/diff/monaco-view/useDiffViewerFirstChangeAutoScroll.ts +++ b/src/renderer/src/components/editor/diff/monaco-view/useDiffViewerFirstChangeAutoScroll.ts @@ -1,7 +1,7 @@ import { useEffect, useRef } from 'react' import type { RefObject } from 'react' import type { editor } from 'monaco-editor' -import { diffViewStateCache } from '@/lib/scroll-cache' +import { diffViewStateCache } from '@/components/editor/model-lifetime/retention/editor-view-state-cache' type DiffViewerFirstChangeAutoScrollInput = { diffEditorRef: RefObject diff --git a/src/renderer/src/components/editor/diff/sections/DiffSectionBody.tsx b/src/renderer/src/components/editor/diff/sections/DiffSectionBody.tsx index fd9801a52e6..b0eec634f4c 100644 --- a/src/renderer/src/components/editor/diff/sections/DiffSectionBody.tsx +++ b/src/renderer/src/components/editor/diff/sections/DiffSectionBody.tsx @@ -1,10 +1,10 @@ import { DiffTooLargeNotice } from '../large-files/DiffTooLargeNotice' import { Suspense, useEffect, useLayoutEffect, useMemo, useRef } from 'react' import type { editor } from 'monaco-editor' -import { lazyWithRetry as lazy } from '@/lib/lazy-with-retry' +import { lazyWithRetry as lazy } from '@/app-shell/startup/lazy-with-retry' import { AlertCircle, RefreshCw } from 'lucide-react' import { DiffEditor, type DiffOnMount } from '@monaco-editor/react' -import { cn } from '@/lib/utils' +import { cn } from '@/lib/class-names' import { Button } from '@/components/ui/button' import { combinedDiffSectionScrollbarOptions } from '../monaco-view/diff-editor-scrollbar-options' import { isCombinedDiffSizeUnknown } from '../../combined-diff/load-sections/combined-diff-on-demand-load' diff --git a/src/renderer/src/components/editor/editor-lazy-views.ts b/src/renderer/src/components/editor/editor-lazy-views.ts index 1d256cec6fa..73971845fb4 100644 --- a/src/renderer/src/components/editor/editor-lazy-views.ts +++ b/src/renderer/src/components/editor/editor-lazy-views.ts @@ -1,4 +1,4 @@ -import { lazyWithRetry as lazy } from '@/lib/lazy-with-retry' +import { lazyWithRetry as lazy } from '@/app-shell/startup/lazy-with-retry' // Share lazy component identities across surfaces; a second lazy wrapper over the same module causes separate boundaries and remounts. export const MonacoEditor = lazy(() => import('./MonacoEditor')) diff --git a/src/renderer/src/components/editor/external-changes/ExternalFileChangeCompareDialog.tsx b/src/renderer/src/components/editor/external-changes/ExternalFileChangeCompareDialog.tsx index 1ba9c61bfe4..77a10ab494e 100644 --- a/src/renderer/src/components/editor/external-changes/ExternalFileChangeCompareDialog.tsx +++ b/src/renderer/src/components/editor/external-changes/ExternalFileChangeCompareDialog.tsx @@ -9,7 +9,7 @@ import { DialogHeader, DialogTitle } from '@/components/ui/dialog' -import { lazyWithRetry as lazy } from '@/lib/lazy-with-retry' +import { lazyWithRetry as lazy } from '@/app-shell/startup/lazy-with-retry' import { getConnectionIdForFile } from '@/lib/workspace/ownership/connection-context' import { editorTabFileAccess } from '@/lib/files/access/local-file-access' import { detectLanguage } from '../../../../../shared/editor-language/editor-language-detect' diff --git a/src/renderer/src/components/editor/external-changes/editor-external-change-telemetry.ts b/src/renderer/src/components/editor/external-changes/editor-external-change-telemetry.ts index 88770dbe900..35f6d88d50c 100644 --- a/src/renderer/src/components/editor/external-changes/editor-external-change-telemetry.ts +++ b/src/renderer/src/components/editor/external-changes/editor-external-change-telemetry.ts @@ -1,5 +1,5 @@ // Share path-free conflict enums across marking and banner actions so false-banner rates remain comparable by transport. -import { track } from '@/lib/telemetry' +import { track } from '@/diagnostics/telemetry/telemetry' import { getConnectionIdForFile } from '@/lib/workspace/ownership/connection-context' import type { OpenFile } from '@/store/slices/editor/types/open-file' diff --git a/src/renderer/src/components/editor/git-graph/git-graph-commit-action-copy.ts b/src/renderer/src/components/editor/git-graph/git-graph-commit-action-copy.ts index c2d33d145d7..7581c44fda4 100644 --- a/src/renderer/src/components/editor/git-graph/git-graph-commit-action-copy.ts +++ b/src/renderer/src/components/editor/git-graph/git-graph-commit-action-copy.ts @@ -1,5 +1,5 @@ import { translate } from '@/i18n/i18n' -import { displayIpcErrorMessage } from '@/lib/ipc-error' +import { displayIpcErrorMessage } from '@/runtime/errors/ipc-error' import type { Translate } from '@/i18n/use-translate' import type { GitCommitActionResult } from '../../../../../shared/git/commands/git-commit-action' diff --git a/src/renderer/src/components/editor/git-graph/git-graph-ref-menu.tsx b/src/renderer/src/components/editor/git-graph/git-graph-ref-menu.tsx index 428bec78c9e..30ada310811 100644 --- a/src/renderer/src/components/editor/git-graph/git-graph-ref-menu.tsx +++ b/src/renderer/src/components/editor/git-graph/git-graph-ref-menu.tsx @@ -11,14 +11,14 @@ import { } from '@/components/ui/context-menu' import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover' import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip' -import { useAppStore } from '@/store' +import { useAppStore } from '@/store/index' import { selectWorktreesByRepo } from '@/store/workspaces/catalog/workspace-record-fields' import type { gitGraphScope } from '@/lib/source-control/graph/git-graph-tab' import { gitGraphWorkspaceCatalog } from './git-graph-workspace-navigation' import { useTranslate } from '@/i18n/use-translate' import type { GitHistoryItemRef } from '../../../../../shared/git/history/git-history-types' import type { Worktree } from '../../../../../shared/worktree/types' -import { cn } from '@/lib/utils' +import { cn } from '@/lib/class-names' export function useGitGraphWorkspaces(scope: ReturnType) { const worktrees = useAppStore(selectWorktreesByRepo) diff --git a/src/renderer/src/components/editor/git-graph/git-graph-tab.tsx b/src/renderer/src/components/editor/git-graph/git-graph-tab.tsx index 8e3abc51ba8..4e581dd97fc 100644 --- a/src/renderer/src/components/editor/git-graph/git-graph-tab.tsx +++ b/src/renderer/src/components/editor/git-graph/git-graph-tab.tsx @@ -22,7 +22,7 @@ import { useGitGraphHistory, gitGraphFilterSupported } from './use-git-graph-his import { GitGraphFilter } from './git-graph-filter' import { GitGraphDetails } from './git-graph-details' import { GitGraphRefs, useGitGraphWorkspaces } from './git-graph-ref-menu' -import { cn } from '@/lib/utils' +import { cn } from '@/lib/class-names' import { useIntlLocale, useTranslate } from '@/i18n/use-translate' const sameGroup = () => undefined diff --git a/src/renderer/src/components/editor/markdown-preview/viewport/VirtualMarkdownPreviewBody.tsx b/src/renderer/src/components/editor/markdown-preview/viewport/VirtualMarkdownPreviewBody.tsx index fb3a3ab6b70..6cfadb88ac5 100644 --- a/src/renderer/src/components/editor/markdown-preview/viewport/VirtualMarkdownPreviewBody.tsx +++ b/src/renderer/src/components/editor/markdown-preview/viewport/VirtualMarkdownPreviewBody.tsx @@ -12,7 +12,7 @@ import type { Components } from 'react-markdown' import { createProgrammaticScrollMarks } from '@/hooks/programmatic-scroll-marks' import { useTranslate } from '@/i18n/use-translate' import { useUiLanguageRevision } from '@/i18n/use-ui-language-revision' -import { scrollTopCache } from '@/lib/scroll-cache' +import { scrollTopCache } from '@/components/editor/model-lifetime/retention/editor-view-state-cache' import { renderMarkdownPreviewTree } from '../render-tree/markdown-preview-render-tree' import { scrollMarkdownPreviewVirtualizer } from './markdown-preview-anchor-navigation' import type { MarkdownPreviewSearchInstance } from '../search/markdown-preview-search' diff --git a/src/renderer/src/components/editor/markdown-preview/viewport/use-markdown-preview-scroll-anchor.ts b/src/renderer/src/components/editor/markdown-preview/viewport/use-markdown-preview-scroll-anchor.ts index b167962df8b..2cb2162019a 100644 --- a/src/renderer/src/components/editor/markdown-preview/viewport/use-markdown-preview-scroll-anchor.ts +++ b/src/renderer/src/components/editor/markdown-preview/viewport/use-markdown-preview-scroll-anchor.ts @@ -5,7 +5,10 @@ import { type VirtualizedScrollAnchor } from '@/hooks/useVirtualizedScrollAnchor' import type { ProgrammaticScrollMarks } from '@/hooks/programmatic-scroll-marks' -import { scrollTopCache, setWithLRU } from '@/lib/scroll-cache' +import { + scrollTopCache, + setWithLRU +} from '@/components/editor/model-lifetime/retention/editor-view-state-cache' import type { MarkdownPreviewBlock } from '../document-worker/markdown-preview-document-types' const anchors = new Map() diff --git a/src/renderer/src/components/editor/markdown-preview/viewport/use-markdown-preview-scroll-viewport.ts b/src/renderer/src/components/editor/markdown-preview/viewport/use-markdown-preview-scroll-viewport.ts index f84e079b797..befb6d9879b 100644 --- a/src/renderer/src/components/editor/markdown-preview/viewport/use-markdown-preview-scroll-viewport.ts +++ b/src/renderer/src/components/editor/markdown-preview/viewport/use-markdown-preview-scroll-viewport.ts @@ -1,5 +1,8 @@ import { useLayoutEffect } from 'react' -import { scrollTopCache, setWithLRU } from '@/lib/scroll-cache' +import { + scrollTopCache, + setWithLRU +} from '@/components/editor/model-lifetime/retention/editor-view-state-cache' import type { MarkdownPreviewFoundation } from '../surface/use-markdown-preview-foundation' export function useMarkdownPreviewScrollViewport({ diff --git a/src/renderer/src/components/editor/markdown/navigation/MarkdownTableOfContentsRow.tsx b/src/renderer/src/components/editor/markdown/navigation/MarkdownTableOfContentsRow.tsx index 68fc6bb4af8..a3bb3b562bc 100644 --- a/src/renderer/src/components/editor/markdown/navigation/MarkdownTableOfContentsRow.tsx +++ b/src/renderer/src/components/editor/markdown/navigation/MarkdownTableOfContentsRow.tsx @@ -1,5 +1,5 @@ import { ChevronRight } from 'lucide-react' -import { cn } from '@/lib/utils' +import { cn } from '@/lib/class-names' import { useTranslate } from '@/i18n/use-translate' import type { MarkdownTocItem } from './markdown-table-of-contents' import { isMarkdownTocItemExpanded } from './markdown-toc-collapse-state' diff --git a/src/renderer/src/components/editor/mermaid-config.test.ts b/src/renderer/src/components/editor/mermaid-config.test.ts index 3da9ab84853..390435c48bb 100644 --- a/src/renderer/src/components/editor/mermaid-config.test.ts +++ b/src/renderer/src/components/editor/mermaid-config.test.ts @@ -13,6 +13,16 @@ const darkColors = { border: '#8ec5ff' } +// Catppuccin Mocha: pastel chart tokens on a dark background. +const pastelDarkColors = { + background: '#1e1e2e', + foreground: '#cdd6f4', + primary: '#f5c2e7', + secondary: '#fab387', + tertiary: '#a6e3a1', + border: '#cba6f7' +} + function luminance(color: string | boolean | undefined): number { if (typeof color !== 'string') { throw new Error('Expected a resolved Mermaid color') @@ -28,10 +38,10 @@ function luminance(color: string | boolean | undefined): number { return channels[0] * 0.2126 + channels[1] * 0.7152 + channels[2] * 0.0722 } -function resolvedDarkTheme(): NonNullable< - ReturnType['themeVariables'] -> { - mermaid.initialize(getMermaidConfig(true, darkColors)) +function resolvedDarkTheme( + colors = darkColors +): NonNullable['themeVariables']> { + mermaid.initialize(getMermaidConfig(true, colors)) const variables = mermaid.mermaidAPI.getConfig().themeVariables if (!variables) { throw new Error('Mermaid did not resolve the theme') @@ -39,18 +49,35 @@ function resolvedDarkTheme(): NonNullable< return variables } +function expectReadable( + variables: ReturnType, + pairs: [text: string, background: string][] +): void { + for (const [text, background] of pairs) { + const first = luminance(variables[text]) + const second = luminance(variables[background]) + const contrast = (Math.max(first, second) + 0.05) / (Math.min(first, second) + 0.05) + expect(contrast, `${text} on ${background}`).toBeGreaterThanOrEqual(4.5) + } +} + describe('getMermaidConfig', () => { it('keeps Gantt labels readable on completed and active tasks and alternate sections', () => { - const variables = resolvedDarkTheme() - for (const [text, background] of [ + expectReadable(resolvedDarkTheme(), [ ['taskTextDarkColor', 'doneTaskBkgColor'], ['taskTextDarkColor', 'activeTaskBkgColor'], ['taskTextOutsideColor', 'altSectionBkgColor'] - ]) { - const first = luminance(variables[text]) - const second = luminance(variables[background]) - const contrast = (Math.max(first, second) + 0.05) / (Math.min(first, second) + 0.05) - expect(contrast, `${text} on ${background}`).toBeGreaterThanOrEqual(4.5) - } + ]) + }) + + it('keeps labels readable on fills from a pastel dark palette', () => { + expectReadable(resolvedDarkTheme(pastelDarkColors), [ + ['actorTextColor', 'actorBkg'], + ['nodeTextColor', 'mainBkg'], + ['textColor', 'clusterBkg'], + ['taskTextColor', 'taskBkgColor'], + ['taskTextClickableColor', 'taskBkgColor'], + ['taskTextDarkColor', 'activeTaskBkgColor'] + ]) }) }) diff --git a/src/renderer/src/components/editor/mermaid-config.ts b/src/renderer/src/components/editor/mermaid-config.ts index c727ad087f2..bae98aa3d25 100644 --- a/src/renderer/src/components/editor/mermaid-config.ts +++ b/src/renderer/src/components/editor/mermaid-config.ts @@ -1,4 +1,6 @@ import type mermaid from 'mermaid' +import { hexToRgb, readableOn, rgbaToHex } from '../../../../shared/color/rgba-contrast' +import { READABLE_CONTRAST } from '../../../../shared/mermaid-flowchart-contrast' export type MermaidThemeColors = { background: string @@ -20,33 +22,54 @@ export function getMermaidConfig( // The legacy dark theme removes color from flowcharts. theme: isDark ? (colors ? 'base' : 'dark') : 'default', darkMode: isDark, - ...(isDark && colors - ? { - themeVariables: { - darkMode: true, - background: colors.background, - primaryColor: colors.primary, - secondaryColor: colors.secondary, - tertiaryColor: colors.tertiary, - primaryTextColor: colors.foreground, - secondaryTextColor: colors.foreground, - tertiaryTextColor: colors.foreground, - primaryBorderColor: colors.border, - secondaryBorderColor: colors.border, - tertiaryBorderColor: colors.border, - lineColor: colors.foreground, - textColor: colors.foreground, - edgeLabelBackground: colors.background, - // Base defaults to light Gantt surfaces even when darkMode is enabled. - altSectionBkgColor: colors.background, - excludeBkgColor: colors.background, - doneTaskBkgColor: colors.background, - doneTaskBorderColor: colors.border, - activeTaskBkgColor: colors.secondary - } - } - : {}), + ...(isDark && colors ? { themeVariables: darkThemeVariables(colors) } : {}), // Strict mode sanitizes label HTML; sanitizeMermaidSvg keeps the foreignObject labels it emits. htmlLabels: true } } + +function darkThemeVariables(colors: MermaidThemeColors): Record { + // Mermaid draws dark-mode labels in the foreground colour, so darken a pastel chart token until it reads. + const surface = (fill: string): string => + rgbaToHex(readableOn(hexToRgb(fill), [hexToRgb(colors.foreground)], true, READABLE_CONTRAST)) + // Seeds stay the theme's because git and venn pair them with their own label colours. Fills are + // pinned only when tinted, so otherwise a diagram's own primaryColor/tertiaryColor still drives them. + const tinted = (fill: string, keys: string[]): Record => { + const readable = surface(fill) + return readable === fill.toLowerCase() + ? {} + : Object.fromEntries(keys.map((key) => [key, readable])) + } + return { + darkMode: true, + background: colors.background, + primaryColor: colors.primary, + secondaryColor: colors.secondary, + tertiaryColor: colors.tertiary, + ...tinted(colors.primary, [ + 'mainBkg', + 'requirementBackground', + 'taskBkgColor', + 'tagLabelBackground' + ]), + ...tinted(colors.secondary, ['secondBkg']), + ...tinted(colors.tertiary, ['clusterBkg', 'labelBackground']), + primaryTextColor: colors.foreground, + secondaryTextColor: colors.foreground, + tertiaryTextColor: colors.foreground, + primaryBorderColor: colors.border, + secondaryBorderColor: colors.border, + tertiaryBorderColor: colors.border, + lineColor: colors.foreground, + textColor: colors.foreground, + edgeLabelBackground: colors.background, + // Base defaults to light Gantt surfaces even when darkMode is enabled. + altSectionBkgColor: colors.background, + excludeBkgColor: colors.background, + doneTaskBkgColor: colors.background, + doneTaskBorderColor: colors.border, + // Base's dark-blue clickable label is drawn for light bars, inside and beside the bar. + taskTextClickableColor: colors.foreground, + activeTaskBkgColor: surface(colors.secondary) + } +} diff --git a/src/renderer/src/components/editor/model-lifetime/retention/closed-editor-model-lifetime.test.ts b/src/renderer/src/components/editor/model-lifetime/retention/closed-editor-model-lifetime.test.ts index 770bebbe8de..7a6a5186e7c 100644 --- a/src/renderer/src/components/editor/model-lifetime/retention/closed-editor-model-lifetime.test.ts +++ b/src/renderer/src/components/editor/model-lifetime/retention/closed-editor-model-lifetime.test.ts @@ -2,7 +2,6 @@ import * as monaco from 'monaco-editor/esm/vs/editor/editor.api.js' import { afterEach, expect, it, vi } from 'vitest' import { - attachModelLifetimeView, createModelLifetimeFixture, modelLifetimeFile, modelLifetimeTextModel, @@ -13,7 +12,11 @@ import { getDiffViewerMonacoModelPaths, rememberDiffViewerModelPaths } from '../../diff/monaco-view/diff-monaco-model-disposal' -import { scrollTopCache, diffViewStateCache, setWithLRU } from '@/lib/scroll-cache' +import { + scrollTopCache, + diffViewStateCache, + setWithLRU +} from '@/components/editor/model-lifetime/retention/editor-view-state-cache' import { checkDetailsReadingKey, @@ -26,38 +29,6 @@ import { vi.mock('sonner', () => ({ toast: { info: vi.fn(), error: vi.fn(), success: vi.fn() } })) afterEach(resetModelLifetimeFixtures) -it('waits beyond the real detach stack and preserves its bounded scroll snapshot', async () => { - const { store, attach, add } = createModelLifetimeFixture() - const { file, model } = add('attached') - const detachView = attachModelLifetimeView(model) - attach() - store.getState().closeFile(file.id) - await Promise.resolve() - expect(model.isDisposed()).toBe(false) - scrollTopCache.set(file.filePath, 42) - detachView() - expect(model.isDisposed()).toBe(false) - await Promise.resolve() - expect(model.isDisposed()).toBe(true) - expect(scrollTopCache.get(file.filePath)).toBe(42) -}) - -it('protects a reopened URI owner from a pending detach callback', async () => { - const { store, attach, add } = createModelLifetimeFixture() - const { file, model } = add('reopened-old') - const detachView = attachModelLifetimeView(model) - attach() - store.getState().closeFile(file.id) - await Promise.resolve() - store.setState({ openFiles: [{ ...file, id: 'reopened-new' }] }) - detachView() - await Promise.resolve() - expect(model.isDisposed()).toBe(false) - store.getState().closeFile('reopened-new') - await Promise.resolve() - expect(model.isDisposed()).toBe(true) -}) - it('does not replay earlier model-disposal authority after first registry registration', async () => { const { store, bridge, attach } = createModelLifetimeFixture(false) const file = modelLifetimeFile('unloaded') @@ -95,36 +66,6 @@ it('does not let a stale HMR unregister clear a successor registration', async ( } }) -it('releases generated closed diff namespaces after detachment and preserves sibling prefixes', async () => { - const { store, attach } = createModelLifetimeFixture() - const file = modelLifetimeFile('diff-a', 'diff') - const sibling = modelLifetimeFile('diff-a-longer', 'diff') - const paths = getDiffViewerMonacoModelPaths({ - modelKey: file.id, - generationSuffix: ':large-diff-generation:2' - }) - const siblingPaths = getDiffViewerMonacoModelPaths({ - modelKey: sibling.id, - generationSuffix: '' - }) - const original = modelLifetimeTextModel(paths.originalModelPath) - const modified = modelLifetimeTextModel(paths.modifiedModelPath) - const live = modelLifetimeTextModel(siblingPaths.originalModelPath) - const detachView = attachModelLifetimeView(original) - store.setState({ openFiles: [file, sibling] }) - attach() - store.getState().closeFile(file.id) - await Promise.resolve() - expect(original.isDisposed()).toBe(false) - expect(modified.isDisposed()).toBe(true) - expect(live.isDisposed()).toBe(false) - detachView() - expect(original.isDisposed()).toBe(false) - await Promise.resolve() - expect(original.isDisposed()).toBe(true) - expect(live.isDisposed()).toBe(false) -}) - it('preserves queued model custody across registry removal and replacement', async () => { const { store, bridge, attach, add } = createModelLifetimeFixture(false) const unregister = bridge.register(monaco) @@ -143,27 +84,6 @@ it('preserves queued model custody across registry removal and replacement', asy } }) -it('preserves retained attachment custody across registry replacement', async () => { - const { store, bridge, attach, add } = createModelLifetimeFixture(false) - const unregister = bridge.register(monaco) - const { file, model } = add('attached-replacement') - const detachView = attachModelLifetimeView(model) - attach() - store.getState().closeFile(file.id) - await Promise.resolve() - unregister() - detachView() - await Promise.resolve() - expect(model.isDisposed()).toBe(false) - const unregisterNext = bridge.register(monaco) - try { - await Promise.resolve() - expect(model.isDisposed()).toBe(true) - } finally { - unregisterNext() - } -}) - it('preserves successor models at a captured URI across registry replacement', async () => { const { store, bridge, attach, add } = createModelLifetimeFixture(false) const unregister = bridge.register(monaco) @@ -309,18 +229,6 @@ it('sweeps never-mounted close-all and same-ID mode replacements without Monaco' expect(scrollTopCache.size).toBe(0) }) -it('spares a check ID reopened before the pending flush', async () => { - const { store, attach } = createModelLifetimeFixture(false) - const file = modelLifetimeFile('reopened', 'check-details') - store.setState({ openFiles: [file] }) - attach() - seed(file.id) - store.setState({ openFiles: [] }) - store.setState({ openFiles: [file] }) - await Promise.resolve() - expect(scrollTopCache.size).toBe(5) -}) - it('releases tab-scoped diff models when their file closes', async () => { const { store, attach } = createModelLifetimeFixture() const file = modelLifetimeFile('scoped-diff', 'diff') diff --git a/src/renderer/src/components/editor/model-lifetime/retention/closed-editor-tab-disposal.ts b/src/renderer/src/components/editor/model-lifetime/retention/closed-editor-tab-disposal.ts index 8092e8b1d4b..ef28c1b15be 100644 --- a/src/renderer/src/components/editor/model-lifetime/retention/closed-editor-tab-disposal.ts +++ b/src/renderer/src/components/editor/model-lifetime/retention/closed-editor-tab-disposal.ts @@ -1,5 +1,5 @@ import type { OpenFile } from '@/store/slices/editor/types/open-file' -import { scrollTopCache } from '@/lib/scroll-cache' +import { scrollTopCache } from '@/components/editor/model-lifetime/retention/editor-view-state-cache' import { disposeUnattachedMonacoModelsByPathPrefixes, forgetDiffViewerModelPaths, diff --git a/src/renderer/src/components/editor/model-lifetime/retention/closed-editor-view-state-retention.test.ts b/src/renderer/src/components/editor/model-lifetime/retention/closed-editor-view-state-retention.test.ts index 22c96ca76ab..1ca1c10b406 100644 --- a/src/renderer/src/components/editor/model-lifetime/retention/closed-editor-view-state-retention.test.ts +++ b/src/renderer/src/components/editor/model-lifetime/retention/closed-editor-view-state-retention.test.ts @@ -6,7 +6,11 @@ import type { OpenFile } from '@/store/slices/editor/types/open-file' import { createEditorModelRegistry } from '@/lib/editor/monaco/editor-model-registry' import { attachClosedEditorTabCleanup } from '@/components/editor/model-lifetime/retention/closed-editor-tab-controller' import { toEditorModelUri } from '@/components/editor/model-lifetime/identity/editor-model-uri' -import { scrollTopCache, editorSelectionCache, pdfViewPositionCache } from '@/lib/scroll-cache' +import { + scrollTopCache, + editorSelectionCache, + pdfViewPositionCache +} from '@/components/editor/model-lifetime/retention/editor-view-state-cache' const disposeOwners: (() => void)[] = [] afterEach(() => { @@ -21,65 +25,6 @@ afterEach(() => { pdfViewPositionCache.clear() }) -function open(path: string, text = 'original') { - const file: OpenFile = { - id: path, - worktreeId: 'fixture', - filePath: path, - relativePath: path, - mode: 'edit', - language: 'plaintext', - isDirty: false - } - // Match the React wrapper’s path-to-Uri.parse conversion. - const model = monaco.editor.createModel( - text, - 'plaintext', - monaco.Uri.parse(toEditorModelUri(path)) - ) - const store = createStore(() => ({ - openFiles: [file], - worktreesByRepo: { fixture: [{ id: 'fixture', repoId: 'fixture', hostId: 'local' as const }] } - })) - const bridge = createEditorModelRegistry() - disposeOwners.push(bridge.register(monaco), attachClosedEditorTabCleanup(store, bridge)) - return { - model, - close: async () => { - store.setState({ openFiles: [] }) - await Promise.resolve() - expect(model.isDisposed()).toBe(true) - } - } -} - -it.each([ - '/tradeoff/undo-posix.txt', - 'file:///C:/tradeoff/undo-file-uri.txt', - 'C:/tradeoff/undo-raw-drive.txt', - 'C:\\tradeoff\\undo-raw-drive-backslash.txt', - '\\\\server\\share\\undo-unc.txt' -] as const)('restores closed-file undo after reopening %s', async (path) => { - const owner = open(path) - owner.model.pushEditOperations( - [], - [{ range: new monaco.Range(1, 1, 1, 1), text: 'saved ' }], - () => null - ) - owner.model.pushStackElement() - expect(owner.model.canUndo()).toBe(true) - const content = owner.model.getValue() - await owner.close() - const reopened = monaco.editor.createModel( - content, - 'plaintext', - monaco.Uri.parse(toEditorModelUri(path)) - ) - expect(reopened.canUndo()).toBe(true) - await reopened.undo() - expect(reopened.getValue()).toBe('original') -}) - // Disposal and ownership lookup must normalize Windows paths identically or one close can destroy another tab’s model. it('keeps a Windows-path model that a second open tab still owns', async () => { const filePath = 'C:\\repo\\shared.ts' diff --git a/src/renderer/src/components/editor/model-lifetime/retention/editor-model-lifetime-fixture.ts b/src/renderer/src/components/editor/model-lifetime/retention/editor-model-lifetime-fixture.ts index c1564d6759e..c31c32ad554 100644 --- a/src/renderer/src/components/editor/model-lifetime/retention/editor-model-lifetime-fixture.ts +++ b/src/renderer/src/components/editor/model-lifetime/retention/editor-model-lifetime-fixture.ts @@ -14,7 +14,7 @@ import { diffViewStateCache, editorViewStateCache, pdfViewPositionCache -} from '@/lib/scroll-cache' +} from '@/components/editor/model-lifetime/retention/editor-view-state-cache' const workspace = 'model-fixture::/fixture/workspace' const models: monaco.editor.ITextModel[] = [] diff --git a/src/renderer/src/lib/scroll-cache.ts b/src/renderer/src/components/editor/model-lifetime/retention/editor-view-state-cache.ts similarity index 100% rename from src/renderer/src/lib/scroll-cache.ts rename to src/renderer/src/components/editor/model-lifetime/retention/editor-view-state-cache.ts diff --git a/src/renderer/src/components/editor/monaco-view-state-persistence.ts b/src/renderer/src/components/editor/monaco-view-state-persistence.ts index 9a1a3719f07..e49ced11a52 100644 --- a/src/renderer/src/components/editor/monaco-view-state-persistence.ts +++ b/src/renderer/src/components/editor/monaco-view-state-persistence.ts @@ -5,7 +5,7 @@ import { editorViewStateCache, scrollTopCache, setWithLRU -} from '@/lib/scroll-cache' +} from '@/components/editor/model-lifetime/retention/editor-view-state-cache' type MonacoViewStateTrackingParams = { editorInstance: editor.IStandaloneCodeEditor diff --git a/src/renderer/src/components/editor/notebook/cells/IpynbCellEditor.tsx b/src/renderer/src/components/editor/notebook/cells/IpynbCellEditor.tsx index f9aef8b6d7e..84c96d49922 100644 --- a/src/renderer/src/components/editor/notebook/cells/IpynbCellEditor.tsx +++ b/src/renderer/src/components/editor/notebook/cells/IpynbCellEditor.tsx @@ -8,7 +8,7 @@ import { monacoTypographyOptions } from '@/lib/editor/appearance/editor-typography' import { useEditorTypography } from '@/hooks/use-editor-typography' -import { cn } from '@/lib/utils' +import { cn } from '@/lib/class-names' import { installMonacoEditorFindShortcut } from '../../editor-shortcuts' import { syncContentUpdate } from '../../monaco-content-sync' import { diff --git a/src/renderer/src/components/editor/notebook/cells/IpynbCellToolbar.tsx b/src/renderer/src/components/editor/notebook/cells/IpynbCellToolbar.tsx index 5d81f4a5758..670084629aa 100644 --- a/src/renderer/src/components/editor/notebook/cells/IpynbCellToolbar.tsx +++ b/src/renderer/src/components/editor/notebook/cells/IpynbCellToolbar.tsx @@ -27,7 +27,7 @@ import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip import type { ShortcutKeyComboDetails } from '@/hooks/useShortcutLabel' import { translate } from '@/i18n/i18n' import { useTranslate, type Translate } from '@/i18n/use-translate' -import { cn } from '@/lib/utils' +import { cn } from '@/lib/class-names' import type { IpynbCellKind } from '../document/ipynb-parse' const CELL_KINDS: readonly IpynbCellKind[] = ['code', 'markdown', 'raw'] diff --git a/src/renderer/src/components/editor/notebook/document/useIpynbDocumentEditing.test.tsx b/src/renderer/src/components/editor/notebook/document/useIpynbDocumentEditing.test.tsx index 57c9d27e0ad..5c2f50535af 100644 --- a/src/renderer/src/components/editor/notebook/document/useIpynbDocumentEditing.test.tsx +++ b/src/renderer/src/components/editor/notebook/document/useIpynbDocumentEditing.test.tsx @@ -9,11 +9,11 @@ import { useIpynbDocumentEditing } from './useIpynbDocumentEditing' import { EMPTY_EDITOR_BUFFER_VIEW_INDEX as NO_SHARING } from '@/store/slices/editor/buffers/editor-buffer-views' import type * as StaleViewEdit from '../../save/flush/editor-stale-view-edit' import { notifyStaleViewEditRejected } from '../../save/flush/editor-stale-view-edit' +import { discardEditorBuffer } from '../../save/flush/discard-editor-file-changes' vi.mock('../../save/flush/editor-stale-view-edit', async (importOriginal) => ({ ...(await importOriginal()), - notifyStaleViewEditRejected: vi.fn(), - staleViewEditEpoch: vi.fn(() => 0) + notifyStaleViewEditRejected: vi.fn() })) function renderSplitPanes(initialContent: string) { @@ -129,6 +129,32 @@ describe('notebook document editing lifecycle', () => { expect(Object.hasOwn(hook.result.current.sourceDrafts, 'a')).toBe(false) }) + it('drops pending discarded cells and accepts typing begun afterwards', async () => { + const content = notebookContent() + const committed: string[] = [] + const hook = renderHook(() => + useIpynbDocumentEditing({ + content, + fileId: 'discard-notebook', + notebook: parseIpynb(content), + onContentChange: (text) => committed.push(text), + onDirtyStateHint: vi.fn(), + onDeactivateEditor: vi.fn() + }) + ) + await act(async () => { + hook.result.current.updateCellSource(0, 'discarded draft') + const release = await discardEditorBuffer('discard-notebook') + release() + }) + expect(parseIpynb(committed.at(-1)!).cells[0]?.source).toBe('a') + act(() => { + hook.result.current.updateCellSource(0, 'new draft') + flushPendingEditorBuffer(NO_SHARING, 'discard-notebook') + }) + expect(parseIpynb(committed.at(-1)!).cells[0]?.source).toBe('new draft') + }) + it('does not republish unchanged text when flushed with no pending typing', () => { const onContentChange = vi.fn() const content = notebookContent() diff --git a/src/renderer/src/components/editor/notebook/document/useIpynbDocumentEditing.ts b/src/renderer/src/components/editor/notebook/document/useIpynbDocumentEditing.ts index 97f2e138b56..68a64fc32c2 100644 --- a/src/renderer/src/components/editor/notebook/document/useIpynbDocumentEditing.ts +++ b/src/renderer/src/components/editor/notebook/document/useIpynbDocumentEditing.ts @@ -1,3 +1,4 @@ +import type { EditorDiscardGeneration } from '../../save/flush/editor-discard-epoch' import { useCallback, useEffect, @@ -10,7 +11,7 @@ import { registerPendingEditorFlush } from '../../save/flush/editor-pending-flus import { focusLeftView, notifyStaleViewEditRejected, - staleViewEditEpoch + captureViewEditGeneration } from '../../save/flush/editor-stale-view-edit' import { deleteIpynbCell, @@ -84,7 +85,7 @@ export function useIpynbDocumentEditing({ const sourceCommitTimerRef = useRef | null>(null) // Why: each drafted cell's source when typing began; a draft onto a cell changed elsewhere is refused. const draftBasesRef = useRef>({}) - const draftEpochRef = useRef(0) + const draftGenerationRef = useRef(null) const parsedContentRef = useRef(content) const structuralFrameIdsRef = useRef([]) useLayoutEffect(() => { @@ -118,7 +119,7 @@ export function useIpynbDocumentEditing({ return contentRef.current } const cells = latestCells() ?? [] - const discarded = staleViewEditEpoch(fileId) !== draftEpochRef.current + const discarded = draftGenerationRef.current?.discarded === true const rebase = discarded ? { updates: [], dropped: Object.keys(drafts), lostTyping: false } : rebaseIpynbSourceDrafts(cells, drafts, draftBasesRef.current) @@ -135,7 +136,7 @@ export function useIpynbDocumentEditing({ sourceDraftsRef.current = nextDrafts setSourceDrafts(nextDrafts) if (rebase.lostTyping) { - notifyStaleViewEditRejected(fileId, draftEpochRef.current) + notifyStaleViewEditRejected(draftGenerationRef.current) } } draftBasesRef.current = nextBases @@ -228,7 +229,7 @@ export function useIpynbDocumentEditing({ } const key = getIpynbCellKey(cell, index) if (sourceCommitTimerRef.current === null) { - draftEpochRef.current = staleViewEditEpoch(fileId) + draftGenerationRef.current = captureViewEditGeneration(fileId) } if (!Object.hasOwn(draftBasesRef.current, key)) { draftBasesRef.current = { diff --git a/src/renderer/src/components/editor/notebook/document/useIpynbScrollRestoration.test.tsx b/src/renderer/src/components/editor/notebook/document/useIpynbScrollRestoration.test.tsx deleted file mode 100644 index b428425e048..00000000000 --- a/src/renderer/src/components/editor/notebook/document/useIpynbScrollRestoration.test.tsx +++ /dev/null @@ -1,39 +0,0 @@ -// @vitest-environment happy-dom -import { cleanup, fireEvent, render, screen } from '@testing-library/react' -import { useRef } from 'react' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { scrollTopCache } from '@/lib/scroll-cache' -import { useIpynbScrollRestoration } from './useIpynbScrollRestoration' - -function NotebookScrollSurface({ ready }: { ready: boolean }) { - const rootRef = useRef(null) - useIpynbScrollRestoration(rootRef, 'notebook', ready) - return ready ?
: null -} - -beforeEach(() => { - vi.useFakeTimers() - scrollTopCache.clear() -}) - -afterEach(() => { - cleanup() - vi.useRealTimers() - scrollTopCache.clear() -}) - -describe('notebook scroll restoration', () => { - it('remembers scroll when invalid source becomes a notebook without remounting the viewer', () => { - const view = render() - view.rerender() - const notebook = screen.getByTestId('notebook') - notebook.scrollTop = 500 - fireEvent.scroll(notebook) - vi.advanceTimersByTime(150) - expect(scrollTopCache.get('notebook')).toBe(500) - - view.unmount() - render() - expect(screen.getByTestId('notebook').scrollTop).toBe(500) - }) -}) diff --git a/src/renderer/src/components/editor/notebook/document/useIpynbScrollRestoration.ts b/src/renderer/src/components/editor/notebook/document/useIpynbScrollRestoration.ts index ab8187afc27..afeee13c249 100644 --- a/src/renderer/src/components/editor/notebook/document/useIpynbScrollRestoration.ts +++ b/src/renderer/src/components/editor/notebook/document/useIpynbScrollRestoration.ts @@ -1,5 +1,8 @@ import { useLayoutEffect, type RefObject } from 'react' -import { scrollTopCache, setWithLRU } from '@/lib/scroll-cache' +import { + scrollTopCache, + setWithLRU +} from '@/components/editor/model-lifetime/retention/editor-view-state-cache' export function useIpynbScrollRestoration( rootRef: RefObject, diff --git a/src/renderer/src/components/editor/notebook/kernel/IpynbKernelToolbar.tsx b/src/renderer/src/components/editor/notebook/kernel/IpynbKernelToolbar.tsx index df3684825f7..608c2933aee 100644 --- a/src/renderer/src/components/editor/notebook/kernel/IpynbKernelToolbar.tsx +++ b/src/renderer/src/components/editor/notebook/kernel/IpynbKernelToolbar.tsx @@ -24,7 +24,7 @@ import { } from '@/components/ui/dropdown-menu' import { translate } from '@/i18n/i18n' import { useTranslate, type Translate } from '@/i18n/use-translate' -import { cn } from '@/lib/utils' +import { cn } from '@/lib/class-names' import type { PythonEnvironment, PythonEnvironments diff --git a/src/renderer/src/components/editor/notebook/kernel/ipynb-kernel-setup-commands.ts b/src/renderer/src/components/editor/notebook/kernel/ipynb-kernel-setup-commands.ts index 6f8e4d548ff..7efc4148c4e 100644 --- a/src/renderer/src/components/editor/notebook/kernel/ipynb-kernel-setup-commands.ts +++ b/src/renderer/src/components/editor/notebook/kernel/ipynb-kernel-setup-commands.ts @@ -1,5 +1,5 @@ import { quotePosixShell } from '../../../../../../shared/shell/launch/shell-argument-quoting' -import { getRendererAppPlatform } from '@/lib/renderer-app-platform' +import { getRendererAppPlatform } from '@/app-shell/platform/renderer-app-platform' import { venvInterpreterSegments } from '../../../../../../shared/notebook-venv-location' import { quotePowerShellLiteral } from '../../../../../../shared/powershell-native-argument' diff --git a/src/renderer/src/components/editor/notebook/outputs/IpynbCellOutputs.tsx b/src/renderer/src/components/editor/notebook/outputs/IpynbCellOutputs.tsx index f2c9d0f0cb1..64854e84dc6 100644 --- a/src/renderer/src/components/editor/notebook/outputs/IpynbCellOutputs.tsx +++ b/src/renderer/src/components/editor/notebook/outputs/IpynbCellOutputs.tsx @@ -1,5 +1,5 @@ import type { ITheme } from '@xterm/xterm' -import { cn } from '@/lib/utils' +import { cn } from '@/lib/class-names' import '@/lib/terminal-theme' import { getTheme } from '@/lib/terminal-themes-data' import { diff --git a/src/renderer/src/components/editor/pdf-view-position.test.ts b/src/renderer/src/components/editor/pdf-view-position.test.ts index e174c4c691d..0f2cf803953 100644 --- a/src/renderer/src/components/editor/pdf-view-position.test.ts +++ b/src/renderer/src/components/editor/pdf-view-position.test.ts @@ -1,5 +1,5 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import type { PdfViewPosition } from '@/lib/scroll-cache' +import type { PdfViewPosition } from '@/components/editor/model-lifetime/retention/editor-view-state-cache' import { createPdfViewPositionRecorder, PDF_POSITION_FLUSH_MS } from './pdf-view-position' describe('createPdfViewPositionRecorder', () => { @@ -38,27 +38,7 @@ describe('createPdfViewPositionRecorder', () => { expect(writes).toEqual([['a.pdf:pdf', { pageNumber: 7, top: 400, left: 20 }]]) }) - it('fires the debounced write once and reflects the latest of several rapid records', () => { - const recorder = makeRecorder() - recorder.arm() - recorder.record(location(2)) - recorder.record(location(3)) - recorder.record(location(4)) - expect(writes).toEqual([]) - vi.advanceTimersByTime(PDF_POSITION_FLUSH_MS) - expect(writes).toEqual([['a.pdf:pdf', { pageNumber: 4, top: 400, left: 20 }]]) - }) - // Restarting the timer would starve LRU refresh during continuous scrolling, when the entry most needs to stay warm. - it('does not restart the pending timer when a later record arrives', () => { - const recorder = makeRecorder() - recorder.arm() - recorder.record(location(2)) - vi.advanceTimersByTime(PDF_POSITION_FLUSH_MS - 50) - recorder.record(location(3)) - vi.advanceTimersByTime(50) - expect(writes).toEqual([['a.pdf:pdf', { pageNumber: 3, top: 400, left: 20 }]]) - }) it('ignores a malformed location without clearing the last good position', () => { const recorder = makeRecorder() diff --git a/src/renderer/src/components/editor/pdf-view-position.ts b/src/renderer/src/components/editor/pdf-view-position.ts index 300dc476491..be942ebc5a6 100644 --- a/src/renderer/src/components/editor/pdf-view-position.ts +++ b/src/renderer/src/components/editor/pdf-view-position.ts @@ -1,4 +1,4 @@ -import type { PdfViewPosition } from '@/lib/scroll-cache' +import type { PdfViewPosition } from '@/components/editor/model-lifetime/retention/editor-view-state-cache' /** Argument object for pdf.js `PDFViewer.scrollPageIntoView`. */ export type PdfScrollDestination = { diff --git a/src/renderer/src/components/editor/pdf-viewer-failed-load-recovery.test.tsx b/src/renderer/src/components/editor/pdf-viewer-failed-load-recovery.test.tsx deleted file mode 100644 index 94037acc869..00000000000 --- a/src/renderer/src/components/editor/pdf-viewer-failed-load-recovery.test.tsx +++ /dev/null @@ -1,504 +0,0 @@ -// @vitest-environment happy-dom - -import { act, cleanup, fireEvent, render, waitFor } from '@testing-library/react' -import { StrictMode } from 'react' -import { afterEach, describe, expect, it, vi } from 'vitest' -import PdfViewer from './PdfViewer' -import { pdfViewPositionCache } from '@/lib/scroll-cache' - -const getDocument = vi.hoisted(() => vi.fn()) -const shownDocuments = vi.hoisted((): unknown[] => []) -const viewers = vi.hoisted((): { currentScale: number; currentScaleValue: string }[] => []) -const eventBuses = vi.hoisted( - (): { - dispatch: (name: string, event: { location?: unknown; scale: number }) => void - listenerCount: () => number - }[] => [] -) -const scrollDestinations = vi.hoisted((): unknown[] => []) -const viewerSignals = vi.hoisted((): AbortSignal[] => []) -const localizationResources = vi.hoisted( - (): { active: boolean; destroy: ReturnType Promise>> }[] => [] -) - -vi.mock('pdfjs-dist', () => ({ - GlobalWorkerOptions: {}, - getDocument, - PDFDataRangeTransport: class {} -})) -vi.mock('pdfjs-dist/web/pdf_viewer.mjs', () => { - class EventBus { - listeners = new Map void>>() - constructor() { - eventBuses.push(this) - } - on(name: string, callback: (event: { location?: unknown; scale: number }) => void): void { - const listeners = this.listeners.get(name) ?? new Set() - listeners.add(callback) - this.listeners.set(name, listeners) - } - off(name: string, callback: (event: { location?: unknown; scale: number }) => void): void { - this.listeners.get(name)?.delete(callback) - } - dispatch(name: string, event: { location?: unknown; scale: number }): void { - for (const callback of this.listeners.get(name) ?? []) { - callback(event) - } - } - listenerCount(): number { - return [...this.listeners.values()].reduce((count, listeners) => count + listeners.size, 0) - } - } - class PDFLinkService { - setViewer(): void {} - setDocument(): void {} - } - class PDFFindController { - setDocument(): void {} - } - class PDFViewer { - pagesCount = 10 - currentScale = 1 - currentScaleValue = 'page-width' - l10n: { active: boolean; destroy: ReturnType Promise>> } - constructor(options: { container: HTMLDivElement; abortSignal?: AbortSignal }) { - viewers.push(this) - const observer = new MutationObserver(() => {}) - observer.observe(options.container, { childList: true, subtree: true }) - const resource = { active: true, destroy: vi.fn(() => Promise.resolve()) } - resource.destroy.mockImplementation(() => { - observer.disconnect() - resource.active = false - return Promise.resolve() - }) - this.l10n = resource - localizationResources.push(resource) - if (options.abortSignal) { - viewerSignals.push(options.abortSignal) - } - } - setDocument(doc: unknown): void { - shownDocuments.push(doc) - } - scrollPageIntoView(destination: unknown): void { - scrollDestinations.push(destination) - } - update(): void {} - } - return { EventBus, PDFLinkService, PDFFindController, PDFViewer } -}) -vi.mock('pdfjs-dist/web/pdf_viewer.css', () => ({})) -vi.mock('pdfjs-dist/build/pdf.worker.min.mjs?url', () => ({ default: '' })) -vi.mock('@/i18n/i18n', () => ({ translate: (_key: string, fallback: string) => fallback })) -vi.mock('@/hooks/useShortcutLabel', () => ({ useShortcutLabel: () => '' })) -vi.mock('@/store', () => ({ - useAppStore: (selector: (state: { keybindings: Record }) => unknown) => - selector({ keybindings: {} }) -})) - -const ERROR_TEXT = 'Failed to load PDF preview' - -type PdfDocumentFixture = { name: string } | { index: number } - -function loadingTask(doc: PdfDocumentFixture | 'fail'): { - promise: Promise - destroy: ReturnType Promise>> -} { - return { - promise: - doc === 'fail' ? Promise.reject(new Error('Invalid PDF structure')) : Promise.resolve(doc), - destroy: vi.fn(() => Promise.resolve()) - } -} - -function pendingTask(): { - promise: Promise - resolve: (doc: PdfDocumentFixture) => void - destroy: ReturnType Promise>> -} { - let resolve: (doc: PdfDocumentFixture) => void = () => {} - const promise = new Promise((done) => { - resolve = done - }) - return { promise, resolve, destroy: vi.fn(() => Promise.resolve()) } -} - -async function finishTask( - task: ReturnType, - doc: PdfDocumentFixture -): Promise { - await act(async () => { - task.resolve(doc) - await task.promise - }) -} - -afterEach(() => { - cleanup() - getDocument.mockReset() - shownDocuments.length = 0 - viewers.length = 0 - eventBuses.length = 0 - scrollDestinations.length = 0 - viewerSignals.length = 0 - localizationResources.length = 0 - pdfViewPositionCache.clear() - localStorage.clear() -}) - -describe('PdfViewer when the file is rewritten', () => { - it('clears the previous version and reports a broken rewrite, then recovers', async () => { - const previous = { name: 'previous build' } - const next = { name: 'next build' } - getDocument - .mockImplementationOnce(() => loadingTask(previous)) - .mockImplementationOnce(() => loadingTask('fail')) - .mockImplementationOnce(() => loadingTask(next)) - const view = render() - await waitFor(() => expect(shownDocuments.at(-1)).toBe(previous)) - - view.rerender() - await waitFor(() => expect(view.queryByText(ERROR_TEXT)).toBeTruthy()) - expect(shownDocuments.at(-1)).toBeNull() - - view.rerender() - await waitFor(() => expect(shownDocuments.at(-1)).toBe(next)) - expect(view.queryByText(ERROR_TEXT)).toBeNull() - }) - - it.each([ - { content: '', error: ERROR_TEXT, label: 'empty' }, - { content: '%%%', error: 'Failed to decode PDF content', label: 'invalid base64' } - ])( - 'clears its previous document when rewritten with $label content', - async ({ content, error }) => { - const previous = { name: 'previous build' } - const task = loadingTask(previous) - getDocument.mockImplementationOnce(() => task) - const view = render() - await waitFor(() => expect(shownDocuments.at(-1)).toBe(previous)) - - view.rerender() - - expect(shownDocuments.at(-1)).toBeNull() - expect(view.queryByText(error)).toBeTruthy() - expect(task.destroy).toHaveBeenCalledTimes(1) - expect(getDocument).toHaveBeenCalledTimes(1) - } - ) - - it('recovers after invalid base64 without remounting the preview container', async () => { - const finished = { name: 'finished' } - getDocument.mockImplementationOnce(() => loadingTask(finished)) - const view = render() - await waitFor(() => expect(view.queryByText('Failed to decode PDF content')).toBeTruthy()) - const container = view.container.querySelector('.pdfViewer') - - view.rerender() - - await waitFor(() => expect(shownDocuments.at(-1)).toBe(finished)) - expect(view.queryByText('Failed to decode PDF content')).toBeNull() - expect(view.container.querySelector('.pdfViewer')).toBe(container) - }) - - it.each([ - { - label: 'file path', - filePath: 'b.pdf', - preferenceKey: 'owner-a', - scrollCacheKey: 'a:pdf', - sameBytes: false - }, - { - label: 'file path with identical bytes', - filePath: 'b.pdf', - preferenceKey: 'owner-a', - scrollCacheKey: 'a:pdf', - sameBytes: true - }, - { - label: 'execution owner with identical paths and bytes', - filePath: 'a.pdf', - preferenceKey: 'owner-b', - scrollCacheKey: 'a:pdf', - sameBytes: true - }, - { - label: 'scroll scope with identical paths and bytes', - filePath: 'a.pdf', - preferenceKey: 'owner-a', - scrollCacheKey: 'b:pdf', - sameBytes: true - } - ])( - 'clears the old document while loading another $label', - async ({ filePath, preferenceKey, scrollCacheKey, sameBytes }) => { - const previous = { name: 'previous' } - const previousTask = loadingTask(previous) - const nextTask = pendingTask() - getDocument.mockImplementationOnce(() => previousTask).mockImplementationOnce(() => nextTask) - const view = render( - - ) - await waitFor(() => expect(shownDocuments.at(-1)).toBe(previous)) - - view.rerender( - - ) - - expect(shownDocuments.at(-1)).toBeNull() - expect(previousTask.destroy).toHaveBeenCalledTimes(1) - expect(getDocument).toHaveBeenCalledTimes(2) - const next = { name: 'next' } - await finishTask(nextTask, next) - expect(shownDocuments.at(-1)).toBe(next) - } - ) - - it('ignores out-of-order results and destroys every superseded task once', async () => { - const first = pendingTask() - const second = pendingTask() - const third = pendingTask() - getDocument - .mockImplementationOnce(() => first) - .mockImplementationOnce(() => second) - .mockImplementationOnce(() => third) - const view = render() - view.rerender() - view.rerender() - const newest = { name: 'newest' } - await finishTask(third, newest) - await finishTask(second, { name: 'obsolete second' }) - await finishTask(first, { name: 'obsolete first' }) - - expect(shownDocuments.filter((doc) => doc !== null)).toEqual([newest]) - view.unmount() - for (const task of [first, second, third]) { - expect(task.destroy).toHaveBeenCalledTimes(1) - } - }) - - it('destroys a parsed task when closed before React commits the result', async () => { - const task = pendingTask() - getDocument.mockImplementationOnce(() => task) - const view = render() - - await act(async () => { - task.resolve({ name: 'parsed' }) - await task.promise - view.unmount() - }) - - expect(task.destroy).toHaveBeenCalledTimes(1) - }) - - it.each(['pending', 'displayed'] as const)( - 'destroys a $0 task exactly once on close', - async (phase) => { - const task = pendingTask() - getDocument.mockImplementationOnce(() => task) - const view = render() - if (phase === 'displayed') { - await finishTask(task, { name: 'displayed' }) - } - - view.unmount() - if (phase === 'pending') { - await finishTask(task, { name: 'closed' }) - } - - expect(task.destroy).toHaveBeenCalledTimes(1) - } - ) - - it('detaches before loading a replacement and restores the prior scroll and zoom', async () => { - const previous = { name: 'previous' } - const previousTask = loadingTask(previous) - let shownOnDestroy: unknown - previousTask.destroy.mockImplementation(() => { - shownOnDestroy = shownDocuments.at(-1) - return Promise.resolve() - }) - const nextTask = pendingTask() - let parsedAfterDestroy = false - getDocument - .mockImplementationOnce(() => previousTask) - .mockImplementationOnce(() => { - parsedAfterDestroy = previousTask.destroy.mock.calls.length === 1 - return nextTask - }) - const view = render( - - ) - await waitFor(() => expect(shownDocuments.at(-1)).toBe(previous)) - eventBuses.at(-1)?.dispatch('pagesinit', { scale: 1 }) - fireEvent.click(view.getByTitle('Zoom in')) - const position = { pageNumber: 7, top: 420, left: 12 } - eventBuses.at(-1)?.dispatch('updateviewarea', { scale: 1.25, location: position }) - view.rerender( - - ) - expect(shownDocuments.at(-1)).toBeNull() - expect(previousTask.destroy).toHaveBeenCalledTimes(1) - expect(parsedAfterDestroy).toBe(true) - expect(viewerSignals.at(-1)?.aborted).toBe(true) - expect(shownOnDestroy).toBeNull() - const next = { name: 'next' } - await finishTask(nextTask, next) - eventBuses.at(-1)?.dispatch('pagesinit', { scale: 1.25 }) - - expect(viewers.at(-1)?.currentScale).toBe(1.25) - expect(previousTask.destroy).toHaveBeenCalledTimes(1) - expect(viewerSignals[0]?.aborted).toBe(true) - expect(pdfViewPositionCache.get('main:pdf')).toEqual(position) - expect(scrollDestinations.at(-1)).toMatchObject({ - pageNumber: 7, - destArray: [null, { name: 'XYZ' }, 12, 420, null] - }) - view.unmount() - expect(nextTask.destroy).toHaveBeenCalledTimes(1) - expect(viewerSignals.every((signal) => signal.aborted)).toBe(true) - }) - - it('owns tasks across StrictMode effect replay', async () => { - const tasks: ReturnType[] = [] - getDocument.mockImplementation(() => { - const task = pendingTask() - tasks.push(task) - return task - }) - const view = render( - - - - ) - expect(tasks).toHaveLength(2) - const active = tasks.at(-1) - expect(active).toBeDefined() - if (active) { - await finishTask(active, { name: 'active' }) - } - - view.unmount() - for (const task of tasks) { - expect(task.destroy).toHaveBeenCalledTimes(1) - } - }) - - it('bounds active resources across 25 failed and successful rewrite cycles', async () => { - const tasks: ReturnType[] = [] - let activeTasks = 0 - let peakTasks = 0 - let peakLocalization = 0 - getDocument.mockImplementation(() => { - const index = tasks.length - const task = loadingTask(index % 2 ? 'fail' : { index }) - activeTasks += 1 - peakTasks = Math.max(peakTasks, activeTasks) - task.destroy.mockImplementation(() => { - activeTasks -= 1 - return Promise.resolve() - }) - tasks.push(task) - return task - }) - const view = render() - await waitFor(() => expect(viewers).toHaveLength(1)) - - for (let index = 0; index < 50; index += 1) { - await act(async () => { - view.rerender() - await Promise.resolve() - }) - const live = index % 2 === 0 ? 0 : 1 - expect(activeTasks).toBe(live) - expect(viewerSignals.filter((signal) => !signal.aborted)).toHaveLength(live) - peakLocalization = Math.max( - peakLocalization, - localizationResources.filter((resource) => resource.active).length - ) - expect(eventBuses.filter((bus) => bus.listenerCount() > 0)).toHaveLength(live) - if (live) { - expect(view.queryByText(ERROR_TEXT)).toBeNull() - } else { - expect(view.queryByText(ERROR_TEXT)).toBeTruthy() - } - } - - expect(peakTasks).toBe(1) - expect(peakLocalization).toBe(1) - expect(getDocument).toHaveBeenCalledTimes(51) - expect(viewers).toHaveLength(26) - view.unmount() - expect(activeTasks).toBe(0) - expect(viewerSignals.every((signal) => signal.aborted)).toBe(true) - expect(eventBuses.every((bus) => bus.listenerCount() === 0)).toBe(true) - expect(localizationResources.every((resource) => !resource.active)).toBe(true) - for (const resource of localizationResources) { - expect(resource.destroy).toHaveBeenCalledTimes(1) - } - for (const task of tasks) { - expect(task.destroy).toHaveBeenCalledTimes(1) - } - }) - - it('releases superseded tasks when asynchronous worker teardown finishes after a burst', async () => { - const tasks: ReturnType[] = [] - const finishDestroy: (() => void)[] = [] - getDocument.mockImplementation(() => { - const task = pendingTask() - task.destroy.mockImplementation( - () => - new Promise((resolve) => { - finishDestroy.push(resolve) - }) - ) - tasks.push(task) - return task - }) - const view = render() - for (let index = 0; index < 30; index += 1) { - view.rerender() - } - const newest = { name: 'newest' } - const active = tasks.at(-1) - expect(active).toBeDefined() - if (active) { - await finishTask(active, newest) - } - expect(shownDocuments.filter((doc) => doc !== null)).toEqual([newest]) - expect(viewers).toHaveLength(1) - - view.unmount() - await act(async () => { - for (const finish of finishDestroy) { - finish() - } - for (const task of tasks) { - task.resolve({ name: 'closed' }) - } - await Promise.all(tasks.map((task) => task.promise)) - }) - - expect(shownDocuments.filter((doc) => doc !== null)).toEqual([newest]) - expect(viewerSignals.every((signal) => signal.aborted)).toBe(true) - for (const task of tasks) { - expect(task.destroy).toHaveBeenCalledTimes(1) - await expect(task.destroy.mock.results[0]?.value).resolves.toBeUndefined() - } - }) -}) diff --git a/src/renderer/src/components/editor/pdf-viewer-session.ts b/src/renderer/src/components/editor/pdf-viewer-session.ts index ce439e92ac3..4b0c26c7d45 100644 --- a/src/renderer/src/components/editor/pdf-viewer-session.ts +++ b/src/renderer/src/components/editor/pdf-viewer-session.ts @@ -10,7 +10,10 @@ import { zoomPdfViewerWithWheel, type PdfScalePreference } from './pdf-scale-preference' -import { pdfViewPositionCache, setWithLRU } from '@/lib/scroll-cache' +import { + pdfViewPositionCache, + setWithLRU +} from '@/components/editor/model-lifetime/retention/editor-view-state-cache' import { buildPdfScrollDestination, clampPdfViewPosition, diff --git a/src/renderer/src/components/editor/review-note-delivery/NotesSendMenu.tsx b/src/renderer/src/components/editor/review-note-delivery/NotesSendMenu.tsx index 05d8adb700f..7b09978a250 100644 --- a/src/renderer/src/components/editor/review-note-delivery/NotesSendMenu.tsx +++ b/src/renderer/src/components/editor/review-note-delivery/NotesSendMenu.tsx @@ -1,4 +1,4 @@ -import { useAppStore } from '@/store' +import { useAppStore } from '@/store/index' import { useAppStateValue } from '@/store/retained-views/app-state-view' import type { DiffCommentOwner } from '@/store/slices/diff-comments/diff-comment-owner' import React, { useCallback, useEffect, useMemo, useState } from 'react' @@ -14,7 +14,7 @@ import { DropdownMenuTrigger } from '@/components/ui/dropdown-menu' import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip' -import { cn } from '@/lib/utils' +import { cn } from '@/lib/class-names' import { ReviewNotesSendMenuContent } from './ReviewNotesSendMenuContent' import type { DiffCommentDeliverySnapshot } from '@/store/slices/diff-comments/create-diff-comments-slice' import { diff --git a/src/renderer/src/components/editor/review-note-delivery/ReviewNotesSendMenuContent.tsx b/src/renderer/src/components/editor/review-note-delivery/ReviewNotesSendMenuContent.tsx index d4917f2b16f..40bc1576fec 100644 --- a/src/renderer/src/components/editor/review-note-delivery/ReviewNotesSendMenuContent.tsx +++ b/src/renderer/src/components/editor/review-note-delivery/ReviewNotesSendMenuContent.tsx @@ -41,7 +41,7 @@ import { } from '@/lib/agent-session/messaging/notes-send-agent-targets' import { agentKindForAgentType } from '@/lib/agent-status/aggregation/worktree-agent-status' import { formatAgentTypeLabel } from '../../../../../shared/agent-status/presentation/agent-type-label' -import { track } from '@/lib/telemetry' +import { track } from '@/diagnostics/telemetry/telemetry' import { useNow } from '@/hooks/use-now' import type { DashboardAgentRow as DashboardAgentRowData } from '@/components/dashboard/useDashboardData' import { lastEnteredDoneAt } from '@/components/dashboard/agent-finished-timestamp' diff --git a/src/renderer/src/components/editor/rich-markdown/commands/RichMarkdownSlashMenu.tsx b/src/renderer/src/components/editor/rich-markdown/commands/RichMarkdownSlashMenu.tsx index b4b609c2c8e..569e498fc17 100644 --- a/src/renderer/src/components/editor/rich-markdown/commands/RichMarkdownSlashMenu.tsx +++ b/src/renderer/src/components/editor/rich-markdown/commands/RichMarkdownSlashMenu.tsx @@ -1,7 +1,7 @@ import React from 'react' import type { Editor } from '@tiptap/react' import { Search } from 'lucide-react' -import { cn } from '@/lib/utils' +import { cn } from '@/lib/class-names' import { runSlashCommand } from './rich-markdown-slash-commands' import type { SlashCommand, diff --git a/src/renderer/src/components/editor/rich-markdown/commands/RichMarkdownToolbarButton.tsx b/src/renderer/src/components/editor/rich-markdown/commands/RichMarkdownToolbarButton.tsx index 2234e044eb8..ca9ae654ee8 100644 --- a/src/renderer/src/components/editor/rich-markdown/commands/RichMarkdownToolbarButton.tsx +++ b/src/renderer/src/components/editor/rich-markdown/commands/RichMarkdownToolbarButton.tsx @@ -1,5 +1,5 @@ import React from 'react' -import { cn } from '@/lib/utils' +import { cn } from '@/lib/class-names' import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@/components/ui/tooltip' type RichMarkdownToolbarButtonProps = { diff --git a/src/renderer/src/components/editor/rich-markdown/doc-links/RichMarkdownDocLinkMenu.tsx b/src/renderer/src/components/editor/rich-markdown/doc-links/RichMarkdownDocLinkMenu.tsx index 02d5d563c8c..1ad43bfa103 100644 --- a/src/renderer/src/components/editor/rich-markdown/doc-links/RichMarkdownDocLinkMenu.tsx +++ b/src/renderer/src/components/editor/rich-markdown/doc-links/RichMarkdownDocLinkMenu.tsx @@ -1,6 +1,6 @@ import React from 'react' import type { Editor } from '@tiptap/react' -import { cn } from '@/lib/utils' +import { cn } from '@/lib/class-names' import { commitRow } from './rich-markdown-commands' import type { DocLinkMenuRow, DocLinkMenuState } from './rich-markdown-commands' import { useTranslate } from '@/i18n/use-translate' diff --git a/src/renderer/src/components/editor/rich-markdown/document/useRichMarkdownPendingSerialization.ts b/src/renderer/src/components/editor/rich-markdown/document/useRichMarkdownPendingSerialization.ts index 0b5b011be2e..eb154c8ddb7 100644 --- a/src/renderer/src/components/editor/rich-markdown/document/useRichMarkdownPendingSerialization.ts +++ b/src/renderer/src/components/editor/rich-markdown/document/useRichMarkdownPendingSerialization.ts @@ -1,3 +1,4 @@ +import type { EditorDiscardGeneration } from '../../save/flush/editor-discard-epoch' import { useCallback, useEffect, @@ -8,7 +9,7 @@ import { } from 'react' import type { Editor } from '@tiptap/react' import { registerPendingEditorFlush } from '../../save/flush/editor-pending-flush' -import { focusLeftView, staleViewEditEpoch } from '../../save/flush/editor-stale-view-edit' +import { focusLeftView } from '../../save/flush/editor-stale-view-edit' import { commitRichMarkdownSerialization } from './rich-markdown-serialization-commit' type PendingSerializationParams = { @@ -32,15 +33,15 @@ export function useRichMarkdownPendingSerialization({ reconcileRoundTripRef }: PendingSerializationParams) { const serializeTimerRef = useRef(null) - // Why: the discard epoch when the pending edit began; a Discard since then drops it silently. - const pendingEditEpochRef = useRef(0) + // Why: the discard generation when the pending edit began; a Discard since then drops it silently. + const pendingEditGenerationRef = useRef(null) const flushPendingSerialization = useCallback((): boolean => { if (serializeTimerRef.current === null) { return false } window.clearTimeout(serializeTimerRef.current) serializeTimerRef.current = null - if (pendingEditEpochRef.current !== staleViewEditEpoch(fileId)) { + if (pendingEditGenerationRef.current?.discarded === true) { // Why: a Discard since typing began owns the text and dirty flag now. return true } @@ -91,7 +92,7 @@ export function useRichMarkdownPendingSerialization({ return { serializeTimerRef, - pendingEditEpochRef, + pendingEditGenerationRef, flushPendingSerialization, flushOnFocusLeave } diff --git a/src/renderer/src/components/editor/rich-markdown/instance/RichMarkdownEditor.tsx b/src/renderer/src/components/editor/rich-markdown/instance/RichMarkdownEditor.tsx index bb612b1978d..f1cf8b0f3b6 100644 --- a/src/renderer/src/components/editor/rich-markdown/instance/RichMarkdownEditor.tsx +++ b/src/renderer/src/components/editor/rich-markdown/instance/RichMarkdownEditor.tsx @@ -144,16 +144,20 @@ export default function RichMarkdownEditor({ worktreeRoot }) - const { serializeTimerRef, pendingEditEpochRef, flushPendingSerialization, flushOnFocusLeave } = - useRichMarkdownPendingSerialization({ - fileId, - editorRef, - lastCommittedMarkdownRef, - originalSourceRef, - baseCanonicalRef, - onContentChangeRef, - reconcileRoundTripRef - }) + const { + serializeTimerRef, + pendingEditGenerationRef, + flushPendingSerialization, + flushOnFocusLeave + } = useRichMarkdownPendingSerialization({ + fileId, + editorRef, + lastCommittedMarkdownRef, + originalSourceRef, + baseCanonicalRef, + onContentChangeRef, + reconcileRoundTripRef + }) const editor = useRichMarkdownEditorInstance({ codec, @@ -191,7 +195,7 @@ export default function RichMarkdownEditor({ cancelAutoFocusRef, fileId, serializeTimerRef, - pendingEditEpochRef, + pendingEditGenerationRef, isInitializingRef, isApplyingProgrammaticUpdateRef, markdownCommentsRef: review.markdownCommentsRef, @@ -279,7 +283,7 @@ export default function RichMarkdownEditor({ rootRef, runtimeTarget, serializeTimerRef, - pendingEditEpochRef, + pendingEditGenerationRef, slashMenuSetter: menu.setSlashMenu, worktreeId, worktreeRoot diff --git a/src/renderer/src/components/editor/rich-markdown/instance/RichMarkdownErrorBoundary.lazy-chunk.test.tsx b/src/renderer/src/components/editor/rich-markdown/instance/RichMarkdownErrorBoundary.lazy-chunk.test.tsx deleted file mode 100644 index bd5303b953c..00000000000 --- a/src/renderer/src/components/editor/rich-markdown/instance/RichMarkdownErrorBoundary.lazy-chunk.test.tsx +++ /dev/null @@ -1,109 +0,0 @@ -// @vitest-environment happy-dom - -import { Suspense, act, type ReactElement, type ReactNode } from 'react' -import { createRoot, type Root } from 'react-dom/client' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' - -import { lazyWithRetry } from '@/lib/lazy-with-retry' -import { - clearLazyChunkBreadcrumbDedupeForTest, - RichMarkdownErrorBoundary -} from './RichMarkdownErrorBoundary' - -const reportCrashMock = vi.hoisted(() => vi.fn()) -const recordBreadcrumbMock = vi.hoisted(() => vi.fn()) - -vi.mock('@/lib/react-error-boundary-reporting', () => ({ - reportReactErrorBoundaryCrash: reportCrashMock -})) - -vi.mock('@/lib/crash-breadcrumb-recorder', () => ({ - recordRendererCrashBreadcrumb: recordBreadcrumbMock -})) - -const RELOAD_GUARD_KEY = 'orca:lazy-chunk-reload-attempted' -const LANDED_RELOAD_GUARD_VALUE = 'doc-before-the-reload' - -globalThis.IS_REACT_ACT_ENVIRONMENT = true - -function createContainer(): { container: HTMLDivElement; root: Root } { - const container = document.createElement('div') - document.body.appendChild(container) - return { container, root: createRoot(container) } -} - -function BoundaryHarness({ - children, - boundaryKey = 'pane-a' -}: { - children: ReactNode - boundaryKey?: string -}): ReactElement { - return ( - Loading...
}> - - {children} - - - ) -} - -async function flushReactWork(): Promise { - await act(async () => { - await new Promise((resolve) => setTimeout(resolve, 0)) - }) -} - -const CORRUPT_CHUNK_PARSE_ERROR = "Unexpected token ':'" - -describe('RichMarkdownErrorBoundary lazy chunk containment', () => { - let root: Root | null = null - let container: HTMLDivElement | null = null - let consoleError: ReturnType - - beforeEach(() => { - reportCrashMock.mockReset() - recordBreadcrumbMock.mockReset() - clearLazyChunkBreadcrumbDedupeForTest() - window.sessionStorage.clear() - consoleError = vi.spyOn(console, 'error').mockImplementation(() => undefined) - }) - - afterEach(() => { - if (root) { - act(() => root?.unmount()) - } - container?.remove() - root = null - container = null - window.sessionStorage.clear() - consoleError.mockRestore() - }) - - it('renders the fallback without reporting after guarded dynamic import exhaustion', async () => { - window.sessionStorage.setItem(RELOAD_GUARD_KEY, LANDED_RELOAD_GUARD_VALUE) - const LazyRejectingImport = lazyWithRetry( - () => Promise.reject(new SyntaxError(CORRUPT_CHUNK_PARSE_ERROR)), - { retries: 0, reloadKey: 'rich-markdown-editor' } - ) - ;({ container, root } = createContainer()) - - await act(async () => { - root?.render( - - - - ) - }) - await flushReactWork() - await flushReactWork() - - expect(container?.textContent).toContain('rich markdown editor') - expect(reportCrashMock).not.toHaveBeenCalled() - expect(recordBreadcrumbMock).toHaveBeenCalledWith('lazy_chunk_boundary_degraded', { - boundaryId: 'editor.rich-markdown', - reloadKey: 'rich-markdown-editor', - cause: `SyntaxError: ${CORRUPT_CHUNK_PARSE_ERROR}` - }) - }) -}) diff --git a/src/renderer/src/components/editor/rich-markdown/instance/RichMarkdownErrorBoundary.tsx b/src/renderer/src/components/editor/rich-markdown/instance/RichMarkdownErrorBoundary.tsx index 00b0450cccf..74ceadcb2d4 100644 --- a/src/renderer/src/components/editor/rich-markdown/instance/RichMarkdownErrorBoundary.tsx +++ b/src/renderer/src/components/editor/rich-markdown/instance/RichMarkdownErrorBoundary.tsx @@ -1,7 +1,7 @@ import React from 'react' -import { recordRendererCrashBreadcrumb } from '@/lib/crash-breadcrumb-recorder' -import { isLazyChunkLoadError } from '@/lib/lazy-with-retry' -import { reportReactErrorBoundaryCrash } from '@/lib/react-error-boundary-reporting' +import { recordRendererCrashBreadcrumb } from '@/diagnostics/crash-reporting/crash-breadcrumb-recorder' +import { isLazyChunkLoadError } from '@/app-shell/startup/lazy-with-retry' +import { reportReactErrorBoundaryCrash } from '@/diagnostics/crash-reporting/react-error-boundary-reporting' import { translate } from '@/i18n/i18n' type Props = { diff --git a/src/renderer/src/components/editor/rich-markdown/instance/rich-markdown-editor-config.test.ts b/src/renderer/src/components/editor/rich-markdown/instance/rich-markdown-editor-config.test.ts index e305c9504b8..b8593e1e2f2 100644 --- a/src/renderer/src/components/editor/rich-markdown/instance/rich-markdown-editor-config.test.ts +++ b/src/renderer/src/components/editor/rich-markdown/instance/rich-markdown-editor-config.test.ts @@ -71,7 +71,7 @@ function createConfigParams(overrides: Partial = {}): Editor cancelAutoFocusRef: ref(null), fileId: 'file-a', serializeTimerRef: ref(null), - pendingEditEpochRef: ref(0), + pendingEditGenerationRef: ref({ discarded: false }), isInitializingRef: ref(false), isApplyingProgrammaticUpdateRef: ref(false), markdownCommentsRef: ref([]), diff --git a/src/renderer/src/components/editor/rich-markdown/instance/rich-markdown-editor-config.ts b/src/renderer/src/components/editor/rich-markdown/instance/rich-markdown-editor-config.ts index b3833891fc5..0c8b8898de8 100644 --- a/src/renderer/src/components/editor/rich-markdown/instance/rich-markdown-editor-config.ts +++ b/src/renderer/src/components/editor/rich-markdown/instance/rich-markdown-editor-config.ts @@ -1,3 +1,4 @@ +import type { EditorDiscardGeneration } from '../../save/flush/editor-discard-epoch' import { handleRichMarkdownViewportReveal } from '../viewport/rich-markdown-viewport' import type { Editor, UseEditorOptions } from '@tiptap/react' import type { EditorView } from '@tiptap/pm/view' @@ -24,7 +25,7 @@ import { type ActivateMarkdownLink } from '../links/rich-markdown-editor-click-routing' import { createRichMarkdownKeyHandler } from '../commands/rich-markdown-key-handler' -import { staleViewEditEpoch } from '../../save/flush/editor-stale-view-edit' +import { captureViewEditGeneration } from '../../save/flush/editor-stale-view-edit' import { createRichMarkdownImageResolverContext, setRichMarkdownImageResolverContext @@ -77,8 +78,8 @@ export type EditorConfigParams = { cancelAutoFocusRef: MutableRefObject<(() => void) | null> fileId: string serializeTimerRef: MutableRefObject - /** Discard epoch when the pending serialization began. */ - pendingEditEpochRef: MutableRefObject + /** Discard generation when the pending serialization began. */ + pendingEditGenerationRef: MutableRefObject isInitializingRef: MutableRefObject isApplyingProgrammaticUpdateRef: MutableRefObject markdownCommentsRef: MutableRefObject @@ -274,7 +275,7 @@ export function createRichMarkdownEditorConfig(params: EditorConfigParams): UseE if (serializeTimerRef.current !== null) { window.clearTimeout(serializeTimerRef.current) } else { - params.pendingEditEpochRef.current = staleViewEditEpoch(params.fileId) + params.pendingEditGenerationRef.current = captureViewEditGeneration(params.fileId) } serializeTimerRef.current = window.setTimeout(() => { params.flushPendingSerialization() diff --git a/src/renderer/src/components/editor/rich-markdown/instance/useRichMarkdownProgrammaticSync.test.ts b/src/renderer/src/components/editor/rich-markdown/instance/useRichMarkdownProgrammaticSync.test.ts index cd4c319527b..d497fd493b5 100644 --- a/src/renderer/src/components/editor/rich-markdown/instance/useRichMarkdownProgrammaticSync.test.ts +++ b/src/renderer/src/components/editor/rich-markdown/instance/useRichMarkdownProgrammaticSync.test.ts @@ -2,6 +2,7 @@ import { describe, expect, it, vi } from 'vitest' import { renderHook } from '@testing-library/react' import { Editor } from '@tiptap/core' +import { toast } from 'sonner' import { useRichMarkdownProgrammaticSync } from './useRichMarkdownProgrammaticSync' import { createRichMarkdownExtensions } from '../schema/rich-markdown-extensions' import { @@ -13,11 +14,8 @@ import { type RichMarkdownHtmlSuperscriptLinkContext } from '../citations/rich-markdown-html-superscript-link-context' import { encodeRawMarkdownHtmlForRichEditor } from '../raw-source/raw-markdown-html' -import { notifyStaleViewEditRejected } from '../../save/flush/editor-stale-view-edit' - -vi.mock('../../save/flush/editor-stale-view-edit', () => ({ - notifyStaleViewEditRejected: vi.fn(), - staleViewEditEpoch: vi.fn(() => 0) +vi.mock('sonner', () => ({ + toast: { error: vi.fn() } })) function buildEditor( @@ -39,7 +37,7 @@ function buildEditor( } describe('useRichMarkdownProgrammaticSync stale pending edit', () => { - function renderPane(paneText: string, pendingCommit: (() => void) | null) { + function renderPane(paneText: string, pendingCommit: boolean) { const codec = createRichMarkdownEditorCodec() const editor = buildEditor( codec, @@ -54,10 +52,13 @@ describe('useRichMarkdownProgrammaticSync stale pending edit', () => { const lastCommittedMarkdownRef = { current: 'base' } const originalSourceRef = { current: 'base' } const baseCanonicalRef = { current: 'base' } - const pendingEditEpochRef = { current: 0 } - const onContentChangeRef = { current: vi.fn<(content: string) => void>() } + const pendingEditGenerationRef = { current: { discarded: false } } + const published: string[] = [] + const onContentChangeRef = { current: (content: string) => published.push(content) } const serializeTimerRef = { - current: pendingCommit ? window.setTimeout(pendingCommit, 300) : null + current: pendingCommit + ? window.setTimeout(() => onContentChangeRef.current(paneText), 300) + : null } const hook = renderHook( ({ content }: { content: string }) => @@ -77,34 +78,30 @@ describe('useRichMarkdownProgrammaticSync stale pending edit', () => { rootRef: { current: null }, runtimeTarget: { kind: 'local' }, serializeTimerRef, - pendingEditEpochRef, + pendingEditGenerationRef, slashMenuSetter: vi.fn(), worktreeId: 'w1', worktreeRoot: null }), { initialProps: { content: 'base' } } ) - return { editor, hook, serializeTimerRef, onContentChangeRef } + return { editor, hook, published } } it('rejects a split pane pending edit once the other pane replaced the shared text', () => { vi.useFakeTimers() - vi.mocked(notifyStaleViewEditRejected).mockClear() - const commitPaneB = vi.fn() - const { editor, hook, serializeTimerRef, onContentChangeRef } = renderPane( - 'pane b', - commitPaneB - ) + vi.mocked(toast.error).mockClear() + const { editor, hook, published } = renderPane('pane b', true) try { hook.rerender({ content: 'pane a' }) vi.advanceTimersByTime(300) - expect(commitPaneB).not.toHaveBeenCalled() - expect(serializeTimerRef.current).toBeNull() - expect(notifyStaleViewEditRejected).toHaveBeenCalledExactlyOnceWith('f1', 0) + expect(toast.error).toHaveBeenCalledWith(expect.any(String), { + id: 'editor-stale-view-edit' + }) expect(editor.getMarkdown()).toBe('pane a') // Republished so the dirty flag this pane's typing raised is recomputed. - expect(onContentChangeRef.current).toHaveBeenCalledWith('pane a') + expect(published).toEqual(['pane a']) } finally { editor.destroy() vi.useRealTimers() @@ -147,7 +144,7 @@ describe('useRichMarkdownProgrammaticSync undo history', () => { rootRef: { current: null }, runtimeTarget: { kind: 'local' }, serializeTimerRef: { current: null }, - pendingEditEpochRef: { current: 0 }, + pendingEditGenerationRef: { current: { discarded: false } }, slashMenuSetter: vi.fn(), worktreeId: 'w1', worktreeRoot: null diff --git a/src/renderer/src/components/editor/rich-markdown/instance/useRichMarkdownProgrammaticSync.ts b/src/renderer/src/components/editor/rich-markdown/instance/useRichMarkdownProgrammaticSync.ts index 209081bc07e..577202e69d9 100644 --- a/src/renderer/src/components/editor/rich-markdown/instance/useRichMarkdownProgrammaticSync.ts +++ b/src/renderer/src/components/editor/rich-markdown/instance/useRichMarkdownProgrammaticSync.ts @@ -1,3 +1,4 @@ +import type { EditorDiscardGeneration } from '../../save/flush/editor-discard-epoch' import { useEffect } from 'react' import type { Dispatch, MutableRefObject, SetStateAction } from 'react' import type { Editor } from '@tiptap/react' @@ -13,10 +14,7 @@ import { } from '../images/rich-markdown-image-context' import type { RuntimeClientTarget } from '../../../../../../shared/runtime-client-target' import type { RichMarkdownEditorCodec } from '../document/rich-markdown-source-transport' -import { - notifyStaleViewEditRejected, - staleViewEditEpoch -} from '../../save/flush/editor-stale-view-edit' +import { notifyStaleViewEditRejected } from '../../save/flush/editor-stale-view-edit' type RichMarkdownProgrammaticSyncOptions = { codec: RichMarkdownEditorCodec @@ -36,7 +34,7 @@ type RichMarkdownProgrammaticSyncOptions = { runtimeTarget: RuntimeClientTarget | null /** Pending debounced commit, based on the text this view last synced. */ serializeTimerRef: MutableRefObject - pendingEditEpochRef: MutableRefObject + pendingEditGenerationRef: MutableRefObject slashMenuSetter: Dispatch> worktreeId: string worktreeRoot: string | null @@ -65,7 +63,7 @@ export function useRichMarkdownProgrammaticSync({ rootRef, runtimeTarget, serializeTimerRef, - pendingEditEpochRef, + pendingEditGenerationRef, slashMenuSetter, worktreeId, worktreeRoot @@ -117,8 +115,8 @@ export function useRichMarkdownProgrammaticSync({ if (!editor) { return } - const editEpoch = pendingEditEpochRef.current - const discarded = staleViewEditEpoch(fileId) !== editEpoch + const editGeneration = pendingEditGenerationRef.current + const discarded = editGeneration?.discarded === true const pendingTimer = serializeTimerRef.current if (content === lastCommittedMarkdownRef.current && !(pendingTimer !== null && discarded)) { return @@ -128,7 +126,7 @@ export function useRichMarkdownProgrammaticSync({ window.clearTimeout(pendingTimer) serializeTimerRef.current = null if (!discarded && !matchesSharedText) { - notifyStaleViewEditRejected(fileId, editEpoch) + notifyStaleViewEditRejected(editGeneration) } } if (matchesSharedText) { @@ -169,7 +167,7 @@ export function useRichMarkdownProgrammaticSync({ isApplyingProgrammaticUpdateRef, lastCommittedMarkdownRef, onContentChangeRef, - pendingEditEpochRef, + pendingEditGenerationRef, originalSourceRef, baseCanonicalRef, rootRef, diff --git a/src/renderer/src/components/editor/rich-markdown/schema/rich-markdown-extensions.ts b/src/renderer/src/components/editor/rich-markdown/schema/rich-markdown-extensions.ts index 6deada4d943..653b47c2f71 100644 --- a/src/renderer/src/components/editor/rich-markdown/schema/rich-markdown-extensions.ts +++ b/src/renderer/src/components/editor/rich-markdown/schema/rich-markdown-extensions.ts @@ -125,13 +125,15 @@ export function createRichMarkdownExtensions({ return ({ node, HTMLAttributes, editor }) => { // A wrapper prevents native image-byte dragging from conflicting with ProseMirror’s schema-node relocation. const dom = document.createElement('span') - // Keep the image wrapper inline so it cannot break surrounding text onto separate lines. - dom.style.display = 'inline-block' + // Inline, not inline-block: a shrink-to-fit wrapper collapses an SVG that has a viewBox but no width to 0×0. + dom.style.display = 'inline' dom.style.lineHeight = '0' - dom.style.maxWidth = '100%' const img = document.createElement('img') img.draggable = false + // Undo preflight's block, middle-aligned images so text keeps flowing around them as before. + img.style.display = 'inline-block' + img.style.verticalAlign = 'baseline' let renderedAttributeNames = new Set() const syncImageAttributes = (attributes: Record): void => { const nextNames = new Set() diff --git a/src/renderer/src/components/editor/rich-markdown/viewport/useEditorScrollRestore.ts b/src/renderer/src/components/editor/rich-markdown/viewport/useEditorScrollRestore.ts index b0b5a759580..2ec457630de 100644 --- a/src/renderer/src/components/editor/rich-markdown/viewport/useEditorScrollRestore.ts +++ b/src/renderer/src/components/editor/rich-markdown/viewport/useEditorScrollRestore.ts @@ -1,6 +1,9 @@ import { useLayoutEffect, type RefObject } from 'react' import type { Editor } from '@tiptap/react' -import { scrollTopCache, setWithLRU } from '@/lib/scroll-cache' +import { + scrollTopCache, + setWithLRU +} from '@/components/editor/model-lifetime/retention/editor-view-state-cache' export function useEditorScrollRestore( scrollContainerRef: RefObject, diff --git a/src/renderer/src/components/editor/save/flush/discard-editor-file-changes.save-race.test.ts b/src/renderer/src/components/editor/save/flush/discard-editor-file-changes.save-race.test.ts index b74dd8fd23d..5115e8936b1 100644 --- a/src/renderer/src/components/editor/save/flush/discard-editor-file-changes.save-race.test.ts +++ b/src/renderer/src/components/editor/save/flush/discard-editor-file-changes.save-race.test.ts @@ -26,12 +26,15 @@ vi.mock('@/lib/workspace/ownership/connection-context', () => ({ getConnectionIdForFile: () => undefined })) // Hold the remote capability/status round trip before bytes are sent. -const hostCheck = vi.hoisted((): { wait: Promise | null } => ({ wait: null })) +const hostCheck = vi.hoisted((): { wait: Promise | null; arrived?: () => void } => ({ + wait: null +})) vi.mock('@/runtime/files/mutations/runtime-file-mutation-client', async (importOriginal) => { const actual = await importOriginal() return { ...actual, writeRuntimeFile: async (...args: Parameters) => { + hostCheck.arrived?.() await hostCheck.wait return actual.writeRuntimeFile(...args) } @@ -100,6 +103,7 @@ describe("Don't Save against running and queued saves", () => { afterEach(() => { hostCheck.wait = null + hostCheck.arrived = undefined detach() vi.useRealTimers() __clearSelfWriteRegistryForTests() @@ -161,6 +165,35 @@ describe("Don't Save against running and queued saves", () => { expect(written()).toEqual(['a']) }) + it('never sends a stale Overwrite after discard and reopening the same file', async () => { + const waiting = gate() + const arrived = gate() + hostCheck.wait = waiting.wait + hostCheck.arrived = arrived.open + edit('discarded draft') + const saving = requestEditorFileSave({ fileId: PATH, overwrite: true }) + await vi.advanceTimersByTimeAsync(0) + await arrived.wait + const discarding = discardEditorBuffer(PATH) + store.getState().closeFile(PATH) + store.getState().openFile({ + filePath: PATH, + relativePath: 'a.ts', + worktreeId: 'wt-1', + language: 'typescript', + mode: 'edit' + }) + withLoadedBaselines(store, createFakeEditorDisk({ [PATH]: '' })) + edit('new draft') + hostCheck.wait = null + waiting.open() + const [, release] = await Promise.all([saving, discarding]) + release() + expect(disk.files.get(PATH)).toBe('') + await requestEditorFileSave({ fileId: PATH }) + expect(disk.files.get(PATH)).toBe('new draft') + }) + it('a save asked for after the discard still writes', async () => { edit('a') const release = await discardEditorBuffer(PATH) diff --git a/src/renderer/src/components/editor/save/flush/discard-editor-file-changes.ts b/src/renderer/src/components/editor/save/flush/discard-editor-file-changes.ts index 01258099529..d225765cdc1 100644 --- a/src/renderer/src/components/editor/save/flush/discard-editor-file-changes.ts +++ b/src/renderer/src/components/editor/save/flush/discard-editor-file-changes.ts @@ -1,9 +1,10 @@ import { useAppStore } from '@/store/index' import { editorBufferIdOfView, + editorBufferSiblingViewIds, isLastEditorBufferView } from '@/store/slices/editor/buffers/editor-buffer-views' -import { bumpEditorDiscardEpoch } from './editor-discard-epoch' +import { discardEditorGenerations } from './editor-discard-epoch' import { requestEditorSaveQuiesce } from '../../autosave/editor-autosave' import { flushPendingEditorBuffer } from './editor-pending-flush' @@ -14,7 +15,11 @@ export async function discardEditorBuffer(fileId: string): Promise<() => void> { return release } // Fence pending edits before flushing so intentional discards stay silent. - bumpEditorDiscardEpoch(editorBufferIdOfView(useAppStore.getState(), fileId)) + const before = useAppStore.getState() + discardEditorGenerations( + editorBufferIdOfView(before, fileId), + editorBufferSiblingViewIds(before, fileId) + ) try { flushPendingEditorBuffer(useAppStore.getState(), fileId) } catch (error) { diff --git a/src/renderer/src/components/editor/save/flush/editor-discard-epoch.ts b/src/renderer/src/components/editor/save/flush/editor-discard-epoch.ts index 0cac8e7f125..43e2c3244c3 100644 --- a/src/renderer/src/components/editor/save/flush/editor-discard-epoch.ts +++ b/src/renderer/src/components/editor/save/flush/editor-discard-epoch.ts @@ -1,13 +1,55 @@ -// Keyed by buffer record. Dirty state can be republished after a discard, so saves compare this. -const epochs = new Map() +export type EditorDiscardGeneration = { discarded: boolean } -export function editorDiscardEpoch(recordId: string): number { - return epochs.get(recordId) ?? 0 +// Pending work owns the generation; these weak lookups only let Don't Save reach it. +function generationLookup() { + const generations = new Map>() + const finalized = new FinalizationRegistry<{ + key: string + reference: WeakRef + }>(({ key, reference }) => { + if (generations.get(key) === reference) { + generations.delete(key) + } + }) + return { + capture(key: string): EditorDiscardGeneration { + const current = generations.get(key)?.deref() + if (current) { + return current + } + const generation = { discarded: false } + const reference = new WeakRef(generation) + generations.set(key, reference) + finalized.register(generation, { key, reference }) + return generation + }, + discard(key: string): void { + const current = generations.get(key)?.deref() + if (current) { + current.discarded = true + } + generations.delete(key) + } + } } -/** "Don't Save": every save requested before this writes nothing. */ -export function bumpEditorDiscardEpoch(recordId: string): void { - epochs.set(recordId, editorDiscardEpoch(recordId) + 1) +const saves = generationLookup() +const viewEdits = generationLookup() + +export function captureEditorDiscardGeneration(recordId: string): EditorDiscardGeneration { + return saves.capture(recordId) +} + +export function captureEditorViewEditGeneration(viewId: string): EditorDiscardGeneration { + return viewEdits.capture(viewId) +} + +/** "Don't Save": every operation captured before this writes nothing. */ +export function discardEditorGenerations(recordId: string, viewIds: readonly string[]): void { + saves.discard(recordId) + for (const viewId of viewIds) { + viewEdits.discard(viewId) + } } /** Thrown before sending a save that a discard voided while it waited on the host. */ diff --git a/src/renderer/src/components/editor/save/flush/editor-stale-view-edit.ts b/src/renderer/src/components/editor/save/flush/editor-stale-view-edit.ts index 9cb3d672b04..762c83a4a23 100644 --- a/src/renderer/src/components/editor/save/flush/editor-stale-view-edit.ts +++ b/src/renderer/src/components/editor/save/flush/editor-stale-view-edit.ts @@ -1,12 +1,13 @@ import { toast } from 'sonner' import { translate } from '@/i18n/i18n' -import { useAppStore } from '@/store/index' -import { editorBufferIdOfView } from '@/store/slices/editor/buffers/editor-buffer-views' -import { editorDiscardEpoch } from './editor-discard-epoch' +import { + captureEditorViewEditGeneration, + type EditorDiscardGeneration +} from './editor-discard-epoch' /** Snapshot when a delayed view edit starts; a Discard since then drops the edit silently. */ -export function staleViewEditEpoch(fileId: string): number { - return editorDiscardEpoch(editorBufferIdOfView(useAppStore.getState(), fileId)) +export function captureViewEditGeneration(fileId: string): EditorDiscardGeneration { + return captureEditorViewEditGeneration(fileId) } /** Focus moved outside the view, e.g. into another view of the same file, so its delayed edit must commit now. */ @@ -19,8 +20,8 @@ export function focusLeftView(event: { } /** A delayed view edit was dropped because the shared text changed after the edit began. */ -export function notifyStaleViewEditRejected(fileId: string, editEpoch: number): void { - if (staleViewEditEpoch(fileId) !== editEpoch) { +export function notifyStaleViewEditRejected(generation: EditorDiscardGeneration | null): void { + if (generation?.discarded) { return } toast.error( diff --git a/src/renderer/src/components/editor/save/queue/editor-save-queue.ts b/src/renderer/src/components/editor/save/queue/editor-save-queue.ts index 282f898454b..b2376882b6c 100644 --- a/src/renderer/src/components/editor/save/queue/editor-save-queue.ts +++ b/src/renderer/src/components/editor/save/queue/editor-save-queue.ts @@ -47,7 +47,7 @@ import { captureEditorSaveRequest } from './editor-save-writer-view' import { createEditorSaveSlots, type EditorSaveRequest } from './editor-save-slots' -import { EditorSaveDiscardedError, editorDiscardEpoch } from '../flush/editor-discard-epoch' +import { EditorSaveDiscardedError } from '../flush/editor-discard-epoch' import { hasEditorBytesDraft, saveEditorBytesDraft } from '../bytes/editor-bytes-documents' import { insertFinalNewlineBeforeSave } from '../transforms/editor-final-newline' @@ -103,8 +103,8 @@ export function createEditorSaveQueue(store: AppStoreApi): EditorSaveQueue { } const nothingToWrite = trigger === 'autosave' ? 'failed' : 'written' - // Check the queued record’s epoch before flushing discarded text; rejoined views may now have a different epoch. - const discarded = (): boolean => editorDiscardEpoch(request.recordId) !== request.discardEpoch + // Check the queued record’s generation before flushing discarded text; rejoined views may now have a different generation. + const discarded = (): boolean => request.discardGeneration.discarded if (discarded()) { return nothingToWrite } diff --git a/src/renderer/src/components/editor/save/queue/editor-save-slots.ts b/src/renderer/src/components/editor/save/queue/editor-save-slots.ts index 7b796312202..27adb95e21a 100644 --- a/src/renderer/src/components/editor/save/queue/editor-save-slots.ts +++ b/src/renderer/src/components/editor/save/queue/editor-save-slots.ts @@ -1,3 +1,4 @@ +import type { EditorDiscardGeneration } from '../flush/editor-discard-epoch' import type { acquireEditorFileOperation } from '@/lib/editor/file-operations/editor-file-operation-owner' import type { LocalFileAccess } from '../../../../../../shared/file-access/local-file-access' import type { EditorSaveResult, EditorSaveTrigger } from './editor-save-disk-precondition' @@ -19,10 +20,10 @@ export type EditorSaveRequest = { requestedDirty: boolean /** Preserve the saving view's kind if a different view takes over. */ requestedFromCodeView: boolean - /** The record the request was queued under; `discardEpoch` is its epoch then. */ + /** The record the request was queued under; `discardGeneration` fences its pending work. */ recordId: string /** A discard since the request voids it, whatever the trigger. */ - discardEpoch: number + discardGeneration: EditorDiscardGeneration } type SaveSlot = { @@ -56,8 +57,8 @@ export function createEditorSaveSlots( if (slot?.queued) { // Queued saves read live text, so subsequent requests can join the same write. const { request } = slot.queued - if (request.discardEpoch !== incoming.discardEpoch) { - // A discard invalidates the old request; retain the new request’s epoch and intent. + if (request.discardGeneration !== incoming.discardGeneration) { + // A discard invalidates the old request; retain the new request’s generation and intent. Object.assign(request, incoming) return slot.queued.promise } diff --git a/src/renderer/src/components/editor/save/queue/editor-save-writer-view.ts b/src/renderer/src/components/editor/save/queue/editor-save-writer-view.ts index 0e7e2edd4a5..285e73f4683 100644 --- a/src/renderer/src/components/editor/save/queue/editor-save-writer-view.ts +++ b/src/renderer/src/components/editor/save/queue/editor-save-writer-view.ts @@ -12,7 +12,7 @@ import { } from '@/store/slices/editor/buffers/editor-buffer-views' import { isCodeViewTab, type EditorSaveTrigger } from './editor-save-disk-precondition' import { canAutoSaveOpenFile } from '../../autosave/editor-autosave' -import { editorDiscardEpoch } from '../flush/editor-discard-epoch' +import { captureEditorDiscardGeneration } from '../flush/editor-discard-epoch' export function sameEditorSaveResource(state: AppState, source: OpenFile, view: OpenFile): boolean { const key = editorSaveResourceKey(source, state) @@ -129,6 +129,6 @@ export function captureEditorSaveRequest( requestedDirty: state.openFiles.some((tab) => tab.id === captured.id && tab.isDirty), requestedFromCodeView: isCodeViewTab(state, captured), recordId, - discardEpoch: editorDiscardEpoch(recordId) + discardGeneration: captureEditorDiscardGeneration(recordId) } } diff --git a/src/renderer/src/components/editor/save/transforms/editor-format-on-save.test.ts b/src/renderer/src/components/editor/save/transforms/editor-format-on-save.test.ts index 34d8f382841..93930f49129 100644 --- a/src/renderer/src/components/editor/save/transforms/editor-format-on-save.test.ts +++ b/src/renderer/src/components/editor/save/transforms/editor-format-on-save.test.ts @@ -14,7 +14,7 @@ import { __clearSelfWriteRegistryForTests } from '../../external-changes/editor- import { registerPendingEditorFlush } from '../flush/editor-pending-flush' import { usePluginPanelsStore } from '@/store/plugins/catalog/plugin-contribution-catalog' -import { bumpEditorDiscardEpoch, EditorSaveDiscardedError } from '../flush/editor-discard-epoch' +import { discardEditorGenerations, EditorSaveDiscardedError } from '../flush/editor-discard-epoch' import { editorBufferIdOfView } from '@/store/slices/editor/buffers/editor-buffer-views' vi.mock('@/lib/workspace/ownership/connection-context', () => ({ @@ -156,7 +156,7 @@ describe('format on the guarded save path', () => { const saving = queue.queueSave(file(), 'one') const rejection = expect(saving).rejects.toBeInstanceOf(EditorSaveDiscardedError) await vi.waitFor(() => expect(callRuntimeRpc).toHaveBeenCalledOnce()) - bumpEditorDiscardEpoch(editorBufferIdOfView(store.getState(), file().id)) + discardEditorGenerations(editorBufferIdOfView(store.getState(), file().id), [file().id]) finish({ kind: 'formatted', text: 'ONE' }) await rejection expect(disk.files.get('/repo/a.ts')).toBe('') diff --git a/src/renderer/src/components/editor/save/transforms/editor-save-transform-pipeline.ts b/src/renderer/src/components/editor/save/transforms/editor-save-transform-pipeline.ts index 53516666e4e..2bfae4253aa 100644 --- a/src/renderer/src/components/editor/save/transforms/editor-save-transform-pipeline.ts +++ b/src/renderer/src/components/editor/save/transforms/editor-save-transform-pipeline.ts @@ -1,7 +1,7 @@ import type { OpenFile } from '@/store/slices/editor/types/open-file' import type { AppStoreApi } from '../queue/editor-save-queue-contract' import type { EditorSaveRequest } from '../queue/editor-save-slots' -import { EditorSaveDiscardedError, editorDiscardEpoch } from '../flush/editor-discard-epoch' +import { EditorSaveDiscardedError } from '../flush/editor-discard-epoch' import { editorFormatOnSave } from './editor-format-on-save' import { editorSavePluginHook } from './editor-save-plugin-hook' @@ -23,7 +23,7 @@ export function editorSaveTransform( text, () => { operation.assertAuthorityCurrent() - if (editorDiscardEpoch(request.recordId) !== request.discardEpoch) { + if (request.discardGeneration.discarded) { throw new EditorSaveDiscardedError() } } diff --git a/src/renderer/src/components/editor/use-pdf-viewer-find-shortcut.test.tsx b/src/renderer/src/components/editor/use-pdf-viewer-find-shortcut.test.tsx deleted file mode 100644 index 03b34ea2780..00000000000 --- a/src/renderer/src/components/editor/use-pdf-viewer-find-shortcut.test.tsx +++ /dev/null @@ -1,164 +0,0 @@ -// @vitest-environment happy-dom -import { act, cleanup, render } from '@testing-library/react' -import { useContext, useRef } from 'react' -import { afterEach, describe, expect, it, vi } from 'vitest' -import { EditorCommandOwnerContext } from './editor-command-owner-context' -import { usePdfViewerFindShortcut } from './use-pdf-viewer-find-shortcut' -import { useNativeChatFind } from '../native-chat/viewport/find/use-native-chat-find' - -vi.mock('@/store', () => ({ useAppStore: { getState: () => ({ keybindings: undefined }) } })) -vi.mock('../../store', () => ({ useAppStore: { getState: () => ({ keybindings: undefined }) } })) -vi.mock('@/lib/web-client-location', () => ({ isWebClientLocation: () => false })) - -afterEach(() => { - cleanup() - document.body.replaceChildren() -}) - -function pressFind(target: EventTarget): KeyboardEvent { - const isMac = navigator.userAgent.includes('Mac') - const event = new KeyboardEvent('keydown', { - key: 'f', - code: 'KeyF', - bubbles: true, - cancelable: true, - metaKey: isMac, - ctrlKey: !isMac - }) - target.dispatchEvent(event) - return event -} - -function PdfViewerStandIn({ - name, - openFind -}: { - name: string - openFind: () => void -}): React.JSX.Element { - const rootRef = useRef(null) - const ownsCommands = useContext(EditorCommandOwnerContext) - usePdfViewerFindShortcut({ rootRef, ownsCommands, keybindings: undefined, openFind }) - return ( -
- -
- ) -} - -/** Match split-group strip/body roots with retained terminal/chat/browser overlays outside the bodies. */ -function Workspace({ - focusedGroup, - openFind -}: { - focusedGroup: 'pdf' | 'chat' | 'second-pdf' | null - openFind: Record<'pdf' | 'second-pdf', () => void> -}): React.JSX.Element { - return ( -
-
-
-
-
- -
-
- - - -
-
-
-
-
-
-