From d23e47411ae7cfcd2ce51187d3ae07ff0a95e586 Mon Sep 17 00:00:00 2001 From: Neil <4138956+nwparker@users.noreply.github.com> Date: Mon, 16 Nov 2026 14:42:12 -0800 Subject: [PATCH] refactor: organize backend agent-session and tab owners (#43268) * refactor(main): organize agent session and tab lifecycle owners * fix(ci): carry moved backend test and mobile routing metadata * test: retire copy assertions in headless notification test --- .github/workflows/macos-updater-tests.yml | 1 - .github/workflows/mobile.yml | 28 +- .github/workflows/performance-contracts.yml | 1 - config/flaky-test-pattern-baseline.txt | 5 +- config/main-layout-writer-baseline.txt | 12 +- config/main-sync-fs-baseline.txt | 2 +- config/reliability-gates.jsonc | 3 +- .../scripts/ci/sharding/ci-shard-timings.json | 71 +-- .../check-entry/mobile-test-change-scope.mjs | 13 +- .../check-compat-boundary-imports.mjs | 2 +- .../vitest-node-runtime-files.mjs | 3 - .../vitest-sqlite-runtime-scan.mjs | 2 +- .../source-routing/pr-layout-oracle-route.mjs | 10 +- config/vitest.performance.config.ts | 1 - .../structured-session-ownership.ts | 2 +- .../launch/automation-chat-session-reuse.ts | 2 +- .../claude-lifecycle-capture-batch-lead.jsonl | 28 -- .../child-work/claude-child-work-evidence.ts | 2 +- .../claude-conversation-naming.ts | 2 +- ...laude-structured-conversation-stop.test.ts | 77 ---- ...claude-structured-dispatch-test-support.ts | 76 ---- ...ude-structured-execution-recording.test.ts | 170 ------- ...ude-structured-option-confirmation.test.ts | 92 ---- .../claude-structured-requested-stop.test.ts | 87 ---- .../claude-structured-resume-point.test.ts | 189 -------- ...ed-session-acquisition-processless.test.ts | 77 ---- .../claude-structured-session-adapter.ts | 24 +- .../claude-structured-session-close.test.ts | 108 ----- .../claude-structured-session-state.ts | 12 +- .../claude-structured-session-test-support.ts | 8 +- .../claude-structured-steer-dispatch.test.ts | 82 ---- .../claude-structured-steer-handoff.test.ts | 236 ---------- .../claude-structured-dispatch-content.ts | 16 +- .../claude-structured-dispatch-waiters.ts | 2 +- .../claude-structured-dispatch.ts | 32 +- .../claude-journal-translator-contract.ts | 2 +- .../claude-plugin-input-failure-journal.ts | 2 +- ...de-structured-journal-prompt-cards.test.ts | 2 +- .../claude-structured-journal-prompts.ts | 2 +- ...ed-journal-translation-turn-timing.test.ts | 2 +- .../claude-structured-prompt-ownership.ts | 2 +- ...aude-structured-session-journal-control.ts | 2 +- .../claude-structured-acquisition-launch.ts | 2 +- .../claude-structured-launch-resolution.ts | 2 +- .../claude-structured-message-options.ts | 4 +- .../launch/claude-structured-options.ts | 2 +- ...laude-structured-provider-fallback.test.ts | 211 +-------- .../claude-kill-delivered-exit-receipt.ts | 2 +- .../claude-structured-acquisition-release.ts | 6 +- .../claude-structured-event-delivery.ts | 10 +- .../{ => lifecycle}/claude-structured-mcp.ts | 6 +- .../claude-structured-owner-identity.ts | 10 +- .../claude-structured-plugin-ui-recovery.ts | 4 +- .../claude-structured-session-acquisition.ts | 58 +-- .../claude-structured-session-close.ts | 26 +- .../claude-structured-session-event.ts | 8 +- ...laude-structured-session-exit-lifecycle.ts | 32 +- .../claude-structured-session-id.ts | 0 .../claude-full-access-policy.ts | 4 +- .../claude-structured-inbound-control.test.ts | 2 +- .../claude-structured-inbound-control.ts | 12 +- .../claude-structured-init-proof.ts | 9 +- .../claude-structured-session-open.ts | 18 +- .../claude-structured-session-publication.ts | 32 +- .../claude-structured-session-startup-exit.ts | 14 +- .../claude-structured-session-startup.test.ts | 58 +-- .../claude-structured-session-startup.ts | 24 +- .../claude-structured-start-ending.ts | 12 +- .../claude-structured-startup-outcome.ts | 2 +- ...structured-startup-settled-test-support.ts | 4 +- .../turns/claude-command-lifecycle.test.ts | 2 +- .../turns/claude-command-lifecycle.ts | 4 +- .../turns/claude-replay-turn-resolution.ts | 6 +- .../claude-structured-command-dispatch.ts | 8 +- .../claude-structured-control-actions.ts | 14 +- ...laude-structured-execution-observations.ts | 4 +- .../claude-structured-resume-point.ts | 6 +- .../structured/turns/claude-turn-activity.ts | 2 +- ...claude-conversation-worker.test-fixture.ts | 22 - ...claude-conversation-worker.test-loader.mjs | 41 -- .../claude/transcripts/claude-rewind-fork.ts | 2 +- ...claude-transcript-catch-up-test-support.ts | 266 ----------- .../claude-transcript-catch-up.test.ts | 167 ------- src/main/ipc/ai-vault/ai-vault-resume.ts | 2 +- .../register-core-handlers.ts | 2 +- .../database/journal-sql-database.ts | 2 +- .../journal-creation-fact.test.ts | 2 +- .../journal-history-items.ts | 2 +- .../journal-sql-claude-identities.test.ts | 2 +- .../journal-sql-history-items.test.ts | 2 +- .../journal-sql-stop-queue-adapters.test.ts | 101 +---- .../journal-sql-store.test.ts | 159 +------ .../journal-sql-timeline-resolution.test.ts | 111 +---- .../journal-start-failure-settlement.test.ts | 2 +- .../journal-unheld-turns-settlement.test.ts | 2 +- .../journal-writer-effects.ts | 2 +- .../journal-writer-store-mutation.ts | 2 +- .../journal-writer-store-row-changes.ts | 2 +- .../imported-agent-session-fork-tip.ts | 2 +- ...red-agent-session-failed-create-refusal.ts | 2 +- .../structured-agent-session-fork-intent.ts | 2 +- .../structured-agent-session-fork.ts | 2 +- ...ion-claude-account-routing.test-fixture.ts | 2 +- ...-agent-session-claude-echo-working.test.ts | 168 ------- ...t-session-claude-resume-exit-start.test.ts | 102 ----- ...ssion-claude-stop-contract.test-fixture.ts | 2 +- ...-agent-session-direct-sink.test-fixture.ts | 12 - ...t-session-usage-limit-chain-claude.test.ts | 188 -------- ...ed-agent-session-stale-state-settlement.ts | 2 +- ...structured-agent-session-stale-stop-row.ts | 2 +- ...ctured-agent-session-stale-turn-verdict.ts | 2 +- .../orcad-lifecycle-host.test.ts | 180 -------- .../orcad/host-lifecycle/orcad-lifecycle.ts | 2 +- src/main/pi/rpc/prompts/rpc-prompt.ts | 2 +- src/main/pi/rpc/rpc-message-dispatch.ts | 2 +- ...-session-conversation-clear-commit.test.ts | 176 -------- ...nt-session-status-cut-work.test-support.ts | 103 ----- .../agent-session-account-env.ts | 0 ...structured-fake-connection-test-fixture.ts | 178 -------- .../runtime-structured-agent-host.ts | 2 +- ...ctured-agent-runtime-registration-types.ts | 2 +- ...ructured-agent-session-attachment-sweep.ts | 6 +- ...ed-agent-session-attachment-wiring.test.ts | 24 +- ...uctured-agent-session-attachment-wiring.ts | 14 +- ...ructured-agent-session-held-signal.test.ts | 70 +-- .../structured-agent-session-host-assembly.ts | 12 +- .../structured-agent-session-host-refusal.ts | 2 +- ...d-agent-session-integration-replay.test.ts | 71 +-- .../structured-agent-session-journal-open.ts | 6 +- ...ructured-agent-session-runtime-contract.ts | 4 +- ...ructured-agent-session-runtime-teardown.ts | 8 +- .../structured-agent-session-runtime.ts | 22 +- ...tured-agent-session-transport-overrides.ts | 18 +- .../structured-claude-piped-test-support.ts | 2 +- .../structured-claude-runtime-adapter.ts | 4 +- ...ed-claude-scripted-runtime-test-support.ts | 302 ------------- .../agent-session-launch-directory.test.ts | 12 +- .../agent-session-launch-directory.ts | 12 +- .../structured-agent-launch-composition.ts | 2 +- ...laude-structured-exit-mid-response.test.ts | 71 --- ...ude-structured-failed-start-resume.test.ts | 74 --- ...e-structured-resumed-start-failure.test.ts | 90 ---- ...tured-startup-fault-is-not-an-exit.test.ts | 123 ----- .../{ => lifecycle}/pr-watch-runtime.ts | 18 +- .../pr-watch-workspace-sources.ts | 12 +- .../structured-agent-session-close.ts | 12 +- ...ctured-agent-session-dispatch-followups.ts | 4 +- ...ctured-agent-session-lifecycle-delivery.ts | 4 +- ...ructured-agent-session-mobile-attention.ts | 28 +- ...gent-session-tab-authority.test-support.ts | 4 +- ...tructured-codex-child-work-runtime.test.ts | 153 ------- ...t-session-provider-naming-shutdown.test.ts | 168 ------- .../structured-claude-naming-test-support.ts | 2 +- ...ent-session-acquisition-exit-transition.ts | 10 +- ...-session-acquisition-failure-settlement.ts | 12 +- .../agent-session-permission-backfill.test.ts | 45 +- .../agent-session-replaced-runtime.ts | 4 +- .../agent-session-reservation-admission.ts | 2 +- ...tructured-agent-session-create-adoption.ts | 34 +- .../structured-agent-session-owner-probe.ts | 10 +- ...nt-session-spawn-token-descendants.test.ts | 4 +- .../agent-session/pr-watch-runtime.test.ts | 232 ---------- .../agent-session-conversation-receipts.ts | 8 +- .../agent-session-founding-admission.ts | 2 +- .../agent-session-inventory-scale.test.ts | 200 --------- .../agent-session-operation-receipt.ts | 10 +- .../records/agent-session-record-command.ts | 2 +- .../records/agent-session-record-rows.ts | 2 +- .../agent-session-record-store-slot.ts | 2 +- ...agent-session-record-store-test-harness.ts | 2 +- .../records/agent-session-record-store.ts | 8 +- .../agent-session-rewind-completion.ts | 16 +- .../agent-session-runtime-attribution.ts | 4 +- .../agent-session-runtime-end-record.test.ts | 14 +- .../records/agent-session-store-cache.ts | 2 +- .../records/agent-session-store-command.ts | 4 +- .../records/agent-session-store-mutation.ts | 2 +- .../records/agent-session-store-row-rules.ts | 2 +- .../records/agent-session-store-state.ts | 2 +- .../agent-session-store-transactions.ts | 4 +- .../{ => records}/agent-session-tab-table.ts | 12 +- ...sion-unsaved-creation-supersession.test.ts | 12 +- ...agent-session-record-store-startup-open.ts | 2 +- ...tured-agent-session-mobile-restore.test.ts | 139 ------ ...-agent-session-startup-tab-restore.test.ts | 421 ------------------ .../structured-agent-session-close.test.ts | 182 -------- ...ession-held-identity-start-failure.test.ts | 357 --------------- ...uctured-agent-session-host-refusal.test.ts | 91 ---- ...session-legacy-send-behind-command.test.ts | 107 ----- ...t-session-runtime-provider-started.test.ts | 92 ---- .../structured-agent-session-runtime.test.ts | 110 ----- ...ed-agent-session-startup-reconcile.test.ts | 113 ----- .../browser-session-tab-selection-snapshot.ts | 2 +- .../construction/runtime-identity-state.ts | 2 +- .../paths/markdown-tab-disk-documents.ts | 2 +- .../paths/runtime-markdown-tab-operations.ts | 4 +- .../orca-runtime-test-lifecycle.spec.ts | 2 +- .../legacy-worker-runtime-recovery.ts | 2 +- .../worker-terminal-release-runtime.ts | 2 +- ...-chat-coordinator-mail-rig.test-fixture.ts | 2 +- ...rdinator-observation-clock.test-fixture.ts | 2 +- ...red-chat-dispatch-worker-lifecycle.test.ts | 236 ---------- .../structured-worker-at-rest.test.ts | 259 ----------- ...worker-request-failure-rig.test-fixture.ts | 2 +- .../runtime/rpc/methods/history/ai-vault.ts | 2 +- ...on-structured-worker-close.test-fixture.ts | 73 --- ...chestration-structured-worker-lifecycle.ts | 2 +- ...orchestration-structured-worker-session.ts | 2 +- .../follow-up/worker-follow-up-placement.ts | 2 +- .../release/worker-auto-release-turns.test.ts | 75 ---- .../readiness/failed-worker-start-teardown.ts | 2 +- .../session-tab-mutation-methods.ts | 4 +- .../structured-chat-tab-table.test-fixture.ts | 2 +- .../structured-agent-session-close-method.ts | 2 +- .../structured-agent-session-reveal.ts | 4 +- ...tured-agent-session-close-before-create.ts | 2 +- ...structured-agent-session-create-handler.ts | 2 +- .../structured-agent-session-create.ts | 4 +- .../creation/structured-agent-session-gate.ts | 2 +- ...ured-agent-session-at-rest-options.test.ts | 137 ------ ...gent-session-rest-contract-test-fixture.ts | 104 ----- ...ructured-agent-session-rpc.test-fixture.ts | 2 +- ...ctured-agent-session-paired-caller.test.ts | 4 +- ...ructured-codex-session-rpc-test-harness.ts | 2 +- .../get-agent-session-execution-namespace.ts | 2 +- .../session-graph/session-graph-promotion.ts | 12 +- .../session-graph-reload-lifecycle.ts | 2 +- .../session-graph/session-window-graph.ts | 2 +- .../close/close-mobile-row-in-main-layout.ts | 4 +- .../close/close-mobile-session-tab.ts | 6 +- ...ersisted-serve-or-ssh-owned-pty-binding.ts | 6 +- .../apply-mobile-session-tab-navigation.ts | 6 +- ...ld-headless-mobile-session-browser-tabs.ts | 6 +- ...mobile-session-browser-group-projection.ts | 2 +- ...form-mobile-session-pty-records-refresh.ts | 2 +- .../prune-mobile-session-tab-group-layout.ts | 4 +- ...le-headless-mobile-session-browser-tabs.ts | 6 +- ...time-mobile-session-result-finalization.ts | 2 +- ...terminal-tab-retirement-main-close.test.ts | 65 --- .../chat}/agent-session-tab-identity.ts | 10 +- .../chat}/agent-session-tab-layout-queue.ts | 8 +- .../chat}/agent-session-tab-layout.test.ts | 22 +- .../chat}/agent-session-tab-layout.ts | 24 +- .../background-chat-tab-publication.ts | 4 +- .../{ => chat}/restored-chat-tab-changes.ts | 16 +- .../saved-conversation-title-publication.ts | 16 +- ...tructured-agent-session-tab-close-cause.ts | 4 +- ...structured-agent-session-tab-index-seed.ts | 4 +- ...structured-agent-session-tab-retirement.ts | 8 +- .../structured-conversation-label-changes.ts | 8 +- .../structured-conversation-tab-title.ts | 6 +- .../structured-session-account-home.ts | 14 +- .../structured-session-cli-writer-host.ts | 20 +- .../structured-session-create-support.ts | 36 +- .../structured-session-renderer-close.ts | 2 +- .../structured-session-tab-close.ts | 44 +- .../structured-session-tab-presentation.ts | 20 +- .../structured-session-tab-publication.ts | 30 +- .../structured-session-tab-rename.ts | 4 +- .../structured-session-tab-restoration.ts | 34 +- .../structured-session-workspace-scope.ts | 28 +- ...ctured-workspace-authority.test-fixture.ts | 2 +- .../structured-workspace-authority.ts | 40 +- .../graph-sync-mobile-snapshot-gating.test.ts | 158 ------- ...minal-close-persistence-durability.test.ts | 73 --- .../mobile-session-inventory-base.ts | 4 +- .../session-tabs-inventory-publication.ts | 4 +- .../{ => inventory}/session-tabs-inventory.ts | 38 +- ...structured-agent-session-inventory-hold.ts | 0 .../headless-pane-move-to-new-tab.ts | 14 +- .../{ => layout}/headless-tab-group-moves.ts | 8 +- .../headless-tab-group-selection.ts | 4 +- .../{ => layout}/headless-tab-properties.ts | 19 +- .../{ => layout}/main-handle-close.ts | 10 +- .../main-layout-agent-launch-tabs.ts | 16 +- .../{ => layout}/main-layout-close-command.ts | 8 +- .../{ => layout}/main-layout-renames.ts | 14 +- .../main-layout-session-tab-move.ts | 20 +- .../main-session-tab-group-placement.ts | 4 +- .../{ => layout}/main-session-tab-order.ts | 4 +- .../{ => layout}/main-session-tab-rows.ts | 4 +- .../{ => layout}/mobile-session-tab-order.ts | 8 +- .../mobile-session-tab-selection.ts | 6 +- .../mobile-session-inventory-base.test.ts | 240 ---------- .../paired-host-terminal-close.test.ts | 196 -------- .../desktop-pane-title-forwarding.ts | 6 +- .../headless-terminal-tab-titles.ts | 4 +- .../mobile-session-snapshot-equality.ts | 2 +- .../mobile-session-snapshot-version.ts | 2 +- .../mobile-session-tab-subscriptions.ts | 8 +- .../mobile-session-tabs-delivery.ts | 6 +- ...ca-runtime-session-tabs-path-alias.test.ts | 76 +--- .../pty-backed-session-publication.ts | 22 +- .../session-tabs-change-publication.ts | 20 +- .../session-title-publisher.ts | 4 +- .../renderer-owned-tab-properties.test.ts | 192 -------- .../headless-editor-tabs.test.ts | 6 +- .../{ => restoration}/headless-editor-tabs.ts | 16 +- .../mobile-session-hydration.ts | 28 +- .../mobile-session-membership.ts | 24 +- .../mobile-session-preservation.ts | 20 +- ...mobile-session-publication-preservation.ts | 16 +- .../mobile-session-reconciliation.ts | 24 +- .../renderer-session-terminal-rescue.ts | 12 +- ...me-inventory-publication-authority.test.ts | 202 --------- .../session-tab-close-force.test.ts | 110 ----- .../session-tab-prototype-dispatch.test.ts | 61 --- .../session-tabs-headless-main-change.test.ts | 79 ---- ...session-tabs-inventory-publication.test.ts | 121 ----- .../session-tabs-inventory-test-fixture.ts | 26 -- .../session-tabs-layout-moves.test-fixture.ts | 85 ---- .../session-tabs-main-rows-parity.test.ts | 107 ----- .../session-tabs-phone-layout-moves.test.ts | 107 ----- .../session-tabs-windowed-main-change.test.ts | 137 ------ .../session-title-publisher.test.ts | 118 ----- ...rminal-close-observed-exit-test-fixture.ts | 157 ------- .../terminal-close-observed-exit.test.ts | 44 -- ...wledged-terminal-tab-retirement-fixture.ts | 22 +- ...knowledged-terminal-tab-retirement.test.ts | 4 +- .../explicit-terminal-close-pty-stops.ts | 8 +- .../explicit-terminal-close-stops.ts | 18 +- .../headless-terminal-tab-close.ts | 28 +- .../paired-host-terminal-close.ts | 8 +- ...rminal-retirement-async-durability.test.ts | 30 +- .../terminal-surface-retirements.ts | 26 +- .../driver/terminal-driver-resources.ts | 2 +- .../identity/preallocated-terminal-handles.ts | 2 +- .../terminal/launch/mobile-terminal-create.ts | 2 +- .../launch/mobile-terminal-owned-create.ts | 2 +- .../runtime/terminal/launch/terminal-split.ts | 2 +- .../surface/main-terminal-surfaces.ts | 6 +- .../surface/terminal-surface-index.ts | 2 +- .../wsl-distro-loss-exit-retention.test.ts | 2 +- .../view/renderer-terminal-snapshot.ts | 2 +- .../wait/terminal-interactive-wait.ts | 2 +- .../workspace-process-listing.ts | 8 +- .../structured-session-worktree-teardown.ts | 2 +- .../runtime-workspace-sleep-operations.ts | 2 +- .../workspace-host-notifications.ts | 4 +- .../main-process-quit-pending-writer.test.ts | 212 --------- .../main-process-quit-update-veto.test.ts | 118 ----- src/main/startup/quit/main-process-quit.ts | 4 +- .../window/attach-main-window-services.ts | 2 +- .../__tests__/wsl-orcad-midturn-stop-lane.ts | 2 +- .../wsl-orcad-structured-chat-contract.ts | 2 +- ...uctured-agent-session-surface-execution.ts | 4 +- ...e-chat-startup-option-pickers.unit.test.ts | 180 -------- ...le-session-active-publication.unit.test.ts | 128 ------ ...d-attention-headless-delivery.unit.test.ts | 69 --- ...attention-read-retirement.test-fixture.tsx | 2 +- .../structured-chat-tabs-open-close.spec.ts | 187 -------- 351 files changed, 1102 insertions(+), 11934 deletions(-) delete mode 100644 src/main/claude/__fixtures__/claude-lifecycle-capture-batch-lead.jsonl delete mode 100644 src/main/claude/structured/claude-structured-conversation-stop.test.ts delete mode 100644 src/main/claude/structured/claude-structured-dispatch-test-support.ts delete mode 100644 src/main/claude/structured/claude-structured-execution-recording.test.ts delete mode 100644 src/main/claude/structured/claude-structured-option-confirmation.test.ts delete mode 100644 src/main/claude/structured/claude-structured-requested-stop.test.ts delete mode 100644 src/main/claude/structured/claude-structured-resume-point.test.ts delete mode 100644 src/main/claude/structured/claude-structured-session-acquisition-processless.test.ts delete mode 100644 src/main/claude/structured/claude-structured-session-close.test.ts delete mode 100644 src/main/claude/structured/claude-structured-steer-dispatch.test.ts delete mode 100644 src/main/claude/structured/claude-structured-steer-handoff.test.ts rename src/main/claude/structured/{ => dispatch}/claude-structured-dispatch-content.ts (91%) rename src/main/claude/structured/{ => dispatch}/claude-structured-dispatch-waiters.ts (94%) rename src/main/claude/structured/{ => dispatch}/claude-structured-dispatch.ts (81%) rename src/main/claude/structured/{ => lifecycle}/claude-kill-delivered-exit-receipt.ts (78%) rename src/main/claude/structured/{ => lifecycle}/claude-structured-acquisition-release.ts (89%) rename src/main/claude/structured/{ => lifecycle}/claude-structured-event-delivery.ts (87%) rename src/main/claude/structured/{ => lifecycle}/claude-structured-mcp.ts (93%) rename src/main/claude/structured/{ => lifecycle}/claude-structured-owner-identity.ts (71%) rename src/main/claude/structured/{ => lifecycle}/claude-structured-plugin-ui-recovery.ts (95%) rename src/main/claude/structured/{ => lifecycle}/claude-structured-session-acquisition.ts (81%) rename src/main/claude/structured/{ => lifecycle}/claude-structured-session-close.ts (88%) rename src/main/claude/structured/{ => lifecycle}/claude-structured-session-event.ts (84%) rename src/main/claude/structured/{ => lifecycle}/claude-structured-session-exit-lifecycle.ts (87%) rename src/main/claude/structured/{ => lifecycle}/claude-structured-session-id.ts (100%) rename src/main/claude/structured/{ => permissions}/claude-full-access-policy.ts (97%) rename src/main/claude/structured/{ => permissions}/claude-structured-inbound-control.test.ts (96%) rename src/main/claude/structured/{ => permissions}/claude-structured-inbound-control.ts (91%) rename src/main/claude/structured/{ => startup}/claude-structured-init-proof.ts (92%) rename src/main/claude/structured/{ => startup}/claude-structured-session-open.ts (84%) rename src/main/claude/structured/{ => startup}/claude-structured-session-publication.ts (83%) rename src/main/claude/structured/{ => startup}/claude-structured-session-startup-exit.ts (76%) rename src/main/claude/structured/{ => startup}/claude-structured-session-startup.test.ts (54%) rename src/main/claude/structured/{ => startup}/claude-structured-session-startup.ts (90%) rename src/main/claude/structured/{ => startup}/claude-structured-start-ending.ts (84%) rename src/main/claude/structured/{ => startup}/claude-structured-startup-outcome.ts (96%) rename src/main/claude/structured/{ => startup}/claude-structured-startup-settled-test-support.ts (95%) rename src/main/claude/structured/{ => turns}/claude-structured-command-dispatch.ts (75%) rename src/main/claude/structured/{ => turns}/claude-structured-control-actions.ts (90%) rename src/main/claude/structured/{ => turns}/claude-structured-execution-observations.ts (92%) rename src/main/claude/structured/{ => turns}/claude-structured-resume-point.ts (94%) delete mode 100644 src/main/claude/transcripts/claude-conversation-worker.test-fixture.ts delete mode 100644 src/main/claude/transcripts/claude-conversation-worker.test-loader.mjs delete mode 100644 src/main/claude/transcripts/claude-transcript-catch-up-test-support.ts delete mode 100644 src/main/claude/transcripts/claude-transcript-catch-up.test.ts delete mode 100644 src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-claude-echo-working.test.ts delete mode 100644 src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-claude-resume-exit-start.test.ts delete mode 100644 src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-direct-sink.test-fixture.ts delete mode 100644 src/main/native-chat/agent-session-wire/recovery/structured-agent-session-usage-limit-chain-claude.test.ts delete mode 100644 src/main/orcad/host-lifecycle/orcad-lifecycle-host.test.ts delete mode 100644 src/main/runtime/agent-session/agent-session-conversation-clear-commit.test.ts delete mode 100644 src/main/runtime/agent-session/agent-session-status-cut-work.test-support.ts rename src/main/runtime/agent-session/{ => environment}/agent-session-account-env.ts (100%) delete mode 100644 src/main/runtime/agent-session/installation/claude-structured-fake-connection-test-fixture.ts rename src/main/runtime/agent-session/{ => installation}/structured-agent-session-attachment-sweep.ts (83%) rename src/main/runtime/agent-session/{ => installation}/structured-agent-session-attachment-wiring.test.ts (54%) rename src/main/runtime/agent-session/{ => installation}/structured-agent-session-attachment-wiring.ts (71%) rename src/main/runtime/agent-session/{ => installation}/structured-agent-session-held-signal.test.ts (54%) rename src/main/runtime/agent-session/{ => installation}/structured-agent-session-host-refusal.ts (95%) rename src/main/runtime/agent-session/{ => installation}/structured-agent-session-integration-replay.test.ts (58%) rename src/main/runtime/agent-session/{ => installation}/structured-agent-session-journal-open.ts (86%) rename src/main/runtime/agent-session/{ => installation}/structured-agent-session-runtime-teardown.ts (85%) rename src/main/runtime/agent-session/{ => installation}/structured-agent-session-runtime.ts (85%) rename src/main/runtime/agent-session/{ => installation}/structured-agent-session-transport-overrides.ts (60%) delete mode 100644 src/main/runtime/agent-session/installation/structured-claude-scripted-runtime-test-support.ts rename src/main/runtime/agent-session/{ => launch}/agent-session-launch-directory.test.ts (86%) rename src/main/runtime/agent-session/{ => launch}/agent-session-launch-directory.ts (76%) delete mode 100644 src/main/runtime/agent-session/lifecycle/claude-structured-exit-mid-response.test.ts delete mode 100644 src/main/runtime/agent-session/lifecycle/claude-structured-failed-start-resume.test.ts delete mode 100644 src/main/runtime/agent-session/lifecycle/claude-structured-resumed-start-failure.test.ts delete mode 100644 src/main/runtime/agent-session/lifecycle/claude-structured-startup-fault-is-not-an-exit.test.ts rename src/main/runtime/agent-session/{ => lifecycle}/pr-watch-runtime.ts (82%) rename src/main/runtime/agent-session/{ => lifecycle}/pr-watch-workspace-sources.ts (73%) rename src/main/runtime/agent-session/{ => lifecycle}/structured-agent-session-close.ts (90%) rename src/main/runtime/agent-session/{ => lifecycle}/structured-agent-session-dispatch-followups.ts (79%) rename src/main/runtime/agent-session/{ => lifecycle}/structured-agent-session-lifecycle-delivery.ts (91%) rename src/main/runtime/agent-session/{ => lifecycle}/structured-agent-session-mobile-attention.ts (80%) delete mode 100644 src/main/runtime/agent-session/lifecycle/structured-codex-child-work-runtime.test.ts delete mode 100644 src/main/runtime/agent-session/naming/structured-agent-session-provider-naming-shutdown.test.ts rename src/main/runtime/agent-session/{ => ownership}/agent-session-acquisition-exit-transition.ts (79%) rename src/main/runtime/agent-session/{ => ownership}/agent-session-acquisition-failure-settlement.ts (91%) rename src/main/runtime/agent-session/{ => ownership}/agent-session-replaced-runtime.ts (90%) rename src/main/runtime/agent-session/{ => ownership}/structured-agent-session-create-adoption.ts (85%) rename src/main/runtime/agent-session/{ => ownership}/structured-agent-session-owner-probe.ts (87%) delete mode 100644 src/main/runtime/agent-session/pr-watch-runtime.test.ts rename src/main/runtime/agent-session/{ => records}/agent-session-conversation-receipts.ts (62%) delete mode 100644 src/main/runtime/agent-session/records/agent-session-inventory-scale.test.ts rename src/main/runtime/agent-session/{ => records}/agent-session-operation-receipt.ts (64%) rename src/main/runtime/agent-session/{ => records}/agent-session-rewind-completion.ts (77%) rename src/main/runtime/agent-session/{ => records}/agent-session-runtime-attribution.ts (92%) rename src/main/runtime/agent-session/{ => records}/agent-session-tab-table.ts (93%) rename src/main/runtime/agent-session/{ => records}/agent-session-unsaved-creation-supersession.test.ts (84%) delete mode 100644 src/main/runtime/agent-session/records/structured-agent-session-mobile-restore.test.ts delete mode 100644 src/main/runtime/agent-session/records/structured-agent-session-startup-tab-restore.test.ts delete mode 100644 src/main/runtime/agent-session/structured-agent-session-close.test.ts delete mode 100644 src/main/runtime/agent-session/structured-agent-session-held-identity-start-failure.test.ts delete mode 100644 src/main/runtime/agent-session/structured-agent-session-host-refusal.test.ts delete mode 100644 src/main/runtime/agent-session/structured-agent-session-legacy-send-behind-command.test.ts delete mode 100644 src/main/runtime/agent-session/structured-agent-session-runtime-provider-started.test.ts delete mode 100644 src/main/runtime/agent-session/structured-agent-session-runtime.test.ts delete mode 100644 src/main/runtime/agent-session/structured-agent-session-startup-reconcile.test.ts delete mode 100644 src/main/runtime/orchestration/terminal-authority/structured-sessions/structured-chat-dispatch-worker-lifecycle.test.ts delete mode 100644 src/main/runtime/orchestration/terminal-authority/structured-sessions/structured-worker-at-rest.test.ts delete mode 100644 src/main/runtime/rpc/methods/orchestration/structured-workers/orchestration-structured-worker-close.test-fixture.ts delete mode 100644 src/main/runtime/rpc/methods/orchestration/worker/release/worker-auto-release-turns.test.ts delete mode 100644 src/main/runtime/rpc/methods/structured-sessions/protocol/structured-agent-session-at-rest-options.test.ts delete mode 100644 src/main/runtime/rpc/methods/structured-sessions/protocol/structured-agent-session-rest-contract-test-fixture.ts rename src/main/runtime/{agent-session => rpc/methods/structured-sessions}/structured-agent-session-paired-caller.test.ts (92%) delete mode 100644 src/main/runtime/session-tabs/acknowledged-terminal-tab-retirement-main-close.test.ts rename src/main/runtime/{agent-session => session-tabs/chat}/agent-session-tab-identity.ts (91%) rename src/main/runtime/{agent-session => session-tabs/chat}/agent-session-tab-layout-queue.ts (91%) rename src/main/runtime/{agent-session => session-tabs/chat}/agent-session-tab-layout.test.ts (80%) rename src/main/runtime/{agent-session => session-tabs/chat}/agent-session-tab-layout.ts (80%) rename src/main/runtime/session-tabs/{ => chat}/background-chat-tab-publication.ts (74%) rename src/main/runtime/session-tabs/{ => chat}/restored-chat-tab-changes.ts (83%) rename src/main/runtime/session-tabs/{ => chat}/saved-conversation-title-publication.ts (86%) rename src/main/runtime/{agent-session => session-tabs/chat}/structured-agent-session-tab-close-cause.ts (59%) rename src/main/runtime/{agent-session => session-tabs/chat}/structured-agent-session-tab-index-seed.ts (84%) rename src/main/runtime/{agent-session => session-tabs/chat}/structured-agent-session-tab-retirement.ts (82%) rename src/main/runtime/session-tabs/{ => chat}/structured-conversation-label-changes.ts (91%) rename src/main/runtime/session-tabs/{ => chat}/structured-conversation-tab-title.ts (86%) rename src/main/runtime/session-tabs/{ => chat}/structured-session-account-home.ts (83%) rename src/main/runtime/session-tabs/{ => chat}/structured-session-cli-writer-host.ts (75%) rename src/main/runtime/session-tabs/{ => chat}/structured-session-create-support.ts (86%) rename src/main/runtime/{agent-session => session-tabs/chat}/structured-session-renderer-close.ts (83%) rename src/main/runtime/session-tabs/{ => chat}/structured-session-tab-close.ts (86%) rename src/main/runtime/session-tabs/{ => chat}/structured-session-tab-presentation.ts (80%) rename src/main/runtime/session-tabs/{ => chat}/structured-session-tab-publication.ts (86%) rename src/main/runtime/session-tabs/{ => chat}/structured-session-tab-rename.ts (83%) rename src/main/runtime/session-tabs/{ => chat}/structured-session-tab-restoration.ts (87%) rename src/main/runtime/session-tabs/{ => chat}/structured-session-workspace-scope.ts (84%) rename src/main/runtime/session-tabs/{ => chat}/structured-workspace-authority.test-fixture.ts (79%) rename src/main/runtime/session-tabs/{ => chat}/structured-workspace-authority.ts (79%) delete mode 100644 src/main/runtime/session-tabs/graph-sync-mobile-snapshot-gating.test.ts delete mode 100644 src/main/runtime/session-tabs/host-terminal-close-persistence-durability.test.ts rename src/main/runtime/session-tabs/{ => inventory}/mobile-session-inventory-base.ts (93%) rename src/main/runtime/session-tabs/{ => inventory}/session-tabs-inventory-publication.ts (92%) rename src/main/runtime/session-tabs/{ => inventory}/session-tabs-inventory.ts (89%) rename src/main/runtime/{agent-session => session-tabs/inventory}/structured-agent-session-inventory-hold.ts (100%) rename src/main/runtime/session-tabs/{ => layout}/headless-pane-move-to-new-tab.ts (91%) rename src/main/runtime/session-tabs/{ => layout}/headless-tab-group-moves.ts (96%) rename src/main/runtime/session-tabs/{ => layout}/headless-tab-group-selection.ts (76%) rename src/main/runtime/session-tabs/{ => layout}/headless-tab-properties.ts (93%) rename src/main/runtime/session-tabs/{ => layout}/main-handle-close.ts (85%) rename src/main/runtime/session-tabs/{ => layout}/main-layout-agent-launch-tabs.ts (88%) rename src/main/runtime/session-tabs/{ => layout}/main-layout-close-command.ts (91%) rename src/main/runtime/session-tabs/{ => layout}/main-layout-renames.ts (91%) rename src/main/runtime/session-tabs/{ => layout}/main-layout-session-tab-move.ts (82%) rename src/main/runtime/session-tabs/{ => layout}/main-session-tab-group-placement.ts (89%) rename src/main/runtime/session-tabs/{ => layout}/main-session-tab-order.ts (94%) rename src/main/runtime/session-tabs/{ => layout}/main-session-tab-rows.ts (97%) rename src/main/runtime/session-tabs/{ => layout}/mobile-session-tab-order.ts (91%) rename src/main/runtime/session-tabs/{ => layout}/mobile-session-tab-selection.ts (95%) delete mode 100644 src/main/runtime/session-tabs/mobile-session-inventory-base.test.ts delete mode 100644 src/main/runtime/session-tabs/paired-host-terminal-close.test.ts rename src/main/runtime/session-tabs/{ => publication}/desktop-pane-title-forwarding.ts (82%) rename src/main/runtime/session-tabs/{ => publication}/headless-terminal-tab-titles.ts (86%) rename src/main/runtime/session-tabs/{ => publication}/mobile-session-snapshot-equality.ts (98%) rename src/main/runtime/session-tabs/{ => publication}/mobile-session-snapshot-version.ts (93%) rename src/main/runtime/session-tabs/{ => publication}/mobile-session-tab-subscriptions.ts (91%) rename src/main/runtime/session-tabs/{ => publication}/mobile-session-tabs-delivery.ts (92%) rename src/main/runtime/session-tabs/{ => publication}/orca-runtime-session-tabs-path-alias.test.ts (54%) rename src/main/runtime/session-tabs/{ => publication}/pty-backed-session-publication.ts (90%) rename src/main/runtime/session-tabs/{ => publication}/session-tabs-change-publication.ts (92%) rename src/main/runtime/session-tabs/{ => publication}/session-title-publisher.ts (91%) delete mode 100644 src/main/runtime/session-tabs/renderer-owned-tab-properties.test.ts rename src/main/runtime/session-tabs/{ => restoration}/headless-editor-tabs.test.ts (92%) rename src/main/runtime/session-tabs/{ => restoration}/headless-editor-tabs.ts (93%) rename src/main/runtime/session-tabs/{ => restoration}/mobile-session-hydration.ts (91%) rename src/main/runtime/session-tabs/{ => restoration}/mobile-session-membership.ts (85%) rename src/main/runtime/session-tabs/{ => restoration}/mobile-session-preservation.ts (91%) rename src/main/runtime/session-tabs/{ => restoration}/mobile-session-publication-preservation.ts (92%) rename src/main/runtime/session-tabs/{ => restoration}/mobile-session-reconciliation.ts (92%) rename src/main/runtime/session-tabs/{ => restoration}/renderer-session-terminal-rescue.ts (92%) delete mode 100644 src/main/runtime/session-tabs/runtime-inventory-publication-authority.test.ts delete mode 100644 src/main/runtime/session-tabs/session-tab-close-force.test.ts delete mode 100644 src/main/runtime/session-tabs/session-tab-prototype-dispatch.test.ts delete mode 100644 src/main/runtime/session-tabs/session-tabs-headless-main-change.test.ts delete mode 100644 src/main/runtime/session-tabs/session-tabs-inventory-publication.test.ts delete mode 100644 src/main/runtime/session-tabs/session-tabs-inventory-test-fixture.ts delete mode 100644 src/main/runtime/session-tabs/session-tabs-layout-moves.test-fixture.ts delete mode 100644 src/main/runtime/session-tabs/session-tabs-main-rows-parity.test.ts delete mode 100644 src/main/runtime/session-tabs/session-tabs-phone-layout-moves.test.ts delete mode 100644 src/main/runtime/session-tabs/session-tabs-windowed-main-change.test.ts delete mode 100644 src/main/runtime/session-tabs/session-title-publisher.test.ts delete mode 100644 src/main/runtime/session-tabs/terminal-close-observed-exit-test-fixture.ts delete mode 100644 src/main/runtime/session-tabs/terminal-close-observed-exit.test.ts rename src/main/runtime/session-tabs/{ => terminal-retirement}/acknowledged-terminal-tab-retirement-fixture.ts (85%) rename src/main/runtime/session-tabs/{ => terminal-retirement}/acknowledged-terminal-tab-retirement.test.ts (92%) rename src/main/runtime/session-tabs/{ => terminal-retirement}/explicit-terminal-close-pty-stops.ts (86%) rename src/main/runtime/session-tabs/{ => terminal-retirement}/explicit-terminal-close-stops.ts (93%) rename src/main/runtime/session-tabs/{ => terminal-retirement}/headless-terminal-tab-close.ts (88%) rename src/main/runtime/session-tabs/{ => terminal-retirement}/paired-host-terminal-close.ts (91%) rename src/main/runtime/session-tabs/{ => terminal-retirement}/terminal-retirement-async-durability.test.ts (51%) rename src/main/runtime/session-tabs/{ => terminal-retirement}/terminal-surface-retirements.ts (87%) delete mode 100644 src/main/startup/quit/main-process-quit-pending-writer.test.ts delete mode 100644 src/main/startup/quit/main-process-quit-update-veto.test.ts delete mode 100644 tests/e2e/native-chat-startup-option-pickers.unit.test.ts delete mode 100644 tests/e2e/session-tabs/mobile-session-active-publication.unit.test.ts delete mode 100644 tests/e2e/structured-attention-headless-delivery.unit.test.ts delete mode 100644 tests/e2e/structured-chat-tabs-open-close.spec.ts diff --git a/.github/workflows/macos-updater-tests.yml b/.github/workflows/macos-updater-tests.yml index ae6eee94d3b..d48a8858094 100644 --- a/.github/workflows/macos-updater-tests.yml +++ b/.github/workflows/macos-updater-tests.yml @@ -55,4 +55,3 @@ jobs: src/main/updater/mac-install/updater.mac-install.test.ts src/main/updater/updater.headless-serve-install.test.ts src/main/updater/mac-install/updater-mac-quit-guard.test.ts - src/main/startup/quit/main-process-quit-update-veto.test.ts diff --git a/.github/workflows/mobile.yml b/.github/workflows/mobile.yml index 05e3ee482de..06cbed8bb6f 100644 --- a/.github/workflows/mobile.yml +++ b/.github/workflows/mobile.yml @@ -21,17 +21,13 @@ on: - 'src/main/runtime/rpc/server/runtime-rpc.ts' - 'src/main/runtime/rpc/server/pairing/device-registry.ts' - 'src/main/runtime/orca-runtime.ts' - - 'src/main/runtime/agent-session/agent-session-*.ts' + - 'src/main/runtime/agent-session/environment/agent-session-account-env.ts' + - 'src/main/runtime/agent-session/launch/agent-session-launch-directory.ts' + - 'src/main/runtime/session-tabs/chat/agent-session-tab-identity.ts' + - 'src/main/runtime/session-tabs/chat/agent-session-tab-layout-queue.ts' + - 'src/main/runtime/session-tabs/chat/agent-session-tab-layout.ts' - 'src/main/runtime/agent-session/ownership/agent-session-*.ts' - 'src/main/runtime/agent-session/records/agent-session-*.ts' - - 'src/main/runtime/agent-session/agent-session-account-*.ts' - - 'src/main/runtime/agent-session/agent-session-acquisition-*.ts' - - 'src/main/runtime/agent-session/agent-session-conversation-*.ts' - - 'src/main/runtime/agent-session/agent-session-launch-*.ts' - - 'src/main/runtime/agent-session/agent-session-operation-*.ts' - - 'src/main/runtime/agent-session/agent-session-rewind-*.ts' - - 'src/main/runtime/agent-session/agent-session-runtime-*.ts' - - 'src/main/runtime/agent-session/agent-session-unsaved-*.ts' # The phone/host contract program's unmocked desktop sources and its declaration owner's inputs. - 'src/main/runtime/integrations/github/runtime-github-repository-query-commands.ts' - 'src/main/github/issues/issue-field-options.ts' @@ -152,17 +148,13 @@ on: - 'src/main/runtime/rpc/server/runtime-rpc.ts' - 'src/main/runtime/rpc/server/pairing/device-registry.ts' - 'src/main/runtime/orca-runtime.ts' - - 'src/main/runtime/agent-session/agent-session-*.ts' + - 'src/main/runtime/agent-session/environment/agent-session-account-env.ts' + - 'src/main/runtime/agent-session/launch/agent-session-launch-directory.ts' + - 'src/main/runtime/session-tabs/chat/agent-session-tab-identity.ts' + - 'src/main/runtime/session-tabs/chat/agent-session-tab-layout-queue.ts' + - 'src/main/runtime/session-tabs/chat/agent-session-tab-layout.ts' - 'src/main/runtime/agent-session/ownership/agent-session-*.ts' - 'src/main/runtime/agent-session/records/agent-session-*.ts' - - 'src/main/runtime/agent-session/agent-session-account-*.ts' - - 'src/main/runtime/agent-session/agent-session-acquisition-*.ts' - - 'src/main/runtime/agent-session/agent-session-conversation-*.ts' - - 'src/main/runtime/agent-session/agent-session-launch-*.ts' - - 'src/main/runtime/agent-session/agent-session-operation-*.ts' - - 'src/main/runtime/agent-session/agent-session-rewind-*.ts' - - 'src/main/runtime/agent-session/agent-session-runtime-*.ts' - - 'src/main/runtime/agent-session/agent-session-unsaved-*.ts' # The phone/host contract program's unmocked desktop sources and its declaration owner's inputs. - 'src/main/runtime/integrations/github/runtime-github-repository-query-commands.ts' - 'src/main/github/issues/issue-field-options.ts' diff --git a/.github/workflows/performance-contracts.yml b/.github/workflows/performance-contracts.yml index c7dd6a802b5..12b883ce691 100644 --- a/.github/workflows/performance-contracts.yml +++ b/.github/workflows/performance-contracts.yml @@ -18,7 +18,6 @@ on: - '**/*.performance.test.tsx' # Contracts without the .performance suffix. Keep in sync with config/vitest.performance.config.ts; # without these a rename lands green and only breaks the next nightly. - - 'src/main/runtime/session-tabs/session-tabs-phone-layout-moves.test.ts' - 'src/renderer/src/components/agent/launch-menu/use-new-tab-agent-menu-host-preferences.test.tsx' - 'src/main/codex-usage/codex-rollout-file-lifetime.test.ts' - 'src/main/codex-usage/scanner-incremental-append.test.ts' diff --git a/config/flaky-test-pattern-baseline.txt b/config/flaky-test-pattern-baseline.txt index 31a63970f6a..6dacbb3d5d3 100644 --- a/config/flaky-test-pattern-baseline.txt +++ b/config/flaky-test-pattern-baseline.txt @@ -148,7 +148,6 @@ 1 test-no-real-time-wait:src/main/pty/process-retirement/node-pty-master-fd-retirement.test.ts 1 test-no-real-time-wait:src/main/pty/process-retirement/posix-pty-process-groups.integration.test.ts 5 test-no-real-time-wait:src/main/pty/process-retirement/windows-live-tree-kill.win32.test.ts -1 test-no-real-time-wait:src/main/runtime/agent-session/structured-agent-session-legacy-send-behind-command.test.ts 3 test-no-real-time-wait:src/main/runtime/orchestration/mailbox/terminal-pointer/orchestration-codex-real-pty.integration.test.ts 1 test-no-real-time-wait:src/main/runtime/rpc/terminal/terminal-subscribe-mounted-pane.test.ts 1 test-no-real-time-wait:src/main/runtime/terminal/wait/launched-agent-crash-guard.live-shell.test.ts @@ -389,8 +388,7 @@ 1 test-no-wall-clock:src/main/rate-limits/service/service-cursor-usage.test.ts 1 test-no-wall-clock:src/main/rate-limits/service/service-minimax-usage.test.ts 3 test-no-wall-clock:src/main/rate-limits/service/service-zcode-usage.test.ts -1 test-no-wall-clock:src/main/runtime/agent-session/lifecycle/structured-codex-child-work-runtime.test.ts -2 test-no-wall-clock:src/main/runtime/agent-session/structured-agent-session-held-signal.test.ts +1 test-no-wall-clock:src/main/runtime/agent-session/installation/structured-agent-session-held-signal.test.ts 1 test-no-wall-clock:src/main/runtime/mobile-cloud-relay/testing/mobile-relay-e2ee.integration.test.ts 2 test-no-wall-clock:src/main/runtime/orchestration/mailbox/terminal-pointer/orchestration-codex-real-pty.integration.test.ts 1 test-no-wall-clock:src/main/runtime/push/push-registration-rpc.test.ts @@ -679,7 +677,6 @@ 1 test-timeout-needs-reason:tests/e2e/ssh-orcad-windows-cli-matrix.spec.ts 4 test-timeout-needs-reason:tests/e2e/ssh-orcad-workspace-tools.spec.ts 1 test-timeout-needs-reason:tests/e2e/staging-skill-sharing.spec.ts -1 test-timeout-needs-reason:tests/e2e/structured-chat-tabs-open-close.spec.ts 1 test-timeout-needs-reason:tests/e2e/terminal-cli-split-closed-before-mount.spec.ts 6 test-timeout-needs-reason:tests/e2e/terminal-column-desync-repro.spec.ts 1 test-timeout-needs-reason:tests/e2e/terminal-inline-images-memory.spec.ts diff --git a/config/main-layout-writer-baseline.txt b/config/main-layout-writer-baseline.txt index e9eeb661ea1..f24c64d75f5 100644 --- a/config/main-layout-writer-baseline.txt +++ b/config/main-layout-writer-baseline.txt @@ -60,12 +60,12 @@ 2 src/main/runtime/session-graph/session-graph-promotion.ts 2 src/main/runtime/session-lifecycle/projection/apply-mobile-session-tab-navigation.ts 2 src/main/runtime/session-lifecycle/projection/build-headless-mobile-session-browser-tabs.ts -1 src/main/runtime/session-tabs/headless-editor-tabs.ts -2 src/main/runtime/session-tabs/headless-tab-group-moves.ts -6 src/main/runtime/session-tabs/headless-tab-properties.ts -2 src/main/runtime/session-tabs/headless-terminal-tab-titles.ts -1 src/main/runtime/session-tabs/structured-session-tab-close.ts -1 src/main/runtime/session-tabs/terminal-surface-retirements.ts +1 src/main/runtime/session-tabs/restoration/headless-editor-tabs.ts +2 src/main/runtime/session-tabs/layout/headless-tab-group-moves.ts +6 src/main/runtime/session-tabs/layout/headless-tab-properties.ts +2 src/main/runtime/session-tabs/publication/headless-terminal-tab-titles.ts +1 src/main/runtime/session-tabs/chat/structured-session-tab-close.ts +1 src/main/runtime/session-tabs/terminal-retirement/terminal-surface-retirements.ts 2 src/main/runtime/terminal/adoption/adopt-terminal-orphans-from-inventory.ts 7 src/main/runtime/terminal/adoption/runtime-terminal-orphan-session-adoption.ts 1 src/main/runtime/terminal/driver/terminal-driver-resources.ts diff --git a/config/main-sync-fs-baseline.txt b/config/main-sync-fs-baseline.txt index a09646330c8..6627d70f7cc 100644 --- a/config/main-sync-fs-baseline.txt +++ b/config/main-sync-fs-baseline.txt @@ -473,7 +473,7 @@ 8 src/main/runtime/agent-session/ownership/agent-session-claim-identity.ts 1 src/main/runtime/agent-session/records/agent-session-record-store-slot.ts 7 src/main/runtime/agent-session/records/agent-session-runtime-end-record.ts -1 src/main/runtime/agent-session/structured-agent-session-attachment-wiring.ts +1 src/main/runtime/agent-session/installation/structured-agent-session-attachment-wiring.ts 1 src/main/runtime/client/navigation/desktop-chat-creation-history.ts 9 src/main/runtime/host-instance-identity.ts 4 src/main/runtime/hosts/platform-probe/host-descriptor.ts diff --git a/config/reliability-gates.jsonc b/config/reliability-gates.jsonc index e14dc54b6a3..17382640995 100644 --- a/config/reliability-gates.jsonc +++ b/config/reliability-gates.jsonc @@ -7849,7 +7849,7 @@ "pnpm exec vitest run --config config/vitest.config.ts tests/e2e/session-tabs-decorative-title-fanout.unit.test.ts --maxWorkers=1", "pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/construction/orca-runtime.test.ts src/main/runtime/rpc/terminal/terminal-multiplex-initial-snapshot-buffering.test.ts src/main/runtime/rpc/terminal/terminal-multiplex-pty-wait-capacity.test.ts src/main/runtime/rpc/terminal/terminal-subscribe-buffer.test.ts src/renderer/src/components/terminal-pane/pty-transport/output/terminal-side-effect-facts-handler.test.ts src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport-activation-inventory-fallback.test.ts src/renderer/src/runtime/rpc/subscriptions/runtime-client-events.test.ts src/renderer/src/web/web-preload-api-runtime-environment.test.ts src/main/ipc/runtime-environments/pairing/runtime-environments-pairing.test.ts", "pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/terminal/adoption/terminal-subscriber-driven-daemon-attach.test.ts", - "pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/session-tabs/runtime-inventory-publication-authority.test.ts src/main/runtime/rpc/methods/session-tabs/session-tabs-inventory-census-race.test.ts src/main/daemon/terminal-host/testing/terminal-host-agent-session.test.ts tests/e2e/session-tabs-empty-inventory-daemon-oracle.unit.test.ts --maxWorkers=1", + "pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/rpc/methods/session-tabs/session-tabs-inventory-census-race.test.ts src/main/daemon/terminal-host/testing/terminal-host-agent-session.test.ts tests/e2e/session-tabs-empty-inventory-daemon-oracle.unit.test.ts --maxWorkers=1", "pnpm exec vitest run --config config/vitest.config.ts src/shared/remote-runtime/control/remote-runtime-shared-control-connection.test.ts", "SKIP_BUILD=1 pnpm exec playwright test tests/e2e/paired-remote-terminal-host-restart-background-sync.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1", "ORCA_E2E_FORWARD_APP_LOGS=1 SKIP_BUILD=1 pnpm exec playwright test tests/e2e/paired-remote-terminal-host-restart-background-sync.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1 --repeat-each=10 --max-failures=1", @@ -7873,7 +7873,6 @@ "src/main/runtime/rpc/terminal/terminal-multiplex-pty-wait-capacity.test.ts", "src/main/runtime/rpc/terminal/terminal-subscribe-buffer.test.ts", "src/main/runtime/terminal/adoption/terminal-subscriber-driven-daemon-attach.test.ts", - "src/main/runtime/session-tabs/runtime-inventory-publication-authority.test.ts", "src/main/runtime/rpc/methods/session-tabs/session-tabs-inventory-census-race.test.ts", "src/main/daemon/terminal-host/testing/terminal-host-agent-session.test.ts", "tests/e2e/session-tabs-empty-inventory-daemon-oracle.unit.test.ts", diff --git a/config/scripts/ci/sharding/ci-shard-timings.json b/config/scripts/ci/sharding/ci-shard-timings.json index b060998b364..4f477dc7664 100644 --- a/config/scripts/ci/sharding/ci-shard-timings.json +++ b/config/scripts/ci/sharding/ci-shard-timings.json @@ -810,29 +810,21 @@ "src/main/claude/subagents/claude-subagent-resume-after-restart.test.ts": 825, "src/main/claude/claude-supervised-stop-real-cli.test.ts": 382, "src/main/claude/claude-supervised-stop.integration.test.ts": 3821, - "src/main/claude/transcripts/claude-transcript-catch-up.test.ts": 4017, "src/main/claude/claude-transcript-duration.test.ts": 1411, "src/main/claude/hooks/post-compact-hook-command.test.ts": 314, - "src/main/claude/structured/claude-structured-conversation-stop.test.ts": 884, "src/main/claude/structured/claude-structured-dispatch-admission.test.ts": 426, "src/main/claude/structured/claude-structured-dispatch-queue-boundary.test.ts": 911, "src/main/claude/structured/claude-structured-effort-reporting.test.ts": 1127, - "src/main/claude/structured/claude-structured-execution-recording.test.ts": 2228, "src/main/claude/structured/claude-structured-in-turn-stop.test.ts": 1017, - "src/main/claude/structured/claude-structured-inbound-control.test.ts": 55, - "src/main/claude/structured/claude-structured-option-confirmation.test.ts": 919, + "src/main/claude/structured/permissions/claude-structured-inbound-control.test.ts": 55, "src/main/claude/structured/claude-structured-real-cli-fold.test.ts": 921, "src/main/claude/structured/claude-structured-real-cli-rewind.test.ts": 933, "src/main/claude/structured/claude-structured-real-cli-stop-task.test.ts": 888, "src/main/claude/structured/claude-structured-real-cli-visuals.test.ts": 945, "src/main/claude/structured/claude-structured-real-cli.test.ts": 918, - "src/main/claude/structured/claude-structured-requested-stop.test.ts": 925, - "src/main/claude/structured/claude-structured-resume-point.test.ts": 1713, - "src/main/claude/structured/claude-structured-session-acquisition-processless.test.ts": 778, "src/main/claude/structured/claude-structured-session-adapter.test.ts": 1034, - "src/main/claude/structured/claude-structured-session-close.test.ts": 1040, "src/main/claude/structured/claude-structured-session-exit-blame.test.ts": 1176, - "src/main/claude/structured/claude-structured-session-startup.test.ts": 1002, + "src/main/claude/structured/startup/claude-structured-session-startup.test.ts": 1002, "src/main/claude/structured/claude-structured-turn-resume-point.test.ts": 1989, "src/main/claude/structured/journal/claude-structured-journal-prompt-cards.test.ts": 62, "src/main/claude/structured/journal/claude-structured-journal-prompt-retry.test.ts": 282, @@ -1712,7 +1704,6 @@ "src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-adopted-import.test.ts": 2881, "src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-attachment-admission.test.ts": 2402, "src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-background-stop-unreadable.test.ts": 1988, - "src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-claude-echo-working.test.ts": 2219, "src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-clear-queued-command.test.ts": 2168, "src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-close-aborts-start.test.ts": 1806, "src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-codex-held-goal.test.ts": 2081, @@ -1819,7 +1810,6 @@ "src/main/orcad/serve-startup/orcad-help.integration.test.ts": 5016, "src/main/orcad/instance-lock/orcad-instance-lock.test.ts": 315, "src/main/orcad/runtime-launch/orcad-launcher-isolation.integration.test.ts": 617, - "src/main/orcad/host-lifecycle/orcad-lifecycle-host.test.ts": 407, "src/main/orcad/host-lifecycle/managed-stop/orcad-managed-stop-identity.test.ts": 270, "src/main/orcad/host-lifecycle/managed-stop/orcad-managed-stop.test.ts": 1726, "src/main/orcad/native-runtime/orcad-packaged-node-pty.integration.test.ts": 78, @@ -2087,8 +2077,7 @@ "src/main/ripgrep/bundled-ripgrep-text-search.test.ts": 707, "src/main/ripgrep/ripgrep-filename-identity-real.test.ts": 274, "src/main/ripgrep/text-search-unicode-real.test.ts": 332, - "src/main/runtime/session-tabs/acknowledged-terminal-tab-retirement-main-close.test.ts": 6833, - "src/main/runtime/session-tabs/acknowledged-terminal-tab-retirement.test.ts": 6423, + "src/main/runtime/session-tabs/terminal-retirement/acknowledged-terminal-tab-retirement.test.ts": 6423, "src/main/runtime/terminal/input/agent-prompt-line-settle.test.ts": 4085, "src/main/runtime/terminal/input/agent-prompt-permission-wait.test.ts": 4446, "src/main/runtime/terminal/input/agent-prompt-receipt-correlation.test.ts": 4439, @@ -2096,14 +2085,12 @@ "src/main/runtime/terminal/input/agent-prompt-submission-runtime.test.ts": 5619, "src/main/runtime/terminal/input/agent-prompt-submission-windows-submit-delay.test.ts": 4664, "src/main/runtime/agent-session/records/agent-session-acquired-account.test.ts": 2056, - "src/main/runtime/agent-session/records/agent-session-inventory-scale.test.ts": 2496, "src/main/runtime/agent-session/records/agent-session-record-store-damaged.test.ts": 1557, "src/main/runtime/agent-session/records/agent-session-store-load-scale.test.ts": 732, "src/main/runtime/agent-session/agent-session-tab-layout-queue.test.ts": 4061, - "src/main/runtime/agent-session/agent-session-conversation-clear-commit.test.ts": 957, - "src/main/runtime/agent-session/agent-session-launch-directory.test.ts": 926, - "src/main/runtime/agent-session/agent-session-tab-layout.test.ts": 275, - "src/main/runtime/agent-session/agent-session-unsaved-creation-supersession.test.ts": 726, + "src/main/runtime/agent-session/launch/agent-session-launch-directory.test.ts": 926, + "src/main/runtime/session-tabs/chat/agent-session-tab-layout.test.ts": 275, + "src/main/runtime/agent-session/records/agent-session-unsaved-creation-supersession.test.ts": 726, "src/main/runtime/agent-session/ownership/agent-session-launch-env-admission.test.ts": 676, "src/main/runtime/agent-session/ownership/agent-session-lease-renewal.test.ts": 699, "src/main/runtime/agent-session/ownership/agent-session-operation-admission.test.ts": 150, @@ -2119,19 +2106,11 @@ "src/main/runtime/agent-session/records/agent-session-recovery-capsule.test.ts": 1074, "src/main/runtime/agent-session/records/agent-session-runtime-end-record.test.ts": 284, "src/main/runtime/agent-session/records/agent-session-store-transactions.test.ts": 1528, - "src/main/runtime/agent-session/records/structured-agent-session-mobile-restore.test.ts": 1965, - "src/main/runtime/agent-session/records/structured-agent-session-startup-tab-restore.test.ts": 7761, - "src/main/runtime/agent-session/structured-agent-session-attachment-wiring.test.ts": 521, - "src/main/runtime/agent-session/structured-agent-session-close.test.ts": 256, - "src/main/runtime/agent-session/structured-agent-session-held-signal.test.ts": 2773, - "src/main/runtime/agent-session/structured-agent-session-host-refusal.test.ts": 6115, + "src/main/runtime/agent-session/installation/structured-agent-session-attachment-wiring.test.ts": 521, + "src/main/runtime/agent-session/installation/structured-agent-session-held-signal.test.ts": 2773, "src/main/runtime/agent-session/structured-agent-session-install-failure.test.ts": 2103, - "src/main/runtime/agent-session/structured-agent-session-integration-replay.test.ts": 5400, - "src/main/runtime/agent-session/structured-agent-session-legacy-send-behind-command.test.ts": 6238, - "src/main/runtime/agent-session/structured-agent-session-paired-caller.test.ts": 5749, - "src/main/runtime/agent-session/structured-agent-session-runtime-provider-started.test.ts": 2576, - "src/main/runtime/agent-session/structured-agent-session-runtime.test.ts": 2581, - "src/main/runtime/agent-session/structured-agent-session-startup-reconcile.test.ts": 6294, + "src/main/runtime/agent-session/installation/structured-agent-session-integration-replay.test.ts": 5400, + "src/main/runtime/rpc/methods/structured-sessions/structured-agent-session-paired-caller.test.ts": 5749, "src/main/runtime/agent-state-rules/agent-state-rules-live-update.test.ts": 379, "src/main/runtime/workspaces/sleep/automatic-activation-host-sleep.test.ts": 4073, "src/main/runtime/browser-host/commands/browser-host-command-ledger-capacity.test.ts": 140, @@ -2146,10 +2125,6 @@ "src/main/runtime/terminal/launch/claude-agent-teams-shim-env.test.ts": 84, "src/main/runtime/terminal/wait/claude-dialog-interactive-wait.test.ts": 3975, "src/main/runtime/terminal/wait/claude-open-dialog-hold.test.ts": 44, - "src/main/runtime/agent-session/lifecycle/claude-structured-exit-mid-response.test.ts": 2509, - "src/main/runtime/agent-session/lifecycle/claude-structured-failed-start-resume.test.ts": 2454, - "src/main/runtime/agent-session/lifecycle/claude-structured-resumed-start-failure.test.ts": 4153, - "src/main/runtime/agent-session/lifecycle/claude-structured-startup-fault-is-not-an-exit.test.ts": 2741, "src/main/runtime/browser/client-pages/client-hosted-browser-page-persistence.integration.test.ts": 4022, "src/main/runtime/browser/client-pages/client-hosted-browser-page-persistence.test.ts": 315, "src/main/runtime/browser/client-pages/client-hosted-browser-row-publication.test.ts": 73, @@ -2182,12 +2157,10 @@ "src/main/runtime/workspaces/session-hosts/folder-workspace-mixed-host-routing.test.ts": 5271, "src/main/runtime/workspaces/session-hosts/folder-workspace-pty-identity.test.ts": 4131, "src/main/runtime/session-graph/graph-sync-deletion-fence.test.ts": 4552, - "src/main/runtime/session-tabs/graph-sync-mobile-snapshot-gating.test.ts": 4333, "src/main/runtime/terminal/surface/headless-create-terminal-handle-main.test.ts": 3873, "src/main/runtime/terminal/recovery/held-pane-reopen-layout-owner.test.ts": 5093, "src/main/runtime/terminal/wait/hermes-slash-readiness-transcript.test.ts": 4931, "src/main/runtime/terminal/surface/host-pane-remount-terminal-handle.test.ts": 5293, - "src/main/runtime/session-tabs/host-terminal-close-persistence-durability.test.ts": 1953, "src/main/runtime/terminal/output/host-terminal-scrollback-read.test.ts": 41, "src/main/runtime/terminal/wait/launched-agent-composer-readiness-claude.test.ts": 4750, "src/main/runtime/terminal/wait/launched-agent-crash-guard.live-shell.test.ts": 407, @@ -2213,7 +2186,7 @@ "src/main/runtime/push/notifications/mobile-notification-dismissal-store.test.ts": 214, "src/main/runtime/rpc/server/pairing/mobile-pairing-userdata-path.test.ts": 171, "src/main/runtime/terminal/layout/mobile-presence-lock.test.ts": 25928, - "src/main/runtime/session-tabs/headless-editor-tabs.test.ts": 57, + "src/main/runtime/session-tabs/restoration/headless-editor-tabs.test.ts": 57, "src/main/runtime/terminal/surface/mobile-session-terminal-persistence-retirement.test.ts": 278, "src/main/runtime/terminal/layout/mobile-subscribe-idle-pane-hydrate.test.ts": 4782, "src/main/runtime/client/navigation/multi-client-navigation-isolation.integration.test.ts": 5640, @@ -2238,7 +2211,7 @@ "src/main/runtime/session-lifecycle/projection/orca-runtime-mobile-markdown-tab-routes.test.ts": 8386, "src/main/runtime/files/paths/orca-runtime-read-kitty-file.test.ts": 4304, "src/main/runtime/browser/headless/orca-runtime-serve-browser-restore.test.ts": 4469, - "src/main/runtime/session-tabs/orca-runtime-session-tabs-path-alias.test.ts": 4827, + "src/main/runtime/session-tabs/publication/orca-runtime-session-tabs-path-alias.test.ts": 4827, "src/main/runtime/terminal/surface/orca-runtime-terminal-close-continuity.test.ts": 4439, "src/main/runtime/terminal/surface/orca-runtime-terminal-close-no-widening-layout-owner.test.ts": 4997, "src/main/runtime/terminal/surface/orca-runtime-terminal-close-no-widening.test.ts": 4509, @@ -2339,7 +2312,6 @@ "src/main/runtime/orchestration/workers/transcripts/worker-transcript-read.test.ts": 466, "src/main/runtime/orchestration/workers/turn-stops/worker-turn-stops.test.ts": 979, "src/main/runtime/workspaces/removal/owned-session-teardown-policy.test.ts": 9728, - "src/main/runtime/session-tabs/paired-host-terminal-close.test.ts": 4284, "src/main/runtime/client/peer-desktops.integration.test.ts": 4695, "src/main/runtime/terminal/wait/prime-agent-screen-readiness-transcripts.test.ts": 7843, "src/main/runtime/repositories/project-group-folder-workspace-selectors.test.ts": 3915, @@ -2366,7 +2338,6 @@ "src/main/runtime/rpc/server/remote-runtime-request-connection.integration.test.ts": 3961, "src/main/runtime/browser/client-pages/renderer-browser-lifecycle.test.ts": 3851, "src/main/runtime/browser/client-pages/renderer-browser-ownership.test.ts": 3800, - "src/main/runtime/session-tabs/renderer-owned-tab-properties.test.ts": 15027, "src/main/runtime/repositories/repo-icon-fork-backfill.test.ts": 4159, "src/main/runtime/workspaces/catalog/repo-worktree-row-resolution.test.ts": 664, "src/main/runtime/terminal/layout/restored-editor-move-restart.test.ts": 5390, @@ -2467,7 +2438,6 @@ "src/main/runtime/rpc/methods/orchestration/worker/follow-up/helper-follow-up-ownership-cli.integration.test.ts": 8091, "src/main/runtime/rpc/methods/orchestration/worker/observation/manual-dispatch-observation.test.ts": 5272, "src/main/runtime/rpc/methods/orchestration/worker/stop/manual-dispatch-release.test.ts": 5196, - "src/main/runtime/rpc/methods/orchestration/worker/release/worker-auto-release-turns.test.ts": 3578, "src/main/runtime/rpc/methods/orchestration/worker/release/worker-auto-release.test.ts": 4863, "src/main/runtime/rpc/methods/orchestration/worker/fleet/worker-list-pagination.test.ts": 4740, "src/main/runtime/rpc/methods/orchestration/worker/output/worker-output.test.ts": 541, @@ -2494,7 +2464,6 @@ "src/main/runtime/rpc/methods/ssh/ssh.test.ts": 938, "src/main/runtime/rpc/methods/host-management/status-machine-name-publish-budget.test.ts": 4191, "src/main/runtime/rpc/methods/structured-sessions/creation/structured-agent-session-adoption-replay.test.ts": 6090, - "src/main/runtime/rpc/methods/structured-sessions/protocol/structured-agent-session-at-rest-options.test.ts": 6634, "src/main/runtime/rpc/methods/structured-sessions/attachments/structured-agent-session-attachments.test.ts": 2006, "src/main/runtime/rpc/methods/structured-sessions/conversation/structured-agent-session-legacy-command-wait.test.ts": 2712, "src/main/runtime/rpc/methods/structured-sessions/catalog/structured-agent-session-options-read.test.ts": 1676, @@ -2657,14 +2626,6 @@ "src/main/runtime/workspaces/startup/runtime-worktree-startup-readiness.test.ts": 289, "src/main/runtime/workspaces/process-listing/runtime-worktree-structured-agent-rows-liveness.test.ts": 1412, "src/main/runtime/session-lifecycle/projection/pane-sleeping-record.test.ts": 76, - "src/main/runtime/session-tabs/session-tab-close-force.test.ts": 7089, - "src/main/runtime/session-tabs/runtime-inventory-publication-authority.test.ts": 5775, - "src/main/runtime/session-tabs/session-tab-prototype-dispatch.test.ts": 4888, - "src/main/runtime/session-tabs/session-tabs-headless-main-change.test.ts": 4320, - "src/main/runtime/session-tabs/session-tabs-inventory-publication.test.ts": 4166, - "src/main/runtime/session-tabs/session-tabs-main-rows-parity.test.ts": 4606, - "src/main/runtime/session-tabs/session-tabs-phone-layout-moves.test.ts": 4153, - "src/main/runtime/session-tabs/session-tabs-windowed-main-change.test.ts": 4444, "src/main/runtime/orchestration/terminal-authority/settled-worker-process-replacement.test.ts": 5013, "src/main/runtime/sidebar-inputs/temporal/orca-runtime-closed-tab-retention.test.ts": 5233, "src/main/runtime/sidebar-inputs/catalog/orca-runtime-project-catalog.test.ts": 4975, @@ -2687,10 +2648,8 @@ "src/main/runtime/sidebar-inputs/temporal/workspace-viewers.test.ts": 65, "src/main/runtime/terminal/output/stale-title-display-surfaces.test.ts": 4456, "src/main/runtime/agent-session/lifecycle/structured-agent-session-history-close-race.test.ts": 5020, - "src/main/runtime/agent-session/naming/structured-agent-session-provider-naming-shutdown.test.ts": 1987, "src/main/runtime/agent-session/environment/structured-agent-shell-environment-catalog.test.ts": 720, "src/main/runtime/orchestration/terminal-authority/structured-sessions/structured-chat-coordinator-mail.test.ts": 38220, - "src/main/runtime/orchestration/terminal-authority/structured-sessions/structured-chat-dispatch-worker-lifecycle.test.ts": 9312, "src/main/runtime/orchestration/terminal-authority/structured-sessions/structured-chat-dispatch-worker-mail.test.ts": 6125, "src/main/runtime/orchestration/terminal-authority/structured-sessions/structured-chat-dispatch-worker.test.ts": 6981, "src/main/runtime/orchestration/terminal-authority/structured-sessions/structured-chat-worker-helpers.test.ts": 8057, @@ -2698,15 +2657,12 @@ "src/main/runtime/orchestration/terminal-authority/structured-sessions/structured-chat-worker-start-unknown.test.ts": 7813, "src/main/runtime/orchestration/terminal-authority/structured-sessions/structured-chat-worker-start.test.ts": 6239, "src/main/runtime/agent-session/lifecycle/structured-claude-thinking-display-refusal.test.ts": 1295, - "src/main/runtime/agent-session/lifecycle/structured-codex-child-work-runtime.test.ts": 5959, "src/main/runtime/agent-session/environment/structured-session-cli-login-shell.test.ts": 307, "src/main/runtime/workspaces/removal/structured-session-worktree-teardown.test.ts": 476, - "src/main/runtime/orchestration/terminal-authority/structured-sessions/structured-worker-at-rest.test.ts": 2297, "src/main/runtime/orchestration/terminal-authority/structured-sessions/structured-worker-cleared-session.test.ts": 6104, "src/main/runtime/orchestration/terminal-authority/structured-sessions/structured-worker-hook-attestation.test.ts": 3455, "src/main/runtime/terminal/input/terminal-agent-fenced-keys.test.ts": 74, "src/main/runtime/terminal/input/terminal-agent-interrupt.test.ts": 54, - "src/main/runtime/session-tabs/terminal-close-observed-exit.test.ts": 5914, "src/main/runtime/orchestration/terminal-authority/release/terminal-close-slow-agent-exit.test.ts": 15751, "src/main/runtime/session-tabs/terminal-create-closed-tab-durability.test.ts": 5767, "src/main/runtime/terminal/focus/terminal-focus-navigation-coalescer.test.ts": 55, @@ -2719,7 +2675,7 @@ "src/main/runtime/terminal/recovery/terminal-pane-recovery-liveness-gate.test.ts": 4411, "src/main/runtime/terminal/output/terminal-query-responder.test.ts": 27968, "src/main/runtime/terminal/output/terminal-restore-record-seed.test.ts": 4073, - "src/main/runtime/session-tabs/terminal-retirement-async-durability.test.ts": 5903, + "src/main/runtime/session-tabs/terminal-retirement/terminal-retirement-async-durability.test.ts": 5903, "src/main/runtime/terminal/lifecycle/terminal-run-facts.test.ts": 68, "src/main/runtime/terminal/view/terminal-screen-row-metadata.test.ts": 175, "src/main/runtime/terminal/wait/terminal-start-failure-readiness.test.ts": 3416, @@ -4637,7 +4593,6 @@ "tests/e2e/multi-workspace-typing-bench.unit.test.ts": 550, "tests/e2e/native-chat-live-history.unit.test.ts": 3258, "tests/e2e/native-chat-ssh-transcript.unit.test.ts": 1166, - "tests/e2e/native-chat-startup-option-pickers.unit.test.ts": 9377, "tests/e2e/nested-agent-idle-owner.unit.test.ts": 2469, "tests/e2e/omp-retired-host-renderer.unit.test.ts": 2546, "tests/e2e/omp-risk-remote-review.unit.test.ts": 1137, diff --git a/config/scripts/mobile-web/check-entry/mobile-test-change-scope.mjs b/config/scripts/mobile-web/check-entry/mobile-test-change-scope.mjs index 1c2c90ff286..86e483d7a57 100644 --- a/config/scripts/mobile-web/check-entry/mobile-test-change-scope.mjs +++ b/config/scripts/mobile-web/check-entry/mobile-test-change-scope.mjs @@ -13,7 +13,9 @@ const NON_TEST_FILES = new Set([ 'config/scripts/workflow/source-routing/pr-layout-oracle-route.mjs', 'config/scripts/workflow/source-routing/pr-shell-contract-prefixes.mjs', 'config/scripts/mobile-web/check-entry/mobile-release-check-scope.mjs', - 'config/scripts/mobile-web/check-entry/mobile-release-check-scope.test.mjs' + 'config/scripts/mobile-web/check-entry/mobile-release-check-scope.test.mjs', + 'src/main/runtime/agent-session/launch/agent-session-launch-directory.test.ts', + 'src/main/runtime/session-tabs/chat/agent-session-tab-layout.test.ts' ]) const DESKTOP_SUITE_PREFIXES = [ @@ -21,17 +23,8 @@ const DESKTOP_SUITE_PREFIXES = [ 'src/packages/process-host/', 'src/main/agent-launch/', 'src/main/runtime/rpc/', - 'src/main/runtime/agent-session/agent-session-', 'src/main/runtime/agent-session/ownership/agent-session-', 'src/main/runtime/agent-session/records/agent-session-', - 'src/main/runtime/agent-session/agent-session-account-', - 'src/main/runtime/agent-session/agent-session-acquisition-', - 'src/main/runtime/agent-session/agent-session-conversation-', - 'src/main/runtime/agent-session/agent-session-launch-', - 'src/main/runtime/agent-session/agent-session-operation-', - 'src/main/runtime/agent-session/agent-session-rewind-', - 'src/main/runtime/agent-session/agent-session-runtime-', - 'src/main/runtime/agent-session/agent-session-unsaved-', 'src/main/native-chat/agent-session-wire/' ] diff --git a/config/scripts/static-analysis/process-boundaries/check-compat-boundary-imports.mjs b/config/scripts/static-analysis/process-boundaries/check-compat-boundary-imports.mjs index ba823b7e646..cdb6c336700 100644 --- a/config/scripts/static-analysis/process-boundaries/check-compat-boundary-imports.mjs +++ b/config/scripts/static-analysis/process-boundaries/check-compat-boundary-imports.mjs @@ -14,7 +14,7 @@ export const COMPAT_FOLDERS = [ 'old-client-session-tabs-projection' ], importers: [ - 'src/main/runtime/session-tabs/main-layout-session-tab-move.ts', + 'src/main/runtime/session-tabs/layout/main-layout-session-tab-move.ts', 'src/main/runtime/terminal/launch/mobile-terminal-chat-fork-create.ts', 'src/main/runtime/terminal/surface/terminal-surface-index.ts' ] 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 6acc7449789..b973f8ce073 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 @@ -29,8 +29,6 @@ const NODE_RUNTIME_INCLUDE = [ 'config/scripts/test-runtime/dom/happy-dom-mutation-observer-retention.test.ts', // These reach Node SQLite through a shared helper or a dynamic import, which the scan skips. 'src/main/agent-hooks/server/testing/providers/codex/server-codex-session-start.test.ts', - 'src/main/claude/transcripts/claude-transcript-catch-up.test.ts', - 'tests/e2e/native-chat-startup-option-pickers.unit.test.ts', 'src/main/ai-vault/transcripts/session-document-consumer-replacement.test.ts', 'src/main/runtime/rpc/server/orchestration-cli-subprocess.test.ts', 'src/main/runtime/orchestration/mailbox/terminal-pointer/orchestration-mailbox-delivery.test.ts', @@ -118,7 +116,6 @@ const NODE_RUNTIME_INCLUDE = [ 'src/main/ipc/settings-delayed-response.test.ts', 'src/main/ipc/session-window-view-save.test.ts', 'src/main/ipc/renderer-shutdown-checkpoint-sleep-records.test.ts', - 'src/main/runtime/agent-session/records/structured-agent-session-startup-tab-restore.test.ts', 'src/shared/remote-runtime/control/remote-runtime-shared-control-connection.test.ts', 'src/main/runtime/mobile-cloud-relay/control-channel/relay-control-client.test.ts', 'src/main/ipc/filesystem/watchers/filesystem-watcher-ignore-real.test.ts', diff --git a/config/scripts/test-runtime/sqlite-admission/vitest-sqlite-runtime-scan.mjs b/config/scripts/test-runtime/sqlite-admission/vitest-sqlite-runtime-scan.mjs index f19ff5ce7e0..9e2fd6dc453 100644 --- a/config/scripts/test-runtime/sqlite-admission/vitest-sqlite-runtime-scan.mjs +++ b/config/scripts/test-runtime/sqlite-admission/vitest-sqlite-runtime-scan.mjs @@ -37,7 +37,7 @@ export const SQLITE_MODULES = [ 'src/main/native-chat/agent-session-journal/database/journal-host-database', 'src/main/runtime/orchestration/db', 'src/main/runtime/orchestration/db/orchestration-db', - 'src/main/runtime/agent-session/structured-agent-session-runtime', + 'src/main/runtime/agent-session/installation/structured-agent-session-runtime', 'src/main/runtime/agent-session/records/agent-session-record-store-slot' ] const SQLITE_MODULE_PATHS = new Set(SQLITE_MODULES.map((module) => resolve(root, module))) diff --git a/config/scripts/workflow/source-routing/pr-layout-oracle-route.mjs b/config/scripts/workflow/source-routing/pr-layout-oracle-route.mjs index fd1441c9004..990a930f65b 100644 --- a/config/scripts/workflow/source-routing/pr-layout-oracle-route.mjs +++ b/config/scripts/workflow/source-routing/pr-layout-oracle-route.mjs @@ -44,9 +44,9 @@ const LAYOUT_ORACLE_PREFIXES = [ 'src/main/runtime/terminal/output/terminal-derived-agent-facts.ts', 'src/main/runtime/terminal/output/terminal-output-generation.ts', 'src/main/runtime/session-graph/session-window-graph.ts', - 'src/main/runtime/session-tabs/mobile-session-hydration.ts', - 'src/main/runtime/session-tabs/mobile-session-reconciliation.ts', - 'src/main/runtime/session-tabs/mobile-session-preservation.ts', + 'src/main/runtime/session-tabs/restoration/mobile-session-hydration.ts', + 'src/main/runtime/session-tabs/restoration/mobile-session-reconciliation.ts', + 'src/main/runtime/session-tabs/restoration/mobile-session-preservation.ts', 'src/main/runtime/workspaces/session-hosts/get-runtime-id.ts', 'src/renderer/src/components/terminal/terminal-tab-actions.ts', 'src/renderer/src/runtime/web-session-tabs-sync/placement/web-runtime-tab-move-mirror.ts', @@ -82,8 +82,8 @@ const RUNTIME_LAYOUT_WRITERS = [ 'src/main/runtime/workspaces/persisted-surfaces/has-exact-persisted-terminal-surface-identity.ts', 'src/main/runtime/terminal/adoption/runtime-terminal-orphan-adoption.ts', 'src/main/runtime/terminal/adoption/adopt-terminal-orphans-from-inventory.ts', - 'src/main/runtime/session-tabs/mobile-session-membership.ts', - 'src/main/runtime/session-tabs/pty-backed-session-publication.ts' + 'src/main/runtime/session-tabs/restoration/mobile-session-membership.ts', + 'src/main/runtime/session-tabs/publication/pty-backed-session-publication.ts' ] // Runtime matches only the modules that create, move, close, persist or publish layout. diff --git a/config/vitest.performance.config.ts b/config/vitest.performance.config.ts index a42d75de18f..eb762898f4d 100644 --- a/config/vitest.performance.config.ts +++ b/config/vitest.performance.config.ts @@ -5,7 +5,6 @@ import baseConfig from './vitest.config.ts' import { nodeRuntimePool } from './scripts/test-runtime/node-worker/vitest-node-runtime-pool.ts' const contracts = [ - 'src/main/runtime/session-tabs/session-tabs-phone-layout-moves.test.ts', 'src/renderer/src/components/agent/launch-menu/use-new-tab-agent-menu-host-preferences.test.tsx', 'src/main/codex-usage/codex-rollout-file-lifetime.test.ts', 'src/main/codex-usage/scanner-incremental-append.test.ts', diff --git a/src/main/ai-vault/structured-sessions/structured-session-ownership.ts b/src/main/ai-vault/structured-sessions/structured-session-ownership.ts index aaa04be46bc..3c435eabdf4 100644 --- a/src/main/ai-vault/structured-sessions/structured-session-ownership.ts +++ b/src/main/ai-vault/structured-sessions/structured-session-ownership.ts @@ -21,7 +21,7 @@ import { } from '../../../shared/ai-vault/search/ai-vault-search-transport' import type { AiVaultPrepareSessionResumeArgs } from '../../../shared/ai-vault/resume/ai-vault-resume-preparation' import { getStructuredAgentSessionHost } from '../../native-chat/agent-session-wire/host/structured-agent-session-registry' -import { ensureStructuredAgentSessionHostUnlessRefused } from '../../runtime/agent-session/structured-agent-session-host-refusal' +import { ensureStructuredAgentSessionHostUnlessRefused } from '../../runtime/agent-session/installation/structured-agent-session-host-refusal' import { listStructuredProviderSessionOwnership, terminalResumeBlocked, diff --git a/src/main/automations/launch/automation-chat-session-reuse.ts b/src/main/automations/launch/automation-chat-session-reuse.ts index f16d3cfcd99..3921d3d7d71 100644 --- a/src/main/automations/launch/automation-chat-session-reuse.ts +++ b/src/main/automations/launch/automation-chat-session-reuse.ts @@ -12,7 +12,7 @@ import { structuredAgentSessionSendBody } from '../../../shared/agent-session/requests/structured-agent-session-send-mutation' import { automationRunAcceptedTarget } from './automation-agent-run-result' -import { publishChatTabInBackground } from '../../runtime/session-tabs/background-chat-tab-publication' +import { publishChatTabInBackground } from '../../runtime/session-tabs/chat/background-chat-tab-publication' export async function reuseAutomationChat( runtime: OrcaRuntimeService, diff --git a/src/main/claude/__fixtures__/claude-lifecycle-capture-batch-lead.jsonl b/src/main/claude/__fixtures__/claude-lifecycle-capture-batch-lead.jsonl deleted file mode 100644 index 50cab7abe66..00000000000 --- a/src/main/claude/__fixtures__/claude-lifecycle-capture-batch-lead.jsonl +++ /dev/null @@ -1,28 +0,0 @@ -{"at": 15, "kind": "meta", "scenario": "batch-lead", "providerSessionId": "00000000-0000-4000-8000-00000000c1a0", "note": "Recorded against Claude CLI 2.1.280 through the Agent SDK transport; scrubbed: session id, home paths, API request and message ids, initialize answer; stream_event frames dropped."} -{"at": 334, "kind": "frame", "frame": {"type": "system", "subtype": "hook_started", "hook_id": "adafe449-4ded-495b-a4db-b82589e901e6", "hook_name": "SessionStart:startup", "hook_event": "SessionStart", "uuid": "9d3d1c58-6d69-408a-ae73-73d5c9656e9f", "session_id": "00000000-0000-4000-8000-00000000c1a0"}} -{"at": 376, "kind": "frame", "frame": {"type": "system", "subtype": "hook_response", "hook_id": "adafe449-4ded-495b-a4db-b82589e901e6", "hook_name": "SessionStart:startup", "hook_event": "SessionStart", "exit_code": 0, "outcome": "success", "uuid": "30ed6f57-a819-4c93-b4d3-7d76838c1950", "session_id": "00000000-0000-4000-8000-00000000c1a0"}} -{"at": 410, "kind": "dispatch", "clientMessageId": "client-A", "sentUuid": "0e1f8935-c61a-480b-8877-72c10dd1adda", "text": "Reply with text only; do not use any tools. Write the numbers from one to two hundred in English words, one per line, lowercase, nothing else."} -{"at": 413, "kind": "frame", "frame": {"type": "system", "subtype": "session_state_changed", "state": "running", "uuid": "2dfef2b1-c08e-4a66-94b9-c3bbbe8d6adb", "session_id": "00000000-0000-4000-8000-00000000c1a0"}} -{"at": 413, "kind": "frame", "frame": {"type": "command_lifecycle", "command_uuid": "0e1f8935-c61a-480b-8877-72c10dd1adda", "state": "queued", "uuid": "378fac6f-7ffb-417f-b9d3-4311c3d99d64", "session_id": "00000000-0000-4000-8000-00000000c1a0"}} -{"at": 414, "kind": "frame", "frame": {"type": "command_lifecycle", "command_uuid": "0e1f8935-c61a-480b-8877-72c10dd1adda", "state": "started", "uuid": "4bdc9a15-e613-42f3-a912-f6bcf8712999", "session_id": "00000000-0000-4000-8000-00000000c1a0"}} -{"at": 474, "kind": "frame", "frame": {"type": "system", "subtype": "init", "cwd": "/Users/user/scrubbed", "session_id": "00000000-0000-4000-8000-00000000c1a0", "tools": [], "mcp_servers": [], "model": "claude-opus-5-5[1m]", "permissionMode": "default", "slash_commands": [], "terminal_slash_commands": [], "apiKeySource": "none", "claude_code_version": "2.1.280", "output_style": "default", "agents": [], "skills": [], "plugins": [], "capabilities": ["interrupt_receipt_v1", "interrupt_cancel_queued_v1", "msg_lifecycle_v1", "mcp_read_resource_v1", "mcp_tool_ui_meta_v1"], "analytics_disabled": false, "product_feedback_disabled": false, "uuid": "b3869f1d-27b1-488a-a8a1-bde1a52fbf84", "fast_mode_state": "off", "fast_mode_disabled_reason": "sdk_opt_in_required"}} -{"at": 477, "kind": "frame", "frame": {"type": "system", "subtype": "status", "status": "requesting", "session_id": "00000000-0000-4000-8000-00000000c1a0", "uuid": "1e0b56e7-60ab-430d-910f-06c0337fb209"}} -{"at": 1478, "kind": "frame", "frame": {"type": "user", "message": {"role": "user", "content": [{"type": "text", "text": "Reply with text only; do not use any tools. Write the numbers from one to two hundred in English words, one per line, lowercase, nothing else."}]}, "session_id": "00000000-0000-4000-8000-00000000c1a0", "parent_tool_use_id": null, "uuid": "0e1f8935-c61a-480b-8877-72c10dd1adda", "timestamp": "2026-09-29T10:36:14.355Z", "isReplay": true}} -{"at": 1478, "kind": "dispatch", "clientMessageId": "client-B", "sentUuid": "ff373ed9-cde2-4a49-b83f-09157a686ee8", "text": "Reply with text only; do not use any tools. Reply with exactly: B-DONE"} -{"at": 1479, "kind": "frame", "frame": {"type": "command_lifecycle", "command_uuid": "ff373ed9-cde2-4a49-b83f-09157a686ee8", "state": "queued", "uuid": "9438512a-5380-48da-8ddf-6adffc28cfbb", "session_id": "00000000-0000-4000-8000-00000000c1a0"}} -{"at": 1479, "kind": "dispatch", "clientMessageId": "client-C", "sentUuid": "19ec4a51-3c43-4197-9305-f7e6e5ae96c5", "text": "Reply with text only; do not use any tools. Reply with exactly: C-DONE"} -{"at": 1479, "kind": "frame", "frame": {"type": "command_lifecycle", "command_uuid": "19ec4a51-3c43-4197-9305-f7e6e5ae96c5", "state": "queued", "uuid": "4f1b992a-26e8-43c5-af40-c3e5ef5707c8", "session_id": "00000000-0000-4000-8000-00000000c1a0"}} -{"at": 1479, "kind": "control", "request": {"subtype": "cancel_async_message", "message_uuid": "ff373ed9-cde2-4a49-b83f-09157a686ee8"}} -{"at": 1479, "kind": "frame", "frame": {"type": "command_lifecycle", "command_uuid": "ff373ed9-cde2-4a49-b83f-09157a686ee8", "state": "cancelled", "uuid": "f52f03d1-df02-432c-8bb6-c94062877e6f", "session_id": "00000000-0000-4000-8000-00000000c1a0"}} -{"at": 1479, "kind": "control-answer", "response": {"cancelled": true}} -{"at": 10848, "kind": "frame", "frame": {"type": "assistant", "message": {"model": "claude-opus-5-5", "id": "msg_scrubbed02", "type": "message", "role": "assistant", "content": [{"type": "text", "text": "one\ntwo\nthree\nfour\nfive\nsix\nseven\neight\nnine\nten\neleven\ntwelve\nthirteen\nfourteen\nfifteen\nsixteen\nseventeen\neighteen\nnineteen\ntwenty\ntwenty-one\ntwenty-two\ntwenty-three\ntwenty-four\ntwenty-five\ntwenty-six\ntwenty-seven\ntwenty-eight\ntwenty-nine\nthirty\nthirty-one\nthirty-two\nthirty-three\nthirty-four\nthirty-five\nthirty-six\nthirty-seven\nthirty-eight\nthirty-nine\nforty\nforty-one\nforty-two\nforty-three\nforty-four\nforty-five\nforty-six\nforty-seven\nforty-eight\nforty-nine\nfifty\nfifty-one\nfifty-two\nfifty-three\nfifty-four\nfifty-five\nfifty-six\nfifty-seven\nfifty-eight\nfifty-nine\nsixty\nsixty-one\nsixty-two\nsixty-three\nsixty-four\nsixty-five\nsixty-six\nsixty-seven\nsixty-eight\nsixty-nine\nseventy\nseventy-one\nseventy-two\nseventy-three\nseventy-four\nseventy-five\nseventy-six\nseventy-seven\nseventy-eight\nseventy-nine\neighty\neighty-one\neighty-two\neighty-three\neighty-four\neighty-five\neighty-six\neighty-seven\neighty-eight\neighty-nine\nninety\nninety-one\nninety-two\nninety-three\nninety-four\nninety-five\nninety-six\nninety-seven\nninety-eight\nninety-nine\none hundred\none hundred one\none hundred two\none hundred three\none hundred four\none hundred five\none hundred six\none hundred seven\none hundred eight\none hundred nine\none hundred ten\none hundred eleven\none hundred twelve\none hundred thirteen\none hundred fourteen\none hundred fifteen\none hundred sixteen\none hundred seventeen\none hundred eighteen\none hundred nineteen\none hundred twenty\none hundred twenty-one\none hundred twenty-two\none hundred twenty-three\none hundred twenty-four\none hundred twenty-five\none hundred twenty-six\none hundred twenty-seven\none hundred twenty-eight\none hundred twenty-nine\none hundred thirty\none hundred thirty-one\none hundred thirty-two\none hundred thirty-three\none hundred thirty-four\none hundred thirty-five\none hundred thirty-six\none hundred thirty-seven\none hundred thirty-eight\none hundred thirty-nine\none hundred forty\none hundred forty-one\none hundred forty-two\none hundred forty-three\none hundred forty-four\none hundred forty-five\none hundred forty-six\none hundred forty-seven\none hundred forty-eight\none hundred forty-nine\none hundred fifty\none hundred fifty-one\none hundred fifty-two\none hundred fifty-three\none hundred fifty-four\none hundred fifty-five\none hundred fifty-six\none hundred fifty-seven\none hundred fifty-eight\none hundred fifty-nine\none hundred sixty\none hundred sixty-one\none hundred sixty-two\none hundred sixty-three\none hundred sixty-four\none hundred sixty-five\none hundred sixty-six\none hundred sixty-seven\none hundred sixty-eight\none hundred sixty-nine\none hundred seventy\none hundred seventy-one\none hundred seventy-two\none hundred seventy-three\none hundred seventy-four\none hundred seventy-five\none hundred seventy-six\none hundred seventy-seven\none hundred seventy-eight\none hundred seventy-nine\none hundred eighty\none hundred eighty-one\none hundred eighty-two\none hundred eighty-three\none hundred eighty-four\none hundred eighty-five\none hundred eighty-six\none hundred eighty-seven\none hundred eighty-eight\none hundred eighty-nine\none hundred ninety\none hundred ninety-one\none hundred ninety-two\none hundred ninety-three\none hundred ninety-four\none hundred ninety-five\none hundred ninety-six\none hundred ninety-seven\none hundred ninety-eight\none hundred ninety-nine\ntwo hundred"}], "container": null, "stop_reason": null, "stop_sequence": null, "stop_details": null, "usage": {"input_tokens": 2, "cache_creation_input_tokens": 0, "cache_read_input_tokens": 23004, "cache_creation": {"ephemeral_5m_input_tokens": 0, "ephemeral_1h_input_tokens": 0}, "output_tokens": 8, "service_tier": "standard", "inference_geo": "not_available"}, "diagnostics": null, "context_management": null}, "parent_tool_use_id": null, "session_id": "00000000-0000-4000-8000-00000000c1a0", "uuid": "89d623dc-6a78-46fc-9123-ee06e2d61a6b", "timestamp": "2026-09-29T10:36:24.740Z", "request_id": "req_scrubbed01", "user_message_uuid": "0e1f8935-c61a-480b-8877-72c10dd1adda", "user_message_uuids": ["0e1f8935-c61a-480b-8877-72c10dd1adda"]}} -{"at": 10885, "kind": "frame", "frame": {"duration_api_ms": 11864, "stop_reason": "end_turn", "session_id": "00000000-0000-4000-8000-00000000c1a0", "total_cost_usd": 0.0398048, "usage": {"input_tokens": 2, "cache_creation_input_tokens": 0, "cache_read_input_tokens": 23004, "output_tokens": 1497, "output_tokens_details": {"thinking_tokens": 0}, "server_tool_use": {"web_search_requests": 0, "web_fetch_requests": 0}, "service_tier": "standard", "cache_creation": {"ephemeral_1h_input_tokens": 0, "ephemeral_5m_input_tokens": 0}, "inference_geo": "not_available", "iterations": [{"input_tokens": 2, "output_tokens": 1497, "cache_read_input_tokens": 23004, "cache_creation_input_tokens": 0, "cache_creation": {"ephemeral_5m_input_tokens": 0, "ephemeral_1h_input_tokens": 0}, "type": "message"}], "speed": "standard"}, "modelUsage": {"claude-opus-5-5[1m]": {"inputTokens": 1211, "outputTokens": 1518, "cacheReadInputTokens": 23004, "cacheCreationInputTokens": 0, "webSearchRequests": 0, "costUSD": 0.0398048, "contextWindow": 1000000, "maxOutputTokens": 128000, "thinkingTokens": 0, "canonicalModel": "claude-opus-5-5", "provider": "firstParty", "costBasis": "list"}}, "permission_denials": [], "terminal_reason": "completed", "fast_mode_state": "off", "fast_mode_disabled_reason": "sdk_opt_in_required", "subagent_stats": {"spawned": 0, "requested": {"background": 0, "foreground": 0, "unset": 0}, "started_in_background": 0, "max_depth": 0, "spawned_by_subagents": 0, "completed": 0, "failed": 0, "killed": {"parent": 0, "user": 0, "system": 0}, "refused": {"depth_limit": 0, "concurrency_limit": 0, "budget": 0}, "by_type": {}}, "is_error": false, "num_turns": 1, "subtype": "success", "api_error_status": null, "result": "one\ntwo\nthree\nfour\nfive\nsix\nseven\neight\nnine\nten\neleven\ntwelve\nthirteen\nfourteen\nfifteen\nsixteen\nseventeen\neighteen\nnineteen\ntwenty\ntwenty-one\ntwenty-two\ntwenty-three\ntwenty-four\ntwenty-five\ntwenty-six\ntwenty-seven\ntwenty-eight\ntwenty-nine\nthirty\nthirty-one\nthirty-two\nthirty-three\nthirty-four\nthirty-five\nthirty-six\nthirty-seven\nthirty-eight\nthirty-nine\nforty\nforty-one\nforty-two\nforty-three\nforty-four\nforty-five\nforty-six\nforty-seven\nforty-eight\nforty-nine\nfifty\nfifty-one\nfifty-two\nfifty-three\nfifty-four\nfifty-five\nfifty-six\nfifty-seven\nfifty-eight\nfifty-nine\nsixty\nsixty-one\nsixty-two\nsixty-three\nsixty-four\nsixty-five\nsixty-six\nsixty-seven\nsixty-eight\nsixty-nine\nseventy\nseventy-one\nseventy-two\nseventy-three\nseventy-four\nseventy-five\nseventy-six\nseventy-seven\nseventy-eight\nseventy-nine\neighty\neighty-one\neighty-two\neighty-three\neighty-four\neighty-five\neighty-six\neighty-seven\neighty-eight\neighty-nine\nninety\nninety-one\nninety-two\nninety-three\nninety-four\nninety-five\nninety-six\nninety-seven\nninety-eight\nninety-nine\none hundred\none hundred one\none hundred two\none hundred three\none hundred four\none hundred five\none hundred six\none hundred seven\none hundred eight\none hundred nine\none hundred ten\none hundred eleven\none hundred twelve\none hundred thirteen\none hundred fourteen\none hundred fifteen\none hundred sixteen\none hundred seventeen\none hundred eighteen\none hundred nineteen\none hundred twenty\none hundred twenty-one\none hundred twenty-two\none hundred twenty-three\none hundred twenty-four\none hundred twenty-five\none hundred twenty-six\none hundred twenty-seven\none hundred twenty-eight\none hundred twenty-nine\none hundred thirty\none hundred thirty-one\none hundred thirty-two\none hundred thirty-three\none hundred thirty-four\none hundred thirty-five\none hundred thirty-six\none hundred thirty-seven\none hundred thirty-eight\none hundred thirty-nine\none hundred forty\none hundred forty-one\none hundred forty-two\none hundred forty-three\none hundred forty-four\none hundred forty-five\none hundred forty-six\none hundred forty-seven\none hundred forty-eight\none hundred forty-nine\none hundred fifty\none hundred fifty-one\none hundred fifty-two\none hundred fifty-three\none hundred fifty-four\none hundred fifty-five\none hundred fifty-six\none hundred fifty-seven\none hundred fifty-eight\none hundred fifty-nine\none hundred sixty\none hundred sixty-one\none hundred sixty-two\none hundred sixty-three\none hundred sixty-four\none hundred sixty-five\none hundred sixty-six\none hundred sixty-seven\none hundred sixty-eight\none hundred sixty-nine\none hundred seventy\none hundred seventy-one\none hundred seventy-two\none hundred seventy-three\none hundred seventy-four\none hundred seventy-five\none hundred seventy-six\none hundred seventy-seven\none hundred seventy-eight\none hundred seventy-nine\none hundred eighty\none hundred eighty-one\none hundred eighty-two\none hundred eighty-three\none hundred eighty-four\none hundred eighty-five\none hundred eighty-six\none hundred eighty-seven\none hundred eighty-eight\none hundred eighty-nine\none hundred ninety\none hundred ninety-one\none hundred ninety-two\none hundred ninety-three\none hundred ninety-four\none hundred ninety-five\none hundred ninety-six\none hundred ninety-seven\none hundred ninety-eight\none hundred ninety-nine\ntwo hundred", "ttft_ms": 10419, "type": "result", "duration_ms": 10453, "uuid": "922da184-ba96-4a9e-a133-27dd7f45818f", "ttft_stream_ms": 1063, "time_to_request_ms": 71, "first_content_frame_ms": 1063, "user_message_uuid": "0e1f8935-c61a-480b-8877-72c10dd1adda", "user_message_uuids": ["0e1f8935-c61a-480b-8877-72c10dd1adda"], "request_sent_wall_ms": 1790678174393, "queued_turn_count": 0, "result_index": 0}} -{"at": 10886, "kind": "frame", "frame": {"type": "command_lifecycle", "command_uuid": "0e1f8935-c61a-480b-8877-72c10dd1adda", "state": "completed", "uuid": "3df6d400-c72e-4521-92f4-cc286ab007b7", "session_id": "00000000-0000-4000-8000-00000000c1a0"}} -{"at": 10886, "kind": "frame", "frame": {"type": "command_lifecycle", "command_uuid": "19ec4a51-3c43-4197-9305-f7e6e5ae96c5", "state": "started", "uuid": "e7087639-8080-4803-b8e4-638cc31888e5", "session_id": "00000000-0000-4000-8000-00000000c1a0"}} -{"at": 10904, "kind": "frame", "frame": {"type": "system", "subtype": "init", "cwd": "/Users/user/scrubbed", "session_id": "00000000-0000-4000-8000-00000000c1a0", "tools": [], "mcp_servers": [], "model": "claude-opus-5-5[1m]", "permissionMode": "default", "slash_commands": [], "terminal_slash_commands": [], "apiKeySource": "none", "claude_code_version": "2.1.280", "output_style": "default", "agents": [], "skills": [], "plugins": [], "capabilities": ["interrupt_receipt_v1", "interrupt_cancel_queued_v1", "msg_lifecycle_v1", "mcp_read_resource_v1", "mcp_tool_ui_meta_v1"], "analytics_disabled": false, "product_feedback_disabled": false, "uuid": "6fce32e9-e653-477f-b6b6-4d10267b2991", "fast_mode_state": "off", "fast_mode_disabled_reason": "sdk_opt_in_required"}} -{"at": 10904, "kind": "frame", "frame": {"type": "system", "subtype": "status", "status": "requesting", "session_id": "00000000-0000-4000-8000-00000000c1a0", "uuid": "e546544b-76be-4d78-9094-9a8329a6a756"}} -{"at": 12309, "kind": "frame", "frame": {"type": "user", "message": {"role": "user", "content": [{"type": "text", "text": "Reply with text only; do not use any tools. Reply with exactly: C-DONE"}]}, "session_id": "00000000-0000-4000-8000-00000000c1a0", "parent_tool_use_id": null, "uuid": "19ec4a51-3c43-4197-9305-f7e6e5ae96c5", "timestamp": "2026-09-29T10:36:24.795Z", "isReplay": true}} -{"at": 12310, "kind": "frame", "frame": {"type": "assistant", "message": {"model": "claude-opus-5-5", "id": "msg_scrubbed03", "type": "message", "role": "assistant", "content": [{"type": "text", "text": "C-DONE"}], "container": null, "stop_reason": null, "stop_sequence": null, "stop_details": null, "usage": {"input_tokens": 4, "cache_creation_input_tokens": 9027, "cache_read_input_tokens": 15502, "cache_creation": {"ephemeral_5m_input_tokens": 0, "ephemeral_1h_input_tokens": 9027}, "output_tokens": 7, "service_tier": "standard", "inference_geo": "not_available"}, "diagnostics": null, "context_management": null}, "parent_tool_use_id": null, "session_id": "00000000-0000-4000-8000-00000000c1a0", "uuid": "63316a0d-face-40ab-b7c5-a2f3c7aef73b", "timestamp": "2026-09-29T10:36:26.216Z", "request_id": "req_scrubbed02", "user_message_uuid": "19ec4a51-3c43-4197-9305-f7e6e5ae96c5", "user_message_uuids": ["19ec4a51-3c43-4197-9305-f7e6e5ae96c5"]}} -{"at": 12331, "kind": "frame", "frame": {"duration_api_ms": 13267, "stop_reason": "end_turn", "session_id": "00000000-0000-4000-8000-00000000c1a0", "total_cost_usd": 0.11527720000000001, "usage": {"input_tokens": 4, "cache_creation_input_tokens": 9027, "cache_read_input_tokens": 15502, "output_tokens": 7, "output_tokens_details": {"thinking_tokens": 0}, "server_tool_use": {"web_search_requests": 0, "web_fetch_requests": 0}, "service_tier": "standard", "cache_creation": {"ephemeral_1h_input_tokens": 9027, "ephemeral_5m_input_tokens": 0}, "inference_geo": "not_available", "iterations": [{"input_tokens": 4, "output_tokens": 7, "cache_read_input_tokens": 15502, "cache_creation_input_tokens": 9027, "cache_creation": {"ephemeral_5m_input_tokens": 0, "ephemeral_1h_input_tokens": 9027}, "type": "message"}], "speed": "standard"}, "modelUsage": {"claude-opus-5-5[1m]": {"inputTokens": 1215, "outputTokens": 1525, "cacheReadInputTokens": 38506, "cacheCreationInputTokens": 9027, "webSearchRequests": 0, "costUSD": 0.11527720000000001, "contextWindow": 1000000, "maxOutputTokens": 128000, "thinkingTokens": 0, "canonicalModel": "claude-opus-5-5", "provider": "firstParty", "costBasis": "list"}}, "permission_denials": [], "terminal_reason": "completed", "fast_mode_state": "off", "fast_mode_disabled_reason": "sdk_opt_in_required", "subagent_stats": {"spawned": 0, "requested": {"background": 0, "foreground": 0, "unset": 0}, "started_in_background": 0, "max_depth": 0, "spawned_by_subagents": 0, "completed": 0, "failed": 0, "killed": {"parent": 0, "user": 0, "system": 0}, "refused": {"depth_limit": 0, "concurrency_limit": 0, "budget": 0}, "by_type": {}}, "is_error": false, "num_turns": 1, "subtype": "success", "api_error_status": null, "result": "C-DONE", "ttft_ms": 1424, "type": "result", "duration_ms": 1438, "uuid": "fb897d43-901b-4f47-a701-d4d5f4cf8562", "ttft_stream_ms": 1423, "time_to_request_ms": 23, "first_content_frame_ms": 1423, "user_message_uuid": "19ec4a51-3c43-4197-9305-f7e6e5ae96c5", "user_message_uuids": ["19ec4a51-3c43-4197-9305-f7e6e5ae96c5"], "request_sent_wall_ms": 1790678184816, "queued_turn_count": 0, "result_index": 1}} -{"at": 12331, "kind": "frame", "frame": {"type": "command_lifecycle", "command_uuid": "19ec4a51-3c43-4197-9305-f7e6e5ae96c5", "state": "completed", "uuid": "bccf83ae-642e-42f8-8a33-1448870fb137", "session_id": "00000000-0000-4000-8000-00000000c1a0"}} -{"at": 12332, "kind": "frame", "frame": {"type": "system", "subtype": "session_state_changed", "state": "idle", "uuid": "5277a376-53d0-4a5d-b6f6-7669baccb91f", "session_id": "00000000-0000-4000-8000-00000000c1a0"}} diff --git a/src/main/claude/child-work/claude-child-work-evidence.ts b/src/main/claude/child-work/claude-child-work-evidence.ts index 14e9a171f17..a6f774a4787 100644 --- a/src/main/claude/child-work/claude-child-work-evidence.ts +++ b/src/main/claude/child-work/claude-child-work-evidence.ts @@ -10,7 +10,7 @@ import type { } from '../../../shared/agent-status/child-work/agent-status-child-work-evidence' import { taskText, taskUsageTotalTokens } from '../background-tasks/claude-background-task-frames' import type { ClaudeSession } from '../structured/claude-structured-session-state' -import type { ClaudeStructuredSessionEvent } from '../structured/claude-structured-session-event' +import type { ClaudeStructuredSessionEvent } from '../structured/lifecycle/claude-structured-session-event' import { deriveToolInputPreview } from '../../../shared/agent-hook-listener/tool-input-preview' import { claudeRecord, diff --git a/src/main/claude/conversation-naming/claude-conversation-naming.ts b/src/main/claude/conversation-naming/claude-conversation-naming.ts index b7513fc807a..91402acd5f0 100644 --- a/src/main/claude/conversation-naming/claude-conversation-naming.ts +++ b/src/main/claude/conversation-naming/claude-conversation-naming.ts @@ -1,6 +1,6 @@ import { activeProviderContext } from '../../../shared/agent-session/conversation-context/agent-session-provider-context' import type { AgentSessionRecord } from '../../../shared/agent-session/lifecycle/agent-session-record' -import { claudeSessionIdForOrcaSession } from '../structured/claude-structured-session-id' +import { claudeSessionIdForOrcaSession } from '../structured/lifecycle/claude-structured-session-id' import { createClaudeNamingGeneration, type ClaudeNamingGeneration diff --git a/src/main/claude/structured/claude-structured-conversation-stop.test.ts b/src/main/claude/structured/claude-structured-conversation-stop.test.ts deleted file mode 100644 index eedb688e198..00000000000 --- a/src/main/claude/structured/claude-structured-conversation-stop.test.ts +++ /dev/null @@ -1,77 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { acquired, fakeClaude, USER_MESSAGE } from './claude-structured-session-test-support' - -function interrupts(claude: ReturnType): number { - return claude.connections[0]!.calls.filter((call) => call.subtype === 'interrupt').length -} - -async function written(claude: ReturnType) { - const adapter = await acquired(claude) - await expect( - adapter.dispatch({ - sessionId: 'session-1', - clientMessageId: 'client-1', - body: USER_MESSAGE, - fence: 7 - }) - ).resolves.toMatchObject({ state: 'admitted' }) - return adapter -} - -describe('Claude Stop that names no turn', () => { - it('interrupts a written message before its turn opens', async () => { - const claude = fakeClaude({ replayUuid: null }) - const adapter = await written(claude) - - await expect(adapter.cancelTurn({ sessionId: 'session-1', fence: 7 })).resolves.toEqual({ - cancelled: true - }) - expect(interrupts(claude)).toBe(1) - }) - - it('does nothing for another fence, or with nothing in flight', async () => { - const claude = fakeClaude({ replayUuid: null }) - const adapter = await acquired(claude) - - await expect(adapter.cancelTurn({ sessionId: 'session-1', fence: 7 })).resolves.toEqual({ - cancelled: false - }) - await adapter.dispatch({ - sessionId: 'session-1', - clientMessageId: 'client-1', - body: USER_MESSAGE, - fence: 7 - }) - await expect(adapter.cancelTurn({ sessionId: 'session-1', fence: 6 })).resolves.toEqual({ - cancelled: false - }) - expect(interrupts(claude)).toBe(0) - }) - - it('ends a turn that opens while the interrupt is on its way once, and the next send lands', async () => { - const claude = fakeClaude({ replayUuid: null }) - const adapter = await written(claude) - const connection = claude.connections[0]! - // Deliver the echo between the interrupt write and its acknowledgement. - claude.routes.interrupt = () => { - connection.handlers.onMessage?.({ ...connection.sent[0]!, uuid: 'turn-late' }) - return undefined - } - - await expect(adapter.cancelTurn({ sessionId: 'session-1', fence: 7 })).resolves.toEqual({ - cancelled: true - }) - expect(interrupts(claude)).toBe(1) - - delete claude.routes.interrupt - await expect( - adapter.dispatch({ - sessionId: 'session-1', - clientMessageId: 'client-2', - body: USER_MESSAGE, - fence: 7 - }) - ).resolves.toMatchObject({ state: 'admitted' }) - expect(connection.sent).toHaveLength(2) - }) -}) diff --git a/src/main/claude/structured/claude-structured-dispatch-test-support.ts b/src/main/claude/structured/claude-structured-dispatch-test-support.ts deleted file mode 100644 index 02e3dab8dff..00000000000 --- a/src/main/claude/structured/claude-structured-dispatch-test-support.ts +++ /dev/null @@ -1,76 +0,0 @@ -import { ClaudeJournalBoundDelivery } from './journal/claude-journal-bound-delivery' -import { vi, type Mock } from 'vitest' -import type { AgentJournalMessageItem } from '../../../shared/agent-session/journal/agent-session-journal-types' -import { retireClaudeDispatchWaiters } from './claude-structured-dispatch' -import type { ClaudeSession } from './claude-structured-session-state' -import { ClaudeBackgroundTaskTracker } from '../background-tasks/claude-background-task-tracker' -import { ClaudeChildWorkDecoder } from '../child-work/claude-child-work-decoder' -import { ClaudeSlashCommandCatalog } from '../command-catalog/claude-slash-command-catalog' -import { createClaudeInitProof } from './claude-structured-init-proof' -import { createClaudeStartupOutcome } from './claude-structured-startup-outcome' -import { claudeProviderHandleLink } from './claude-structured-owner-identity' - -export function sessionFor(send: Mock = vi.fn().mockResolvedValue(undefined)): ClaudeSession { - return { - connection: { send } as unknown as ClaudeSession['connection'], - providerSessionId: 'provider-session', - leafUuid: null, - turnEndLeafUuid: null, - fence: 1, - acquisitionGeneration: 'generation-1', - prompts: {} as ClaudeSession['prompts'], - dispatchWaiters: [], - retiredDispatchWaiters: [], - replayContentFallbackBlocked: false, - delivery: new ClaudeJournalBoundDelivery(), - backgroundTasks: new ClaudeBackgroundTaskTracker(), - childWork: new ClaudeChildWorkDecoder(), - commands: new ClaudeSlashCommandCatalog(), - dispatchSequence: 0, - optionMutationSequence: 0, - options: new Map(), - reportedOptions: {}, - reportedModelMutation: 0, - confirmedOptions: new Set(), - appliedInputOptions: new Map(), - fastModeAtStart: false, - capabilities: [], - events: undefined, - translator: null, - link: claudeProviderHandleLink({ - sessionId: 'provider-session', - leafUuid: null, - resumed: false, - fence: 1, - observedAt: 1 - }), - initialization: { - proof: createClaudeInitProof(), - account: undefined, - resumesTranscript: false, - claudeConfigDir: '/claude-home', - cwd: '/work', - history: { leafUuid: null, covered: true, contextActivity: 0 }, - onLateRefusal: () => {}, - startup: createClaudeStartupOutcome() - } - } -} - -export function userMessage(blocks: AgentJournalMessageItem['blocks']): AgentJournalMessageItem { - return { kind: 'message', role: 'user', blocks } -} - -export function childExited(session: ClaudeSession): void { - retireClaudeDispatchWaiters(session) -} - -export function userReplayFrame(uuid: string, text: string): Record { - return { - type: 'user', - parent_tool_use_id: null, - session_id: 'provider-session', - uuid, - message: { role: 'user', content: [{ type: 'text', text }] } - } -} diff --git a/src/main/claude/structured/claude-structured-execution-recording.test.ts b/src/main/claude/structured/claude-structured-execution-recording.test.ts deleted file mode 100644 index 8bb23ab067a..00000000000 --- a/src/main/claude/structured/claude-structured-execution-recording.test.ts +++ /dev/null @@ -1,170 +0,0 @@ -import { expect, it } from 'vitest' -import { - acquired, - claudeFrame, - fakeClaude, - USER_MESSAGE -} from './claude-structured-session-test-support' -import { recordAgentSessionRanOptions } from '../../runtime/agent-session/records/agent-session-record-options' -import { createQueuedMessageTestRig } from '../../native-chat/agent-session-wire/host/testing/structured-agent-session-queued-message-rig.test-fixture' -import { eventually } from '../../native-chat/agent-session-wire/host/testing/structured-agent-session-queued-message-rig-provider.test-fixture' -import { HOST_TEST_SESSION as SESSION } from '../../native-chat/agent-session-wire/host/testing/structured-agent-session-host-test-data.test-fixture' - -/** Claude ends a turn; a message sent before this joins the running turn on its choices. */ -const claudeTurnEnds = (connection: Parameters[0]) => - claudeFrame(connection, { type: 'system', subtype: 'session_state_changed', state: 'idle' }) - -it.each(['high', undefined])( - 'admits accepted high independently of resolved effort (effective %s)', - async (effective) => { - const models = [ - { - value: 'sonnet', - supportsEffort: true, - supportedEffortLevels: ['low', 'high'], - supportsFastMode: true - } - ] - const claude = fakeClaude({ - initModels: models, - routes: { list_models: () => models }, - settings: { - ...(effective ? { applied: { model: 'sonnet', effort: 'low' } } : {}), - effective: { effortLevel: effective, fastMode: false } - } - }) - const adapter = await acquired(claude) - const rig = await createQueuedMessageTestRig() - const choices = { model: 'sonnet', effort: 'high', fastMode: 'true' } as const - try { - rig.dispatch.mockImplementation((input) => - adapter.dispatch({ ...input, sessionId: 'session-1', fence: 7 }) - ) - const first = rig.send('first', undefined, { carried: choices }) - expect(await first.result).toMatchObject({ ok: true }) - await eventually(() => expect(rig.dispatch).toHaveBeenCalledTimes(1)) - await eventually(() => - expect(rig.store.getRecord(SESSION)?.options).toEqual( - effective ? { model: 'sonnet', effort: 'low' } : undefined - ) - ) - const outcome = await rig.dispatch.mock.results[0]!.value - expect(outcome).toEqual({ - state: 'admitted', - ranOptions: effective ? { model: 'sonnet', effort: 'low' } : {} - }) - expect(outcome.ranOptions).not.toHaveProperty('fastMode') - const record = rig.store.getRecord(SESSION)! - expect( - recordAgentSessionRanOptions( - { ...record, options: { model: 'sonnet', effort: 'high' } }, - { - sessionId: SESSION, - fence: record.lease.runtimeFence, - model: 'sonnet', - options: outcome.ranOptions!, - models: undefined, - now: record.updatedAt - } - ).options - ).toEqual({ model: 'sonnet', effort: 'high' }) - claudeTurnEnds(claude.connections[0]!) - await adapter.dispatch({ - sessionId: 'session-1', - clientMessageId: 'again', - body: USER_MESSAGE, - executionOptions: choices, - fence: 7 - }) - expect( - claude.connections[0]!.calls.filter( - (call) => - call.subtype === 'apply_flag_settings' && JSON.stringify(call.params).includes('high') - ) - ).toHaveLength(2) - expect(claude.connections[0]!.sent).toHaveLength(2) - } finally { - await adapter.closeAll() - await rig.dispose() - } - } -) - -it('never pairs an earlier unknown-model low run with the next prepared model', async () => { - const applied: { model?: string; effort: string } = { effort: 'low' } - const claude = fakeClaude({ initModel: '', settings: { applied } }) - const events: Parameters[2] = [] - const adapter = await acquired(claude, {}, events) - const rig = await createQueuedMessageTestRig() - try { - rig.dispatch.mockImplementation((input) => - adapter.dispatch({ ...input, sessionId: 'session-1', fence: 7 }) - ) - const first = rig.send('first') - await first.result - await eventually(async () => - expect((await rig.submission(first.id))?.handedOverAt).toBeDefined() - ) - expect(await rig.dispatch.mock.results[0]!.value).toEqual({ - state: 'admitted', - ranOptions: { effort: 'low' } - }) - expect(rig.store.getRecord(SESSION)?.options).toBeUndefined() - await rig.settleAccepted(first.id, 'a') - claudeTurnEnds(claude.connections[0]!) - claude.routes.set_model = async () => { - claudeFrame(claude.connections[0]!, { type: 'system', subtype: 'init', model: 'B' }) - const report = events.findLast((event) => event.type === 'options-reported')! - await rig.host.handleAdapterEvent({ - ...report, - sessionId: SESSION, - fence: rig.store.getRecord(SESSION)!.lease.runtimeFence, - acquisitionGeneration: 'generation-1' - }) - expect(rig.store.getRecord(SESSION)?.options).toBeUndefined() - Object.assign(applied, { model: 'B', effort: 'high' }) - } - await rig.send('second', undefined, { carried: { model: 'B', effort: 'high' } }).result - await eventually(() => - expect(rig.store.getRecord(SESSION)?.options).toEqual({ model: 'B', effort: 'high' }) - ) - expect(claude.connections[0]!.sent).toHaveLength(2) - } finally { - await adapter.closeAll() - await rig.dispose() - } -}) - -it('does not save a deferred model with a live unknown-model turn’s observed effort through handover', async () => { - // Same partial get_settings shape as the CLI capture: applied effort without model. - const claude = fakeClaude({ - initModel: '', - settings: { applied: { effort: 'low' }, effective: { effortLevel: 'low' } } - }) - const adapter = await acquired(claude) - const rig = await createQueuedMessageTestRig() - try { - rig.dispatch.mockImplementation((input) => - adapter.dispatch({ ...input, sessionId: 'session-1', fence: 7 }) - ) - const first = rig.send('open the turn') - await first.result - await eventually(async () => - expect((await rig.submission(first.id))?.handedOverAt).toBeDefined() - ) - await rig.settleAccepted(first.id, 'first') - const followup = rig.send('keep working', undefined, { carried: { model: 'opus[1m]' } }) - await followup.result - await eventually(() => expect(claude.connections[0]!.sent).toHaveLength(2)) - await rig.host.collaboratorsForTests().conversationDelivery.loop.wake(SESSION) - expect(await rig.dispatch.mock.results[1]!.value).toEqual({ - state: 'admitted', - ranOptions: { effort: 'low' } - }) - expect(claude.connections[0]!.calls.filter((call) => call.subtype === 'set_model')).toEqual([]) - expect(rig.store.getRecord(SESSION)?.options).toBeUndefined() - } finally { - await adapter.closeAll() - await rig.dispose() - } -}) diff --git a/src/main/claude/structured/claude-structured-option-confirmation.test.ts b/src/main/claude/structured/claude-structured-option-confirmation.test.ts deleted file mode 100644 index 8128620a7ff..00000000000 --- a/src/main/claude/structured/claude-structured-option-confirmation.test.ts +++ /dev/null @@ -1,92 +0,0 @@ -import { describe, expect, it, vi } from 'vitest' -import { setClaudeStructuredOption } from './launch/claude-structured-options' -import { - readClaudeStructuredSessionOptions, - refreshClaudeStructuredSessionOptions -} from './launch/claude-structured-session-options' -import type { ClaudeSession } from './claude-structured-session-state' - -/** Claude Code 2.1.260 list_models fixture; Haiku omits both effort keys. */ -const CATALOG = [ - { - value: 'sonnet', - resolvedModel: 'claude-sonnet-5', - displayName: 'Sonnet', - supportsEffort: true, - supportedEffortLevels: ['low', 'medium', 'high', 'xhigh', 'max'] - }, - { value: 'haiku', resolvedModel: 'claude-haiku-4-5-20251001', displayName: 'Haiku' } -] - -describe('confirmation never outlives the write it belongs to', () => { - it('corroborates only the current held effort across fresh native observations', async () => { - const calls: string[] = [] - let settings: unknown = { applied: { effort: 'high' } } - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the fixture supplies every session member the option paths under test read. - const session = { - options: new Map([['model', 'sonnet']]), - reportedOptions: {}, - optionMutationSequence: 0, - confirmedOptions: new Set(), - appliedInputOptions: new Map(), - connection: { - supportedModels: async () => CATALOG, - applyFlagSettings: async (s: { effortLevel?: string }) => { - calls.push(`apply:${s.effortLevel}`) - }, - getSettings: async () => settings - }, - startup: { state: 'proven' } - } as unknown as ClaudeSession - - const current = async () => (await readClaudeStructuredSessionOptions(session)).current - await expect( - setClaudeStructuredOption(session, { key: 'effort', value: 'high' }, undefined) - ).resolves.toMatchObject({ effort: 'high' }) - await vi.waitFor(async () => expect((await current()).confirmed).toContain('effort')) - const refresh = async (next: unknown) => { - settings = next - await refreshClaudeStructuredSessionOptions( - session, - undefined, - () => true, - () => {} - ) - expect((await current()).effort).toBe('high') - expect(session.appliedInputOptions.get('effort')).toBe('high') - } - await refresh({}) - expect((await current()).confirmed).toContain('effort') - await refresh({ applied: { effort: 'low' } }) - expect((await current()).confirmed ?? []).not.toContain('effort') - await refresh({ applied: { effort: 'high' } }) - expect((await current()).confirmed).toContain('effort') - await refresh({ applied: { effort: null } }) - expect((await current()).confirmed ?? []).not.toContain('effort') - - await refresh({ applied: { effort: 'high' } }) - expect((await current()).confirmed).toContain('effort') - let releaseRead!: (value: unknown) => void - session.connection.getSettings = () => - new Promise((resolve) => { - releaseRead = resolve - }) - const lateRead = refreshClaudeStructuredSessionOptions( - session, - undefined, - () => true, - () => {} - ) - await expect( - setClaudeStructuredOption(session, { key: 'effort', value: 'max' }, undefined) - ).resolves.toMatchObject({ effort: 'max' }) - expect((await current()).effort).toBe('max') - expect((await current()).confirmed ?? []).not.toContain('effort') - releaseRead({ applied: { effort: 'max' } }) - await lateRead - expect((await current()).effort).toBe('max') - expect(session.appliedInputOptions.get('effort')).toBe('max') - expect((await current()).confirmed ?? []).not.toContain('effort') - expect(calls).toEqual(['apply:high', 'apply:max']) - }) -}) diff --git a/src/main/claude/structured/claude-structured-requested-stop.test.ts b/src/main/claude/structured/claude-structured-requested-stop.test.ts deleted file mode 100644 index 520c06187b8..00000000000 --- a/src/main/claude/structured/claude-structured-requested-stop.test.ts +++ /dev/null @@ -1,87 +0,0 @@ -import { describe, expect, it } from 'vitest' -import type { AgentJournalItemBody } from '../../../shared/agent-session/journal/agent-session-journal-types' -import type { AgentJournalItemIdentity } from '../../../shared/agent-session/journal/agent-session-journal-identity' -import { readAgentJournalTurn } from '../../../shared/agent-session/lifecycle/records/agent-session-turn-record' -import type { StructuredAgentSessionEventSink } from '../../native-chat/agent-session-wire/journal-ingress/structured-agent-session-event-sink' -import type { ClaudeStructuredSessionEvent } from './claude-structured-session-state' -import { - PROVIDER_SESSION_ID, - USER_MESSAGE, - adapterFor, - fakeClaude, - identityFor -} from './claude-structured-session-test-support' - -function journalSink() { - const items: { identity: AgentJournalItemIdentity; body: AgentJournalItemBody }[] = [] - const sink: StructuredAgentSessionEventSink = { - appendItem: (identity, body) => items.push({ identity, body }), - appendTombstone: () => {}, - publish: () => {} - } - return { sink, items } -} - -function frame(type: 'assistant' | 'user', uuid: string, content: unknown[]) { - return { - type, - uuid, - session_id: PROVIDER_SESSION_ID, - parent_tool_use_id: null, - message: { role: type, content } - } -} - -describe('a requested stop of a structured Claude chat', () => { - it('reads interrupted, not failed or crashed, through the frames the stop makes Claude emit', async () => { - const claude = fakeClaude({ replayUuid: 'turn-1' }) - const events: ClaudeStructuredSessionEvent[] = [] - const adapter = adapterFor(claude, {}, events) - const journal = journalSink() - await adapter.acquire({ - identity: identityFor(), - fence: 7, - spawnToken: 'spawn-9', - events: journal.sink - }) - await adapter.dispatch({ - sessionId: 'session-1', - clientMessageId: 'client-1', - body: USER_MESSAGE, - fence: 7 - }) - const connection = claude.connections[0]! - connection.handlers.onMessage?.( - frame('assistant', 'assistant-1', [ - { type: 'tool_use', id: 'tool-1', name: 'Bash', input: { command: 'sleep 120' } } - ]) - ) - // Captured from Claude 2.1.283 after mid-tool SIGTERM: tool/status frames without a result. - connection.close = async () => { - connection.handlers.onMessage?.( - frame('user', 'user-2', [ - { type: 'tool_result', tool_use_id: 'tool-1', is_error: true, content: 'Exit code 137' } - ]) - ) - connection.handlers.onMessage?.({ - type: 'system', - subtype: 'status', - uuid: 'status-1', - session_id: PROVIDER_SESSION_ID - }) - connection.closed = true - return true - } - - await expect(adapter.closeSession('session-1')).resolves.toBe(true) - - const turns = journal.items.flatMap((item) => { - const turn = readAgentJournalTurn(item.body) - return turn ? [turn] : [] - }) - expect(turns.at(-1)).toMatchObject({ turnId: 'turn-1', state: 'interrupted' }) - const ended = events.filter((event) => event.type === 'ended') - expect(ended).toEqual([expect.objectContaining({ reason: 'claude session closed' })]) - expect(ended[0]).toMatchObject({ cause: 'requested-close' }) - }) -}) diff --git a/src/main/claude/structured/claude-structured-resume-point.test.ts b/src/main/claude/structured/claude-structured-resume-point.test.ts deleted file mode 100644 index 8eb68dbb700..00000000000 --- a/src/main/claude/structured/claude-structured-resume-point.test.ts +++ /dev/null @@ -1,189 +0,0 @@ -import { followTestSinkSnapshots } from '../../native-chat/agent-session-wire/host/testing/structured-agent-session-direct-sink.test-fixture' -import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { afterEach, describe, expect, it, vi } from 'vitest' -import { createTrackedJournalOpener } from '../../native-chat/agent-session-journal/store-lifecycle/journal-host-database-test-support' -import { createDeferredStructuredAgentSessionEventSink } from '../../native-chat/agent-session-wire/journal-ingress/structured-agent-session-event-sink' -import { testEventSinkLogging } from '../../native-chat/agent-session-wire/host/testing/structured-agent-session-logger.test-fixture' -import type { ClaudeStructuredSessionEvent } from './claude-structured-session-state' -import { - adapterFor, - fakeClaude, - identityFor, - PROVIDER_SESSION_ID, - recordingJournalSink, - tick -} from './claude-structured-session-test-support' -import { claudeOpened } from './claude-structured-startup-settled-test-support' - -const journals = createTrackedJournalOpener() -const cleanups: (() => Promise)[] = [] - -async function ownerMidSecondTurn(persisted: unknown[]) { - const root = await mkdtemp(join(tmpdir(), 'orca-claude-completed-leaf-')) - const claudeConfigDir = join(root, 'claude') - const project = join(claudeConfigDir, 'projects', '-work-repo') - await mkdir(project, { recursive: true }) - await writeFile( - join(project, `${PROVIDER_SESSION_ID}.jsonl`), - `${JSON.stringify({ - type: 'assistant', - uuid: 'a3', - parentUuid: null, - sessionId: PROVIDER_SESSION_ID, - message: { role: 'assistant', content: [{ type: 'text', text: 'previous answer' }] } - })}\n` - ) - const journal = await journals.open({ identity: identityFor(), stateDirectory: root }) - const deferred = createDeferredStructuredAgentSessionEventSink(testEventSinkLogging()) - await followTestSinkSnapshots(deferred, journal) - deferred.bind({ journal, fence: 7, publish: () => {} }) - const claude = fakeClaude() - const adapter = adapterFor( - claude, - { - resumesTranscript: true, - continuesChain: true, - resumeLeafUuid: 'a3', - claudeConfigDir, - options: { resume: PROVIDER_SESSION_ID } - }, - [], - persisted - ) - cleanups.push(async () => { - await adapter.closeAll() - deferred.close() - await journals.closeAll() - await rm(root, { recursive: true, force: true }) - }) - await adapter.acquire({ - identity: identityFor(), - fence: 7, - spawnToken: 'spawn-7', - events: deferred.sink - }) - const frame = (message: Record) => - claude.connections[0]!.handlers.onMessage?.({ session_id: PROVIDER_SESSION_ID, ...message }) - frame({ type: 'user', uuid: 'u4', message: { role: 'user', content: 'ask' } }) - frame({ - type: 'assistant', - uuid: 'a4', - message: { role: 'assistant', content: [{ type: 'text', text: 'answer' }] } - }) - frame({ type: 'result', subtype: 'success', uuid: 'a4-result' }) - frame({ type: 'user', uuid: 'u5', message: { role: 'user', content: 'next' } }) - return { adapter, claude, frame } -} - -const lastCompletedTurn = { providerSessionId: PROVIDER_SESSION_ID, leafUuid: 'a4', fence: 7 } - -afterEach(async () => { - for (const cleanup of cleanups.splice(0)) { - await cleanup() - } - vi.restoreAllMocks() -}) - -describe('Claude resume point is the last completed turn on every exit path', () => { - it('on close', async () => { - const persisted: unknown[] = [] - const { adapter } = await ownerMidSecondTurn(persisted) - await expect(adapter.closeSession('session-1')).resolves.toBe(true) - await vi.waitFor(() => expect(persisted).toEqual([expect.objectContaining(lastCompletedTurn)])) - }) - - it('on an unexpected exit', async () => { - const persisted: unknown[] = [] - const { adapter, claude } = await ownerMidSecondTurn(persisted) - claude.connections[0]!.handlers.onExit?.(new Error('claude crashed')) - await adapter.drainObservedExits() - await tick() - expect(persisted).toEqual([expect.objectContaining(lastCompletedTurn)]) - }) - - it('on an acquisition release', async () => { - const persisted: unknown[] = [] - const { adapter } = await ownerMidSecondTurn(persisted) - await expect(adapter.releaseAcquisition({ sessionId: 'session-1' })).resolves.toBe(true) - await vi.waitFor(() => expect(persisted).toEqual([expect.objectContaining(lastCompletedTurn)])) - }) - - it('carries the launch leaf forward when no turn completed', async () => { - const persisted: unknown[] = [] - const claude = fakeClaude() - const adapter = adapterFor( - claude, - { - resumesTranscript: true, - continuesChain: true, - resumeLeafUuid: 'a3', - options: { resume: PROVIDER_SESSION_ID } - }, - [], - persisted - ) - await adapter.acquire({ - identity: identityFor(), - fence: 7, - spawnToken: 'spawn-7', - events: recordingJournalSink() - }) - expect((await claudeOpened(adapter, 'session-1')).link?.handle).toMatchObject({ - resumeCursor: 'a3' - }) - await expect(adapter.closeSession('session-1')).resolves.toBe(true) - expect(persisted).toEqual([expect.objectContaining({ leafUuid: 'a3' })]) - }) - - it('saves only real messages: hook, attachment, and result frames never become the leaf', async () => { - const persisted: unknown[] = [] - const { adapter, frame } = await ownerMidSecondTurn(persisted) - frame({ - type: 'assistant', - uuid: 'a5', - message: { role: 'assistant', content: [{ type: 'text', text: 'next answer' }] } - }) - frame({ type: 'system', subtype: 'stop_hook_summary', uuid: 'a5-hook-summary' }) - frame({ type: 'attachment', uuid: 'a5-attachment' }) - frame({ type: 'result', subtype: 'success', uuid: 'a5-result' }) - await expect(adapter.closeSession('session-1')).resolves.toBe(true) - await vi.waitFor(() => expect(persisted).toEqual([expect.objectContaining({ leafUuid: 'a5' })])) - }) - - it('on an unexpected exit whose durable write fails, still ends the session and logs', async () => { - const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) - const events: ClaudeStructuredSessionEvent[] = [] - const claude = fakeClaude() - const adapter = adapterFor( - claude, - { - resumesTranscript: true, - continuesChain: true, - resumeLeafUuid: 'a3', - options: { resume: PROVIDER_SESSION_ID } - }, - events, - [], - undefined, - async () => { - throw new Error('record write failed') - } - ) - await adapter.acquire({ - identity: identityFor(), - fence: 7, - spawnToken: 'spawn-7', - events: recordingJournalSink() - }) - claude.connections[0]!.handlers.onExit?.(new Error('claude crashed')) - await adapter.drainObservedExits() - await tick() - expect(events.at(-1)).toMatchObject({ type: 'ended', cause: 'unexpected-exit' }) - expect(warn).toHaveBeenCalledWith( - '[claude-resume-point] exit cursor was not persisted:', - expect.objectContaining({ sessionId: 'session-1', error: expect.any(Error) }) - ) - }) -}) diff --git a/src/main/claude/structured/claude-structured-session-acquisition-processless.test.ts b/src/main/claude/structured/claude-structured-session-acquisition-processless.test.ts deleted file mode 100644 index b7f7b5fda6a..00000000000 --- a/src/main/claude/structured/claude-structured-session-acquisition-processless.test.ts +++ /dev/null @@ -1,77 +0,0 @@ -import { describe, expect, it, vi } from 'vitest' -import type { AgentSessionJournalIdentity } from '../../../shared/agent-session/journal/agent-session-journal-identity' -import { AgentSessionPreSpawnError } from '../../native-chat/agent-session-wire/providers/structured-agent-session-adapter-errors' -import type { - ClaudeStreamJsonConnection, - openClaudeStreamJsonConnection -} from '../claude-stream-json-connection' -import { ClaudeStructuredSessionAdapter } from './claude-structured-session-adapter' - -const PROVIDER_SESSION_ID = '819cf9f8-e43c-4ad7-b50f-54aa158a726a' -const IDENTITY: AgentSessionJournalIdentity = { - sessionId: 'session-processless', - workspaceId: 'workspace-1', - hostId: 'local', - agent: 'claude', - providerHandle: null -} - -describe('Claude structured processless acquisition', () => { - it('classifies pre-pid error and close as processless with idempotent cleanup', async () => { - const fault = new Error('spawn claude ENOENT') - const close = vi.fn(async () => true) - const openConnection: typeof openClaudeStreamJsonConnection = async ( - _launch, - handlers = {} - ) => { - // A failed spawn reports its error on a later tick, as child_process does. - setTimeout(() => handlers.onFault?.(fault), 0) - const connection: ClaudeStreamJsonConnection = { - pid: undefined, - closed: true, - exitVerdict: { root: 'exited', tree: 'exited', processless: true }, - initializationResult: async () => { - throw fault - }, - getSettings: async () => ({}), - getContextUsage: async () => ({}), - renameSession: async () => {}, - supportedModels: async () => [], - interrupt: async () => undefined, - cancelAsyncMessage: async () => false, - setModel: async () => {}, - setPermissionMode: async () => {}, - applyFlagSettings: async () => {}, - send: async () => {}, - stopTask: async () => {}, - backgroundTask: async () => false, - close - } - return connection - } - const adapter = new ClaudeStructuredSessionAdapter({ - resolveLaunch: async () => ({ - pathToClaudeCodeExecutable: 'claude', - options: {}, - cwd: '/work/repo', - claudeConfigDir: '/accounts/claude', - providerSessionId: PROVIDER_SESSION_ID, - resumeLeafUuid: null, - resumesTranscript: false, - cliFlag: async () => 'supported' as const, - continuesChain: false - }), - openConnection - }) - - const error = await adapter - .acquire({ identity: IDENTITY, fence: 7, spawnToken: 'spawn-9' }) - .catch((cause: unknown) => cause) - - expect(error).toBeInstanceOf(AgentSessionPreSpawnError) - expect(error).toMatchObject({ message: fault.message }) - expect(close).toHaveBeenCalledOnce() - await expect(adapter.releaseAcquisition({ sessionId: IDENTITY.sessionId })).resolves.toBe(true) - expect(close).toHaveBeenCalledOnce() - }) -}) diff --git a/src/main/claude/structured/claude-structured-session-adapter.ts b/src/main/claude/structured/claude-structured-session-adapter.ts index 3db96f0dc92..2a0ddae9b0f 100644 --- a/src/main/claude/structured/claude-structured-session-adapter.ts +++ b/src/main/claude/structured/claude-structured-session-adapter.ts @@ -1,20 +1,20 @@ -import { dispatchClaudeCommand } from './claude-structured-command-dispatch' -import { isKillDeliveredExitReceipt } from './claude-kill-delivered-exit-receipt' -import { manageClaudeMcp } from './claude-structured-mcp' +import { dispatchClaudeCommand } from './turns/claude-structured-command-dispatch' +import { isKillDeliveredExitReceipt } from './lifecycle/claude-kill-delivered-exit-receipt' +import { manageClaudeMcp } from './lifecycle/claude-structured-mcp' import { claudeAcquireFailure } from '../sdk-transport/claude-startup-failure' -import { claudeStartPublication, openClaudeStart } from './claude-structured-start-ending' +import { claudeStartPublication, openClaudeStart } from './startup/claude-structured-start-ending' import { AgentSessionStartEndings } from '../../native-chat/agent-session-wire/startup/structured-agent-session-start-failure' import type { StructuredAgentSessionAcquireInput, StructuredAgentSessionAdapter } from '../../native-chat/agent-session-wire/providers/structured-agent-session-adapter' -import { stopCurrentClaudeBackgroundTasks } from './claude-structured-control-actions' +import { stopCurrentClaudeBackgroundTasks } from './turns/claude-structured-control-actions' import { claudeHeldSends, claudeHoldsDispatch } from './turns/claude-command-lifecycle' import { releaseClaudeAcquisition, type ClaudeReleaseRequest -} from './claude-structured-acquisition-release' -import { acquireClaudeSession } from './claude-structured-session-acquisition' +} from './lifecycle/claude-structured-acquisition-release' +import { acquireClaudeSession } from './lifecycle/claude-structured-session-acquisition' import { supportsClaudeStructuredLocation } from './launch/claude-structured-location-support' import * as claudeOptions from './launch/claude-structured-options' import { dispatchClaudeMessage } from './launch/claude-structured-message-options' @@ -23,10 +23,10 @@ import { ClaudeAcquisitionRegistry, type ClaudeSession, type ClaudeSessionExit, - type ClaudeStructuredSessionAdapterDeps, - type ClaudeStructuredSessionEvent + type ClaudeStructuredSessionAdapterDeps } from './claude-structured-session-state' -import { closeAllClaudeSessions } from './claude-structured-session-close' +import type { ClaudeStructuredSessionEvent } from './lifecycle/claude-structured-session-event' +import { closeAllClaudeSessions } from './lifecycle/claude-structured-session-close' import { claudeStoppedRequestEndWait } from './turns/claude-request-end-wait' import { finishClaudeCloseAfterExit, @@ -35,12 +35,12 @@ import { observeClaudeSessionExit, settleClaudeUnexpectedExit, type ClaudeExitLifecycle -} from './claude-structured-session-exit-lifecycle' +} from './lifecycle/claude-structured-session-exit-lifecycle' import { drainClaudeChildWork } from '../child-work/claude-child-work-evidence' import { deliverClaudeConnectionEvent, emitClaudeStructuredSessionEvent -} from './claude-structured-event-delivery' +} from './lifecycle/claude-structured-event-delivery' import { answerClaudeStructuredPrompt, cancelClaudeStructuredTurn, diff --git a/src/main/claude/structured/claude-structured-session-close.test.ts b/src/main/claude/structured/claude-structured-session-close.test.ts deleted file mode 100644 index cc6f9c1d2f5..00000000000 --- a/src/main/claude/structured/claude-structured-session-close.test.ts +++ /dev/null @@ -1,108 +0,0 @@ -import { describe, expect, it, vi } from 'vitest' -import type { StructuredAgentSessionEventSink } from '../../native-chat/agent-session-wire/journal-ingress/structured-agent-session-event-sink' -import type { - ClaudeStructuredSessionAdapterDeps, - ClaudeStructuredSessionEvent -} from './claude-structured-session-state' -import { - PROVIDER_SESSION_ID, - adapterFor, - fakeClaude, - identityFor -} from './claude-structured-session-test-support' -import type { AgentChildWorkEvidence } from '../../../shared/agent-status/child-work/agent-status-child-work-evidence' -import { AgentSessionAcquisitionRootExitObservedError } from '../../native-chat/agent-session-wire/acquisition/structured-agent-session-acquisition-errors' - -describe('Claude published session close lifecycle', () => { - it('lets the chat start again after a close that saw the root exit', async () => { - const claude = fakeClaude() - const adapter = adapterFor(claude) - await adapter.acquire({ identity: identityFor(), fence: 7, spawnToken: 'spawn-9' }) - const first = claude.connections[0]! - first.exitVerdict = { root: 'exited', tree: 'unverifiable' } - first.close = vi.fn<() => Promise>().mockResolvedValue(false) - await expect(adapter.closeSession('session-1')).rejects.toBeInstanceOf( - AgentSessionAcquisitionRootExitObservedError - ) - - await adapter.acquire({ identity: identityFor(), fence: 8, spawnToken: 'spawn-10' }) - - expect(claude.connections).toHaveLength(2) - expect(first.close).toHaveBeenCalledTimes(1) - }) - - it('starts the chat over a live session whose close saw the root exit', async () => { - const claude = fakeClaude() - const events: ClaudeStructuredSessionEvent[] = [] - const adapter = adapterFor(claude, {}, events) - await adapter.acquire({ identity: identityFor(), fence: 7, spawnToken: 'spawn-9' }) - const first = claude.connections[0]! - first.exitVerdict = { root: 'exited', tree: 'unverifiable' } - first.close = vi.fn<() => Promise>().mockResolvedValue(false) - - await adapter.acquire({ identity: identityFor(), fence: 8, spawnToken: 'spawn-10' }) - - expect(claude.connections).toHaveLength(2) - expect(events.filter((event) => event.type === 'ended')).toHaveLength(1) - }) - - it('ends the session even when the durable handle write rejects', async () => { - const claude = fakeClaude() - const events: ClaudeStructuredSessionEvent[] = [] - const persistenceError = new Error('store unavailable') - const persistHandle = vi - .fn>() - .mockRejectedValueOnce(persistenceError) - .mockResolvedValueOnce(undefined) - const childWork: AgentChildWorkEvidence['type'][] = [] - const adapter = adapterFor( - claude, - {}, - events, - [], - undefined, - persistHandle, - (_sessionId, evidence) => childWork.push(...evidence.map((edge) => edge.type)) - ) - const journalSink: StructuredAgentSessionEventSink = { - appendItem: () => {}, - appendTombstone: () => {}, - publish: () => {} - } - await adapter.acquire({ - identity: identityFor(), - fence: 7, - spawnToken: 'spawn-9', - events: journalSink - }) - claude.connections[0]!.handlers.onMessage?.({ - type: 'system', - subtype: 'task_started', - session_id: PROVIDER_SESSION_ID, - uuid: 'task-start', - task_id: 'background-1', - task_type: 'local_agent', - is_backgrounded: true - }) - expect(childWork).toEqual(['live']) - const session = ( - adapter as unknown as { - sessions: Map void } | null }> - } - ).sessions.get('session-1') - const disposeTranslator = vi.spyOn(session!.translator!, 'dispose') - - await expect(adapter.closeSession('session-1')).resolves.toBe(true) - await vi.waitFor(() => expect(persistHandle).toHaveBeenCalledOnce()) - expect(events.filter((event) => event.type === 'ended')).toHaveLength(1) - expect(events.filter((event) => event.type === 'handle')).toHaveLength(0) - expect(disposeTranslator).toHaveBeenCalledOnce() - // Session close cannot prove how unfinished child work ended. - expect(childWork).toEqual(['live', 'session-ended']) - - await expect(adapter.closeSession('session-1')).resolves.toBe(true) - expect(persistHandle).toHaveBeenCalledOnce() - expect(events.filter((event) => event.type === 'ended')).toHaveLength(1) - expect(disposeTranslator).toHaveBeenCalledOnce() - }) -}) diff --git a/src/main/claude/structured/claude-structured-session-state.ts b/src/main/claude/structured/claude-structured-session-state.ts index ea249090741..748c3aea0f1 100644 --- a/src/main/claude/structured/claude-structured-session-state.ts +++ b/src/main/claude/structured/claude-structured-session-state.ts @@ -1,5 +1,5 @@ import type { StructuredAgentSessionChildWorkProducer } from '../../native-chat/agent-session-wire/observations/structured-agent-session-subagent-rows' -import type { ClaudeStartupOutcome } from './claude-structured-startup-outcome' +import type { ClaudeStartupOutcome } from './startup/claude-structured-startup-outcome' import type { ClaudeCliFlagCheck, ClaudeCliFlagFact @@ -24,17 +24,13 @@ import type { ClaudeBackgroundTaskTracker } from '../background-tasks/claude-bac import type { ClaudeChildWorkDecoder } from '../child-work/claude-child-work-decoder' import type { ClaudeSlashCommandCatalog } from '../command-catalog/claude-slash-command-catalog' import type { ClaudeAtRestCommandCatalog } from '../command-catalog/claude-at-rest-commands' -import type { ClaudeInitProof } from './claude-structured-init-proof' +import type { ClaudeInitProof } from './startup/claude-structured-init-proof' import type { AgentSessionProviderHandleLink } from '../../../shared/agent-session/lifecycle/provider-handles/agent-session-provider-handle' import type { AgentSessionRecord } from '../../../shared/agent-session/lifecycle/agent-session-record' import type { ClaudeNamingInputs } from '../conversation-naming/claude-naming-invocation' -import type { ClaudeInitializeFacts } from './claude-structured-session-startup' +import type { ClaudeInitializeFacts } from './startup/claude-structured-session-startup' -export type { - ClaudeAuthDiagnostic, - ClaudeStructuredSessionEvent -} from './claude-structured-session-event' -import type { ClaudeStructuredSessionEvent } from './claude-structured-session-event' +import type { ClaudeStructuredSessionEvent } from './lifecycle/claude-structured-session-event' export type ClaudeStartedSend = { clientMessageId: string; requestedAt?: number } diff --git a/src/main/claude/structured/claude-structured-session-test-support.ts b/src/main/claude/structured/claude-structured-session-test-support.ts index 75daed068d3..2766d1812de 100644 --- a/src/main/claude/structured/claude-structured-session-test-support.ts +++ b/src/main/claude/structured/claude-structured-session-test-support.ts @@ -9,17 +9,15 @@ import type { } from '../claude-stream-json-connection' import { ClaudeStructuredSessionAdapter } from './claude-structured-session-adapter' import type { ClaudeStructuredLaunch } from './launch/claude-structured-launch-resolution' -import type { - ClaudeStructuredSessionAdapterDeps, - ClaudeStructuredSessionEvent -} from './claude-structured-session-state' +import type { ClaudeStructuredSessionAdapterDeps } from './claude-structured-session-state' +import type { ClaudeStructuredSessionEvent } from './lifecycle/claude-structured-session-event' import type { StructuredAgentSessionEventSink } from '../../native-chat/agent-session-wire/journal-ingress/structured-agent-session-event-sink' import { claudeProviderHandle } from '../../../shared/agent-session/lifecycle/provider-handles/agent-session-provider-handle-encoding' import { type claudeInitialization, claudeInitializationScope, claudeStartupSettled -} from './claude-structured-startup-settled-test-support' +} from './startup/claude-structured-startup-settled-test-support' export const PROVIDER_SESSION_ID = '819cf9f8-e43c-4ad7-b50f-54aa158a726a' diff --git a/src/main/claude/structured/claude-structured-steer-dispatch.test.ts b/src/main/claude/structured/claude-structured-steer-dispatch.test.ts deleted file mode 100644 index 134fcfdca34..00000000000 --- a/src/main/claude/structured/claude-structured-steer-dispatch.test.ts +++ /dev/null @@ -1,82 +0,0 @@ -import { describe, expect, it, vi } from 'vitest' -import { dispatchClaudeMessage } from './launch/claude-structured-message-options' -import { sessionFor, userMessage } from './claude-structured-dispatch-test-support' -import type { ClaudeSession } from './claude-structured-session-state' - -const SESSION = '819cf9f8-e43c-4ad7-b50f-54aa158a726a' - -function runningSession(): { session: ClaudeSession; steps: string[]; sent: unknown[] } { - const steps: string[] = [] - const sent: unknown[] = [] - const session = sessionFor( - vi.fn(async (message: Record, beforeDispatch?: () => Promise) => { - await beforeDispatch?.() - steps.push('write') - sent.push(structuredClone(message)) - }) - ) - Object.assign(session.connection, { - backgroundTask: vi.fn(async (toolUseId: string) => { - steps.push(`background ${toolUseId}`) - return true - }) - }) - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: dispatch reads only these translator flags. - session.translator = { - openTurnHasInputWork: true, - commandTurnId: null - } as unknown as ClaudeSession['translator'] - // Shapes from Claude CLI 2.1.319: a foreground subagent, and a foreground command it runs. - session.childWork.observe({ - type: 'system', - subtype: 'task_started', - task_id: 'agent-parent', - tool_use_id: 'toolu_parent', - is_backgrounded: false, - spawn_depth: 1, - task_type: 'local_agent', - session_id: SESSION - }) - session.childWork.observe({ - type: 'system', - subtype: 'task_started', - task_id: 'shell-child', - owned_by_subagent: true, - tool_use_id: 'toolu_shell', - is_backgrounded: false, - parent_task_id: 'agent-parent', - task_type: 'local_bash', - session_id: SESSION - }) - return { session, steps, sent } -} - -const steer = { - sessionId: 'session-1', - clientMessageId: 'client-1', - body: userMessage([{ type: 'text', text: 'change course' }]), - fence: 1 -} - -describe('Claude steer dispatch', () => { - it('backgrounds only top-level foreground work, then interrupts the running step', async () => { - const { session, steps, sent } = runningSession() - - await expect(dispatchClaudeMessage(session, steer, undefined)).resolves.toMatchObject({ - state: 'admitted' - }) - // The subagent's own command must stay in its foreground, or it dies when the subagent ends. - expect(steps).toEqual(['background toolu_parent', 'write']) - expect(sent).toEqual([expect.objectContaining({ priority: 'now' })]) - }) - - it('still steers when Claude refuses the background request', async () => { - const { session, sent } = runningSession() - session.connection.backgroundTask = vi.fn(async () => { - throw new Error('background tasks are disabled') - }) - - await dispatchClaudeMessage(session, steer, undefined, { warn: () => {}, error: () => {} }) - expect(sent).toEqual([expect.objectContaining({ priority: 'now' })]) - }) -}) diff --git a/src/main/claude/structured/claude-structured-steer-handoff.test.ts b/src/main/claude/structured/claude-structured-steer-handoff.test.ts deleted file mode 100644 index a5859818ec7..00000000000 --- a/src/main/claude/structured/claude-structured-steer-handoff.test.ts +++ /dev/null @@ -1,236 +0,0 @@ -import { describe, expect, it } from 'vitest' -import type { AgentJournalItemBody } from '../../../shared/agent-session/journal/agent-session-journal-types' -import type { AgentJournalItemIdentity } from '../../../shared/agent-session/journal/agent-session-journal-identity' -import { readAgentJournalTurn } from '../../../shared/agent-session/lifecycle/records/agent-session-turn-record' -import { createClaudeJournalTranslator } from './journal/claude-structured-journal-translation' -import type { StructuredAgentSessionEventSink } from '../../native-chat/agent-session-wire/journal-ingress/structured-agent-session-event-sink' -import { - PROVIDER_SESSION_ID, - USER_MESSAGE, - adapterFor, - fakeClaude, - identityFor -} from './claude-structured-session-test-support' - -function journalSink() { - const items: { identity: AgentJournalItemIdentity; body: AgentJournalItemBody }[] = [] - const sink: StructuredAgentSessionEventSink = { - appendItem: (identity, body) => items.push({ identity, body }), - appendTombstone: () => {}, - publish: () => {} - } - return { sink, items } -} - -const root = { session_id: PROVIDER_SESSION_ID, parent_tool_use_id: null } - -async function steeredDuringSubagent() { - // The steer's echo arrives after its interrupt, so the fake does not echo it on send. - const claude = fakeClaude({ replayUuids: ['turn-1', null] }) - const adapter = adapterFor(claude, {}) - const journal = journalSink() - await adapter.acquire({ - identity: identityFor(), - fence: 7, - spawnToken: 'spawn-9', - events: journal.sink - }) - await adapter.dispatch({ - sessionId: 'session-1', - clientMessageId: 'client-1', - body: USER_MESSAGE, - fence: 7 - }) - const connection = claude.connections[0]! - const emit = (message: Record) => connection.handlers.onMessage?.(message) - emit({ - ...root, - type: 'assistant', - uuid: 'assistant-1', - message: { - role: 'assistant', - content: [{ type: 'tool_use', id: 'agent-tool', name: 'Agent', input: { prompt: 'wait' } }] - } - }) - emit({ - ...root, - type: 'system', - subtype: 'task_started', - task_id: 'agent-task', - tool_use_id: 'agent-tool', - is_backgrounded: false, - task_type: 'local_agent', - uuid: 'task-started-1' - }) - await expect( - adapter.dispatch({ - sessionId: 'session-1', - clientMessageId: 'client-2', - body: { kind: 'message', role: 'user', blocks: [{ type: 'text', text: 'change course' }] }, - fence: 7 - }) - ).resolves.toMatchObject({ state: 'admitted' }) - const steer = connection.sent[1]! - expect(steer).toMatchObject({ priority: 'now' }) - expect(connection.calls).toContainEqual({ - subtype: 'background_tasks', - params: { toolUseId: 'agent-tool' } - }) - // Frame order recorded from Claude CLI 2.1.310 for a `now` steer: the cut-off step's result first. - emit({ - ...root, - type: 'result', - subtype: 'success', - uuid: 'result-1', - is_error: false, - num_turns: 1, - terminal_reason: 'aborted_tools' - }) - const turns = () => - journal.items.flatMap((item) => { - const turn = readAgentJournalTurn(item.body) - return turn ? [turn] : [] - }) - return { emit, steer, turns } -} - -describe('a Claude steer during foreground work', () => { - it('continues the running turn through the interrupt, not as a second or superseded turn', async () => { - const { emit, steer, turns } = await steeredDuringSubagent() - emit({ - ...root, - type: 'system', - subtype: 'init', - uuid: 'init-2', - model: 'claude-sonnet-5', - apiKeySource: 'none' - }) - emit({ ...steer, uuid: steer.uuid }) - emit({ - ...root, - type: 'assistant', - uuid: 'assistant-2', - message: { role: 'assistant', content: [{ type: 'text', text: 'Changed course.' }] } - }) - emit({ - ...root, - type: 'result', - subtype: 'success', - uuid: 'result-2', - is_error: false, - num_turns: 1, - terminal_reason: 'completed' - }) - - expect(new Set(turns().map((turn) => turn.turnId))).toEqual(new Set(['turn-1'])) - expect(turns().at(-1)).toMatchObject({ - turnId: 'turn-1', - state: 'completed', - outcome: 'success' - }) - }) - - it("keeps a real result's own ending after the hand-off", async () => { - const { emit, turns } = await steeredDuringSubagent() - emit({ - ...root, - type: 'result', - subtype: 'error_during_execution', - uuid: 'result-2', - is_error: true, - num_turns: 1, - terminal_reason: 'api_error' - }) - - expect(turns().at(-1)).toMatchObject({ turnId: 'turn-1', outcome: 'failure' }) - }) - - it('ends the turn as interrupted when it goes idle before the steer runs', async () => { - const { emit, turns } = await steeredDuringSubagent() - // A Stop can withdraw the queued steer, so Claude goes idle without another result. - emit({ - ...root, - type: 'system', - subtype: 'session_state_changed', - state: 'idle', - uuid: 'idle-1' - }) - - expect(turns().at(-1)).toMatchObject({ - turnId: 'turn-1', - state: 'interrupted', - outcome: 'cancellation' - }) - }) -}) - -function childStreamAfterHandoff() { - const writes: { body: AgentJournalItemBody; lifecycle?: boolean }[] = [] - const translator = createClaudeJournalTranslator({ - sink: { - appendItem: (_identity, body, options) => - writes.push({ body, lifecycle: options?.lifecycle }), - appendTombstone: () => {}, - publish: () => {} - }, - steerAwaitingEcho: () => true - }) - const frame = (message: Record, observedAt: number, startsTurn = false) => - translator.handle({ - type: 'message', - sessionId: 'orca-session', - observedAt, - ...(startsTurn ? { startsTurn: true } : {}), - message: { session_id: 'claude-session', parent_tool_use_id: null, ...message } - }) - frame({ type: 'user', uuid: 'prompt', message: { role: 'user', content: 'go' } }, 1_000, true) - frame( - { - type: 'stream_event', - uuid: 'child-delta', - parent_tool_use_id: 'agent-tool', - event: { type: 'content_block_delta', index: 0, delta: { type: 'text_delta', text: 'Half' } } - }, - 2_000 - ) - frame( - { - type: 'result', - subtype: 'success', - uuid: 'r', - is_error: false, - terminal_reason: 'aborted_tools' - }, - 3_000 - ) - return { translator, frame, writes } -} - -describe('a subagent text stream after a steer hand-off', () => { - it('ends when the turn goes idle, so cancelled turns retain no blocks', () => { - const { translator, frame, writes } = childStreamAfterHandoff() - expect(translator.pendingStreamedBlocks).toBe(1) - - frame({ type: 'system', subtype: 'session_state_changed', state: 'idle', uuid: 'idle' }, 9_000) - - expect(translator.pendingStreamedBlocks).toBe(0) - // The ending write must survive backpressure: no later frame would end the row. - expect(writes.at(-2)).toMatchObject({ - body: { role: 'assistant', blocks: [{ type: 'text', text: 'Half' }] }, - lifecycle: true - }) - }) - - it('keeps streaming into the next turn when a new prompt supersedes this one', () => { - const { translator, frame, writes } = childStreamAfterHandoff() - - frame( - { type: 'user', uuid: 'prompt-2', message: { role: 'user', content: 'next' } }, - 5_000, - true - ) - - expect(translator.pendingStreamedBlocks).toBe(1) - expect(writes.some((write) => write.lifecycle && write.body.kind === 'message')).toBe(false) - }) -}) diff --git a/src/main/claude/structured/claude-structured-dispatch-content.ts b/src/main/claude/structured/dispatch/claude-structured-dispatch-content.ts similarity index 91% rename from src/main/claude/structured/claude-structured-dispatch-content.ts rename to src/main/claude/structured/dispatch/claude-structured-dispatch-content.ts index ea7176ca2af..29a69b07b3d 100644 --- a/src/main/claude/structured/claude-structured-dispatch-content.ts +++ b/src/main/claude/structured/dispatch/claude-structured-dispatch-content.ts @@ -1,25 +1,25 @@ import { createHash } from 'node:crypto' import { open } from 'node:fs/promises' import { extname } from 'node:path' -import type { AgentJournalMessageItem } from '../../../shared/agent-session/journal/agent-session-journal-types' -import type { NativeChatBlock } from '../../../shared/native-chat/native-chat-types' +import type { AgentJournalMessageItem } from '../../../../shared/agent-session/journal/agent-session-journal-types' +import type { NativeChatBlock } from '../../../../shared/native-chat/native-chat-types' import { agentSessionFailureFact, type AgentSessionAttachmentProblem, type SubmissionRejectionFact -} from '../../../shared/agent-session/failures/agent-session-failure' +} from '../../../../shared/agent-session/failures/agent-session-failure' import { agentSessionFailureWords, type AgentJournalDispatchRejection -} from '../../../shared/agent-session/failures/agent-session-failure-words' -import { TUI_AGENT_DISPLAY_NAMES } from '../../../shared/agent-launch/catalog/tui-agent-display-names' +} from '../../../../shared/agent-session/failures/agent-session-failure-words' +import { TUI_AGENT_DISPLAY_NAMES } from '../../../../shared/agent-launch/catalog/tui-agent-display-names' import { AGENT_SESSION_ATTACHMENT_MAX_BYTES, AGENT_SESSION_MESSAGE_IMAGE_MAX_COUNT, AGENT_SESSION_MESSAGE_IMAGE_MAX_TOTAL_BYTES -} from '../../../shared/agent-session/agent-session-attachments' -import { agentInlineImageMimeType } from '../../../shared/native-chat/input/composer/agent-inline-image-types' -import { claudeRecord } from './journal/claude-structured-item-translation' +} from '../../../../shared/agent-session/agent-session-attachments' +import { agentInlineImageMimeType } from '../../../../shared/native-chat/input/composer/agent-inline-image-types' +import { claudeRecord } from '../journal/claude-structured-item-translation' export class ClaudeDispatchContentError extends Error { readonly failure: SubmissionRejectionFact diff --git a/src/main/claude/structured/claude-structured-dispatch-waiters.ts b/src/main/claude/structured/dispatch/claude-structured-dispatch-waiters.ts similarity index 94% rename from src/main/claude/structured/claude-structured-dispatch-waiters.ts rename to src/main/claude/structured/dispatch/claude-structured-dispatch-waiters.ts index f8110bda356..41c0a657698 100644 --- a/src/main/claude/structured/claude-structured-dispatch-waiters.ts +++ b/src/main/claude/structured/dispatch/claude-structured-dispatch-waiters.ts @@ -1,4 +1,4 @@ -import type { ClaudeDispatchWaiter, ClaudeSession } from './claude-structured-session-state' +import type { ClaudeDispatchWaiter, ClaudeSession } from '../claude-structured-session-state' const MAX_RETIRED_DISPATCH_WAITERS = 64 diff --git a/src/main/claude/structured/claude-structured-dispatch.ts b/src/main/claude/structured/dispatch/claude-structured-dispatch.ts similarity index 81% rename from src/main/claude/structured/claude-structured-dispatch.ts rename to src/main/claude/structured/dispatch/claude-structured-dispatch.ts index 925e0e7731e..e837a542ca4 100644 --- a/src/main/claude/structured/claude-structured-dispatch.ts +++ b/src/main/claude/structured/dispatch/claude-structured-dispatch.ts @@ -1,17 +1,17 @@ import { randomUUID } from 'node:crypto' -import { agentJournalSubmissionKey } from '../../../shared/agent-session/journal/agent-session-journal-item-key' -import { claudePromptUuidForSubmission } from './claude-structured-session-id' -import { isAbortSignalReason } from '../../../shared/concurrency/abort-signal-reason' +import { agentJournalSubmissionKey } from '../../../../shared/agent-session/journal/agent-session-journal-item-key' +import { claudePromptUuidForSubmission } from '../lifecycle/claude-structured-session-id' +import { isAbortSignalReason } from '../../../../shared/concurrency/abort-signal-reason' import { forgetRetiredWaiter, forgetWaiter, retireWaiter, waitForReplay } from './claude-structured-dispatch-waiters' -import type { AgentJournalMessageItem } from '../../../shared/agent-session/journal/agent-session-journal-types' -import type { AgentSessionDispatchOutcome } from '../../native-chat/agent-session-wire/providers/structured-agent-session-adapter' -import type { ClaudeDispatchWaiter, ClaudeSession } from './claude-structured-session-state' -import type { ClaudeLateDispatchSettlement } from './turns/claude-replay-turn-resolution' +import type { AgentJournalMessageItem } from '../../../../shared/agent-session/journal/agent-session-journal-types' +import type { AgentSessionDispatchOutcome } from '../../../native-chat/agent-session-wire/providers/structured-agent-session-adapter' +import type { ClaudeDispatchWaiter, ClaudeSession } from '../claude-structured-session-state' +import type { ClaudeLateDispatchSettlement } from '../turns/claude-replay-turn-resolution' import { claudeDispatchContentKey, claudeDispatchContentRejection, @@ -19,29 +19,29 @@ import { claudeDispatchMessageContent, claudeDispatchRejection } from './claude-structured-dispatch-content' -import { dispatchWriteOutcomeUnknownReason } from '../../native-chat/agent-session-journal/projection/journal-dispatch-doubt-reasons' -import { DISPATCH_REJECTED_QUEUE_FULL } from '../../../shared/agent-session/requests/structured-agent-session-dispatch-rejection' +import { dispatchWriteOutcomeUnknownReason } from '../../../native-chat/agent-session-journal/projection/journal-dispatch-doubt-reasons' +import { DISPATCH_REJECTED_QUEUE_FULL } from '../../../../shared/agent-session/requests/structured-agent-session-dispatch-rejection' import { agentSessionFailureFact, providerDiagnostic, type SubmissionRejectionFact -} from '../../../shared/agent-session/failures/agent-session-failure' -import type { AgentJournalDispatchRejection } from '../../../shared/agent-session/failures/agent-session-failure-words' +} from '../../../../shared/agent-session/failures/agent-session-failure' +import type { AgentJournalDispatchRejection } from '../../../../shared/agent-session/failures/agent-session-failure-words' import { claudeUnwrittenUserMessageError, claudeUserMessageWasProvablyUnwritten -} from '../sdk-transport/claude-agent-sdk-user-message-queue' -import { AgentSessionPreDispatchError } from '../../native-chat/agent-session-wire/operations/structured-agent-session-operation-settlement' +} from '../../sdk-transport/claude-agent-sdk-user-message-queue' +import { AgentSessionPreDispatchError } from '../../../native-chat/agent-session-wire/operations/structured-agent-session-operation-settlement' import { ClaudeEffortValidationError, isAgentSessionOptionRejectedError -} from '../../native-chat/agent-session-wire/options/structured-agent-session-option-error' -import { ClaudeControlRequestError } from '../sdk-transport/claude-agent-sdk-control-requests' +} from '../../../native-chat/agent-session-wire/options/structured-agent-session-option-error' +import { ClaudeControlRequestError } from '../../sdk-transport/claude-agent-sdk-control-requests' import { admitStructuredAgentSessionInput, StructuredAgentSessionInputNotAdmitted, type StructuredAgentSessionAdmitFreshInput -} from '../../native-chat/agent-session-wire/delivery/structured-agent-session-input-admission' +} from '../../../native-chat/agent-session-wire/delivery/structured-agent-session-input-admission' const MAX_ACTIVE_DISPATCH_WAITERS = 64 diff --git a/src/main/claude/structured/journal/claude-journal-translator-contract.ts b/src/main/claude/structured/journal/claude-journal-translator-contract.ts index a8da9647f17..a0d0d4d60c7 100644 --- a/src/main/claude/structured/journal/claude-journal-translator-contract.ts +++ b/src/main/claude/structured/journal/claude-journal-translator-contract.ts @@ -12,7 +12,7 @@ import type { ClaudeContextReportTarget } from '../../context-usage/claude-context-facts' import type { ClaudeJournalPrompts } from './claude-structured-journal-prompts' -import type { ClaudeStructuredSessionEvent } from '../claude-structured-session-event' +import type { ClaudeStructuredSessionEvent } from '../lifecycle/claude-structured-session-event' import type { ClaudeCommandStart } from '../turns/claude-command-turn' import type { AgentSessionDeltaCoalescerDeps } from '../../../native-chat/agent-session-wire/publication/subscribers/agent-session-delta-coalescer' diff --git a/src/main/claude/structured/journal/claude-plugin-input-failure-journal.ts b/src/main/claude/structured/journal/claude-plugin-input-failure-journal.ts index 6f0b8735ea5..e9afbe3edcd 100644 --- a/src/main/claude/structured/journal/claude-plugin-input-failure-journal.ts +++ b/src/main/claude/structured/journal/claude-plugin-input-failure-journal.ts @@ -5,7 +5,7 @@ import type { StructuredAgentSessionEventSink } from '../../../native-chat/agent import type { ClaudeOpenTurn } from '../turns/claude-open-turn' import { writeClaudeStopReadings, type ClaudeStopCheck } from '../../claude-stop-readings' import { estimateStructuredAgentSessionItemBytes } from '../../../native-chat/agent-session-wire/journal-ingress/structured-agent-session-event-sink-estimate' -import type { ClaudeStructuredSessionEvent } from '../claude-structured-session-state' +import type { ClaudeStructuredSessionEvent } from '../lifecycle/claude-structured-session-event' export function journalClaudePluginInputFailure({ event, diff --git a/src/main/claude/structured/journal/claude-structured-journal-prompt-cards.test.ts b/src/main/claude/structured/journal/claude-structured-journal-prompt-cards.test.ts index e5904f7b337..e944bfaac65 100644 --- a/src/main/claude/structured/journal/claude-structured-journal-prompt-cards.test.ts +++ b/src/main/claude/structured/journal/claude-structured-journal-prompt-cards.test.ts @@ -2,7 +2,7 @@ import { describe, expect, it, vi } from 'vitest' import { AGENT_JOURNAL_THREAD_SCOPE } from '../../../../shared/agent-session/journal/agent-session-journal-types' import type { StructuredAgentSessionSinkBarrier } from '../../../native-chat/agent-session-wire/journal-ingress/structured-agent-session-event-sink' import { ClaudeJournalPrompts } from './claude-structured-journal-prompts' -import type { ClaudeStructuredSessionEvent } from '../claude-structured-session-state' +import type { ClaudeStructuredSessionEvent } from '../lifecycle/claude-structured-session-event' const PROMPT: Extract = { type: 'prompt', diff --git a/src/main/claude/structured/journal/claude-structured-journal-prompts.ts b/src/main/claude/structured/journal/claude-structured-journal-prompts.ts index fabb8c37682..d0b290d5288 100644 --- a/src/main/claude/structured/journal/claude-structured-journal-prompts.ts +++ b/src/main/claude/structured/journal/claude-structured-journal-prompts.ts @@ -17,7 +17,7 @@ import { claudeQuestionItems, type ClaudeQuestionItem } from './claude-structured-prompt-items' -import type { ClaudeStructuredSessionEvent } from '../claude-structured-session-state' +import type { ClaudeStructuredSessionEvent } from '../lifecycle/claude-structured-session-event' const ADMITTED = { accepted: true } as const diff --git a/src/main/claude/structured/journal/claude-structured-journal-translation-turn-timing.test.ts b/src/main/claude/structured/journal/claude-structured-journal-translation-turn-timing.test.ts index 7b7ad2684eb..a367a192279 100644 --- a/src/main/claude/structured/journal/claude-structured-journal-translation-turn-timing.test.ts +++ b/src/main/claude/structured/journal/claude-structured-journal-translation-turn-timing.test.ts @@ -7,7 +7,7 @@ import type { } from '../../../native-chat/agent-session-wire/journal-ingress/structured-agent-session-event-sink' import { readAgentJournalTurn } from '../../../../shared/agent-session/lifecycle/records/agent-session-turn-record' import { createClaudeJournalTranslator } from './claude-structured-journal-translation' -import type { ClaudeStructuredSessionEvent } from '../claude-structured-session-state' +import type { ClaudeStructuredSessionEvent } from '../lifecycle/claude-structured-session-event' type Append = { identity: AgentJournalItemIdentity diff --git a/src/main/claude/structured/journal/claude-structured-prompt-ownership.ts b/src/main/claude/structured/journal/claude-structured-prompt-ownership.ts index a6313d208f7..77a2e9e28f4 100644 --- a/src/main/claude/structured/journal/claude-structured-prompt-ownership.ts +++ b/src/main/claude/structured/journal/claude-structured-prompt-ownership.ts @@ -4,7 +4,7 @@ import { } from '../../../native-chat/agent-session-wire/providers/structured-agent-session-adapter-errors' import type { StructuredAgentSessionAdapter } from '../../../native-chat/agent-session-wire/providers/structured-agent-session-adapter' import type { StructuredAgentSessionAdapterStop } from '../../../native-chat/agent-session-wire/providers/structured-agent-session-adapter-stop' -import { answerClaudePrompt, cancelClaudeTurn } from '../claude-structured-control-actions' +import { answerClaudePrompt, cancelClaudeTurn } from '../turns/claude-structured-control-actions' import { leaveClaudePlanModeOnApproval } from '../permissions/claude-plan-approval-mode' import type { ClaudeLateDispatchSettlement } from '../turns/claude-replay-turn-resolution' import { buildClaudePromptReply, claudePromptDismissal } from './claude-structured-prompt-replies' diff --git a/src/main/claude/structured/journal/claude-structured-session-journal-control.ts b/src/main/claude/structured/journal/claude-structured-session-journal-control.ts index 9130877a79b..cdf7b12df35 100644 --- a/src/main/claude/structured/journal/claude-structured-session-journal-control.ts +++ b/src/main/claude/structured/journal/claude-structured-session-journal-control.ts @@ -9,7 +9,7 @@ import type { import type { ClaudeStreamJsonConnection } from '../../claude-stream-json-connection' import type { ClaudeJournalTranslator } from './claude-journal-translator-contract' import { createClaudeJournalTranslator } from './claude-structured-journal-translation' -import type { ClaudeInitProof } from '../claude-structured-init-proof' +import type { ClaudeInitProof } from '../startup/claude-structured-init-proof' import type { ClaudeJournalBoundDelivery } from './claude-journal-bound-delivery' import type { ClaudeAcquisitionAttempt, diff --git a/src/main/claude/structured/launch/claude-structured-acquisition-launch.ts b/src/main/claude/structured/launch/claude-structured-acquisition-launch.ts index 026714bc17e..b75babd80a3 100644 --- a/src/main/claude/structured/launch/claude-structured-acquisition-launch.ts +++ b/src/main/claude/structured/launch/claude-structured-acquisition-launch.ts @@ -28,7 +28,7 @@ import { import { claudeCloseReport, closeClaudePublishedSessionForDeps -} from '../claude-structured-session-close' +} from '../lifecycle/claude-structured-session-close' export type ClaudeAcquisitionLaunch = ClaudeStructuredLaunch & { savedOptions: Omit diff --git a/src/main/claude/structured/launch/claude-structured-launch-resolution.ts b/src/main/claude/structured/launch/claude-structured-launch-resolution.ts index 3fde3860357..cc88713b261 100644 --- a/src/main/claude/structured/launch/claude-structured-launch-resolution.ts +++ b/src/main/claude/structured/launch/claude-structured-launch-resolution.ts @@ -34,7 +34,7 @@ import { resolveClaudeLaunchFlags } from './claude-structured-launch-flags' import { withNativeChatVisualsEnv } from '../../../native-chat/conversation-files/native-chat-visuals-delivery' import { claudeLaunchResumesTranscript } from './claude-structured-launch-home' import type { StructuredAgentLaunchPartResolver } from '../../../runtime/agent-session/launch/structured-agent-launch-composition' -import { claudeSessionIdForOrcaSession } from '../claude-structured-session-id' +import { claudeSessionIdForOrcaSession } from '../lifecycle/claude-structured-session-id' import { pendingAgentSessionRewindFork, type AgentSessionRewindFork diff --git a/src/main/claude/structured/launch/claude-structured-message-options.ts b/src/main/claude/structured/launch/claude-structured-message-options.ts index 86dc5e37aa6..7a38d985b14 100644 --- a/src/main/claude/structured/launch/claude-structured-message-options.ts +++ b/src/main/claude/structured/launch/claude-structured-message-options.ts @@ -1,7 +1,7 @@ import { claudeBuildPermissionMode } from '../permissions/claude-plan-approval-mode' import { claudeStartedUnechoedSend } from '../turns/claude-command-lifecycle' -import { claudeExecutionObservations } from '../claude-structured-execution-observations' -import { dispatchClaudeTurn } from '../claude-structured-dispatch' +import { claudeExecutionObservations } from '../turns/claude-structured-execution-observations' +import { dispatchClaudeTurn } from '../dispatch/claude-structured-dispatch' import type { StructuredAgentSessionAdapter } from '../../../native-chat/agent-session-wire/providers/structured-agent-session-adapter' import type { AgentSessionExecutionOptions } from '../../../../shared/agent-session/options/protocol/agent-session-execution-options' import { AgentSessionOptionRejectedError } from '../../../native-chat/agent-session-wire/options/structured-agent-session-option-error' diff --git a/src/main/claude/structured/launch/claude-structured-options.ts b/src/main/claude/structured/launch/claude-structured-options.ts index ffa44e063ba..47343147695 100644 --- a/src/main/claude/structured/launch/claude-structured-options.ts +++ b/src/main/claude/structured/launch/claude-structured-options.ts @@ -12,7 +12,7 @@ import type { ClaudeSession } from '../claude-structured-session-state' import type { StructuredAgentSessionAdapter } from '../../../native-chat/agent-session-wire/providers/structured-agent-session-adapter' import { decodeStructuredAgentSessionOptionValue } from '../../../../shared/agent-session/options/selection/structured-agent-session-option-codec' -import { beginClaudeOptionMutation } from '../claude-structured-execution-observations' +import { beginClaudeOptionMutation } from '../turns/claude-structured-execution-observations' import { CLAUDE_APPLY_FLAG_SETTINGS_CONTROL, CLAUDE_CACHED_FLAG_CHECK_BUDGET_MS diff --git a/src/main/claude/structured/launch/claude-structured-provider-fallback.test.ts b/src/main/claude/structured/launch/claude-structured-provider-fallback.test.ts index 131758ba67b..375262b4e81 100644 --- a/src/main/claude/structured/launch/claude-structured-provider-fallback.test.ts +++ b/src/main/claude/structured/launch/claude-structured-provider-fallback.test.ts @@ -1,55 +1,8 @@ -import { followTestSinkSnapshots } from '../../../native-chat/agent-session-wire/host/testing/structured-agent-session-direct-sink.test-fixture' -import { readTestJournalItems } from '../../../native-chat/agent-session-journal/journal-observation.test-support' -import { openTestAgentSessionDatabase } from '../../../runtime/agent-session/records/agent-session-record-store-test-harness' -import { mkdtemp, rm } from 'node:fs/promises' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { describe, expect, it, vi } from 'vitest' import type { AgentJournalItemBody } from '../../../../shared/agent-session/journal/agent-session-journal-types' -import type { AgentSessionJournalIdentity } from '../../../../shared/agent-session/journal/agent-session-journal-identity' -import { openAgentSessionJournal } from '../../../native-chat/agent-session-journal/journal-store-factory' -import { createDeferredStructuredAgentSessionEventSink } from '../../../native-chat/agent-session-wire/journal-ingress/structured-agent-session-event-sink' + import { createClaudeJournalTranslator } from '../journal/claude-structured-journal-translation' -import type { ClaudeStructuredSessionEvent } from '../claude-structured-session-state' -import { closeTestJournalHostDatabases } from '../../../native-chat/agent-session-journal/store-lifecycle/journal-host-database-test-support' -import { testEventSinkLogging } from '../../../native-chat/agent-session-wire/host/testing/structured-agent-session-logger.test-fixture' -import { claudeProviderHandle } from '../../../../shared/agent-session/lifecycle/provider-handles/agent-session-provider-handle-encoding' - -const IDENTITY: AgentSessionJournalIdentity = { - sessionId: 'session-1', - workspaceId: 'workspace-1', - hostId: 'host-1', - agent: 'claude', - providerHandle: claudeProviderHandle('provider-1', 'leaf-1') -} - -let root = '' - -function message( - role: 'assistant' | 'user', - uuid: string, - content: unknown[] -): ClaudeStructuredSessionEvent { - return { - type: 'message', - sessionId: 'orca-session', - message: { - type: role, - uuid, - session_id: 'provider-1', - message: { role, content } - } - } -} - -beforeEach(async () => { - root = await mkdtemp(join(tmpdir(), 'orca-claude-provider-fallback-')) -}) - -afterEach(async () => { - await closeTestJournalHostDatabases() - await rm(root, { recursive: true, force: true }) -}) +import type { ClaudeStructuredSessionEvent } from '../lifecycle/claude-structured-session-event' describe('Claude provider fallback', () => { it('drops suppressed init frames instead of dereferencing a null translation', () => { @@ -76,162 +29,4 @@ describe('Claude provider fallback', () => { expect(() => translator.handle(initEvent)).not.toThrow() expect(items).toEqual([]) }) - - it('journals the captured model fallback as a notice and continues the same turn', () => { - const items: AgentJournalItemBody[] = [] - const translator = createClaudeJournalTranslator({ - sink: { - appendItem: (_identity, body) => { - items.push(body) - }, - appendTombstone: vi.fn(), - publish: vi.fn() - } - }) - translator.handle( - message('assistant', 'fallback-1', [ - { type: 'fallback', from: { model: 'claude-opus-5-5' }, to: { model: 'claude-opus-4-8' } } - ]) - ) - translator.handle( - message('assistant', 'answer-1', [{ type: 'text', text: 'Continuing the answer.' }]) - ) - translator.handle({ - type: 'message', - sessionId: 'orca-session', - message: { - type: 'result', - subtype: 'success', - session_id: 'provider-1', - uuid: 'result-1', - result: 'Continuing the answer.' - } - }) - - const notices = items.filter((body) => body.kind === 'status') - expect(notices).toHaveLength(1) - expect(notices[0]).toMatchObject({ - text: 'Claude switched models: Claude Opus 5.5 → Claude Opus 4.8.', - tone: 'notice', - presentation: 'turn-notice', - providerFrame: { provider: 'claude', kind: 'message:assistant:content:fallback' } - }) - expect(items).toContainEqual( - expect.objectContaining({ - kind: 'message', - role: 'assistant', - blocks: [{ type: 'text', text: 'Continuing the answer.' }] - }) - ) - expect(items).toContainEqual(expect.objectContaining({ kind: 'turn', state: 'completed' })) - }) - - it('keeps provider-fallback rows distinct across acquisitions', async () => { - const journal = await openAgentSessionJournal({ - identity: IDENTITY, - database: await openTestAgentSessionDatabase(root), - now: () => 1_700_000_000_000, - mintEpoch: () => 'epoch-1' - }) - const deferred = createDeferredStructuredAgentSessionEventSink(testEventSinkLogging()) - await followTestSinkSnapshots(deferred, journal) - deferred.bind({ - journal, - fence: 1, - publish: vi.fn() - }) - - const first = createClaudeJournalTranslator({ sink: deferred.sink, fallbackIdPrefix: '1' }) - const second = createClaudeJournalTranslator({ sink: deferred.sink, fallbackIdPrefix: '2' }) - - first.handle(message('assistant', 'assistant-1', [{ type: 'future_event', message: 'first' }])) - await deferred.drained() - second.handle( - message('assistant', 'assistant-2', [{ type: 'future_event', message: 'second' }]) - ) - await deferred.drained() - - const fallbackRows = (await readTestJournalItems(journal)).filter( - (item) => - item.body.kind === 'status' && - item.body.providerFrame?.kind === 'message:assistant:content:future_event' - ) - - expect(fallbackRows).toHaveLength(2) - expect(fallbackRows.map(statusText)).toEqual(['first', 'second']) - }) - - it.each([false, true])( - 'keeps unknown quota result disclosure only for a stopped turn (stopped: %s)', - async (stopped) => { - const journal = await openAgentSessionJournal({ - identity: IDENTITY, - database: await openTestAgentSessionDatabase(root), - now: () => 1_000 - }) - const deferred = createDeferredStructuredAgentSessionEventSink(testEventSinkLogging()) - await followTestSinkSnapshots(deferred, journal) - deferred.bind({ journal, fence: 1, publish: () => {} }) - const translator = createClaudeJournalTranslator({ sink: deferred.sink }) - const quota = message('assistant', 'quota', [{ type: 'text', text: 'Usage exhausted' }]) - if (quota.type !== 'message') { - throw new Error('expected provider message') - } - translator.handle({ - ...quota, - observedAt: 100, - message: { ...quota.message, api_error: 'usage_limit_reached' } - }) - await deferred.drained() - if (stopped) { - await journal.appendStopEvent({ reason: 'user-stop', turnId: 'quota' }, 1) - } - translator.handle({ - type: 'message', - sessionId: 'orca-session', - observedAt: 2_000, - message: { - type: 'result', - subtype: 'future_error', - is_error: true, - session_id: 'provider-1', - uuid: 'quota-result', - result: 'Usage exhausted', - terminal_reason: 'api_error' - } - }) - await deferred.drained() - const items = await readTestJournalItems(journal) - const disclosure = items.filter( - (item) => - item.body.kind === 'status' && - item.body.providerFrame?.kind === 'message:result:future_error' - ) - expect(disclosure).toHaveLength(stopped ? 1 : 0) - if (stopped) { - expect(disclosure[0]?.body).not.toHaveProperty('tone') - expect(disclosure[0]?.body).not.toHaveProperty('failure') - } - expect(items.find((item) => item.body.kind === 'turn')?.body).toMatchObject({ - kind: 'turn', - state: stopped ? 'interrupted' : 'completed', - ...(stopped ? {} : { outcome: 'failure' }) - }) - deferred.close() - await journal.close() - const reopened = await openAgentSessionJournal({ - identity: IDENTITY, - database: await openTestAgentSessionDatabase(root) - }) - expect(await readTestJournalItems(reopened)).toEqual(items) - await reopened.close() - } - ) }) - -function statusText(row: { body: AgentJournalItemBody }): string { - if (row.body.kind !== 'status') { - throw new Error('expected status row') - } - return row.body.text -} diff --git a/src/main/claude/structured/claude-kill-delivered-exit-receipt.ts b/src/main/claude/structured/lifecycle/claude-kill-delivered-exit-receipt.ts similarity index 78% rename from src/main/claude/structured/claude-kill-delivered-exit-receipt.ts rename to src/main/claude/structured/lifecycle/claude-kill-delivered-exit-receipt.ts index 4fa1bbb75ef..43c537c28cf 100644 --- a/src/main/claude/structured/claude-kill-delivered-exit-receipt.ts +++ b/src/main/claude/structured/lifecycle/claude-kill-delivered-exit-receipt.ts @@ -1,4 +1,4 @@ -import { AgentSessionAcquisitionRootExitObservedError } from '../../native-chat/agent-session-wire/acquisition/structured-agent-session-acquisition-errors' +import { AgentSessionAcquisitionRootExitObservedError } from '../../../native-chat/agent-session-wire/acquisition/structured-agent-session-acquisition-errors' export function isKillDeliveredExitReceipt( receipt: Error | undefined diff --git a/src/main/claude/structured/claude-structured-acquisition-release.ts b/src/main/claude/structured/lifecycle/claude-structured-acquisition-release.ts similarity index 89% rename from src/main/claude/structured/claude-structured-acquisition-release.ts rename to src/main/claude/structured/lifecycle/claude-structured-acquisition-release.ts index 6f5c32a838b..4438273a965 100644 --- a/src/main/claude/structured/claude-structured-acquisition-release.ts +++ b/src/main/claude/structured/lifecycle/claude-structured-acquisition-release.ts @@ -3,14 +3,14 @@ import { claudeCloseReport, claudeAcquisitionCleanupError } from './claude-structured-session-close' -import { AgentSessionAcquisitionExitUnprovenError } from '../../native-chat/agent-session-wire/acquisition/structured-agent-session-acquisition-errors' +import { AgentSessionAcquisitionExitUnprovenError } from '../../../native-chat/agent-session-wire/acquisition/structured-agent-session-acquisition-errors' import type { ClaudeAcquisitionRegistry, ClaudeSession, ClaudeSessionExit, ClaudeStructuredSessionAdapterDeps -} from './claude-structured-session-state' -import type { ProviderProcessCloseOptions } from '../../provider-process/provider-process-close' +} from '../claude-structured-session-state' +import type { ProviderProcessCloseOptions } from '../../../provider-process/provider-process-close' export type ClaudeReleaseRequest = { sessionId: string; closeOptions?: ProviderProcessCloseOptions } diff --git a/src/main/claude/structured/claude-structured-event-delivery.ts b/src/main/claude/structured/lifecycle/claude-structured-event-delivery.ts similarity index 87% rename from src/main/claude/structured/claude-structured-event-delivery.ts rename to src/main/claude/structured/lifecycle/claude-structured-event-delivery.ts index 6d8b79378b3..f15dedcecd8 100644 --- a/src/main/claude/structured/claude-structured-event-delivery.ts +++ b/src/main/claude/structured/lifecycle/claude-structured-event-delivery.ts @@ -1,12 +1,12 @@ -import { ClaudePluginInputError } from '../sdk-transport/claude-plugin-ui' -import { claudePromptCardWritten } from '../child-work/claude-child-work-evidence' +import { ClaudePluginInputError } from '../../sdk-transport/claude-plugin-ui' +import { claudePromptCardWritten } from '../../child-work/claude-child-work-evidence' import type { ClaudeAcquisitionAttempt, ClaudeSessionExit, ClaudeSession, - ClaudeStructuredSessionAdapterDeps, - ClaudeStructuredSessionEvent -} from './claude-structured-session-state' + ClaudeStructuredSessionAdapterDeps +} from '../claude-structured-session-state' +import type { ClaudeStructuredSessionEvent } from './claude-structured-session-event' type ClaudeEventDelivery = { session: ClaudeSession | null diff --git a/src/main/claude/structured/claude-structured-mcp.ts b/src/main/claude/structured/lifecycle/claude-structured-mcp.ts similarity index 93% rename from src/main/claude/structured/claude-structured-mcp.ts rename to src/main/claude/structured/lifecycle/claude-structured-mcp.ts index 41ff00aede6..1e5aecd3340 100644 --- a/src/main/claude/structured/claude-structured-mcp.ts +++ b/src/main/claude/structured/lifecycle/claude-structured-mcp.ts @@ -6,12 +6,12 @@ import { type AgentSessionMcpResult, type AgentSessionMcpServer, type AgentSessionMcpSignIn -} from '../../../shared/agent-session/options/protocol/agent-session-mcp' +} from '../../../../shared/agent-session/options/protocol/agent-session-mcp' import { isClaudeQueryClosed, type ClaudeMcpControls -} from '../sdk-transport/claude-agent-sdk-control-requests' -import type { ClaudeSession } from './claude-structured-session-state' +} from '../../sdk-transport/claude-agent-sdk-control-requests' +import type { ClaudeSession } from '../claude-structured-session-state' // The CLI refuses OAuth for stdio and sdk servers. const SIGN_IN_TRANSPORTS = new Set(['http', 'sse', 'claudeai-proxy']) diff --git a/src/main/claude/structured/claude-structured-owner-identity.ts b/src/main/claude/structured/lifecycle/claude-structured-owner-identity.ts similarity index 71% rename from src/main/claude/structured/claude-structured-owner-identity.ts rename to src/main/claude/structured/lifecycle/claude-structured-owner-identity.ts index 0cb0c69674a..a4ef76b94b4 100644 --- a/src/main/claude/structured/claude-structured-owner-identity.ts +++ b/src/main/claude/structured/lifecycle/claude-structured-owner-identity.ts @@ -1,8 +1,8 @@ -import type { AgentSessionJournalIdentity } from '../../../shared/agent-session/journal/agent-session-journal-identity' -import type { AgentSessionProviderHandleLink } from '../../../shared/agent-session/lifecycle/provider-handles/agent-session-provider-handle' -import { claudeProviderHandle } from '../../../shared/agent-session/lifecycle/provider-handles/agent-session-provider-handle-encoding' -import type { AgentSessionProcessIdentity } from '../../../shared/agent-session/lifecycle/agent-session-record' -import { readProcessStartTimeMs } from '../../runtime/agent-session/ownership/agent-session-process-identity-probe' +import type { AgentSessionJournalIdentity } from '../../../../shared/agent-session/journal/agent-session-journal-identity' +import type { AgentSessionProviderHandleLink } from '../../../../shared/agent-session/lifecycle/provider-handles/agent-session-provider-handle' +import { claudeProviderHandle } from '../../../../shared/agent-session/lifecycle/provider-handles/agent-session-provider-handle-encoding' +import type { AgentSessionProcessIdentity } from '../../../../shared/agent-session/lifecycle/agent-session-record' +import { readProcessStartTimeMs } from '../../../runtime/agent-session/ownership/agent-session-process-identity-probe' export function claudeProviderHandleLink(input: { sessionId: string diff --git a/src/main/claude/structured/claude-structured-plugin-ui-recovery.ts b/src/main/claude/structured/lifecycle/claude-structured-plugin-ui-recovery.ts similarity index 95% rename from src/main/claude/structured/claude-structured-plugin-ui-recovery.ts rename to src/main/claude/structured/lifecycle/claude-structured-plugin-ui-recovery.ts index 2a6b1015456..dedb37bc7d3 100644 --- a/src/main/claude/structured/claude-structured-plugin-ui-recovery.ts +++ b/src/main/claude/structured/lifecycle/claude-structured-plugin-ui-recovery.ts @@ -1,10 +1,10 @@ -import { claudeFocusedPlugin, ClaudePluginInputError } from '../sdk-transport/claude-plugin-ui' +import { claudeFocusedPlugin, ClaudePluginInputError } from '../../sdk-transport/claude-plugin-ui' import type { ClaudeAcquisitionAttempt, ClaudeAcquireCallbacks, ClaudeSession, ClaudeSessionExit -} from './claude-structured-session-state' +} from '../claude-structured-session-state' export function claudePluginUiRecovery( { diff --git a/src/main/claude/structured/claude-structured-session-acquisition.ts b/src/main/claude/structured/lifecycle/claude-structured-session-acquisition.ts similarity index 81% rename from src/main/claude/structured/claude-structured-session-acquisition.ts rename to src/main/claude/structured/lifecycle/claude-structured-session-acquisition.ts index a40295135cc..6efd631852c 100644 --- a/src/main/claude/structured/claude-structured-session-acquisition.ts +++ b/src/main/claude/structured/lifecycle/claude-structured-session-acquisition.ts @@ -1,33 +1,33 @@ -import type { AgentSessionAcquisition } from '../../native-chat/agent-session-wire/providers/structured-agent-session-adapter' -import { openClaudeStreamJsonConnection } from '../claude-stream-json-connection' -import { claudeLaunchPermissions } from './claude-structured-inbound-control' -import * as replay from './turns/claude-replay-turn-resolution' -import { claudeStartedUnechoedSend } from './turns/claude-command-lifecycle' -import { claudeSessionStateEndsTurn } from './turns/claude-session-state-turn-over' -import { settleClaudeTurnEndWaiters } from './turns/claude-request-end-wait' -import * as proof from './claude-structured-init-proof' -import { claudeConfigDirEnvPatch } from './launch/claude-config-dir-pin' +import type { AgentSessionAcquisition } from '../../../native-chat/agent-session-wire/providers/structured-agent-session-adapter' +import { openClaudeStreamJsonConnection } from '../../claude-stream-json-connection' +import { claudeLaunchPermissions } from '../permissions/claude-structured-inbound-control' +import * as replay from '../turns/claude-replay-turn-resolution' +import { claudeStartedUnechoedSend } from '../turns/claude-command-lifecycle' +import { claudeSessionStateEndsTurn } from '../turns/claude-session-state-turn-over' +import { settleClaudeTurnEndWaiters } from '../turns/claude-request-end-wait' +import * as proof from '../startup/claude-structured-init-proof' +import { claudeConfigDirEnvPatch } from '../launch/claude-config-dir-pin' import { claudeProcessIdentity } from './claude-structured-owner-identity' -import { ClaudePromptRegistry } from './permissions/claude-prompt-registry' -import { adoptClaudeStructuredSpawnOptions } from './launch/claude-structured-spawn-options' -import { observeClaudeExecutionModel } from './claude-structured-execution-observations' -import { observeClaudeFastModeFacts } from './launch/claude-structured-session-options' +import { ClaudePromptRegistry } from '../permissions/claude-prompt-registry' +import { adoptClaudeStructuredSpawnOptions } from '../launch/claude-structured-spawn-options' +import { observeClaudeExecutionModel } from '../turns/claude-structured-execution-observations' +import { observeClaudeFastModeFacts } from '../launch/claude-structured-session-options' import { createClaudeSessionPublication, reportClaudeOptions, publishClaudeSessionAttempt -} from './claude-structured-session-publication' -import type * as sessionState from './claude-structured-session-state' +} from '../startup/claude-structured-session-publication' +import type * as sessionState from '../claude-structured-session-state' import { resolveClaudeAcquisitionError } from './claude-structured-session-close' -import { claudeStartupError, claudeStartupExit } from './claude-structured-session-startup-exit' -import { readClaudeTranscriptEntryUuid } from '../transcripts/claude-transcript-entry-uuid' -import { claudeTurnResumePointWriter } from './claude-structured-resume-point' -import { withAgentSessionCreatePhase } from '../../observability/agent-session-instrumentation' -import { resolveClaudeAcquisitionLaunch } from './launch/claude-structured-acquisition-launch' -import * as journal from './journal/claude-structured-session-journal-control' -import { isRootClaudeFrame } from './turns/claude-turn-opening' -import { createClaudeStartupOutcome, endsClaudeStartup } from './claude-structured-startup-outcome' -import { claudeStartupResultError } from '../sdk-transport/claude-stream-json-exit-error' +import * as startupExit from '../startup/claude-structured-session-startup-exit' +import { readClaudeTranscriptEntryUuid } from '../../transcripts/claude-transcript-entry-uuid' +import { claudeTurnResumePointWriter } from '../turns/claude-structured-resume-point' +import { withAgentSessionCreatePhase } from '../../../observability/agent-session-instrumentation' +import { resolveClaudeAcquisitionLaunch } from '../launch/claude-structured-acquisition-launch' +import * as journal from '../journal/claude-structured-session-journal-control' +import { isRootClaudeFrame } from '../turns/claude-turn-opening' +import * as outcome from '../startup/claude-structured-startup-outcome' +import { claudeStartupResultError } from '../../sdk-transport/claude-stream-json-exit-error' import * as ui from './claude-structured-plugin-ui-recovery' export async function acquireClaudeSession({ @@ -54,11 +54,13 @@ export async function acquireClaudeSession({ let childEnded: Error | null = null const initProof = proof.createClaudeInitProof() // Owned by this acquisition alone, so a late frame cannot fail a replacement's open. - const startup = createClaudeStartupOutcome() + const startup = outcome.createClaudeStartupOutcome() const childFailed = (error: Error, ended?: Promise): void => { liveSession?.historyCatchUp?.abort() childEnded ??= error - void (ended ? ended.then(startup.fail) : endsClaudeStartup(error) && startup.fail(error)) + void (ended + ? ended.then(startup.fail) + : outcome.endsClaudeStartup(error) && startup.fail(error)) initProof.reject(error) } const delivery = { attempt, initProof, callbacks, sessionId, sessions } @@ -213,7 +215,7 @@ export async function acquireClaudeSession({ callbacks.finishClose(sessionId, attempt) return } - childFailed(...claudeStartupExit(error, attempt.connection, input.events)) + childFailed(...startupExit.claudeStartupExit(error, attempt.connection, input.events)) if (exits.get(sessionId)?.connection === attempt.connection) { callbacks.finishClose(sessionId, attempt) } else { @@ -295,7 +297,7 @@ export async function acquireClaudeSession({ attempt.delivery.dispose() unbindReadingControl?.() throw await resolveClaudeAcquisitionError({ - error: await claudeStartupError(error, attempt.connection), + error: await startupExit.claudeStartupError(error, attempt.connection), sessionId, sessions, attempt, diff --git a/src/main/claude/structured/claude-structured-session-close.ts b/src/main/claude/structured/lifecycle/claude-structured-session-close.ts similarity index 88% rename from src/main/claude/structured/claude-structured-session-close.ts rename to src/main/claude/structured/lifecycle/claude-structured-session-close.ts index 31902f6d51b..ac9985203af 100644 --- a/src/main/claude/structured/claude-structured-session-close.ts +++ b/src/main/claude/structured/lifecycle/claude-structured-session-close.ts @@ -3,25 +3,25 @@ import { type ClaudeAcquisitionRegistry, type ClaudeSession, type ClaudeSessionExit, - type ClaudeStructuredSessionEvent, cancelClaudeAcquisitionAttempt -} from './claude-structured-session-state' +} from '../claude-structured-session-state' +import type { ClaudeStructuredSessionEvent } from './claude-structured-session-event' import { AgentSessionAcquisitionExitProvenError, AgentSessionAcquisitionExitUnprovenError, AgentSessionAcquisitionRootExitObservedError -} from '../../native-chat/agent-session-wire/acquisition/structured-agent-session-acquisition-errors' -import { AgentSessionPreSpawnError } from '../../native-chat/agent-session-wire/providers/structured-agent-session-adapter-errors' -import type { ClaudeStreamJsonConnection } from '../claude-stream-json-connection' -import type { ClaudeJournalTranslator } from './journal/claude-journal-translator-contract' -import type { ClaudePromptRegistry } from './permissions/claude-prompt-registry' +} from '../../../native-chat/agent-session-wire/acquisition/structured-agent-session-acquisition-errors' +import { AgentSessionPreSpawnError } from '../../../native-chat/agent-session-wire/providers/structured-agent-session-adapter-errors' +import type { ClaudeStreamJsonConnection } from '../../claude-stream-json-connection' +import type { ClaudeJournalTranslator } from '../journal/claude-journal-translator-contract' +import type { ClaudePromptRegistry } from '../permissions/claude-prompt-registry' import { closeProcessRegistry } from '@orca/process-host/close-process-registry' -import { retireClaudeDispatchWaiters } from './claude-structured-dispatch' -import { claudeHeldSends } from './turns/claude-command-lifecycle' -import { settledClaudeTurnEndLeaf } from './claude-structured-resume-point' -import { settleClaudeTurnEndWaiters } from './turns/claude-request-end-wait' -import type { StructuredAgentSessionLogger } from '../../native-chat/agent-session-wire/host/structured-agent-session-logger' -import type { ProviderProcessCloseOptions } from '../../provider-process/provider-process-close' +import { retireClaudeDispatchWaiters } from '../dispatch/claude-structured-dispatch' +import { claudeHeldSends } from '../turns/claude-command-lifecycle' +import { settledClaudeTurnEndLeaf } from '../turns/claude-structured-resume-point' +import { settleClaudeTurnEndWaiters } from '../turns/claude-request-end-wait' +import type { StructuredAgentSessionLogger } from '../../../native-chat/agent-session-wire/host/structured-agent-session-logger' +import type { ProviderProcessCloseOptions } from '../../../provider-process/provider-process-close' /** Root exit releases the lease even with unverified descendants; a failed spawn proves no exit. */ export function claudeRootExitObserved( diff --git a/src/main/claude/structured/claude-structured-session-event.ts b/src/main/claude/structured/lifecycle/claude-structured-session-event.ts similarity index 84% rename from src/main/claude/structured/claude-structured-session-event.ts rename to src/main/claude/structured/lifecycle/claude-structured-session-event.ts index a0b7a15dfd5..72f5029aa51 100644 --- a/src/main/claude/structured/claude-structured-session-event.ts +++ b/src/main/claude/structured/lifecycle/claude-structured-session-event.ts @@ -1,7 +1,7 @@ -import type { SubmissionRejectionFact } from '../../../shared/agent-session/failures/agent-session-failure' -import type * as SessionAdapter from '../../native-chat/agent-session-wire/providers/structured-agent-session-adapter' -import type { ClaudePendingPrompt } from './permissions/claude-prompt-registry' -import type { ClaudeStartedSend } from './claude-structured-session-state' +import type { SubmissionRejectionFact } from '../../../../shared/agent-session/failures/agent-session-failure' +import type * as SessionAdapter from '../../../native-chat/agent-session-wire/providers/structured-agent-session-adapter' +import type { ClaudePendingPrompt } from '../permissions/claude-prompt-registry' +import type { ClaudeStartedSend } from '../claude-structured-session-state' export type ClaudeAuthDiagnostic = { apiKeySourceConfigured: boolean diff --git a/src/main/claude/structured/claude-structured-session-exit-lifecycle.ts b/src/main/claude/structured/lifecycle/claude-structured-session-exit-lifecycle.ts similarity index 87% rename from src/main/claude/structured/claude-structured-session-exit-lifecycle.ts rename to src/main/claude/structured/lifecycle/claude-structured-session-exit-lifecycle.ts index 1ad838f2210..aaca6eb91e0 100644 --- a/src/main/claude/structured/claude-structured-session-exit-lifecycle.ts +++ b/src/main/claude/structured/lifecycle/claude-structured-session-exit-lifecycle.ts @@ -1,41 +1,41 @@ -import type { ClaudeStreamJsonConnection } from '../claude-stream-json-connection' -import { withTimeout } from '../../../shared/concurrency/promise-timeout-fallback' +import type { ClaudeStreamJsonConnection } from '../../claude-stream-json-connection' +import { withTimeout } from '../../../../shared/concurrency/promise-timeout-fallback' import { agentSessionFailureFact, providerDiagnosticOf -} from '../../../shared/agent-session/failures/agent-session-failure' +} from '../../../../shared/agent-session/failures/agent-session-failure' import { providerExitObserved, providerStartupFailureFact, startupAcquisitionRefusal -} from '../../native-chat/agent-session-wire/startup/structured-agent-session-failure-text' -import { providerSpawnAbsent } from '../../provider-process/provider-executable-missing' -import { providerOutcomeLost } from '../../provider-process/provider-process-exit-status' +} from '../../../native-chat/agent-session-wire/startup/structured-agent-session-failure-text' +import { providerSpawnAbsent } from '../../../provider-process/provider-executable-missing' +import { providerOutcomeLost } from '../../../provider-process/provider-process-exit-status' import { claudeSessionHasTurnWork, settledClaudeTurnEndLeaf -} from './claude-structured-resume-point' -import { claudeHeldSends } from './turns/claude-command-lifecycle' -import { ClaudePluginInputError } from '../sdk-transport/claude-plugin-ui' -import type { AgentSessionStartEndings } from '../../native-chat/agent-session-wire/startup/structured-agent-session-start-failure' -import { claudeExitEnding } from './claude-structured-start-ending' +} from '../turns/claude-structured-resume-point' +import { claudeHeldSends } from '../turns/claude-command-lifecycle' +import { ClaudePluginInputError } from '../../sdk-transport/claude-plugin-ui' +import type { AgentSessionStartEndings } from '../../../native-chat/agent-session-wire/startup/structured-agent-session-start-failure' +import { claudeExitEnding } from '../startup/claude-structured-start-ending' import { closeClaudePublishedSessionForDeps, claudeCloseReport, settleClaudeExitedSession } from './claude-structured-session-close' -import { retireClaudeDispatchWaiters } from './claude-structured-dispatch' +import { retireClaudeDispatchWaiters } from '../dispatch/claude-structured-dispatch' import { AgentSessionAcquisitionExitUnprovenError, AgentSessionAcquisitionRootExitObservedError -} from '../../native-chat/agent-session-wire/acquisition/structured-agent-session-acquisition-errors' +} from '../../../native-chat/agent-session-wire/acquisition/structured-agent-session-acquisition-errors' import type { ClaudeAcquisitionAttempt, ClaudeSession, ClaudeSessionExit, - ClaudeStructuredSessionAdapterDeps, - ClaudeStructuredSessionEvent -} from './claude-structured-session-state' + ClaudeStructuredSessionAdapterDeps +} from '../claude-structured-session-state' +import type { ClaudeStructuredSessionEvent } from './claude-structured-session-event' export type ClaudeExitLifecycle = { sessions: Map diff --git a/src/main/claude/structured/claude-structured-session-id.ts b/src/main/claude/structured/lifecycle/claude-structured-session-id.ts similarity index 100% rename from src/main/claude/structured/claude-structured-session-id.ts rename to src/main/claude/structured/lifecycle/claude-structured-session-id.ts diff --git a/src/main/claude/structured/claude-full-access-policy.ts b/src/main/claude/structured/permissions/claude-full-access-policy.ts similarity index 97% rename from src/main/claude/structured/claude-full-access-policy.ts rename to src/main/claude/structured/permissions/claude-full-access-policy.ts index 8bfd7c0a19a..7f1a500c1fe 100644 --- a/src/main/claude/structured/claude-full-access-policy.ts +++ b/src/main/claude/structured/permissions/claude-full-access-policy.ts @@ -1,9 +1,9 @@ import { StringDecoder } from 'node:string_decoder' -import { isRootClaudeFrame } from './turns/claude-turn-opening' +import { isRootClaudeFrame } from '../turns/claude-turn-opening' import { readClaudeFrameString, readClaudeReportedPermissionMode -} from './claude-structured-init-proof' +} from '../startup/claude-structured-init-proof' export type ClaudeFullAccessPolicy = { /** Each raw stdout chunk, no later than the SDK reads it. */ diff --git a/src/main/claude/structured/claude-structured-inbound-control.test.ts b/src/main/claude/structured/permissions/claude-structured-inbound-control.test.ts similarity index 96% rename from src/main/claude/structured/claude-structured-inbound-control.test.ts rename to src/main/claude/structured/permissions/claude-structured-inbound-control.test.ts index 0444b4a350b..bd0a8651d75 100644 --- a/src/main/claude/structured/claude-structured-inbound-control.test.ts +++ b/src/main/claude/structured/permissions/claude-structured-inbound-control.test.ts @@ -1,6 +1,6 @@ import { describe, expect, it, vi } from 'vitest' import type { CanUseTool } from '@anthropic-ai/claude-agent-sdk' -import { ClaudePromptRegistry } from './permissions/claude-prompt-registry' +import { ClaudePromptRegistry } from './claude-prompt-registry' import { buildClaudePermissionCallbacks } from './claude-structured-inbound-control' type CanUseToolOptions = Parameters[2] diff --git a/src/main/claude/structured/claude-structured-inbound-control.ts b/src/main/claude/structured/permissions/claude-structured-inbound-control.ts similarity index 91% rename from src/main/claude/structured/claude-structured-inbound-control.ts rename to src/main/claude/structured/permissions/claude-structured-inbound-control.ts index 5252e0c2217..25020143ba9 100644 --- a/src/main/claude/structured/claude-structured-inbound-control.ts +++ b/src/main/claude/structured/permissions/claude-structured-inbound-control.ts @@ -1,14 +1,14 @@ import type { CanUseTool, OnUserDialog, PermissionResult } from '@anthropic-ai/claude-agent-sdk' -import type { ClaudePromptRegistry } from './permissions/claude-prompt-registry' -import type { ClaudeStructuredSessionEvent } from './claude-structured-session-state' -import type { ClaudeStreamJsonConnectionHandlers } from '../claude-stream-json-connection' -import type { ClaudeStructuredLaunch } from './launch/claude-structured-launch-resolution' -import { claudeLaunchSkipsPermissions } from './launch/claude-structured-spawn-options' +import type { ClaudePromptRegistry } from './claude-prompt-registry' +import type { ClaudeStructuredSessionEvent } from '../lifecycle/claude-structured-session-event' +import type { ClaudeStreamJsonConnectionHandlers } from '../../claude-stream-json-connection' +import type { ClaudeStructuredLaunch } from '../launch/claude-structured-launch-resolution' +import { claudeLaunchSkipsPermissions } from '../launch/claude-structured-spawn-options' import { createClaudeFullAccessPolicy } from './claude-full-access-policy' import { claudePermissionPresentation, claudePermissionSubject -} from './permissions/claude-permission-presentation' +} from './claude-permission-presentation' export type ClaudePermissionCallbackDeps = { sessionId: string diff --git a/src/main/claude/structured/claude-structured-init-proof.ts b/src/main/claude/structured/startup/claude-structured-init-proof.ts similarity index 92% rename from src/main/claude/structured/claude-structured-init-proof.ts rename to src/main/claude/structured/startup/claude-structured-init-proof.ts index 974536e2b38..e1589c13cd7 100644 --- a/src/main/claude/structured/claude-structured-init-proof.ts +++ b/src/main/claude/structured/startup/claude-structured-init-proof.ts @@ -1,7 +1,8 @@ -import type { AgentSessionAccountKind } from '../../../shared/agent-session/failures/agent-session-availability' -import { CLAUDE_DEFAULT_SETTING_SOURCES } from './launch/claude-structured-launch-resolution' -import type { ClaudeAuthDiagnostic, ClaudeSession } from './claude-structured-session-state' -import { AgentSessionAcquisitionRefusal } from '../../native-chat/agent-session-wire/providers/structured-agent-session-adapter-errors' +import type { AgentSessionAccountKind } from '../../../../shared/agent-session/failures/agent-session-availability' +import { CLAUDE_DEFAULT_SETTING_SOURCES } from '../launch/claude-structured-launch-resolution' +import type { ClaudeSession } from '../claude-structured-session-state' +import type { ClaudeAuthDiagnostic } from '../lifecycle/claude-structured-session-event' +import { AgentSessionAcquisitionRefusal } from '../../../native-chat/agent-session-wire/providers/structured-agent-session-adapter-errors' export type ClaudeInitObservation = { providerSessionId: string diff --git a/src/main/claude/structured/claude-structured-session-open.ts b/src/main/claude/structured/startup/claude-structured-session-open.ts similarity index 84% rename from src/main/claude/structured/claude-structured-session-open.ts rename to src/main/claude/structured/startup/claude-structured-session-open.ts index 2183935b7ab..cf46906518b 100644 --- a/src/main/claude/structured/claude-structured-session-open.ts +++ b/src/main/claude/structured/startup/claude-structured-session-open.ts @@ -1,18 +1,18 @@ -import { withStructuredHistoryInvocation } from '../../native-chat/agent-session-wire/acquisition/structured-agent-session-history-invocation' -import { usableJournalHistoryOrigin } from '../../native-chat/agent-session-journal/context-epochs/journal-history-origin' +import { withStructuredHistoryInvocation } from '../../../native-chat/agent-session-wire/acquisition/structured-agent-session-history-invocation' +import { usableJournalHistoryOrigin } from '../../../native-chat/agent-session-journal/context-epochs/journal-history-origin' import type { StructuredAgentSessionProviderOpenInput, StructuredAgentSessionProviderOpenResult -} from '../../native-chat/agent-session-wire/startup/structured-agent-session-provider-open-contract' -import { waitForPromiseWithSignal } from '../../../shared/concurrency/abort-signal-reason' -import { readClaudeStructuredSessionSettings } from './launch/claude-structured-session-acquisition-options' +} from '../../../native-chat/agent-session-wire/startup/structured-agent-session-provider-open-contract' +import { waitForPromiseWithSignal } from '../../../../shared/concurrency/abort-signal-reason' +import { readClaudeStructuredSessionSettings } from '../launch/claude-structured-session-acquisition-options' import { openClaudeSession, readClaudeStartupFacts } from './claude-structured-session-startup' -import { catchUpClaudeTranscript } from '../transcripts/claude-transcript-catch-up' +import { catchUpClaudeTranscript } from '../../transcripts/claude-transcript-catch-up' import type { ClaudeSession, - ClaudeStructuredSessionAdapterDeps, - ClaudeStructuredSessionEvent -} from './claude-structured-session-state' + ClaudeStructuredSessionAdapterDeps +} from '../claude-structured-session-state' +import type { ClaudeStructuredSessionEvent } from '../lifecycle/claude-structured-session-event' type ClaudeOpenInput = { request: StructuredAgentSessionProviderOpenInput diff --git a/src/main/claude/structured/claude-structured-session-publication.ts b/src/main/claude/structured/startup/claude-structured-session-publication.ts similarity index 83% rename from src/main/claude/structured/claude-structured-session-publication.ts rename to src/main/claude/structured/startup/claude-structured-session-publication.ts index 9b38fde6267..72cffb3d502 100644 --- a/src/main/claude/structured/claude-structured-session-publication.ts +++ b/src/main/claude/structured/startup/claude-structured-session-publication.ts @@ -1,29 +1,29 @@ -import { withAgentSessionCreatePhase } from '../../observability/agent-session-instrumentation' -import { agentSessionAccountHome } from '../../../shared/agent-session/lifecycle/accounts/agent-session-account-home' -import { CLAUDE_STRUCTURED_AGENT } from './claude-structured-agent-definition' +import { withAgentSessionCreatePhase } from '../../../observability/agent-session-instrumentation' +import { agentSessionAccountHome } from '../../../../shared/agent-session/lifecycle/accounts/agent-session-account-home' +import { CLAUDE_STRUCTURED_AGENT } from '../claude-structured-agent-definition' import { randomUUID } from 'node:crypto' -import { refreshClaudeStructuredSessionOptions } from './launch/claude-structured-session-options' +import { refreshClaudeStructuredSessionOptions } from '../launch/claude-structured-session-options' import type { AgentSessionAcquisition, StructuredAgentSessionAcquireInput -} from '../../native-chat/agent-session-wire/providers/structured-agent-session-adapter' -import { claudeProviderHandleLink } from './claude-structured-owner-identity' -import type { ClaudePromptRegistry } from './permissions/claude-prompt-registry' -import type { ClaudeJournalTranslator } from './journal/claude-journal-translator-contract' +} from '../../../native-chat/agent-session-wire/providers/structured-agent-session-adapter' +import { claudeProviderHandleLink } from '../lifecycle/claude-structured-owner-identity' +import type { ClaudePromptRegistry } from '../permissions/claude-prompt-registry' +import type { ClaudeJournalTranslator } from '../journal/claude-journal-translator-contract' import type { ClaudeSession, ClaudeSessionExit, ClaudeAcquisitionAttempt, ClaudeAcquireCallbacks, - ClaudeStructuredSessionEvent, ClaudeStructuredSessionAdapterDeps -} from './claude-structured-session-state' -import { ClaudeBackgroundTaskTracker } from '../background-tasks/claude-background-task-tracker' -import { ClaudeChildWorkDecoder } from '../child-work/claude-child-work-decoder' -import { ClaudeSlashCommandCatalog } from '../command-catalog/claude-slash-command-catalog' -import type { ClaudeStructuredLaunch } from './launch/claude-structured-launch-resolution' -import type { ClaudeAcquisitionLaunch } from './launch/claude-structured-acquisition-launch' -import type { ClaudeNamingGeneration } from '../conversation-naming/claude-naming-generation' +} from '../claude-structured-session-state' +import type { ClaudeStructuredSessionEvent } from '../lifecycle/claude-structured-session-event' +import { ClaudeBackgroundTaskTracker } from '../../background-tasks/claude-background-task-tracker' +import { ClaudeChildWorkDecoder } from '../../child-work/claude-child-work-decoder' +import { ClaudeSlashCommandCatalog } from '../../command-catalog/claude-slash-command-catalog' +import type { ClaudeStructuredLaunch } from '../launch/claude-structured-launch-resolution' +import type { ClaudeAcquisitionLaunch } from '../launch/claude-structured-acquisition-launch' +import type { ClaudeNamingGeneration } from '../../conversation-naming/claude-naming-generation' import { readClaudeStartupFacts } from './claude-structured-session-startup' function claudeSessionInitialization(input: { diff --git a/src/main/claude/structured/claude-structured-session-startup-exit.ts b/src/main/claude/structured/startup/claude-structured-session-startup-exit.ts similarity index 76% rename from src/main/claude/structured/claude-structured-session-startup-exit.ts rename to src/main/claude/structured/startup/claude-structured-session-startup-exit.ts index 90df3b954b5..d4c18e04aa1 100644 --- a/src/main/claude/structured/claude-structured-session-startup-exit.ts +++ b/src/main/claude/structured/startup/claude-structured-session-startup-exit.ts @@ -1,14 +1,14 @@ -import { isClaudeQueryClosed } from '../sdk-transport/claude-agent-sdk-control-requests' -import { withTimeout } from '../../../shared/concurrency/promise-timeout-fallback' +import { isClaudeQueryClosed } from '../../sdk-transport/claude-agent-sdk-control-requests' +import { withTimeout } from '../../../../shared/concurrency/promise-timeout-fallback' import { providerExitObserved, startupAcquisitionRefusal, withObservedProviderExit -} from '../../native-chat/agent-session-wire/startup/structured-agent-session-failure-text' -import type { ClaudeStreamJsonConnection } from '../claude-stream-json-connection' -import type { StructuredAgentSessionEventSink } from '../../native-chat/agent-session-wire/journal-ingress/structured-agent-session-event-sink' -import { claudeStartFailure, claudeStartupAnswer } from '../sdk-transport/claude-startup-failure' -import type { AgentSessionStartFailure } from '../../native-chat/agent-session-wire/startup/structured-agent-session-start-failure' +} from '../../../native-chat/agent-session-wire/startup/structured-agent-session-failure-text' +import type { ClaudeStreamJsonConnection } from '../../claude-stream-json-connection' +import type { StructuredAgentSessionEventSink } from '../../../native-chat/agent-session-wire/journal-ingress/structured-agent-session-event-sink' +import { claudeStartFailure, claudeStartupAnswer } from '../../sdk-transport/claude-startup-failure' +import type { AgentSessionStartFailure } from '../../../native-chat/agent-session-wire/startup/structured-agent-session-start-failure' /** A physical exit waits briefly for initialize's answer, which the start's verdict weighs * against the exit; a query closed by that exit is no answer. */ diff --git a/src/main/claude/structured/claude-structured-session-startup.test.ts b/src/main/claude/structured/startup/claude-structured-session-startup.test.ts similarity index 54% rename from src/main/claude/structured/claude-structured-session-startup.test.ts rename to src/main/claude/structured/startup/claude-structured-session-startup.test.ts index ed8332f3dd5..512223d81ec 100644 --- a/src/main/claude/structured/claude-structured-session-startup.test.ts +++ b/src/main/claude/structured/startup/claude-structured-session-startup.test.ts @@ -6,12 +6,11 @@ import { claudeFrame, identityFor, recordingJournalSink, - USER_MESSAGE, PROVIDER_SESSION_ID -} from './claude-structured-session-test-support' -import { claudeOpened } from './claude-structured-startup-settled-test-support' -import type { ClaudeStructuredSessionEvent } from './claude-structured-session-state' -import type { ClaudeStructuredLaunch } from './launch/claude-structured-launch-resolution' +} from '../claude-structured-session-test-support' + +import type { ClaudeStructuredSessionEvent } from '../lifecycle/claude-structured-session-event' +import type { ClaudeStructuredLaunch } from '../launch/claude-structured-launch-resolution' const owned: { claude: ReturnType @@ -22,7 +21,7 @@ const owned: { const ACQUIRE = { identity: identityFor(), fence: 7, spawnToken: 'spawn-9' } const fixture = (name: string): Record[] => - readFileSync(new URL(`../__fixtures__/${name}.jsonl`, import.meta.url), 'utf8') + readFileSync(new URL(`../../__fixtures__/${name}.jsonl`, import.meta.url), 'utf8') .trim() .split('\n') .map((line) => JSON.parse(line)) @@ -86,51 +85,4 @@ describe('Claude host-awaited open', () => { }) // SDK-typed shape; ordering constructed - - it('returns from open without waiting for optional settings', async () => { - let answerSettings: (value: unknown) => void = () => {} - const settings = new Promise((resolve) => { - answerSettings = resolve - }) - const claude = fakeClaude({ settings }) - const { adapter, events } = adapterFor(claude) - try { - await adapter.acquire(ACQUIRE) - const opened = await claudeOpened(adapter, 'session-1') - expect(opened.reportedOptions).toBeDefined() - expect(claude.connections[0].calls.map((call) => call.subtype)).toContain('get_settings') - expect(events.some((event) => event.type === 'options-reported')).toBe(false) - answerSettings({ applied: { model: 'claude-haiku-4-5' }, effective: {} }) - await vi.waitFor(() => - expect(events.find((event) => event.type === 'options-reported')).toMatchObject({ - reportedOptions: { model: 'claude-haiku-4-5' } - }) - ) - await adapter.closeAll() - } finally { - answerSettings({}) - } - }) - - it('opens a healthy Claude session whose initialize takes longer than a minute', async () => { - const claude = fakeClaude({ initDelayMs: 75_000 }) - const { adapter } = adapterFor(claude) - await adapter.acquire(ACQUIRE) - const opened = expect(claudeOpened(adapter, 'session-1')).resolves.toMatchObject({ - reportedOptions: expect.any(Object) - }) - await vi.advanceTimersByTimeAsync(75_000) - await opened - await expect( - adapter.dispatch({ - sessionId: 'session-1', - fence: 7, - clientMessageId: 'slow-start', - body: USER_MESSAGE - }) - ).resolves.toMatchObject({ state: 'admitted' }) - expect(claude.connections[0].sent).toMatchObject([ - { message: { content: [{ type: 'text', text: 'ship it' }] } } - ]) - }) }) diff --git a/src/main/claude/structured/claude-structured-session-startup.ts b/src/main/claude/structured/startup/claude-structured-session-startup.ts similarity index 90% rename from src/main/claude/structured/claude-structured-session-startup.ts rename to src/main/claude/structured/startup/claude-structured-session-startup.ts index 60cc71d166c..70025ba3fd1 100644 --- a/src/main/claude/structured/claude-structured-session-startup.ts +++ b/src/main/claude/structured/startup/claude-structured-session-startup.ts @@ -1,15 +1,15 @@ -import { isClaudeQueryClosed } from '../sdk-transport/claude-agent-sdk-control-requests' -import { claudeStartFailure } from '../sdk-transport/claude-startup-failure' +import { isClaudeQueryClosed } from '../../sdk-transport/claude-agent-sdk-control-requests' +import { claudeStartFailure } from '../../sdk-transport/claude-startup-failure' import { startupAcquisitionRefusal, providerExitObserved -} from '../../native-chat/agent-session-wire/startup/structured-agent-session-failure-text' +} from '../../../native-chat/agent-session-wire/startup/structured-agent-session-failure-text' // Initialize gates host open after process publication; settings enrichment runs independently. -import type { AgentSessionAccountKind } from '../../../shared/agent-session/failures/agent-session-availability' -import type { StructuredAgentSessionProviderOpenResult } from '../../native-chat/agent-session-wire/startup/structured-agent-session-provider-open-contract' -import type { ClaudeStreamJsonConnection } from '../claude-stream-json-connection' -import { ClaudeSlashCommandCatalog } from '../command-catalog/claude-slash-command-catalog' +import type { AgentSessionAccountKind } from '../../../../shared/agent-session/failures/agent-session-availability' +import type { StructuredAgentSessionProviderOpenResult } from '../../../native-chat/agent-session-wire/startup/structured-agent-session-provider-open-contract' +import type { ClaudeStreamJsonConnection } from '../../claude-stream-json-connection' +import { ClaudeSlashCommandCatalog } from '../../command-catalog/claude-slash-command-catalog' import { claudeAuthDiagnostic, claudeInitializationAuthError, @@ -22,24 +22,24 @@ import { import { claudeStructuredSessionPublicationOptions, prepareClaudeStructuredSessionAcquisitionOptions -} from './launch/claude-structured-session-acquisition-options' +} from '../launch/claude-structured-session-acquisition-options' import { claudeStructuredSessionOptionsFrom, observeClaudeSettingsApplied, readClaudeSettingsApplied, readClaudeFastModeFacts, observeClaudeSettingsEffort -} from './launch/claude-structured-session-options' -import { claudeExecutionObservations } from './claude-structured-execution-observations' +} from '../launch/claude-structured-session-options' +import { claudeExecutionObservations } from '../turns/claude-structured-execution-observations' import { claudeExitForReport, claudeStartupAnswerAfterExit } from './claude-structured-session-startup-exit' +import type { ClaudeSession } from '../claude-structured-session-state' import type { ClaudeAuthDiagnostic, - ClaudeSession, ClaudeStructuredSessionEvent -} from './claude-structured-session-state' +} from '../lifecycle/claude-structured-session-event' export type ClaudeOpenFacts = Pick diff --git a/src/main/claude/structured/claude-structured-start-ending.ts b/src/main/claude/structured/startup/claude-structured-start-ending.ts similarity index 84% rename from src/main/claude/structured/claude-structured-start-ending.ts rename to src/main/claude/structured/startup/claude-structured-start-ending.ts index 7d721d7d854..6438786c32a 100644 --- a/src/main/claude/structured/claude-structured-start-ending.ts +++ b/src/main/claude/structured/startup/claude-structured-start-ending.ts @@ -1,16 +1,16 @@ -import { waitForPromiseWithSignal } from '../../../shared/concurrency/abort-signal-reason' -import { withObservedProviderExit } from '../../native-chat/agent-session-wire/startup/structured-agent-session-failure-text' +import { waitForPromiseWithSignal } from '../../../../shared/concurrency/abort-signal-reason' +import { withObservedProviderExit } from '../../../native-chat/agent-session-wire/startup/structured-agent-session-failure-text' import type { AgentSessionStartEndings, AgentSessionStartFailure -} from '../../native-chat/agent-session-wire/startup/structured-agent-session-start-failure' +} from '../../../native-chat/agent-session-wire/startup/structured-agent-session-start-failure' import type { StructuredAgentSessionProviderOpenInput, StructuredAgentSessionProviderOpenResult -} from '../../native-chat/agent-session-wire/startup/structured-agent-session-provider-open-contract' +} from '../../../native-chat/agent-session-wire/startup/structured-agent-session-provider-open-contract' import { openClaudeStructuredSession } from './claude-structured-session-open' -import { claudeStartFailure } from '../sdk-transport/claude-startup-failure' -import type { ClaudeSession, ClaudeSessionExit } from './claude-structured-session-state' +import { claudeStartFailure } from '../../sdk-transport/claude-startup-failure' +import type { ClaudeSession, ClaudeSessionExit } from '../claude-structured-session-state' /** Publishes an acquisition's session with its start ending admitted first, so its exit is never * missed. A failed acquire has no start owner left, so it retires exactly that admission. */ diff --git a/src/main/claude/structured/claude-structured-startup-outcome.ts b/src/main/claude/structured/startup/claude-structured-startup-outcome.ts similarity index 96% rename from src/main/claude/structured/claude-structured-startup-outcome.ts rename to src/main/claude/structured/startup/claude-structured-startup-outcome.ts index c7097121595..d69c253acec 100644 --- a/src/main/claude/structured/claude-structured-startup-outcome.ts +++ b/src/main/claude/structured/startup/claude-structured-startup-outcome.ts @@ -1,7 +1,7 @@ import { providerExitObserved, startupAcquisitionRefusal -} from '../../native-chat/agent-session-wire/startup/structured-agent-session-failure-text' +} from '../../../native-chat/agent-session-wire/startup/structured-agent-session-failure-text' /** One acquisition's startup: its first ending cause is the one its open rejects with. */ export type ClaudeStartupOutcome = { diff --git a/src/main/claude/structured/claude-structured-startup-settled-test-support.ts b/src/main/claude/structured/startup/claude-structured-startup-settled-test-support.ts similarity index 95% rename from src/main/claude/structured/claude-structured-startup-settled-test-support.ts rename to src/main/claude/structured/startup/claude-structured-startup-settled-test-support.ts index a1c2e99aed6..3c0f9f07ccc 100644 --- a/src/main/claude/structured/claude-structured-startup-settled-test-support.ts +++ b/src/main/claude/structured/startup/claude-structured-startup-settled-test-support.ts @@ -1,5 +1,5 @@ -import type { StructuredAgentSessionProviderOpenResult } from '../../native-chat/agent-session-wire/startup/structured-agent-session-provider-open-contract' -import type { ClaudeStructuredSessionAdapter } from './claude-structured-session-adapter' +import type { StructuredAgentSessionProviderOpenResult } from '../../../native-chat/agent-session-wire/startup/structured-agent-session-provider-open-contract' +import type { ClaudeStructuredSessionAdapter } from '../claude-structured-session-adapter' const opened = new WeakMap< ClaudeStructuredSessionAdapter, diff --git a/src/main/claude/structured/turns/claude-command-lifecycle.test.ts b/src/main/claude/structured/turns/claude-command-lifecycle.test.ts index 2f9565b010e..190644a3d9a 100644 --- a/src/main/claude/structured/turns/claude-command-lifecycle.test.ts +++ b/src/main/claude/structured/turns/claude-command-lifecycle.test.ts @@ -14,7 +14,7 @@ import { PROVIDER_SESSION_ID, type FakeConnection } from '../claude-structured-session-test-support' -import { claudeStartupSettled } from '../claude-structured-startup-settled-test-support' +import { claudeStartupSettled } from '../startup/claude-structured-startup-settled-test-support' type CapturedEvent = | { kind: 'meta'; providerSessionId: string } diff --git a/src/main/claude/structured/turns/claude-command-lifecycle.ts b/src/main/claude/structured/turns/claude-command-lifecycle.ts index e08fa2c1b6d..194ae8b1f5e 100644 --- a/src/main/claude/structured/turns/claude-command-lifecycle.ts +++ b/src/main/claude/structured/turns/claude-command-lifecycle.ts @@ -11,8 +11,8 @@ import { import { rejectClaudeDispatchWaiters, releaseClaudeDispatchWaitersInDoubt -} from '../claude-structured-dispatch' -import { readClaudeFrameString } from '../claude-structured-init-proof' +} from '../dispatch/claude-structured-dispatch' +import { readClaudeFrameString } from '../startup/claude-structured-init-proof' import type { ClaudeLateDispatchSettlement } from './claude-replay-turn-resolution' import type { ClaudeSession, ClaudeStartedSend } from '../claude-structured-session-state' diff --git a/src/main/claude/structured/turns/claude-replay-turn-resolution.ts b/src/main/claude/structured/turns/claude-replay-turn-resolution.ts index ef465773977..bd2876296c3 100644 --- a/src/main/claude/structured/turns/claude-replay-turn-resolution.ts +++ b/src/main/claude/structured/turns/claude-replay-turn-resolution.ts @@ -3,7 +3,7 @@ import { releaseClaudeDispatchesUnansweredAtIdle } from './claude-command-lifecycle' import { claudeSessionStateEndsTurn } from './claude-session-state-turn-over' -import { forgetRetiredWaiter } from '../claude-structured-dispatch-waiters' +import { forgetRetiredWaiter } from '../dispatch/claude-structured-dispatch-waiters' import { claudeHasReplayContent, readClaudeMessageEnvelope @@ -13,8 +13,8 @@ import type { ClaudeLateDispatchOutcome, ClaudeSession } from '../claude-structured-session-state' -import { readClaudeFrameString } from '../claude-structured-init-proof' -import { claudeDispatchContentKey } from '../claude-structured-dispatch-content' +import { readClaudeFrameString } from '../startup/claude-structured-init-proof' +import { claudeDispatchContentKey } from '../dispatch/claude-structured-dispatch-content' /** Settle provider-proven delivery independently of replay-row acceptance reconciliation. */ export type ClaudeLateDispatchSettlement = (input: ClaudeLateDispatchOutcome) => void diff --git a/src/main/claude/structured/claude-structured-command-dispatch.ts b/src/main/claude/structured/turns/claude-structured-command-dispatch.ts similarity index 75% rename from src/main/claude/structured/claude-structured-command-dispatch.ts rename to src/main/claude/structured/turns/claude-structured-command-dispatch.ts index d1e28be7a5b..c348439b4fa 100644 --- a/src/main/claude/structured/claude-structured-command-dispatch.ts +++ b/src/main/claude/structured/turns/claude-structured-command-dispatch.ts @@ -1,11 +1,11 @@ import { randomUUID } from 'node:crypto' -import { agentSessionCompactCommandText } from '../../../shared/agent-session/conversation-context/agent-session-conversation-command' +import { agentSessionCompactCommandText } from '../../../../shared/agent-session/conversation-context/agent-session-conversation-command' import type { AgentSessionCommandAdmission, StructuredAgentSessionCommandRun -} from '../../native-chat/agent-session-wire/providers/structured-agent-session-adapter' -import { dispatchClaudeTurn } from './claude-structured-dispatch' -import type { ClaudeSession } from './claude-structured-session-state' +} from '../../../native-chat/agent-session-wire/providers/structured-agent-session-adapter' +import { dispatchClaudeTurn } from '../dispatch/claude-structured-dispatch' +import type { ClaudeSession } from '../claude-structured-session-state' /** Open the command turn before sending; its result settles the waiter and closes that turn. */ export async function dispatchClaudeCommand( diff --git a/src/main/claude/structured/claude-structured-control-actions.ts b/src/main/claude/structured/turns/claude-structured-control-actions.ts similarity index 90% rename from src/main/claude/structured/claude-structured-control-actions.ts rename to src/main/claude/structured/turns/claude-structured-control-actions.ts index 138e3d6c6a9..67bd6b279d3 100644 --- a/src/main/claude/structured/claude-structured-control-actions.ts +++ b/src/main/claude/structured/turns/claude-structured-control-actions.ts @@ -1,14 +1,14 @@ import type { PermissionResult } from '@anthropic-ai/claude-agent-sdk' -import type { AgentChildWorkStopAcknowledgement } from '../../../shared/agent-status/child-work/agent-child-work-stop-targets' -import type { ClaudePromptClaim } from './permissions/claude-prompt-registry' +import type { AgentChildWorkStopAcknowledgement } from '../../../../shared/agent-status/child-work/agent-child-work-stop-targets' +import type { ClaudePromptClaim } from '../permissions/claude-prompt-registry' import { ClaudeControlRequestError, ClaudeControlRequestTimeoutError -} from '../sdk-transport/claude-agent-sdk-control-requests' -import { settleCancelledClaudeDispatchWaiters } from './claude-structured-dispatch' -import type { ClaudeLateDispatchSettlement } from './turns/claude-replay-turn-resolution' -import type { ClaudeSession } from './claude-structured-session-state' -import { CLAUDE_STOP_GRACE_MS } from './turns/claude-request-end-wait' +} from '../../sdk-transport/claude-agent-sdk-control-requests' +import { settleCancelledClaudeDispatchWaiters } from '../dispatch/claude-structured-dispatch' +import type { ClaudeLateDispatchSettlement } from './claude-replay-turn-resolution' +import type { ClaudeSession } from '../claude-structured-session-state' +import { CLAUDE_STOP_GRACE_MS } from './claude-request-end-wait' const INTERRUPT_CANCEL_QUEUED_CAPABILITY = 'interrupt_cancel_queued_v1' diff --git a/src/main/claude/structured/claude-structured-execution-observations.ts b/src/main/claude/structured/turns/claude-structured-execution-observations.ts similarity index 92% rename from src/main/claude/structured/claude-structured-execution-observations.ts rename to src/main/claude/structured/turns/claude-structured-execution-observations.ts index a390ca9cc4f..6753b4872a4 100644 --- a/src/main/claude/structured/claude-structured-execution-observations.ts +++ b/src/main/claude/structured/turns/claude-structured-execution-observations.ts @@ -1,5 +1,5 @@ -import { claudeObservedEffort } from './launch/claude-structured-session-options' -import type { ClaudeSession } from './claude-structured-session-state' +import { claudeObservedEffort } from '../launch/claude-structured-session-options' +import type { ClaudeSession } from '../claude-structured-session-state' /** Fast routing reports precede this input and cannot vouch for its execution. */ export function claudeExecutionObservations(session: ClaudeSession): Record { diff --git a/src/main/claude/structured/claude-structured-resume-point.ts b/src/main/claude/structured/turns/claude-structured-resume-point.ts similarity index 94% rename from src/main/claude/structured/claude-structured-resume-point.ts rename to src/main/claude/structured/turns/claude-structured-resume-point.ts index 286bf9d70f2..e703a4b099d 100644 --- a/src/main/claude/structured/claude-structured-resume-point.ts +++ b/src/main/claude/structured/turns/claude-structured-resume-point.ts @@ -1,9 +1,9 @@ import type { ClaudeSession, ClaudeStructuredSessionAdapterDeps -} from './claude-structured-session-state' -import { settleClaudeTurnEndWaiters } from './turns/claude-request-end-wait' -import { isRootClaudeFrame } from './turns/claude-turn-opening' +} from '../claude-structured-session-state' +import { settleClaudeTurnEndWaiters } from './claude-request-end-wait' +import { isRootClaudeFrame } from './claude-turn-opening' export function claudeTurnResumePointWriter( sessionId: string, diff --git a/src/main/claude/structured/turns/claude-turn-activity.ts b/src/main/claude/structured/turns/claude-turn-activity.ts index 45eecc1f561..f41ee646252 100644 --- a/src/main/claude/structured/turns/claude-turn-activity.ts +++ b/src/main/claude/structured/turns/claude-turn-activity.ts @@ -1,7 +1,7 @@ import { claudeProviderFrameActivity } from '../../../native-chat/agent-session-wire/providers/provider-frame-activity' import type { StructuredAgentSessionEventSink } from '../../../native-chat/agent-session-wire/journal-ingress/structured-agent-session-event-sink' import { claudeProviderFrameKind } from '../launch/claude-structured-provider-fallback' -import type { ClaudeStructuredSessionEvent } from '../claude-structured-session-event' +import type { ClaudeStructuredSessionEvent } from '../lifecycle/claude-structured-session-event' import type { ClaudeOpenTurn } from './claude-open-turn' import { claudeStreamTurnSource, isRootClaudeFrame } from './claude-turn-opening' diff --git a/src/main/claude/transcripts/claude-conversation-worker.test-fixture.ts b/src/main/claude/transcripts/claude-conversation-worker.test-fixture.ts deleted file mode 100644 index 517817a643c..00000000000 --- a/src/main/claude/transcripts/claude-conversation-worker.test-fixture.ts +++ /dev/null @@ -1,22 +0,0 @@ -import type * as WorkerThreads from 'node:worker_threads' -import type { WorkerOptions } from 'node:worker_threads' -import { vi } from 'vitest' - -vi.mock('node:worker_threads', async (importOriginal) => { - const actual = await importOriginal() - return { - ...actual, - Worker: class extends actual.Worker { - constructor(filename: string | URL, options?: WorkerOptions) { - super(filename, { - ...options, - execArgv: [ - ...(options?.execArgv ?? []), - '--import', - new URL('./claude-conversation-worker.test-loader.mjs', import.meta.url).href - ] - }) - } - } - } -}) diff --git a/src/main/claude/transcripts/claude-conversation-worker.test-loader.mjs b/src/main/claude/transcripts/claude-conversation-worker.test-loader.mjs deleted file mode 100644 index 9b2790bc017..00000000000 --- a/src/main/claude/transcripts/claude-conversation-worker.test-loader.mjs +++ /dev/null @@ -1,41 +0,0 @@ -import { readFileSync } from 'node:fs' -import { registerHooks } from 'node:module' -import { dirname, extname } from 'node:path' -import { fileURLToPath } from 'node:url' -import { transformSync } from 'esbuild' - -// Exercise the unbuilt worker and its production dependencies in Node. -registerHooks({ - resolve(specifier, context, nextResolve) { - try { - return nextResolve(specifier, context) - } catch (error) { - if ( - (error.code === 'ERR_MODULE_NOT_FOUND' || error.code === 'ERR_UNSUPPORTED_DIR_IMPORT') && - specifier.startsWith('.') && - !extname(specifier) - ) { - return nextResolve(`${specifier}.ts`, context) - } - throw error - } - }, - load(url, context, nextLoad) { - if (url.endsWith('.ts')) { - return { - format: 'module', - shortCircuit: true, - source: transformSync(readFileSync(new URL(url), 'utf8'), { - loader: 'ts', - format: 'esm', - target: 'esnext', - define: { - __filename: JSON.stringify(fileURLToPath(url)), - __dirname: JSON.stringify(dirname(fileURLToPath(url))) - } - }).code - } - } - return nextLoad(url, context) - } -}) diff --git a/src/main/claude/transcripts/claude-rewind-fork.ts b/src/main/claude/transcripts/claude-rewind-fork.ts index 0deb28356fc..ed2f4c993fc 100644 --- a/src/main/claude/transcripts/claude-rewind-fork.ts +++ b/src/main/claude/transcripts/claude-rewind-fork.ts @@ -10,7 +10,7 @@ import { getClaudeProfileRouter } from '../../claude-accounts/profiles/routing/c import type { StructuredAgentSessionAdapter } from '../../native-chat/agent-session-wire/providers/structured-agent-session-adapter' import { resolveSessionFilePath } from '../../native-chat/session-file-resolver' import { splitTranscriptStreamLines } from '../../native-chat/transcript-streaming/transcript-stream-lines' -import { claudeSessionIdForRewind } from '../structured/claude-structured-session-id' +import { claudeSessionIdForRewind } from '../structured/lifecycle/claude-structured-session-id' import { materializeClaudeRewindTranscript } from './claude-rewind-transcript' type TranscriptUserRow = { diff --git a/src/main/claude/transcripts/claude-transcript-catch-up-test-support.ts b/src/main/claude/transcripts/claude-transcript-catch-up-test-support.ts deleted file mode 100644 index 0ce2723b65a..00000000000 --- a/src/main/claude/transcripts/claude-transcript-catch-up-test-support.ts +++ /dev/null @@ -1,266 +0,0 @@ -import { readTestJournalItems } from '../../native-chat/agent-session-journal/journal-observation.test-support' -// Shared real disk/journal fixture for catch-up and historical-duration contracts. -import { appendFile, mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { afterEach, type Mock, vi } from 'vitest' -import type { AgentSessionJournalIdentity } from '../../../shared/agent-session/journal/agent-session-journal-identity' -import { claudeProviderHandle } from '../../../shared/agent-session/lifecycle/provider-handles/agent-session-provider-handle-encoding' -import { createTrackedJournalOpener } from '../../native-chat/agent-session-journal/store-lifecycle/journal-host-database-test-support' -import { createDeferredStructuredAgentSessionEventSink } from '../../native-chat/agent-session-wire/journal-ingress/structured-agent-session-event-sink' -import { testEventSinkLogging } from '../../native-chat/agent-session-wire/host/testing/structured-agent-session-logger.test-fixture' -import { createClaudeJournalTranslator } from '../structured/journal/claude-structured-journal-translation' -import { catchUpClaudeTranscript } from './claude-transcript-catch-up' -import { StructuredAgentSessionSnapshotRoutes } from '../../native-chat/agent-session-wire/host/structured-agent-session-snapshot-routes' - -export const SESSION = 'session-claude-catch-up' -export const SID = '402eff2b-84dc-4e05-8fe8-49fffb2cd3c3' - -/** One content block of a saved assistant row. */ -type ClaudeContentPart = { type: string } & Record - -export const at = (n: number) => new Date(Date.UTC(2026, 9, 21, 12, 0, n)).toISOString() -export const prompt = (uuid: string, parentUuid: string | null, text: string, n: number) => ({ - type: 'user', - uuid, - parentUuid, - isSidechain: false, - sessionId: SID, - promptSource: 'cli', - timestamp: at(n), - message: { role: 'user', content: text } -}) -export const reply = ( - uuid: string, - parentUuid: string, - messageId: string, - part: ClaudeContentPart, - n: number -) => ({ - type: 'assistant', - uuid, - parentUuid, - isSidechain: false, - sessionId: SID, - apiBlockIndex: 0, - timestamp: at(n), - message: { id: messageId, role: 'assistant', content: [part] } -}) -export const attachment = (uuid: string, parentUuid: string) => ({ - type: 'attachment', - uuid, - parentUuid, - isSidechain: false, - sessionId: SID, - attachment: { type: 'total_tokens_reminder' } -}) -export const bookkeeping = [ - { type: 'last-prompt', leafUuid: 'x', sessionId: SID }, - { type: 'cost-state' } -] - -/** The chat's own turn as Claude saves it; its reply is the streamed `msg_a`. */ -export const chatTurn = [ - prompt('p1', null, 'ask 1', 1), - attachment('t1', 'p1'), - reply('a1', 't1', 'msg_a', { type: 'text', text: 'answer 1' }, 2), - ...bookkeeping -] -/** A terminal turn on the same conversation: a prompt, a tool call and its result, then a reply. */ -export const outsideTurn = [ - { type: 'queue-operation', operation: 'enqueue', sessionId: SID }, - prompt('p2', 'a1', 'ask 2', 3), - attachment('t2', 'p2'), - reply('a2', 't2', 'msg_b', { type: 'tool_use', id: 'toolu_1', name: 'Read', input: {} }, 4), - { - type: 'user', - uuid: 'r2', - parentUuid: 'a2', - isSidechain: false, - sessionId: SID, - timestamp: at(5), - message: { - role: 'user', - content: [{ type: 'tool_result', tool_use_id: 'toolu_1', content: 'hello' }] - } - }, - reply('a3', 'r2', 'msg_c', { type: 'text', text: 'answer 2' }, 6), - ...bookkeeping -] - -const journals = createTrackedJournalOpener() -const cleanups: (() => Promise)[] = [] -afterEach(async () => { - vi.restoreAllMocks() - for (const cleanup of cleanups.splice(0)) { - await cleanup() - } -}) - -export async function chat(project = '-work', cwd = '/work') { - const root = await mkdtemp(join(tmpdir(), 'orca-claude-catch-up-')) - const projects = join(root, 'claude-home', 'projects', project) - await mkdir(projects, { recursive: true }) - const transcript = join(projects, `${SID}.jsonl`) - await writeFile(transcript, '') - const identity = { - sessionId: SESSION, - workspaceId: 'workspace-1', - hostId: 'local', - agent: 'claude', - providerHandle: claudeProviderHandle(SID, 'a1') - } satisfies AgentSessionJournalIdentity - let journal = await journals.open({ - identity, - stateDirectory: root, - now: () => 1_000 - }) - const deferred = createDeferredStructuredAgentSessionEventSink(testEventSinkLogging()) - const routes = new StructuredAgentSessionSnapshotRoutes(testEventSinkLogging().logger) - let releaseReplacement = journal.epochReplacements.observe((replaced) => - routes.replacing(SESSION, journal, replaced) - ) - await deferred.followSnapshots(routes.observe(SESSION, journal)) - deferred.bind({ journal, fence: 1, publish: () => {} }) - cleanups.push(async () => { - releaseReplacement() - deferred.close() - await journals.closeAll() - await rm(root, { recursive: true, force: true }) - }) - const warn: Mock<(...args: unknown[]) => void> = vi.fn() - return { - root, - identity, - get journal() { - return journal - }, - replay: async () => { - await deferred.drained() - releaseReplacement() - await journal.close() - journal = await journals.open({ identity, stateDirectory: root, now: () => 1_000 }) - releaseReplacement = journal.epochReplacements.observe((replaced) => - routes.replacing(SESSION, journal, replaced) - ) - await deferred.followSnapshots(routes.observe(SESSION, journal)) - deferred.bind({ journal, fence: 1, publish: () => {} }) - return journal - }, - warn, - deferred, - write: (rows: readonly Record[]) => - appendFile(transcript, rows.map((row) => `${JSON.stringify(row)}\n`).join('')), - /** The chat's own turn, sent and streamed live the way the SDK reports it. */ - live: async ( - options: { interrupted?: boolean; tool?: boolean; text?: string; thinking?: string } = {} - ) => { - const text = options.text ?? 'answer 1' - await journal.appendSubmission({ - clientMessageId: 'send-1', - body: { kind: 'message', role: 'user', blocks: [{ type: 'text', text: 'ask 1' }] }, - payloadFingerprint: 'send-1', - fence: 1 - }) - await journal.resolveDispatch({ - clientMessageId: 'send-1', - state: 'accepted', - providerIdentity: { provider: 'claude', sessionId: SID, uuid: 'p1' }, - fence: 1 - }) - const translator = createClaudeJournalTranslator({ sink: deferred.sink }) - const frame = (message: Record) => - translator.handle({ type: 'message', sessionId: SESSION, message, observedAt: 2_000 }) - const stream = (uuid: string, event: Record) => - frame({ type: 'stream_event', uuid, session_id: SID, parent_tool_use_id: null, event }) - stream('s1', { type: 'message_start', message: { id: 'msg_a' } }) - stream('s2', { - type: 'content_block_start', - index: 0, - content_block: { type: 'text', text: '' } - }) - stream('s3', { - type: 'content_block_delta', - index: 0, - delta: { type: 'text_delta', text } - }) - if (!options.interrupted) { - frame({ - type: 'assistant', - uuid: 'a1', - session_id: SID, - parent_tool_use_id: null, - message: { id: 'msg_a', role: 'assistant', content: [{ type: 'text', text }] } - }) - } - if (options.tool) { - frame({ - type: 'assistant', - uuid: 'call', - session_id: SID, - parent_tool_use_id: null, - message: { - id: 'call', - role: 'assistant', - content: [ - { type: 'tool_use', id: 'toolu_1', name: 'Read', input: { path: 'original' } } - ] - } - }) - } - if (options.thinking) { - stream('thought-start', { type: 'message_start', message: { id: 'msg_thought' } }) - stream('thought-block', { - type: 'content_block_start', - index: 0, - content_block: { type: 'thinking', thinking: '' } - }) - stream('thought-delta', { - type: 'content_block_delta', - index: 0, - delta: { type: 'thinking_delta', thinking: options.thinking } - }) - } - if (options.interrupted) { - translator.handle({ type: 'ended', sessionId: SESSION, reason: 'crash', observedAt: 3_000 }) - } else { - frame({ type: 'result', subtype: 'success', session_id: SID, parent_tool_use_id: null }) - } - translator.flush() - translator.dispose() - await deferred.drained() - }, - open: async ( - leafUuid: string, - options: Pick< - Parameters[0], - 'signal' | 'timeoutMs' | 'assertCurrent' - > = {} - ) => { - const covered = await catchUpClaudeTranscript({ - sessionId: SESSION, - providerSessionId: SID, - leafUuid, - claudeConfigDir: join(root, 'claude-home'), - cwd, - sink: deferred.sink, - logger: { warn, error: vi.fn() }, - ...options - }) - await deferred.drained() - return covered - }, - rows: async () => - (await readTestJournalItems(journal)).flatMap((item) => { - const { body } = item - if (body.kind === 'message') { - const text = body.blocks.map((block) => (block.type === 'text' ? block.text : '')) - return [`${body.role}:${text.join('')}`] - } - if (body.kind === 'tool-call') { - return [`tool:${body.name}:${body.state}`] - } - return body.kind === 'status' && body.presentation ? [`(${body.presentation})`] : [] - }) - } -} diff --git a/src/main/claude/transcripts/claude-transcript-catch-up.test.ts b/src/main/claude/transcripts/claude-transcript-catch-up.test.ts deleted file mode 100644 index be3b84d8476..00000000000 --- a/src/main/claude/transcripts/claude-transcript-catch-up.test.ts +++ /dev/null @@ -1,167 +0,0 @@ -import { - readTestJournalItems, - readTestJournalSnapshot, - readTestJournalSubmissions -} from '../../native-chat/agent-session-journal/journal-observation.test-support' -import './claude-conversation-worker.test-fixture' - -import { describe, expect, it, vi } from 'vitest' -import { createClaudeJournalTranslator } from '../structured/journal/claude-structured-journal-translation' -import { agentJournalItemKey } from '../../../shared/agent-session/journal/agent-session-journal-item-key' -import { claudePromptUuidForSubmission } from '../structured/claude-structured-session-id' -import { - SESSION, - SID, - chatTurn, - outsideTurn, - prompt, - reply, - attachment, - chat -} from './claude-transcript-catch-up-test-support' -// Real disk tail → isolated translator → deferred sink → on-disk journal contracts. -import * as transcriptTail from './claude-transcript-tail' -import { - withStructuredHistoryInvocation, - type StructuredHistoryInvocationOwner -} from '../../native-chat/agent-session-wire/acquisition/structured-agent-session-history-invocation' - -describe('Claude chat catch-up', () => { - it('revokes a queued catch-up on context activity without a journal write', async () => { - const c = await chat() - await c.live() - await c.write([...chatTurn, ...outsideTurn]) - const translator = createClaudeJournalTranslator({ sink: c.deferred.sink }) - const owner: StructuredHistoryInvocationOwner = {} - const append = c.deferred.sink.tryAppendTransition!.bind(c.deferred.sink) - vi.spyOn(c.deferred.sink, 'tryAppendTransition').mockImplementationOnce((transition) => - append({ - ...transition, - beforeRun: () => { - const allowed = transition.beforeRun?.() !== false - translator.markContextActivity() - return allowed - } - }) - ) - const before = await readTestJournalSnapshot(c.journal) - try { - const covered = await withStructuredHistoryInvocation( - owner, - new AbortController().signal, - async (signal, revoke) => { - const release = translator.subscribeContextActivity(revoke) - try { - return await c.open('a1', { signal }) - } finally { - release() - } - } - ) - expect(covered).toBe(false) - expect(await readTestJournalSnapshot(c.journal)).toEqual(before) - expect(await c.open('a1')).toBe(true) - expect((await readTestJournalItems(c.journal)).length).toBeGreaterThan(before.items.length) - } finally { - translator.dispose() - } - }) - - it('does not place historical lifecycle after live work that arrives during its read', async () => { - const c = await chat() - await c.live() - await c.write([...chatTurn, ...outsideTurn]) - const read = transcriptTail.readClaudeTranscriptTail - const live = createClaudeJournalTranslator({ sink: c.deferred.sink }) - vi.spyOn(transcriptTail, 'readClaudeTranscriptTail').mockImplementationOnce(async (input) => { - const tail = await read(input) - live.handle({ - type: 'message', - sessionId: SESSION, - message: { - type: 'stream_event', - uuid: 'wake', - session_id: SID, - parent_tool_use_id: null, - event: { type: 'message_start', message: { id: 'live-wake' } } - } - }) - return tail - }) - expect(await c.open('a1')).toBe(false) - expect(await c.rows()).not.toContain('user:ask 2') - const running = (await readTestJournalItems(c.journal)).findLast( - (item) => item.body.kind === 'turn' - ) - expect(running?.body).toMatchObject({ state: 'running' }) - live.dispose() - }) - - it('keeps retained aliases and unacknowledged queued prompts deduplicated', async () => { - const prompts = 100, - items = 10_000 - const c = await chat() - await c.live() - const expected = [...(await c.rows()), '(continued-outside)'] - const rows: Record[] = [ - reply('saved-leaf', 'earlier-prompt', 'msg_saved', { type: 'text', text: 'earlier' }, 0), - prompt('p1', 'saved-leaf', 'ask 1', 1), - ...chatTurn.slice(1) - ] - for (let n = 1; n < prompts; n++) { - rows.push( - prompt(`outside-p${n}`, n === 1 ? 'a1' : `outside-a${n - 1}`, `ask ${n}`, n * 2 + 1), - reply( - `outside-a${n}`, - `outside-p${n}`, - `msg_outside${n}`, - { type: 'text', text: `answer ${n}` }, - n * 2 + 2 - ) - ) - expected.push(`user:ask ${n}`, `assistant:answer ${n}`) - } - const alias = agentJournalItemKey({ provider: 'claude', sessionId: SID, uuid: 'p1' }) - const canonical = await c.journal.reads.canonicalItemId(alias) - expect(canonical).not.toBe(alias) - const submissions = await readTestJournalSubmissions(c.journal) - await c.write(rows) - expect(await c.open('saved-leaf')).toBe(true) - expect(await c.rows()).toEqual(expected) - expect(await readTestJournalSubmissions(c.journal)).toEqual(submissions) - await c.journal.appendLifecycleBatch({ - settlementId: 'perf-padding', - fence: 1, - mutations: Array.from( - { length: items - (await readTestJournalItems(c.journal)).length }, - (_, n) => ({ - kind: 'item' as const, - identity: { provider: 'orca' as const, clientMessageId: `padding${n}` }, - body: { kind: 'message' as const, role: 'user' as const, blocks: [] }, - turnScope: { kind: 'thread' as const } - }) - ) - }) - for (let n = 0; n < prompts; n++) { - const key = agentJournalItemKey({ provider: 'orca', clientMessageId: `padding${n}` }) - await c.write([ - { - ...attachment(`queued${n}`, n ? `queued${n - 1}` : `outside-a${prompts - 1}`), - attachment: { - type: 'queued_command', - source_uuid: claudePromptUuidForSubmission(SESSION, key), - commandMode: 'prompt', - prompt: 'local' - } - } - ]) - } - const before = await readTestJournalSnapshot(c.journal) - const itemCount = before.items.length - expect(itemCount).toBe(items) - expect(await c.open('saved-leaf')).toBe(true) - expect(await readTestJournalSnapshot(c.journal)).toEqual(before) - expect(await c.journal.reads.canonicalItemId(alias)).toBe(canonical) - expect(c.warn).not.toHaveBeenCalled() - }) -}) diff --git a/src/main/ipc/ai-vault/ai-vault-resume.ts b/src/main/ipc/ai-vault/ai-vault-resume.ts index ca53cdb6951..10c07cd558c 100644 --- a/src/main/ipc/ai-vault/ai-vault-resume.ts +++ b/src/main/ipc/ai-vault/ai-vault-resume.ts @@ -12,7 +12,7 @@ import { } from '../../../shared/execution-host/execution-host' import { isWslUncPath } from '../../../shared/file-access/wsl-paths' import { assertLegacyAiVaultResumeAllowed } from '../../ai-vault/structured-sessions/structured-session-ownership' -import { tryEnsureStructuredAgentSessionHostForResume } from '../../runtime/agent-session/structured-agent-session-host-refusal' +import { tryEnsureStructuredAgentSessionHostForResume } from '../../runtime/agent-session/installation/structured-agent-session-host-refusal' import { copyStructuredChatConversation } from '../../ai-vault/structured-sessions/structured-chat-conversation-copy' import { wakeNativeChatTranscriptDistro } from '../../native-chat/transcript-discovery/native-chat-open-wake' import { wslDistroForPath } from '../../wsl/filesystem/wsl-unc-access-gate' diff --git a/src/main/ipc/register-core-handlers/register-core-handlers.ts b/src/main/ipc/register-core-handlers/register-core-handlers.ts index b4c88d3ae6b..f6c6f6d9fd2 100644 --- a/src/main/ipc/register-core-handlers/register-core-handlers.ts +++ b/src/main/ipc/register-core-handlers/register-core-handlers.ts @@ -95,7 +95,7 @@ import { } from '../../ai-vault/runtime-hosts/runtime-session-scanner' import { callRuntimeSessionSearch } from '../../ai-vault/runtime-hosts/runtime-session-search-call' import { configureRuntimeAiVaultSessionDelete } from '../ai-vault/ai-vault-delete' -import { ensureStructuredAgentSessionHostUnlessRefused } from '../../runtime/agent-session/structured-agent-session-host-refusal' +import { ensureStructuredAgentSessionHostUnlessRefused } from '../../runtime/agent-session/installation/structured-agent-session-host-refusal' import { getAgentSessionAttachmentStore } from '../../native-chat/agent-session-attachments/agent-session-attachment-store-registry' import type { PluginService } from '../../plugins/plugin-service' import type { PluginMarketplaceHandlerServices } from '../plugin-marketplaces' diff --git a/src/main/native-chat/agent-session-journal/database/journal-sql-database.ts b/src/main/native-chat/agent-session-journal/database/journal-sql-database.ts index f87041ecace..8837782eee6 100644 --- a/src/main/native-chat/agent-session-journal/database/journal-sql-database.ts +++ b/src/main/native-chat/agent-session-journal/database/journal-sql-database.ts @@ -2,7 +2,7 @@ import { JournalSqlForkCopy } from '../journal-sql-fork-copy' import type { JournalForkPreparationInput } from '../journal-fork-preparation' import { randomUUID } from 'node:crypto' import type { AgentSessionJournalIdentity } from '../../../../shared/agent-session/journal/agent-session-journal-identity' -import { AgentSessionTabTable } from '../../../runtime/agent-session/agent-session-tab-table' +import { AgentSessionTabTable } from '../../../runtime/agent-session/records/agent-session-tab-table' import type { AgentSessionStoreState } from '../../../runtime/agent-session/records/agent-session-store-state' import { JournalSqlOwner } from '../journal-sql-owner' import { JournalSqlReaderPool } from '../journal-sql-reader-pool' diff --git a/src/main/native-chat/agent-session-journal/journal-creation-fact.test.ts b/src/main/native-chat/agent-session-journal/journal-creation-fact.test.ts index 862c559af23..d3e5b2e59c5 100644 --- a/src/main/native-chat/agent-session-journal/journal-creation-fact.test.ts +++ b/src/main/native-chat/agent-session-journal/journal-creation-fact.test.ts @@ -3,7 +3,7 @@ import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, expect, it } from 'vitest' import { codexProviderHandle } from '../../../shared/agent-session/lifecycle/provider-handles/agent-session-provider-handle-encoding' -import { openStructuredAgentSessionSqlJournalDatabase } from '../../runtime/agent-session/structured-agent-session-journal-open' +import { openStructuredAgentSessionSqlJournalDatabase } from '../../runtime/agent-session/installation/structured-agent-session-journal-open' import type { JournalSqlDatabase } from './database/journal-sql-database' import type { AgentSessionJournal } from './journal-store' import { SqlAgentSessionJournal } from './journal-sql-store' diff --git a/src/main/native-chat/agent-session-journal/journal-history-items.ts b/src/main/native-chat/agent-session-journal/journal-history-items.ts index 25313039b09..2ab83a52ffc 100644 --- a/src/main/native-chat/agent-session-journal/journal-history-items.ts +++ b/src/main/native-chat/agent-session-journal/journal-history-items.ts @@ -3,7 +3,7 @@ import type { AgentJournalRenderItem } from '../../../shared/agent-session/journal/agent-session-journal-types' import { parseAgentJournalItemKey } from '../../../shared/agent-session/journal/agent-session-journal-item-key' -import { claudePromptUuidForSubmission } from '../../claude/structured/claude-structured-session-id' +import { claudePromptUuidForSubmission } from '../../claude/structured/lifecycle/claude-structured-session-id' export const JOURNAL_HISTORY_ITEMS_LIMIT = 4_096 const JOURNAL_HISTORY_ITEMS_BYTES = 16 * 1024 * 1024 diff --git a/src/main/native-chat/agent-session-journal/journal-sql-claude-identities.test.ts b/src/main/native-chat/agent-session-journal/journal-sql-claude-identities.test.ts index fd17266c7ba..c570751d0e0 100644 --- a/src/main/native-chat/agent-session-journal/journal-sql-claude-identities.test.ts +++ b/src/main/native-chat/agent-session-journal/journal-sql-claude-identities.test.ts @@ -4,7 +4,7 @@ import { join } from 'node:path' import { afterEach, expect, it } from 'vitest' import type { AgentJournalItemBody } from '../../../shared/agent-session/journal/agent-session-journal-types' import { claudeProviderHandle } from '../../../shared/agent-session/lifecycle/provider-handles/agent-session-provider-handle-encoding' -import { openStructuredAgentSessionSqlJournalDatabase } from '../../runtime/agent-session/structured-agent-session-journal-open' +import { openStructuredAgentSessionSqlJournalDatabase } from '../../runtime/agent-session/installation/structured-agent-session-journal-open' import type { JournalSqlDatabase } from './database/journal-sql-database' import { SqlAgentSessionJournal } from './journal-sql-store' import { diff --git a/src/main/native-chat/agent-session-journal/journal-sql-history-items.test.ts b/src/main/native-chat/agent-session-journal/journal-sql-history-items.test.ts index e682f18e14e..6d0a8523b93 100644 --- a/src/main/native-chat/agent-session-journal/journal-sql-history-items.test.ts +++ b/src/main/native-chat/agent-session-journal/journal-sql-history-items.test.ts @@ -4,7 +4,7 @@ import { join } from 'node:path' import { afterEach, expect, it } from 'vitest' import { agentJournalItemKey } from '../../../shared/agent-session/journal/agent-session-journal-item-key' import { claudeProviderHandle } from '../../../shared/agent-session/lifecycle/provider-handles/agent-session-provider-handle-encoding' -import { openStructuredAgentSessionSqlJournalDatabase } from '../../runtime/agent-session/structured-agent-session-journal-open' +import { openStructuredAgentSessionSqlJournalDatabase } from '../../runtime/agent-session/installation/structured-agent-session-journal-open' import type { JournalSqlDatabase } from './database/journal-sql-database' import { SqlAgentSessionJournal } from './journal-sql-store' import { diff --git a/src/main/native-chat/agent-session-journal/journal-sql-stop-queue-adapters.test.ts b/src/main/native-chat/agent-session-journal/journal-sql-stop-queue-adapters.test.ts index be9d656fc2c..cd3e2d1e1fb 100644 --- a/src/main/native-chat/agent-session-journal/journal-sql-stop-queue-adapters.test.ts +++ b/src/main/native-chat/agent-session-journal/journal-sql-stop-queue-adapters.test.ts @@ -4,7 +4,7 @@ import { join } from 'node:path' import { afterEach, expect, it, vi } from 'vitest' import { codexProviderHandle } from '../../../shared/agent-session/lifecycle/provider-handles/agent-session-provider-handle-encoding' import type { AgentJournalMessageItem } from '../../../shared/agent-session/journal/agent-session-journal-types' -import { openStructuredAgentSessionSqlJournalDatabase } from '../../runtime/agent-session/structured-agent-session-journal-open' +import { openStructuredAgentSessionSqlJournalDatabase } from '../../runtime/agent-session/installation/structured-agent-session-journal-open' import type { JournalSqlDatabase } from './database/journal-sql-database' import { SqlAgentSessionJournal } from './journal-sql-store' import { @@ -121,62 +121,6 @@ it('keeps one ordered queue in SQL and pauses cards from before a reopen until r expect((await after.queuedMessages.nextInputCard())?.messageId).toBe('C') }) -it('retains a conservative reopen floor when the mark fails, apart from the opening cursor', async () => { - const { root, database, journal } = await fixture() - await journal.queuedMessages.insert({ messageId: 'A', body: message('A') }) - const restarted = await reopen(root, database, journal) - const after = restarted.journal - const opening = after.openingCursor() - const failure = new Error('disk full') - await restarted.database.serialize('session', (writer) => { - vi.spyOn(writer, 'write').mockRejectedValueOnce(failure) - }) - await expect(after.markQueueReopen(1)).rejects.toBe(failure) - const floor = after.reopenFloor() - expect(floor).toEqual({ - epoch: after.physicalCursor().epoch, - sequence: after.physicalCursor().sequence + 1 - }) - expect(after.openingCursor()).toEqual(opening) - expect((await after.queuedMessages.pauses()).map((pause) => pause.reason)).toEqual(['restarted']) - - await after.markQueueReopen(1) - expect(after.reopenFloor()).toBeNull() -}) - -it('reads the latest Stop from SQL and keeps its settlement in host memory only', async () => { - const { root, database, journal } = await fixture() - await journal.queuedMessages.insert({ messageId: 'A', body: message('A') }) - const accepted = await journal.acceptStop({ - event: { reason: 'user-stop' }, - fence: 1, - liveTurnId: 'turn-1' - }) - expect(accepted.turnId).toBe('turn-1') - expect(await journal.stopMarks.latest()).toMatchObject({ - event: { reason: 'user-stop', turnId: 'turn-1' } - }) - expect(await journal.stopMarks.personStopDecides('turn-1')).toBe(true) - expect(await journal.stopMarks.personStopDecides(null)).toBe(false) - expect(await journal.queuedMessages.nextInputCard()).toBeNull() - - const edges: number[] = [] - journal.stopMarks.observeSettleEdges(() => edges.push(journal.stopMarks.revision())) - const settle = await journal.stopMarks.beginSettle(true) - expect(settle).toEqual({ settling: true }) - expect(await journal.stopMarks.personStopDecides(null)).toBe(true) - journal.stopMarks.settled(settle, 'turn-2') - expect(edges).toEqual([1, 2]) - expect((await journal.stopMarks.latest())?.settle).toEqual({ settling: false, turnId: 'turn-2' }) - expect(await journal.stopMarks.personStopDecides('turn-2')).toBe(true) - - const restarted = await reopen(root, database, journal) - const stop = await restarted.journal.stopMarks.latest() - expect(stop).toMatchObject({ event: { reason: 'user-stop', turnId: 'turn-1' } }) - expect(stop?.settle).toBeUndefined() - expect(restarted.journal.stopMarks.revision()).toBe(0) -}) - it("lets every writer command plan with the host's unsaved Stop settlement", async () => { const { root, database, journal } = await fixture() const turn = (turnId: string, state: 'running' | 'interrupted') => @@ -216,46 +160,3 @@ it("lets every writer command plan with the host's unsaved Stop settlement", asy const restarted = await reopen(root, database, journal) expect((await restarted.journal.stopMarks.latest())?.settle).toBeUndefined() }) - -it('orders a later turn end behind the Stop settlement read', async () => { - const { database, journal } = await fixture() - await journal.appendItem( - { provider: 'orca', clientMessageId: 'later' }, - { kind: 'turn', turnId: 'later', state: 'running' }, - { fence: 1, turnScope: { kind: 'thread' } } - ) - await journal.appendStopEvent({ reason: 'user-stop', turnId: 'earlier' }, 1) - const stop = await journal.reads.latestStop() - const reached = Promise.withResolvers() - const release = Promise.withResolvers() - vi.spyOn(journal.reads, 'latestStop').mockImplementationOnce(() => { - reached.resolve() - return release.promise - }) - const settling = journal.stopMarks.beginSettle(true) - await reached.promise - const ended = database.serialize('session', (writer) => - writer.write({ - target: { - sessionId: 'session', - epoch: journal.physicalCursor().epoch, - ownerToken: journal.observationHandle() - }, - operation: { - kind: 'item', - identity: { provider: 'orca', clientMessageId: 'later' }, - body: { kind: 'turn', turnId: 'later', state: 'interrupted', completedAt: 100 }, - options: { fence: 1, turnScope: { kind: 'thread' } } - }, - facts: { identity, stopSettle: journal.stopMarks.fact() }, - savedAt: 100 - }) - ) - release.resolve(stop) - await settling - await ended - expect((await journal.reads.item('orca:later'))?.body).toMatchObject({ - state: 'interrupted', - outcome: 'cancellation' - }) -}) diff --git a/src/main/native-chat/agent-session-journal/journal-sql-store.test.ts b/src/main/native-chat/agent-session-journal/journal-sql-store.test.ts index 3b17ab4c8c9..e5fca24d8b7 100644 --- a/src/main/native-chat/agent-session-journal/journal-sql-store.test.ts +++ b/src/main/native-chat/agent-session-journal/journal-sql-store.test.ts @@ -1,15 +1,14 @@ import { AgentSessionSubscribers } from '../agent-session-wire/publication/subscribers/structured-agent-session-subscribers' import type { AgentSessionSubscribeEvent } from '../../../shared/agent-session/agent-session-wire' import Database from '../../sqlite/sync-database' -import { StructuredAgentSessionStatusFeed } from '../agent-session-wire/observations/structured-agent-session-status-feed' -import type { StatusFeedSession } from '../agent-session-wire/observations/structured-agent-session-status-feed-deps' + import type { JournalCurrentWorkAuthority } from './journal-observer-read' import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises' import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, expect, it, vi } from 'vitest' import { codexProviderHandle } from '../../../shared/agent-session/lifecycle/provider-handles/agent-session-provider-handle-encoding' -import { openStructuredAgentSessionSqlJournalDatabase } from '../../runtime/agent-session/structured-agent-session-journal-open' +import { openStructuredAgentSessionSqlJournalDatabase } from '../../runtime/agent-session/installation/structured-agent-session-journal-open' import { journalDatabasePath } from './database/journal-host-database' import { journalDomainDatabasePath } from './database/journal-domain-database' import type { JournalSqlDatabase } from './database/journal-sql-database' @@ -68,68 +67,6 @@ async function fixture(now: () => number = () => 100) { return { root, database, journal } } -it('holds automatic delivery for every editor until committed release, expiry or handle close', async () => { - let now = 100 - const { database, journal } = await fixture(() => now) - const card = await journal.queuedMessages.insert({ - messageId: 'draft', - body: { kind: 'message', role: 'user', blocks: [{ type: 'text', text: 'hello' }] } - }) - const desktop = { callerKey: 'desktop', editId: 'editing' } - const phone = { callerKey: 'phone', editId: 'editing' } - await journal.queuedMessages.editLeases.acquire(desktop, { - messageId: 'draft', - fingerprint: card.fingerprint - }) - now = 200 - expect( - await journal.queuedMessages.editLeases.acquire(phone, { - messageId: 'draft', - fingerprint: card.fingerprint - }) - ).toMatchObject({ status: 'held', remainingMs: 120_000 }) - await journal.queuedMessages.editLeases.release(desktop, 'draft') - expect(await journal.queuedMessages.nextInputCard()).toBeNull() - const heldRevision = journal.queuedMessages.revision() - await journal.appendSteps([ - { - kind: 'resolved-item', - resolution: { - kind: 'text-snapshot', - identity: { provider: 'orca', clientMessageId: 'text' }, - body: { - kind: 'message', - role: 'assistant', - blocks: [{ type: 'text', text: 'Still writing' }] - } - }, - options: { fence: 1, turnScope: { kind: 'thread' } }, - reservedBytes: 4096 - } - ]) - expect(journal.queuedMessages.revision()).toBe(heldRevision) - now = 120_200 - const opening = journal.physicalCursor() - const expired = await SqlAgentSessionJournal.open({ database, identity, now: () => now }) - expect(expired.openingCursor()).toEqual(opening) - expect(expired.physicalCursor().sequence).toBe(opening.sequence + 1) - expect(await expired.queuedMessages.nextInputCard()).toMatchObject({ messageId: 'draft' }) - await expired.close() - await journal.queuedMessages.editLeases.expire() - expect(journal.queuedMessages.revision()).not.toBe(heldRevision) - expect(await journal.queuedMessages.nextInputCard()).toMatchObject({ messageId: 'draft' }) - await journal.queuedMessages.editLeases.acquire(phone, { - messageId: 'draft', - fingerprint: card.fingerprint - }) - await journal.close() - const reopened = await SqlAgentSessionJournal.open({ database, identity, now: () => now }) - expect(await reopened.queuedMessages.editLeases.renew(phone, 'draft')).toEqual({ - status: 'expired' - }) - await reopened.close() -}) - function receipt(adopt: (committed: boolean) => void): JournalOperationReceipt { return { write: () => { @@ -361,98 +298,6 @@ it('rechecks row-free owner death before answering an attempt-end action read', }) }) -it('publishes SQL status only with recaptured live owners through the existing refresh path', async () => { - const { journal } = await fixture() - await journal.write({ - kind: 'item', - identity: { provider: 'orca', clientMessageId: 'prompt' }, - body: { kind: 'message', role: 'user', blocks: [{ type: 'text', text: 'Read my chat' }] }, - options: { fence: 0, turnScope: { kind: 'thread' } } - }) - await journal.appendItem( - { provider: 'orca', clientMessageId: 'turn' }, - { kind: 'turn', turnId: 'turn', state: 'running', userItemId: 'orca:prompt' }, - { fence: 0, turnScope: { kind: 'thread' } } - ) - const held = new Set() - const session: StatusFeedSession = { - journal, - params: { - provider: 'codex', - location: { - executionHostId: 'local', - wslDistro: null, - workspaceId: 'workspace', - workspaceKind: 'git-worktree' - } - }, - child: { fence: 0, phase: 'ready', generation: 'generation', heldSends: () => held } - } - const logger = { warn: vi.fn(), error: vi.fn() } - const feed = new StructuredAgentSessionStatusFeed({ - sessions: new Map([['session-1', session]]), - getConversation: () => null, - now: () => 999, - logger - }) - expect(await feed.journalProjection('session-1', journal)).toMatchObject({ stopping: false }) - await journal.appendStopEvent({ reason: 'user-stop' }, 0) - const reached = Promise.withResolvers() - const release = Promise.withResolvers() - const published = Promise.withResolvers() - const alsoPublished = Promise.withResolvers() - const read = journal.reads.observer.bind(journal.reads) - vi.spyOn(journal.reads, 'observer').mockImplementationOnce(async (input) => { - const result = await read(input) - reached.resolve() - await release.promise - return result - }) - const observations: unknown[] = [] - const pending = feed.publish('session-1', journal, { replay: true }, (projection) => { - observations.push({ - revision: projection.workRevision, - held: projection.authority?.child?.heldSends, - stopping: projection.stopping - }) - published.resolve() - }) - const alsoPending = feed.publish('session-1', journal, { replay: true }, (projection) => { - expect(projection).toMatchObject({ - workRevision: 1, - stopping: true, - authority: { child: { heldSends: ['held-without-row'] } } - }) - alsoPublished.resolve() - }) - await reached.promise - expect(feed.readPublished('session-1')).toBeUndefined() - session.operationalRevision = 1 - held.add('held-without-row') - const settle = await journal.stopMarks.beginSettle(true) - release.resolve() - await pending - await published.promise - await alsoPending - await alsoPublished.promise - expect(observations).toEqual([{ revision: 1, held: ['held-without-row'], stopping: true }]) - expect(feed.readPublished('session-1')).toMatchObject({ - latestPrompt: 'Read my chat', - status: 'working', - stopping: true, - updatedAt: 100 - }) - expect(logger.warn).not.toHaveBeenCalled() - const cursor = journal.cursor() - const stopping = await feed.journalProjection('session-1', journal) - journal.stopMarks.settled(settle, 'other-turn') - await feed.publish('session-1', journal, { replay: true }) - expect(feed.readPublished('session-1')).toMatchObject({ status: 'working' }) - expect(feed.readPublished('session-1')).not.toHaveProperty('stopping') - expect(journal.cursor()).toEqual(cursor) - expect(stopping?.authority?.stop?.settle).toEqual({ settling: true }) -}) - it('drops a revoked history invocation after worker dispatch and preserves deduplicated verdicts', async () => { const { root, database, journal } = await fixture() const cursor = journal.physicalCursor() diff --git a/src/main/native-chat/agent-session-journal/journal-sql-timeline-resolution.test.ts b/src/main/native-chat/agent-session-journal/journal-sql-timeline-resolution.test.ts index 324d830c3e4..cf0fb473746 100644 --- a/src/main/native-chat/agent-session-journal/journal-sql-timeline-resolution.test.ts +++ b/src/main/native-chat/agent-session-journal/journal-sql-timeline-resolution.test.ts @@ -6,13 +6,9 @@ import { agentJournalItemKey } from '../../../shared/agent-session/journal/agent import type { AgentJournalApprovalItem } from '../../../shared/agent-session/journal/agent-session-journal-types' import { codexProviderHandle } from '../../../shared/agent-session/lifecycle/provider-handles/agent-session-provider-handle-encoding' import { agentJournalTurnBody } from '../../../shared/agent-session/lifecycle/records/agent-session-turn-record' -import { openStructuredAgentSessionSqlJournalDatabase } from '../../runtime/agent-session/structured-agent-session-journal-open' +import { openStructuredAgentSessionSqlJournalDatabase } from '../../runtime/agent-session/installation/structured-agent-session-journal-open' import type { JournalSqlDatabase } from './database/journal-sql-database' -import { claudeBackgroundTaskIdentity } from '../../claude/background-tasks/claude-background-task-identity' -import { - codexGoalJournalDigest, - codexGoalJournalIdentity -} from '../../codex/structured/journal/codex-goal-journal-identity' + import { SqlAgentSessionJournal } from './journal-sql-store' import { journalSqlReaderPath, @@ -141,106 +137,3 @@ it('chooses request incarnations and settles the session from its unsettled rows completedAt: 300 }) }) - -it("follows a thread's newest saved goal row when choosing a goal identity", async () => { - const sql = await journal() - const goal = (timeUsedSeconds: number, objective = 'Ship it') => ({ - kind: 'status' as const, - text: `Goal set: ${objective}`, - threadGoal: { - state: 'set' as const, - goal: { - objective, - status: 'active' as const, - tokenBudget: null, - tokensUsed: 0, - timeUsedSeconds, - createdAt: 1, - updatedAt: timeUsedSeconds - } - } - }) - const thread = 'a'.repeat(64) - const step = (signature: string, body: ReturnType) => ({ - kind: 'resolved-item' as const, - resolution: { - kind: 'thread-goal' as const, - choice: { thread, signature, body, requirePrevious: false } - }, - options: { fence: 1, turnScope: { kind: 'thread' as const }, lifecycle: true }, - reservedBytes: 8192 - }) - const first = 'b'.repeat(64) - const second = 'c'.repeat(64) - expect(await appendOutcomes(sql, [step(first, goal(0)), step(first, goal(0))])).toEqual({ - outcomes: [{ kind: 'committed', wrote: true }, { kind: 'dropped' }] - }) - expect(await appendOutcomes(sql, [step(first, goal(60)), step(second, goal(0, 'Next'))])).toEqual( - { - outcomes: [ - { kind: 'committed', wrote: true }, - { kind: 'committed', wrote: true } - ] - } - ) - const occurrence = codexGoalJournalDigest(JSON.stringify([thread, first])) - const firstRow = agentJournalItemKey(codexGoalJournalIdentity(thread, first, occurrence)) - const secondRow = agentJournalItemKey( - codexGoalJournalIdentity( - thread, - second, - codexGoalJournalDigest(JSON.stringify([occurrence, second])) - ) - ) - expect(await sql.reads.item(firstRow)).toMatchObject({ - revision: 2, - body: { threadGoal: { goal: { timeUsedSeconds: 60 } } } - }) - expect(await sql.reads.item(secondRow)).toMatchObject({ - revision: 1, - body: { text: 'Goal set: Next' } - }) -}) - -it("chooses a background task's generation from its saved incarnations on the writer", async () => { - const sql = await journal() - const task = (state: 'working' | 'done', parentToolUseId: string) => ({ - kind: 'resolved-item' as const, - resolution: { - kind: 'background-task' as const, - taskId: 'task-1', - toolUseId: parentToolUseId, - body: { - kind: 'message' as const, - role: 'system' as const, - blocks: [ - { - type: 'background-task' as const, - taskId: 'task-1', - kind: 'command' as const, - label: 'Build', - state, - parentToolUseId - } - ] - } - }, - options: { fence: 1, turnScope: { kind: 'thread' as const } }, - reservedBytes: 8192 - }) - await appendOutcomes(sql, [ - task('working', 'tool-1'), - task('done', 'tool-1'), - task('working', 'tool-2') - ]) - const first = agentJournalItemKey(claudeBackgroundTaskIdentity('task-1')) - const second = agentJournalItemKey(claudeBackgroundTaskIdentity('task-1', 2)) - expect(await sql.reads.item(first)).toMatchObject({ - revision: 2, - body: { blocks: [{ state: 'done', parentToolUseId: 'tool-1' }] } - }) - expect(await sql.reads.item(second)).toMatchObject({ - revision: 1, - body: { blocks: [{ state: 'working', parentToolUseId: 'tool-2' }] } - }) -}) diff --git a/src/main/native-chat/agent-session-journal/journal-start-failure-settlement.test.ts b/src/main/native-chat/agent-session-journal/journal-start-failure-settlement.test.ts index ace973a9e0c..c8a9a96325f 100644 --- a/src/main/native-chat/agent-session-journal/journal-start-failure-settlement.test.ts +++ b/src/main/native-chat/agent-session-journal/journal-start-failure-settlement.test.ts @@ -6,7 +6,7 @@ import { agentSessionFailureFact } from '../../../shared/agent-session/failures/ import { agentSessionFailureWords } from '../../../shared/agent-session/failures/agent-session-failure-words' import { codexProviderHandle } from '../../../shared/agent-session/lifecycle/provider-handles/agent-session-provider-handle-encoding' import { recordStructuredAgentSessionStartFailure } from '../agent-session-wire/startup/structured-agent-session-start-failure-row' -import { openStructuredAgentSessionSqlJournalDatabase } from '../../runtime/agent-session/structured-agent-session-journal-open' +import { openStructuredAgentSessionSqlJournalDatabase } from '../../runtime/agent-session/installation/structured-agent-session-journal-open' import type { JournalSqlDatabase } from './database/journal-sql-database' import type { AgentSessionJournal } from './journal-store' import { SqlAgentSessionJournal } from './journal-sql-store' diff --git a/src/main/native-chat/agent-session-journal/journal-unheld-turns-settlement.test.ts b/src/main/native-chat/agent-session-journal/journal-unheld-turns-settlement.test.ts index 5b63963b83a..199497fe445 100644 --- a/src/main/native-chat/agent-session-journal/journal-unheld-turns-settlement.test.ts +++ b/src/main/native-chat/agent-session-journal/journal-unheld-turns-settlement.test.ts @@ -4,7 +4,7 @@ import { join } from 'node:path' import { afterEach, expect, it } from 'vitest' import { codexProviderHandle } from '../../../shared/agent-session/lifecycle/provider-handles/agent-session-provider-handle-encoding' import type { AgentJournalProducerLinkage } from '../../../shared/agent-session/journal/agent-session-journal-types' -import { openStructuredAgentSessionSqlJournalDatabase } from '../../runtime/agent-session/structured-agent-session-journal-open' +import { openStructuredAgentSessionSqlJournalDatabase } from '../../runtime/agent-session/installation/structured-agent-session-journal-open' import type { JournalSqlDatabase } from './database/journal-sql-database' import type { AgentSessionJournal } from './journal-store' import { SqlAgentSessionJournal } from './journal-sql-store' diff --git a/src/main/native-chat/agent-session-journal/journal-writer-effects.ts b/src/main/native-chat/agent-session-journal/journal-writer-effects.ts index 1823b336797..312b7ea6343 100644 --- a/src/main/native-chat/agent-session-journal/journal-writer-effects.ts +++ b/src/main/native-chat/agent-session-journal/journal-writer-effects.ts @@ -8,7 +8,7 @@ import { } from '../../github/pr-watch/pr-watch-storage' import type { AgentSessionStoreRowWrites } from './journal-writer-store-row-changes' import type { AgentSessionStoreMutation } from '../../runtime/agent-session/records/agent-session-store-mutation' -import type { AgentSessionRuntimeFacts } from '../../runtime/agent-session/agent-session-runtime-attribution' +import type { AgentSessionRuntimeFacts } from '../../runtime/agent-session/records/agent-session-runtime-attribution' import { applyJournalWriterStoreEffect } from './journal-writer-store-effect' import { claimAgentSessionAttachmentsInTransaction, diff --git a/src/main/native-chat/agent-session-journal/journal-writer-store-mutation.ts b/src/main/native-chat/agent-session-journal/journal-writer-store-mutation.ts index 510500aa5b6..e8af4699579 100644 --- a/src/main/native-chat/agent-session-journal/journal-writer-store-mutation.ts +++ b/src/main/native-chat/agent-session-journal/journal-writer-store-mutation.ts @@ -25,7 +25,7 @@ import { readJournalSqlUsageLimitContinueIdentity } from './journal-sql-status-c import { attributeAgentSessionRuntimeRecord, type AgentSessionRuntimeFacts -} from '../../runtime/agent-session/agent-session-runtime-attribution' +} from '../../runtime/agent-session/records/agent-session-runtime-attribution' export function emptyJournalWriterStoreRows(): AgentSessionStoreRowWrites { return { diff --git a/src/main/native-chat/agent-session-journal/journal-writer-store-row-changes.ts b/src/main/native-chat/agent-session-journal/journal-writer-store-row-changes.ts index 88dfe1257b5..df8e6d3c9d8 100644 --- a/src/main/native-chat/agent-session-journal/journal-writer-store-row-changes.ts +++ b/src/main/native-chat/agent-session-journal/journal-writer-store-row-changes.ts @@ -11,7 +11,7 @@ import { isReadableAgentSessionStoreTab, isReadableRetiredAgentSessionClaimKey } from '../../runtime/agent-session/records/agent-session-store-row-rules' -import type { PersistedAgentSessionTab } from '../../runtime/agent-session/agent-session-tab-table' +import type { PersistedAgentSessionTab } from '../../runtime/agent-session/records/agent-session-tab-table' type KeyedRowWrites = { upsert: [key: string, json: string][]; remove: string[] } diff --git a/src/main/native-chat/agent-session-wire/acquisition/imported-agent-session-fork-tip.ts b/src/main/native-chat/agent-session-wire/acquisition/imported-agent-session-fork-tip.ts index fb68b3a031f..64d56cf703b 100644 --- a/src/main/native-chat/agent-session-wire/acquisition/imported-agent-session-fork-tip.ts +++ b/src/main/native-chat/agent-session-wire/acquisition/imported-agent-session-fork-tip.ts @@ -1,7 +1,7 @@ import { parseAgentJournalItemKey } from '../../../../shared/agent-session/journal/agent-session-journal-item-key' import type { AgentSessionRecord } from '../../../../shared/agent-session/lifecycle/agent-session-record' import { prepareLegacyTranscriptImport } from '../../agent-session-journal/history-import/journal-legacy-import' -import { resolveStructuredAgentSessionAdoptionForCreate } from '../../../runtime/agent-session/structured-agent-session-create-adoption' +import { resolveStructuredAgentSessionAdoptionForCreate } from '../../../runtime/agent-session/ownership/structured-agent-session-create-adoption' import { structuredAgentRuntimeMetadata } from '../../../runtime/agent-session/installation/structured-agent-runtime-metadata' /** An imported root has no hosted turn receipt; ask the same pinned native history importer. */ diff --git a/src/main/native-chat/agent-session-wire/acquisition/structured-agent-session-failed-create-refusal.ts b/src/main/native-chat/agent-session-wire/acquisition/structured-agent-session-failed-create-refusal.ts index 15df3f50a60..42ea221dee2 100644 --- a/src/main/native-chat/agent-session-wire/acquisition/structured-agent-session-failed-create-refusal.ts +++ b/src/main/native-chat/agent-session-wire/acquisition/structured-agent-session-failed-create-refusal.ts @@ -16,7 +16,7 @@ import type { } from '../../../../shared/agent-session/lifecycle/operations/agent-session-operation-ledger' import { agentSessionLeaseOwnerVerdict } from '../../../../shared/agent-session/lifecycle/leases/agent-session-lease-adjudication' import type { AgentSessionRecord } from '../../../../shared/agent-session/lifecycle/agent-session-record' -import type { AgentSessionAcquisitionExitProof } from '../../../runtime/agent-session/agent-session-acquisition-failure-settlement' +import type { AgentSessionAcquisitionExitProof } from '../../../runtime/agent-session/ownership/agent-session-acquisition-failure-settlement' import '../providers/structured-agent-session-adapter' import { AgentSessionAcquisitionExitProvenError, diff --git a/src/main/native-chat/agent-session-wire/acquisition/structured-agent-session-fork-intent.ts b/src/main/native-chat/agent-session-wire/acquisition/structured-agent-session-fork-intent.ts index 0df306aa8f0..2905de8cb9e 100644 --- a/src/main/native-chat/agent-session-wire/acquisition/structured-agent-session-fork-intent.ts +++ b/src/main/native-chat/agent-session-wire/acquisition/structured-agent-session-fork-intent.ts @@ -1,5 +1,5 @@ import { prepareStructuredAgentSessionFork } from './structured-agent-session-fork' -import { resolveCommittedStructuredAgentSessionAdoptionIntent } from '../../../runtime/agent-session/structured-agent-session-create-adoption' +import { resolveCommittedStructuredAgentSessionAdoptionIntent } from '../../../runtime/agent-session/ownership/structured-agent-session-create-adoption' import { agentConversationCopyRefusal } from '../../conversation-adoption/agent-conversation-copy-error' import { acpAgentName } from '../../../acp/session/acp-structured-agent-definitions' import type { AgentSessionExecutionLocation } from '../../../../shared/agent-session/lifecycle/agent-session-record' diff --git a/src/main/native-chat/agent-session-wire/acquisition/structured-agent-session-fork.ts b/src/main/native-chat/agent-session-wire/acquisition/structured-agent-session-fork.ts index 4e13f1f2e22..64500a4c29f 100644 --- a/src/main/native-chat/agent-session-wire/acquisition/structured-agent-session-fork.ts +++ b/src/main/native-chat/agent-session-wire/acquisition/structured-agent-session-fork.ts @@ -10,7 +10,7 @@ import { AgentConversationCopyError } from '../../conversation-adoption/agent-co import { acpAgentName } from '../../../acp/session/acp-structured-agent-definitions' import { AGENT_CHAT_PERMISSION_MODE_OPTION_ID } from '../../../../shared/agent-launch/permissions/agent-chat-permission-mode' import { isAgentSessionRefusalError } from '../../../../shared/agent-session/failures/agent-session-wire-refusals' -import { requireUnownedStructuredAgentSessionAdoption } from '../../../runtime/agent-session/structured-agent-session-create-adoption' +import { requireUnownedStructuredAgentSessionAdoption } from '../../../runtime/agent-session/ownership/structured-agent-session-create-adoption' import type { AgentSessionAttachParams } from './structured-agent-session-attach' export async function prepareStructuredAgentSessionFork( diff --git a/src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-claude-account-routing.test-fixture.ts b/src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-claude-account-routing.test-fixture.ts index 7558f6528bc..a4a07e2e142 100644 --- a/src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-claude-account-routing.test-fixture.ts +++ b/src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-claude-account-routing.test-fixture.ts @@ -9,7 +9,7 @@ import { import { installClaudeProfileRouter } from '../../../../claude-accounts/profiles/routing/claude-profile-installed-router' import { claudeProfileMarkerPath } from '../../../../claude-accounts/profiles/claude-profile-paths' import { CLAUDE_STRUCTURED_AGENT } from '../../../../claude/structured/claude-structured-agent-definition' -import { claudeInitializationAuthError } from '../../../../claude/structured/claude-structured-init-proof' +import { claudeInitializationAuthError } from '../../../../claude/structured/startup/claude-structured-init-proof' import type { AgentSessionRecordStore } from '../../../../runtime/agent-session/records/agent-session-record-store' import { resolveStructuredClaudeAccountHomePath } from '../../../../runtime/agent-session/environment/structured-agent-account-home' import { createClaudeStructuredLaunchResolver } from '../../../../runtime/agent-session/launch/structured-agent-launch-composition.test-support' diff --git a/src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-claude-echo-working.test.ts b/src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-claude-echo-working.test.ts deleted file mode 100644 index c448eab4569..00000000000 --- a/src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-claude-echo-working.test.ts +++ /dev/null @@ -1,168 +0,0 @@ -// Each intermediate echo/turn frame must preserve Working so Stop and session lists stay consistent. - -import { mkdtemp, rm } from 'node:fs/promises' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { afterEach, beforeEach, expect, it, vi } from 'vitest' -import type { AgentJournalSubmission } from '../../../../../shared/agent-session/journal/agent-session-journal-types' -import { computeAgentSessionPayloadFingerprint } from '../../../../../shared/agent-session/lifecycle/operations/agent-session-mutation-envelope' -import { isStructuredAgentSessionMainAgentWorking } from '../../../../../shared/agent-session/view/structured-agent-session-main-agent-working' -import { ClaudeStructuredSessionAdapter } from '../../../../claude/structured/claude-structured-session-adapter' -import { - fakeClaude, - PROVIDER_SESSION_ID -} from '../../../../claude/structured/claude-structured-session-test-support' -import type { AgentSessionRecordStore } from '../../../../runtime/agent-session/records/agent-session-record-store' -import { - openTestAgentSessionRecordStore, - openTestAgentSessionDatabase -} from '../../../../runtime/agent-session/records/agent-session-record-store-test-harness' -import { structuredClaudeLifecycleEvent } from '../../../../runtime/agent-session/installation/structured-claude-runtime-adapter' -import { StructuredAgentSessionHost } from '../structured-agent-session-host' -import { - HOST_TEST_NOW as NOW, - HOST_TEST_SESSION as SESSION, - hostTestAttachParams, - hostTestMessage, - hostTestOperationId, - resetHostTestOperationIds -} from './structured-agent-session-host-test-data.test-fixture' -import { closeTestJournalHostDatabases } from '../../../agent-session-journal/store-lifecycle/journal-host-database-test-support' -import { createStructuredAgentSessionLogger } from '../structured-agent-session-logger' -import { NO_STRUCTURED_AGENTS } from '../../providers/testing/structured-agent-session-adapter-router.test-fixture' - -const CALLER = { callerKey: 'client-1' } - -let root: string -let host: StructuredAgentSessionHost -let adapter: ClaudeStructuredSessionAdapter -let store: AgentSessionRecordStore -const claude = { current: fakeClaude({ replayUuid: null }) } - -beforeEach(async () => { - root = await mkdtemp(join(tmpdir(), 'orca-claude-echo-working-')) - resetHostTestOperationIds() - claude.current = fakeClaude({ replayUuid: null }) - const lifecycle: Promise[] = [] - adapter = new ClaudeStructuredSessionAdapter({ - resolveLaunch: async () => ({ - pathToClaudeCodeExecutable: 'claude', - options: {}, - cwd: root, - claudeConfigDir: join(root, 'claude-home'), - providerSessionId: PROVIDER_SESSION_ID, - resumeLeafUuid: null, - resumesTranscript: false, - cliFlag: async () => 'supported' as const, - continuesChain: false - }), - onEvent: (event) => { - const mapped = structuredClaudeLifecycleEvent(event) - if (mapped) { - lifecycle.push(host.handleAdapterEvent(mapped)) - } - }, - onDispatchSettledLate: (settlement) => void host.settleLateDispatch(settlement), - openConnection: claude.current.openConnection, - readProcessStartTime: async () => 1_700_000_000_000, - now: () => NOW - }) - store = await openTestAgentSessionRecordStore(root) - host = new StructuredAgentSessionHost({ - agents: NO_STRUCTURED_AGENTS, - logger: createStructuredAgentSessionLogger(), - store, - adapter: Object.assign(adapter, { supportsCreate: () => true }), - journalDatabase: await openTestAgentSessionDatabase(root), - claimKeyId: 'key-1', - mintSpawnToken: () => 'spawn-a', - now: () => NOW - }) - const params = hostTestAttachParams(null, { - provider: 'claude', - agent: 'claude', - accountHome: { variable: 'CLAUDE_CONFIG_DIR', path: join(root, 'claude-home') }, - providerHandle: { kind: 'claude', sessionId: PROVIDER_SESSION_ID, leafUuid: null } - }) - expect(await host.attach(CALLER, params)).toMatchObject({ ok: true }) - await vi.waitFor(() => expect(host.readStatusSummary(SESSION)?.hostExecutionPhase).toBe('ready')) - await Promise.all(lifecycle) -}) - -afterEach(async () => { - await adapter.closeAll() - await host.flushAllStreamedEvents() - await closeTestJournalHostDatabases() - await rm(root, { recursive: true, force: true }) -}) - -async function expectWorkingThroughEcho(backlog: boolean): Promise { - const submissions = new Map() - const turns = new Map() - const working: boolean[] = [] - const fence = store.getRecord(SESSION)!.lease.runtimeFence - await host.subscribe({ - id: 'chat-1', - sessionId: SESSION, - emit: (event) => { - if (event.type !== 'batch') { - return - } - for (const submission of event.batch.submissions) { - submissions.set(submission.clientMessageId, submission) - } - for (const item of event.batch.items) { - if (item.body.kind === 'turn') { - turns.set(item.itemId, item.body.state) - } - } - const running = [...turns].find(([, state]) => state === 'running')?.[0] ?? null - working.push( - isStructuredAgentSessionMainAgentWorking(running, [...submissions.values()], fence) - ) - } - }) - await vi.waitFor(() => expect(working).toEqual([false])) - working.length = 0 - const body = hostTestMessage('hi') - await host.send(CALLER, { - envelope: { - sessionId: SESSION, - clientOperationId: hostTestOperationId(), - expectedRuntimeFence: fence, - payloadFingerprint: computeAgentSessionPayloadFingerprint({ - method: 'agentSession.send', - sessionId: SESSION, - fields: { body } - }) - }, - body - }) - await vi.waitFor(() => expect(claude.current.connections[0]?.sent).toHaveLength(1)) - const connection = claude.current.connections[0]! - if (backlog) { - // Queue the previous result immediately ahead of the new echo in the same read. - connection.handlers.onMessage?.({ - type: 'result', - subtype: 'success', - uuid: 'result-0', - session_id: PROVIDER_SESSION_ID, - duration_ms: 1, - duration_api_ms: 1, - num_turns: 1, - is_error: false, - result: '' - }) - } - connection.handlers.onMessage?.({ ...connection.sent.at(-1)!, uuid: 'echo-uuid' }) - await vi.waitFor(() => - expect([...submissions.values()].map((submission) => submission.dispatchState)).toEqual([ - 'accepted' - ]) - ) - expect([...turns.values()]).toEqual(['running']) - expect(working).not.toContain(false) -} - -it('keeps the settlement behind the turn its echo opens when the previous result arrives in the same read', () => - expectWorkingThroughEcho(true)) diff --git a/src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-claude-resume-exit-start.test.ts b/src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-claude-resume-exit-start.test.ts deleted file mode 100644 index b0db23c790e..00000000000 --- a/src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-claude-resume-exit-start.test.ts +++ /dev/null @@ -1,102 +0,0 @@ -import { expect, it, vi } from 'vitest' -import { ClaudeStructuredSessionAdapter } from '../../../../claude/structured/claude-structured-session-adapter' -import { - PROVIDER_SESSION_ID, - fakeClaude -} from '../../../../claude/structured/claude-structured-session-test-support' -import { structuredClaudeLifecycleEvent } from '../../../../runtime/agent-session/installation/structured-claude-runtime-adapter' -import { withObservedProviderExit } from '../../startup/structured-agent-session-failure-text' -import { HOST_TEST_SESSION as SESSION } from './structured-agent-session-host-test-data.test-fixture' -import type { StructuredAgentSessionSinkBarrier } from '../../journal-ingress/structured-agent-session-event-sink' -import { STRUCTURED_AGENT_SESSION_STARTUP_CEILING_MS } from '../../startup/structured-agent-session-startup-attempt-contract' -import { - accept, - closeSession, - eventually, - host, - providerOpen, - registerStartupAttemptHostTests, - restartWith, - submission -} from './structured-agent-session-startup-attempt-host.test-fixture' - -registerStartupAttemptHostTests() - -const STARTED_AT = 1_800_000_000_000 - -it('ends a resumed start that exits during transcript catch-up without awaiting a cursor write', async () => { - const claude = fakeClaude() - const catchUp = Promise.withResolvers() - const persisted = Promise.withResolvers() - const persistHandle = vi.fn(() => persisted.promise) - let catchingUp = false - let ended = 0 - const lifecycleTypes: (string | undefined)[] = [] - const adapter = new ClaudeStructuredSessionAdapter({ - resolveLaunch: async () => ({ - pathToClaudeCodeExecutable: 'claude', - options: {}, - cwd: '/work/repo', - claudeConfigDir: '/accounts/claude', - providerSessionId: PROVIDER_SESSION_ID, - resumeLeafUuid: 'saved-leaf', - resumesTranscript: true, - continuesChain: true, - cliFlag: async () => 'supported' as const - }), - openConnection: claude.openConnection, - readProcessStartTime: async () => 1_700_000_000_000, - persistHandle, - onEvent: (event) => { - if (event.type === 'ended') { - ended += 1 - const lifecycle = structuredClaudeLifecycleEvent(event) - lifecycleTypes.push(lifecycle?.type) - if (lifecycle) { - void host.handleAdapterEvent(lifecycle) - } - } - } - }) - await restartWith((input) => { - if (!input.events) { - throw new Error('expected the host event sink') - } - return adapter.acquire({ - ...input, - events: { - ...input.events, - written: () => { - catchingUp = true - return catchUp.promise - } - } - }) - }) - providerOpen.mockImplementation(adapter.open) - closeSession.mockImplementation(adapter.closeSession) - host.deps.adapter.releaseAcquisition = adapter.releaseAcquisition - vi.setSystemTime(STARTED_AT) - const id = await accept('resume queued message') - // Initialize has answered; the open still waits on the journal before catch-up. - await eventually(() => expect(catchingUp).toBe(true)) - const flight = host.collaboratorsForTests().runtimeState.startFlights.get(SESSION)! - const connection = claude.connections[0] - connection.closed = true - connection.exitVerdict = { root: 'exited', tree: 'exited' } - connection.handlers.onExit?.(withObservedProviderExit(new Error('claude exited (code 1)')), { - expected: false - }) - await vi.advanceTimersByTimeAsync(2_100) - expect(ended).toBe(1) - expect(lifecycleTypes).toEqual(['ended']) - expect(persistHandle).not.toHaveBeenCalled() - catchUp.resolve({ ok: true }) - persisted.resolve() - await adapter.drainObservedExits() - await flight.outcome - await eventually(async () => expect((await submission(id))?.dispatchState).not.toBe('pending')) - expect(Date.now() - STARTED_AT).toBeLessThan(STRUCTURED_AGENT_SESSION_STARTUP_CEILING_MS) - claude.dispose() - await adapter.closeAll() -}) diff --git a/src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-claude-stop-contract.test-fixture.ts b/src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-claude-stop-contract.test-fixture.ts index 847f8e17b30..1b0b6090e6b 100644 --- a/src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-claude-stop-contract.test-fixture.ts +++ b/src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-claude-stop-contract.test-fixture.ts @@ -6,7 +6,7 @@ import type { AgentStatusStructuredSessionSubject } from '../../../../../shared/ import { AgentHookServer } from '../../../../agent-hooks/server/agent-hook-server' import { runClaudeControl } from '../../../../claude/sdk-transport/claude-agent-sdk-control-requests' import { ClaudeStructuredSessionAdapter } from '../../../../claude/structured/claude-structured-session-adapter' -import type { ClaudeStructuredSessionEvent } from '../../../../claude/structured/claude-structured-session-event' +import type { ClaudeStructuredSessionEvent } from '../../../../claude/structured/lifecycle/claude-structured-session-event' import { fakeClaude, PROVIDER_SESSION_ID diff --git a/src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-direct-sink.test-fixture.ts b/src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-direct-sink.test-fixture.ts deleted file mode 100644 index 2a2bec4ad2c..00000000000 --- a/src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-direct-sink.test-fixture.ts +++ /dev/null @@ -1,12 +0,0 @@ -import type { SqlAgentSessionJournal } from '../../../agent-session-journal/journal-sql-store' -import type { DeferredStructuredAgentSessionEventSink } from '../../journal-ingress/structured-agent-session-event-sink' -import { StructuredAgentSessionSnapshotRoutes } from '../structured-agent-session-snapshot-routes' -import { testEventSinkLogging } from './structured-agent-session-logger.test-fixture' - -export async function followTestSinkSnapshots( - sink: DeferredStructuredAgentSessionEventSink, - journal: SqlAgentSessionJournal -): Promise { - const routes = new StructuredAgentSessionSnapshotRoutes(testEventSinkLogging().logger) - await sink.followSnapshots(routes.observe(journal.identity.sessionId, journal)) -} diff --git a/src/main/native-chat/agent-session-wire/recovery/structured-agent-session-usage-limit-chain-claude.test.ts b/src/main/native-chat/agent-session-wire/recovery/structured-agent-session-usage-limit-chain-claude.test.ts deleted file mode 100644 index d933fdb2857..00000000000 --- a/src/main/native-chat/agent-session-wire/recovery/structured-agent-session-usage-limit-chain-claude.test.ts +++ /dev/null @@ -1,188 +0,0 @@ -import { followTestSinkSnapshots } from '../host/testing/structured-agent-session-direct-sink.test-fixture' -import { readTestJournalSnapshot } from '../../agent-session-journal/journal-observation.test-support' -import { readFileSync } from 'node:fs' -import { join } from 'node:path' -import { expect, it } from 'vitest' -import { agentSessionFailureFact } from '../../../../shared/agent-session/failures/agent-session-failure' -import { agentSessionFailureWords } from '../../../../shared/agent-session/failures/agent-session-failure-words' -import { agentJournalSubmissionKey } from '../../../../shared/agent-session/journal/agent-session-journal-item-key' -import { AGENT_JOURNAL_THREAD_SCOPE } from '../../../../shared/agent-session/journal/agent-session-journal-types' -import { readAgentJournalTurn } from '../../../../shared/agent-session/lifecycle/records/agent-session-turn-record' -import { ClaudeStructuredSessionAdapter } from '../../../claude/structured/claude-structured-session-adapter' -import { - fakeClaude, - identityFor, - PROVIDER_SESSION_ID -} from '../../../claude/structured/claude-structured-session-test-support' -import { claudeStartupSettled } from '../../../claude/structured/claude-structured-startup-settled-test-support' -import { createFixture } from '../../agent-session-journal/store-lifecycle/journal-store-contract-test-fixture' -import { createDeferredStructuredAgentSessionEventSink } from '../journal-ingress/structured-agent-session-event-sink' -import { - usageLimitContinueChain, - usageLimitContinueMessageId, - usageLimitContinueTag -} from './structured-agent-session-usage-limit-chain' - -function isRecord(value: unknown): value is Record { - return typeof value === 'object' && value !== null && !Array.isArray(value) -} - -function record(value: unknown): Record { - if (!isRecord(value)) { - throw new Error('capture event is not a record') - } - return value -} - -const fixture = createFixture() - -it('counts a host continue whose recorded Claude echo opens the turn under its provider key', async () => { - const at = 1_700_000_200_000 - const identity = identityFor() - const journal = await fixture.open({ identity }) - const previous = await journal.appendItem( - { provider: 'orca', clientMessageId: 'previous-turn' }, - { - kind: 'turn', - turnId: 'previous-turn', - state: 'completed', - outcome: 'failure', - userItemId: 'previous-user', - completedAt: at - 2_000 - }, - { fence: 7, turnScope: AGENT_JOURNAL_THREAD_SCOPE } - ) - const previousCut = { turnItemId: previous.itemId, resetsAt: at - 1_000 } - const limitBody = (resetsAt: number) => - ({ - kind: 'status', - ...agentSessionFailureWords( - agentSessionFailureFact('usageLimitReached', { usageLimit: { resetsAt } }), - { surface: 'row' } - ) - }) satisfies Parameters[1] - await journal.appendItem( - { provider: 'orca', clientMessageId: 'previous-limit' }, - limitBody(previousCut.resetsAt), - { fence: 7, turnScope: { kind: 'turn', turnItemId: previous.itemId } } - ) - const clientMessageId = usageLimitContinueMessageId( - at, - usageLimitContinueTag(previousCut), - '0123456789abcdef' - ) - const capture = readFileSync( - join(__dirname, '../../../claude/__fixtures__/claude-lifecycle-capture-batch-lead.jsonl'), - 'utf8' - ) - .trim() - .split('\n') - .map((line) => record(JSON.parse(line))) - const capturedSessionId = capture[0]!.providerSessionId - if (typeof capturedSessionId !== 'string') { - throw new Error('capture has no provider session ID') - } - const claude = fakeClaude({ initProof: 'none', replayUuid: null }) - const sink = createDeferredStructuredAgentSessionEventSink({ - sessionId: identity.sessionId, - logger: { warn: () => {}, error: () => {} } - }) - await followTestSinkSnapshots(sink, journal) - sink.bind({ journal, fence: 7, publish: () => {} }) - const settlements: Promise[] = [] - const adapter = new ClaudeStructuredSessionAdapter({ - resolveLaunch: async () => ({ - pathToClaudeCodeExecutable: 'claude', - options: {}, - cwd: '/work/repo', - claudeConfigDir: '/accounts/claude', - providerSessionId: PROVIDER_SESSION_ID, - resumeLeafUuid: null, - resumesTranscript: false, - cliFlag: async () => 'supported', - continuesChain: false - }), - openConnection: claude.openConnection, - readProcessStartTime: async () => 1, - now: () => at, - persistHandle: async () => {}, - onDispatchSettledLate: (settlement) => { - if ('providerIdentity' in settlement) { - settlements.push( - journal.resolveDispatch({ - clientMessageId: settlement.clientMessageId, - state: 'accepted', - providerIdentity: settlement.providerIdentity, - fence: 7 - }) - ) - } - } - }) - try { - await adapter.acquire({ identity, fence: 7, spawnToken: 'spawn-9', events: sink.sink }) - const connection = claude.connections[0]! - let capturedUuid = '' - let sentUuid = '' - for (const event of capture) { - if (event.kind === 'dispatch') { - if (typeof event.sentUuid !== 'string' || typeof event.text !== 'string') { - throw new Error('capture dispatch has no UUID or text') - } - await claudeStartupSettled(adapter, identity.sessionId) - const body = { - kind: 'message', - role: 'user', - blocks: [{ type: 'text', text: event.text }] - } satisfies Parameters[0]['body'] - await journal.appendSubmission({ - clientMessageId, - payloadFingerprint: 'captured-continue', - body, - origin: 'host', - fence: 7 - }) - await expect( - adapter.dispatch({ sessionId: identity.sessionId, clientMessageId, body, fence: 7 }) - ).resolves.toMatchObject({ state: 'admitted' }) - capturedUuid = event.sentUuid - sentUuid = String(connection.sent.at(-1)!.uuid) - } else if (event.kind === 'frame') { - let frame = JSON.stringify(event.frame).replaceAll(capturedSessionId, PROVIDER_SESSION_ID) - if (capturedUuid) { - frame = frame.replaceAll(capturedUuid, sentUuid) - } - const mapped = record(JSON.parse(frame)) - connection.handlers.onMessage?.(mapped) - // The capture continues with queued sends; this regression ends at the first send's echo. - if (mapped.type === 'user') { - break - } - } - } - await Promise.all(settlements) - expect(await sink.drained()).toEqual({ ok: true }) - const echoed = await readTestJournalSnapshot(journal) - const turnItem = echoed.items.findLast((item) => readAgentJournalTurn(item.body)) - const submission = echoed.submissions.find((input) => input.clientMessageId === clientMessageId) - if (!turnItem || !submission?.providerItemId) { - throw new Error('Claude echo did not open a turn and settle the submission') - } - expect(readAgentJournalTurn(turnItem.body)?.userItemId).toBe(submission.providerItemId) - expect(submission.providerItemId).not.toBe(agentJournalSubmissionKey(clientMessageId)) - expect(submission.dispatchState).toBe('accepted') - await journal.appendItem( - { provider: 'orca', clientMessageId: 'continued-limit' }, - limitBody(at + 1_000), - { fence: 7, turnScope: { kind: 'turn', turnItemId: turnItem.itemId } } - ) - const snapshot = await readTestJournalSnapshot(journal) - expect( - usageLimitContinueChain(snapshot.items, snapshot.submissions, { turnItemId: turnItem.itemId }) - ).toBe(1) - } finally { - await adapter.closeAll() - await sink.drained() - sink.close() - } -}) diff --git a/src/main/native-chat/agent-session-wire/termination/structured-agent-session-stale-state-settlement.ts b/src/main/native-chat/agent-session-wire/termination/structured-agent-session-stale-state-settlement.ts index 79992234cab..817dd3c5f05 100644 --- a/src/main/native-chat/agent-session-wire/termination/structured-agent-session-stale-state-settlement.ts +++ b/src/main/native-chat/agent-session-wire/termination/structured-agent-session-stale-state-settlement.ts @@ -2,7 +2,7 @@ import { providerTimelineExecutionItems } from '../../agent-session-timeline/pro // Plan against queued journal state; death/replacement proof interrupts only matching owners, // otherwise settle unverifiable and revise when later proof arrives. -import type { AgentSessionReplacedRuntime } from '../../../runtime/agent-session/agent-session-replaced-runtime' +import type { AgentSessionReplacedRuntime } from '../../../runtime/agent-session/ownership/agent-session-replaced-runtime' import { AGENT_JOURNAL_THREAD_SCOPE, type AgentJournalRenderItem, diff --git a/src/main/native-chat/agent-session-wire/termination/structured-agent-session-stale-stop-row.ts b/src/main/native-chat/agent-session-wire/termination/structured-agent-session-stale-stop-row.ts index f1a9a617293..ee7575c34f2 100644 --- a/src/main/native-chat/agent-session-wire/termination/structured-agent-session-stale-stop-row.ts +++ b/src/main/native-chat/agent-session-wire/termination/structured-agent-session-stale-stop-row.ts @@ -8,7 +8,7 @@ import type { } from '../../../../shared/agent-session/journal/agent-session-journal-types' import type { AgentSessionDeathEvidence } from '../../../../shared/agent-session/lifecycle/leases/agent-session-death-evidence' import { readAgentJournalTurn } from '../../../../shared/agent-session/lifecycle/records/agent-session-turn-record' -import type { AgentSessionReplacedRuntime } from '../../../runtime/agent-session/agent-session-replaced-runtime' +import type { AgentSessionReplacedRuntime } from '../../../runtime/agent-session/ownership/agent-session-replaced-runtime' import { orcaStopRowBody } from './structured-agent-session-orca-stop-row' export type StaleCut = { by: 'death' } | { by: 'replaced'; fence: number } | null diff --git a/src/main/native-chat/agent-session-wire/termination/structured-agent-session-stale-turn-verdict.ts b/src/main/native-chat/agent-session-wire/termination/structured-agent-session-stale-turn-verdict.ts index 4b4c1025fec..2547ad4e414 100644 --- a/src/main/native-chat/agent-session-wire/termination/structured-agent-session-stale-turn-verdict.ts +++ b/src/main/native-chat/agent-session-wire/termination/structured-agent-session-stale-turn-verdict.ts @@ -14,7 +14,7 @@ import { readAgentJournalTurn } from '../../../../shared/agent-session/lifecycle/records/agent-session-turn-record' import type { AgentSessionDeathEvidence } from '../../../../shared/agent-session/lifecycle/leases/agent-session-death-evidence' -import type { AgentSessionReplacedRuntime } from '../../../runtime/agent-session/agent-session-replaced-runtime' +import type { AgentSessionReplacedRuntime } from '../../../runtime/agent-session/ownership/agent-session-replaced-runtime' import type { JournalLifecycleMutationInput } from '../../agent-session-journal/writing/journal-lifecycle-mutation' import type { JournalLatestStop } from '../../agent-session-journal/context-epochs/journal-stop-turn-end' diff --git a/src/main/orcad/host-lifecycle/orcad-lifecycle-host.test.ts b/src/main/orcad/host-lifecycle/orcad-lifecycle-host.test.ts deleted file mode 100644 index ca9ada8cbcd..00000000000 --- a/src/main/orcad/host-lifecycle/orcad-lifecycle-host.test.ts +++ /dev/null @@ -1,180 +0,0 @@ -import { AGENT_JOURNAL_THREAD_SCOPE } from '../../../shared/agent-session/journal/agent-session-journal-types' -import { - CALLER, - hostTestState -} from '../../native-chat/agent-session-wire/host/testing/structured-agent-session-host.test-fixture' -import { - HOST_TEST_THREAD as THREAD, - HOST_TEST_NOW as NOW, - hostTestAttachParams, - hostTestOperationId -} from '../../native-chat/agent-session-wire/host/testing/structured-agent-session-host-test-data.test-fixture' -import { AgentSessionRecoveryCapsule } from '../../runtime/agent-session/records/agent-session-recovery-capsule' -import { BackendCoreProfileShutdown } from '../../backend/core-profile-shutdown' -import { Store } from '../../persistence/loading-store/store' -import { - closeTestStores, - createSqliteTestStore, - readPersistedStateJson -} from '../../persistence/persistence-test-harness' -import { readFile } from 'node:fs/promises' -import { holdRemovalMetadata } from '../../workspaces/removal/worktree-removal-lifetime.test-fixtures' -import { readWorktreeRemovalRecords } from '../../workspaces/removal/worktree-removal-records' -import { _resetPendingWorktreeRemovalsForTests } from '../../workspaces/removal/worktree-background-removal' -import { existsSync, mkdtempSync, rmSync } from 'node:fs' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { afterEach, describe, expect, it, vi } from 'vitest' - -vi.mock('../browser-providers/orcad-browser-startup', () => ({ - startOrcadBrowserProvider: () => ({ ready: Promise.resolve(), stop: async () => {} }) -})) - -import { ORCAD_LOCK_FILE_NAME } from '../instance-lock/orcad-instance-lock' -import { worktreeRemovalLifetime } from '../../workspaces/removal/worktree-removal-lifetime' -import { - startOrcadWithHost, - startOrcadWithLifecycle, - stopOrcadStructuredAgentSessions -} from './orcad-lifecycle' - -const roots: string[] = [] -afterEach(async () => { - await closeTestStores() - vi.restoreAllMocks() - vi.useRealTimers() - _resetPendingWorktreeRemovalsForTests() - for (const root of roots.splice(0)) { - rmSync(root, { recursive: true, force: true }) - } -}) - -function dataRoot(): string { - const root = mkdtempSync(join(tmpdir(), 'orcad-lifecycle-host-')) - roots.push(root) - return root -} - -describe('startOrcadWithHost', () => { - it('keeps the instance lock when a runtime writer could not be stopped', async () => { - const root = dataRoot() - const failure = new Error('profile writer still running') - const handle = await startOrcadWithHost( - root, - async (registerCleanup) => { - registerCleanup(() => { - throw failure - }) - return {} - }, - () => {} - ) - await expect(handle.stop()).rejects.toBe(failure) - expect(existsSync(join(root, ORCAD_LOCK_FILE_NAME))).toBe(true) - }) -}) - -vi.mock('../../runtime/agent-session/structured-agent-session-runtime', () => ({ - stopStructuredAgentSessionRuntime: async (options: { trigger: 'quit' }) => { - await hostTestState().host.flushAllStreamedEvents(options) - } -})) - -it('saves working-chat offers before profile cleanup and keeps them after repeated stop', async () => { - const { host, acquire, root } = hostTestState() - const ids = ['session-first', 'session-second'] - for (const sessionId of ids) { - const params = hostTestAttachParams(null, { - envelope: { - sessionId, - clientOperationId: hostTestOperationId(), - expectedRuntimeFence: null, - payloadFingerprint: '' - } - }) - expect(await host.attach(CALLER, params)).toMatchObject({ ok: true }) - const events = acquire.mock.calls.at(-1)?.[0].events - if (!events) { - throw new Error('missing provider event sink') - } - events.appendItem( - { provider: 'codex', threadId: THREAD, turnId: 'working', ordinal: 1 }, - { kind: 'turn', turnId: 'working', state: 'running' }, - { turnScope: AGENT_JOURNAL_THREAD_SCOPE } - ) - await host.flushStreamedEvents(sessionId) - } - const close = vi.fn(async () => true) - host.deps.adapter.closeSession = close - const server = await startOrcadWithLifecycle( - async (register) => { - register(async () => { - expect( - (await new AgentSessionRecoveryCapsule(root).list(NOW)).map((row) => row.sessionId).sort() - ).toEqual([...ids].sort()) - }) - register(stopOrcadStructuredAgentSessions) - return {} - }, - async () => {} - ) - await server.stop() - await server.stop() - expect( - (await host.restartResume.list()) - .map(({ sessionId, trigger }) => ({ sessionId, trigger })) - .sort((left, right) => left.sessionId.localeCompare(right.sessionId)) - ).toEqual( - [...ids] - .sort((left, right) => left.localeCompare(right)) - .map((sessionId) => ({ sessionId, trigger: 'quit' })) - ) -}) - -it('joins successful removal metadata and journal before profile ownership is released', async () => { - vi.useFakeTimers() - const root = dataRoot() - const profile = new BackendCoreProfileShutdown() - const dataFile = join(root, 'orca-data.json') - const store = createSqliteTestStore(Store, { dataFile }) - profile.store = store - await profile.store.flushPendingOrThrowAsync({ fullCheckpoint: true }) - store.getWorkspaceSession().activeTabId = 'before-stop' - const savedTab = () => JSON.parse(readPersistedStateJson(dataFile)).workspaceSession.activeTabId - let pending!: Awaited> - let transportStopped!: () => void - const transport = new Promise((resolve) => { - transportStopped = resolve - }) - let checkpointing: Promise | undefined - const handle = await startOrcadWithHost( - root, - async (registerCleanup) => { - registerCleanup(profile.finalize) - registerCleanup(() => worktreeRemovalLifetime.close()) - pending = await holdRemovalMetadata(root, () => { - store.getWorkspaceSession().activeTabId = 'after-delete' - }) - registerCleanup(async () => { - transportStopped() - }) - return {} - }, - () => {}, - () => (checkpointing = profile.checkpoint()) - ) - const stopping = handle.stop() - await transport - expect(() => worktreeRemovalLifetime.acquirePreparation()).toThrow('Orca is stopping') - expect(existsSync(join(root, ORCAD_LOCK_FILE_NAME))).toBe(true) - expect(await readWorktreeRemovalRecords(root)).toHaveLength(1) - await checkpointing - expect(savedTab()).toBe('before-stop') - pending.release() - await stopping - await pending.result - expect(await readFile(join(root, 'metadata-finished'), 'utf8')).toBe('removed') - expect(await readWorktreeRemovalRecords(root)).toEqual([]) - expect(savedTab()).toBe('after-delete') - expect(existsSync(join(root, ORCAD_LOCK_FILE_NAME))).toBe(false) -}) diff --git a/src/main/orcad/host-lifecycle/orcad-lifecycle.ts b/src/main/orcad/host-lifecycle/orcad-lifecycle.ts index 5b19c7fc4e0..89c5c0ffe17 100644 --- a/src/main/orcad/host-lifecycle/orcad-lifecycle.ts +++ b/src/main/orcad/host-lifecycle/orcad-lifecycle.ts @@ -136,7 +136,7 @@ export async function startOrcadAgentSessionRecordStoreOpen( export async function stopOrcadStructuredAgentSessions(): Promise { const { stopStructuredAgentSessionRuntime } = - await import('../../runtime/agent-session/structured-agent-session-runtime') + await import('../../runtime/agent-session/installation/structured-agent-session-runtime') await stopStructuredAgentSessionRuntime({ trigger: 'quit' }) } diff --git a/src/main/pi/rpc/prompts/rpc-prompt.ts b/src/main/pi/rpc/prompts/rpc-prompt.ts index 6da5276361a..f0a07bf95af 100644 --- a/src/main/pi/rpc/prompts/rpc-prompt.ts +++ b/src/main/pi/rpc/prompts/rpc-prompt.ts @@ -19,7 +19,7 @@ import type { AgentSessionAttachmentProblem } from '../../../../shared/agent-ses import { ClaudeDispatchContentError, readClaudeImage -} from '../../../claude/structured/claude-structured-dispatch-content' +} from '../../../claude/structured/dispatch/claude-structured-dispatch-content' type ImageLimits = { image: number; total: number } const SHRUNK_IMAGE_LIMITS: ImageLimits = { diff --git a/src/main/pi/rpc/rpc-message-dispatch.ts b/src/main/pi/rpc/rpc-message-dispatch.ts index e340b1d775c..229974eec9e 100644 --- a/src/main/pi/rpc/rpc-message-dispatch.ts +++ b/src/main/pi/rpc/rpc-message-dispatch.ts @@ -4,7 +4,7 @@ import { withProviderDiagnostic } from '../../../shared/agent-session/failures/agent-session-failure' import { agentSessionFailureWords } from '../../../shared/agent-session/failures/agent-session-failure-words' -import { ClaudeDispatchContentError } from '../../claude/structured/claude-structured-dispatch-content' +import { ClaudeDispatchContentError } from '../../claude/structured/dispatch/claude-structured-dispatch-content' import { JsonlRpcResponseError } from '../../jsonl-rpc/peer-reply' import type { AgentSessionDispatchOutcome, diff --git a/src/main/runtime/agent-session/agent-session-conversation-clear-commit.test.ts b/src/main/runtime/agent-session/agent-session-conversation-clear-commit.test.ts deleted file mode 100644 index 07fa14cf281..00000000000 --- a/src/main/runtime/agent-session/agent-session-conversation-clear-commit.test.ts +++ /dev/null @@ -1,176 +0,0 @@ -import { mkdtemp, rm } from 'node:fs/promises' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { afterEach, beforeEach, describe, expect, it } from 'vitest' -import type { AgentSessionOwnerProbe } from '../../../shared/agent-session/lifecycle/leases/agent-session-lease-adjudication' -import type { AgentSessionJournal } from '../../native-chat/agent-session-journal/journal-store' -import { - closeTestJournalHostDatabases, - createTrackedJournalOpener -} from '../../native-chat/agent-session-journal/store-lifecycle/journal-host-database-test-support' -import { - providerContextBoundaryForClear, - type AgentSessionConversationClear -} from './records/agent-session-conversation-command-record' -import { isAgentSessionRefusalError } from '../../../shared/agent-session/failures/agent-session-wire-refusals' -import { claudeProviderHandle } from '../../../shared/agent-session/lifecycle/provider-handles/agent-session-provider-handle-encoding' -import type { AgentSessionRecordStore } from './records/agent-session-record-store' -import { openTestAgentSessionRecordStore } from './records/agent-session-record-store-test-harness' - -const NOW = 1_800_000_000_000 -const SOURCE = 'session-alpha' -const INDETERMINATE: AgentSessionOwnerProbe = { outcome: 'indeterminate', reason: 'no answer' } - -let directory: string -const journals = createTrackedJournalOpener() - -beforeEach(async () => { - directory = await mkdtemp(join(tmpdir(), 'orca-agent-session-clear-commit-')) -}) - -afterEach(async () => { - await journals.closeAll() - await closeTestJournalHostDatabases() - await rm(directory, { recursive: true, force: true }) -}) - -const open = () => openTestAgentSessionRecordStore(directory) - -async function storeWithSource(): Promise { - const store = await open() - await store.reserveOwner({ - sessionId: SOURCE, - location: { - executionHostId: 'local', - wslDistro: null, - workspaceId: 'workspace-1', - workspaceKind: 'folder' - }, - provider: 'claude', - accountHome: { variable: 'CLAUDE_CONFIG_DIR', path: '/home/dev/.claude-work' }, - launchArgs: ['--flag'], - options: { model: 'sonnet' }, - expectedFence: null, - spawnToken: 'spawn-a', - claimKeyId: 'key-1', - handoffOperationId: null, - probe: INDETERMINATE, - operation: { - callerKey: 'client-1', - operationId: `${NOW}-${'1'.repeat(32)}`, - fingerprint: 'fp' - }, - now: NOW - }) - const fence = store.getRecord(SOURCE)!.lease.runtimeFence - await store.commitProcessIdentity({ - sessionId: SOURCE, - fence, - process: { hostId: 'local', pid: 4242, processStartTimeMs: NOW, spawnToken: 'spawn-a' }, - now: NOW - }) - await store.proveOwner({ - sessionId: SOURCE, - fence, - link: { - linkId: 'pre-clear-proof', - origin: 'created', - mintedAtFence: fence, - observedAt: NOW, - handle: claudeProviderHandle('pre-clear-provider-context', null) - }, - now: NOW - }) - await store.setSessionTabVisibility(SOURCE, true, 'tab-alpha') - return store -} - -function clear(fence: number): AgentSessionConversationClear { - return { - sessionId: SOURCE, - fence, - now: NOW + 5, - command: { - command: 'clear', - state: 'completed', - phase: 'committed', - runtimeFence: fence, - operationId: `${NOW}-${'2'.repeat(32)}`, - callerKey: 'client-1' - } - } -} - -async function prepare(released = true) { - const store = await storeWithSource() - if (released) { - await store.evictProvenDeadOwner({ - sessionId: SOURCE, - expectedFence: store.getRecord(SOURCE)!.lease.runtimeFence, - probe: { outcome: 'exit-observed' }, - now: NOW + 1 - }) - } - const journal = await journals.open({ - stateDirectory: directory, - identity: { - sessionId: SOURCE, - workspaceId: 'workspace-1', - hostId: 'local', - agent: 'claude', - providerHandle: null - }, - now: () => NOW + 5 - }) - const completed = clear(store.getRecord(SOURCE)!.lease.runtimeFence) - const operation = { - callerKey: completed.command.callerKey, - operationId: completed.command.operationId - } - await store.admitOperation({ ...operation, fingerprint: 'clear', now: NOW }) - const append = (input = completed) => - journal.write( - { kind: 'context-clear', boundary: providerContextBoundaryForClear(input) }, - () => ({ receipt: store.conversationReceipts.clear(() => input, operation) }) - ) - return { store, journal, completed, operation, append } -} - -async function queueClearCards(journal: AgentSessionJournal) { - for (const messageId of ['first', 'command', 'last']) { - await journal.queuedMessages.insert({ - messageId, - body: { - kind: 'message', - role: 'user', - blocks: [{ type: 'text', text: messageId }], - ...(messageId === 'command' ? { command: { name: 'compact' } } : {}) - } - }) - } -} - -describe('clear transaction', () => { - it('rolls the divider and receipt back when the fence moved', async () => { - const { store, journal, completed, operation, append } = await prepare() - await queueClearCards(journal) - await store.setConversationName(SOURCE, 'Saved name') - const before = journal.cursor() - const previousChain = store.getRecord(SOURCE)!.providerHandleChain - const refused = await append({ ...completed, fence: completed.fence + 1 }).catch( - (error: unknown) => error - ) - expect(isAgentSessionRefusalError(refused)).toBe(true) - expect(journal.cursor()).toEqual(before) - expect((await open()).getRecord(SOURCE)?.conversationName).toBe('Saved name') - expect( - (await journal.queuedMessages.list()).map(({ messageId, state }) => ({ messageId, state })) - ).toEqual(['first', 'command', 'last'].map((messageId) => ({ messageId, state: 'waiting' }))) - expect(await journal.queuedMessages.pauses()).toEqual([]) - expect((await open()).getRecord(SOURCE)?.providerContextBoundary).toBeUndefined() - expect((await open()).getRecord(SOURCE)?.providerHandleChain).toEqual(previousChain) - expect(store.getOperationRow(operation.callerKey, operation.operationId)?.outcome.status).toBe( - 'pending' - ) - }) -}) diff --git a/src/main/runtime/agent-session/agent-session-status-cut-work.test-support.ts b/src/main/runtime/agent-session/agent-session-status-cut-work.test-support.ts deleted file mode 100644 index c534330ff47..00000000000 --- a/src/main/runtime/agent-session/agent-session-status-cut-work.test-support.ts +++ /dev/null @@ -1,103 +0,0 @@ -import { vi } from 'vitest' -import * as cut from '../../../shared/native-chat/transcript/continuation/native-chat-orca-stop-cut' -import * as commands from '../../../shared/agent-session/requests/structured-agent-session-command-entry' -import type { - AgentJournalRenderItem, - AgentJournalSubmission -} from '../../../shared/agent-session/journal/agent-session-journal-types' - -/** Count only the original status reader, after production context selection. */ -export function countStatusCutWork() { - const counts = { - calls: 0, - items: 0, - submissions: 0, - pending: 0, - bodyEntries: 0, - commandVisits: 0, - backward: 0, - scoped: 0, - indexes: 0, - commandEntries: 0 - } - let reading = false - const index = commands.structuredAgentSessionCommandTurnItemIds - vi.spyOn(commands, 'structuredAgentSessionCommandTurnItemIds').mockImplementation((items) => { - const result = index(items) - if (reading) { - counts.indexes++ - counts.commandEntries += result.size - } - return result - }) - function watchItems(items: readonly AgentJournalRenderItem[]) { - let iterators = 0 - return new Proxy(items, { - get(target, property) { - if (property === 'map') { - return function map( - callback: ( - item: AgentJournalRenderItem, - i: number, - rows: readonly AgentJournalRenderItem[] - ) => U, - thisArg?: unknown - ) { - return target.map((item, i, rows) => { - counts.bodyEntries++ - return callback.call(thisArg, item, i, rows) - }) - } - } - if (property === Symbol.iterator) { - return function* (): Generator { - const phase = iterators++ === 0 ? 'commandVisits' : 'scoped' - for (const item of target) { - counts[phase]++ - yield item - } - return undefined - } - } - if (property === 'length') { - return target.length - } - if (typeof property === 'string' && /^(0|[1-9]\d*)$/.test(property)) { - const index = Number(property) - if (Number.isSafeInteger(index)) { - counts.backward++ - return target[index] - } - } - throw new Error(`Uncounted status-cut item property: ${String(property)}`) - } - }) - } - function watchSubmissions(submissions: readonly Pick[]) { - return new Proxy(submissions, { - get(target, property) { - if (property === 'some') { - return (predicate: Parameters[0], thisArg?: unknown) => - target.some((item, i, rows) => { - counts.pending++ - return predicate.call(thisArg, item, i, rows) - }) - } - throw new Error(`Uncounted status-cut submission property: ${String(property)}`) - } - }) - } - const outcome = cut.nativeChatStatusTurnOutcome - vi.spyOn(cut, 'nativeChatStatusTurnOutcome').mockImplementation((request, items, submissions) => { - counts.calls++ - counts.items += items.length - counts.submissions += submissions.length - reading = true - try { - return outcome(request, watchItems(items), watchSubmissions(submissions)) - } finally { - reading = false - } - }) - return counts -} diff --git a/src/main/runtime/agent-session/agent-session-account-env.ts b/src/main/runtime/agent-session/environment/agent-session-account-env.ts similarity index 100% rename from src/main/runtime/agent-session/agent-session-account-env.ts rename to src/main/runtime/agent-session/environment/agent-session-account-env.ts diff --git a/src/main/runtime/agent-session/installation/claude-structured-fake-connection-test-fixture.ts b/src/main/runtime/agent-session/installation/claude-structured-fake-connection-test-fixture.ts deleted file mode 100644 index 3a81ae2ed18..00000000000 --- a/src/main/runtime/agent-session/installation/claude-structured-fake-connection-test-fixture.ts +++ /dev/null @@ -1,178 +0,0 @@ -import { expect, vi } from 'vitest' -import { getStructuredAgentSessionHost } from '../../../native-chat/agent-session-wire/host/structured-agent-session-registry' -import { - type claudeInitialization, - claudeInitializationScope -} from '../../../claude/structured/claude-structured-startup-settled-test-support' -import type { - ClaudeStreamJsonConnection, - ClaudeStreamJsonConnectionHandlers, - ClaudeStreamJsonLaunch, - openClaudeStreamJsonConnection -} from '../../../claude/claude-stream-json-connection' - -export type FakeClaudeConnection = Omit & { - closed: boolean - exitVerdict: ClaudeStreamJsonConnection['exitVerdict'] - launch: ClaudeStreamJsonLaunch - handlers: ClaudeStreamJsonConnectionHandlers - calls: { subtype: string; params?: Record }[] - sent: Record[] - initialization: ReturnType - closeProven: boolean -} - -export function fakeClaude(providerSession: string) { - const connections: FakeClaudeConnection[] = [] - let initializeAccount: unknown - let initializeHeld = false - const initializationScope = claudeInitializationScope() - let disposed = false - let contextUsage: () => Promise = async () => ({}) - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the fake answers every control request the session issues; the real opener's signature is what the runtime under test calls. - const openConnection = (async (launch, handlers = {}) => { - const initialization = initializationScope.create({ - held: initializeHeld, - response: { - models: [{ value: 'sonnet', displayName: 'Sonnet' }], - ...(initializeAccount === undefined ? {} : { account: initializeAccount }) - }, - deliver: () => - handlers.onMessage?.({ - type: 'system', - subtype: 'init', - session_id: providerSession, - model: 'claude-sonnet-5', - apiKeySource: 'none' - }) - }) - const connection: FakeClaudeConnection = { - launch, - handlers, - calls: [], - sent: [], - pid: 4321 + connections.length, - closed: false, - initialization, - closeProven: true, - initializationResult: () => initialization.read(connection.calls), - getSettings: async () => { - connection.calls.push({ subtype: 'get_settings' }) - return { env: {} } - }, - renameSession: async () => {}, - getContextUsage: async () => { - connection.calls.push({ subtype: 'get_context_usage' }) - return contextUsage() - }, - supportedModels: async () => { - connection.calls.push({ subtype: 'list_models' }) - return [{ value: 'sonnet', displayName: 'Sonnet' }] - }, - setModel: async (model) => { - connection.calls.push({ subtype: 'set_model', params: { model } }) - }, - setPermissionMode: async (mode) => { - connection.calls.push({ subtype: 'set_permission_mode', params: { mode } }) - }, - applyFlagSettings: async (settings) => { - connection.calls.push({ subtype: 'apply_flag_settings', params: { settings } }) - }, - interrupt: async () => { - connection.calls.push({ subtype: 'interrupt', params: {} }) - return undefined - }, - cancelAsyncMessage: async () => false, - stopTask: async (taskId) => { - connection.calls.push({ subtype: 'stop_task', params: { taskId } }) - }, - backgroundTask: async (toolUseId) => { - connection.calls.push({ subtype: 'background_tasks', params: { toolUseId } }) - return false - }, - send: async (message, beforeDispatch) => { - await beforeDispatch?.() - connection.sent.push(message) - if (message.type === 'user') { - handlers.onMessage?.({ ...message, uuid: 'user-1' }) - } - }, - exitVerdict: { root: 'live', tree: 'unverifiable' }, - close: async () => { - connection.closed = true - initialization.dispose() - return disposed || connection.closeProven - } - } - connections.push(connection) - return connection - }) as typeof openClaudeStreamJsonConnection - const live = (): FakeClaudeConnection => { - const connection = connections.at(-1) - if (!connection) { - throw new Error('no Claude connection') - } - return connection - } - return { - connections, - openConnection, - live, - setInitializeAccount: (account: unknown) => { - initializeAccount = account - }, - setInitializeHeld: (held: boolean) => { - initializeHeld = held - }, - dispose: () => { - disposed = true - initializationScope.dispose() - }, - setContextUsage: (answer: () => Promise) => { - contextUsage = answer - } - } -} - -export function leaseOf(sessionId: string): { - claimStatus: string - runtimeFence: number - handoffStage: string | null - deathEvidence: { kind: string; detail: string } | null -} { - const host = getStructuredAgentSessionHost() as unknown as { - deps: { store: { getRecord: (id: string) => { lease: ReturnType } } } - } - return host.deps.store.getRecord(sessionId).lease -} - -export async function startingConnection(claude: ReturnType, sessionId: string) { - const connection = claude.live() - await vi.waitFor(() => { - expect(getStructuredAgentSessionHost()?.['sessions'].get(sessionId)?.child).toMatchObject({ - phase: 'starting', - generation: expect.any(String), - fence: leaseOf(sessionId).runtimeFence - }) - expect(getStructuredAgentSessionHost()?.deps.store.getRecord(sessionId)?.lease).toMatchObject({ - claimStatus: 'live', - handoffStage: null, - ownerProcess: { pid: connection.pid } - }) - }) - return connection -} - -export function failStarting( - claude: ReturnType, - connection: ReturnType, - tree: 'unverifiable' | 'live' | 'exited' -) { - connection.exitVerdict = { root: 'exited', tree } - connection.closeProven = tree === 'exited' - connection.handlers.onExit?.( - new Error('claude stream-json exited (code 1): claude: not signed in') - ) - connection.initialization.reject(new Error('Query closed before response received')) - claude.setInitializeHeld(false) -} diff --git a/src/main/runtime/agent-session/installation/runtime-structured-agent-host.ts b/src/main/runtime/agent-session/installation/runtime-structured-agent-host.ts index ea5696e753e..697313aee00 100644 --- a/src/main/runtime/agent-session/installation/runtime-structured-agent-host.ts +++ b/src/main/runtime/agent-session/installation/runtime-structured-agent-host.ts @@ -15,7 +15,7 @@ import type { RuntimeWorkspaceCatalog } from '../../workspaces/catalog/workspace import type { OrcaRuntimeWithRefreshPtyWorktreeRecordsFromController } from '../../terminal/lifecycle/pty-worktree-refresh' import type { RuntimeAccountController } from '../environment/runtime-account-controller' import type { OrcaRuntimeWithPruneMobileSessionTabGroupLayout } from '../../session-lifecycle/projection/prune-mobile-session-tab-group-layout' -import type { OrcaRuntimeWithGetStructuredAgentSessionCreateSupport } from '../../session-tabs/structured-session-create-support' +import type { OrcaRuntimeWithGetStructuredAgentSessionCreateSupport } from '../../session-tabs/chat/structured-session-create-support' import type { AgentSessionRecord } from '../../../../shared/agent-session/lifecycle/agent-session-record' import type { StructuredAgentSessionHostDeps } from '../../../native-chat/agent-session-wire/host/structured-agent-session-host-types' import { OrcaRuntimeWithStartTuiIdleVisibleReadProbe } from '../../terminal/wait/terminal-wait-visible-probe' diff --git a/src/main/runtime/agent-session/installation/structured-agent-runtime-registration-types.ts b/src/main/runtime/agent-session/installation/structured-agent-runtime-registration-types.ts index 82532120b99..d4085f2ad65 100644 --- a/src/main/runtime/agent-session/installation/structured-agent-runtime-registration-types.ts +++ b/src/main/runtime/agent-session/installation/structured-agent-runtime-registration-types.ts @@ -13,7 +13,7 @@ import type { StructuredAgentSessionHost } from '../../../native-chat/agent-sess import type { JournalSqlDatabase } from '../../../native-chat/agent-session-journal/database/journal-sql-database' import type { AgentModelCatalogDiscovery } from '../../../native-chat/agent-model-catalog/agent-model-catalog-discovery' import type { AgentSessionRecordStore } from '../records/agent-session-record-store' -import type { createStructuredAgentSessionDispatchFollowUps } from '../structured-agent-session-dispatch-followups' +import type { createStructuredAgentSessionDispatchFollowUps } from '../lifecycle/structured-agent-session-dispatch-followups' import type { StructuredAgentSessionRuntimeDeps } from './structured-agent-session-runtime-contract' import type { createStructuredAgentEnvironmentResolvers } from '../environment/structured-agent-shell-environment' import type { diff --git a/src/main/runtime/agent-session/structured-agent-session-attachment-sweep.ts b/src/main/runtime/agent-session/installation/structured-agent-session-attachment-sweep.ts similarity index 83% rename from src/main/runtime/agent-session/structured-agent-session-attachment-sweep.ts rename to src/main/runtime/agent-session/installation/structured-agent-session-attachment-sweep.ts index cd64d975a8b..2da171a592a 100644 --- a/src/main/runtime/agent-session/structured-agent-session-attachment-sweep.ts +++ b/src/main/runtime/agent-session/installation/structured-agent-session-attachment-sweep.ts @@ -1,6 +1,6 @@ -import type { JournalSqlDatabase } from '../../native-chat/agent-session-journal/database/journal-sql-database' -import type { AgentSessionAttachmentSweepFacts } from '../../native-chat/agent-session-attachments/agent-session-attachment-sweep' -import type { JournalWriterEffect } from '../../native-chat/agent-session-journal/journal-writer-effects' +import type { JournalSqlDatabase } from '../../../native-chat/agent-session-journal/database/journal-sql-database' +import type { AgentSessionAttachmentSweepFacts } from '../../../native-chat/agent-session-attachments/agent-session-attachment-sweep' +import type { JournalWriterEffect } from '../../../native-chat/agent-session-journal/journal-writer-effects' /** Filesystem awaits release the writer; each claim decision returns to its sole transaction owner. */ export function structuredAgentSessionAttachmentSweepFacts( diff --git a/src/main/runtime/agent-session/structured-agent-session-attachment-wiring.test.ts b/src/main/runtime/agent-session/installation/structured-agent-session-attachment-wiring.test.ts similarity index 54% rename from src/main/runtime/agent-session/structured-agent-session-attachment-wiring.test.ts rename to src/main/runtime/agent-session/installation/structured-agent-session-attachment-wiring.test.ts index 896e4f75342..e76c493139f 100644 --- a/src/main/runtime/agent-session/structured-agent-session-attachment-wiring.test.ts +++ b/src/main/runtime/agent-session/installation/structured-agent-session-attachment-wiring.test.ts @@ -1,14 +1,14 @@ import { existsSync } from 'node:fs' -import { mkdtemp, rm, writeFile } from 'node:fs/promises' +import { mkdtemp, rm } from 'node:fs/promises' import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { getAgentSessionAttachmentStore } from '../../native-chat/agent-session-attachments/agent-session-attachment-store-registry' -import { agentSessionAttachmentStoreRoot } from '../../native-chat/agent-session-attachments/agent-session-attachment-references' -import { createStructuredAgentSessionLogger } from '../../native-chat/agent-session-wire/host/structured-agent-session-logger' -import { closeTestJournalHostDatabases } from '../../native-chat/agent-session-journal/store-lifecycle/journal-host-database-test-support' -import { openTestAgentSessionDatabase } from './records/agent-session-record-store-test-harness' -import type { AgentSessionRecordStore } from './records/agent-session-record-store' +import { getAgentSessionAttachmentStore } from '../../../native-chat/agent-session-attachments/agent-session-attachment-store-registry' +import { agentSessionAttachmentStoreRoot } from '../../../native-chat/agent-session-attachments/agent-session-attachment-references' +import { createStructuredAgentSessionLogger } from '../../../native-chat/agent-session-wire/host/structured-agent-session-logger' +import { closeTestJournalHostDatabases } from '../../../native-chat/agent-session-journal/store-lifecycle/journal-host-database-test-support' +import { openTestAgentSessionDatabase } from '../records/agent-session-record-store-test-harness' +import type { AgentSessionRecordStore } from '../records/agent-session-record-store' import { installAgentSessionAttachments, stopAgentSessionAttachments @@ -51,14 +51,4 @@ describe('installAgentSessionAttachments', () => { expect(existsSync(root)).toBe(true) expect(getAgentSessionAttachmentStore()?.rootDir).toBe(root) }) - - it('still installs the store when the root cannot be created', async () => { - const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) - // A file where the state directory should be: nothing can be created under it. - const blocked = join(stateDirectory, 'not-a-directory') - await writeFile(blocked, '') - await expect(install(blocked)).resolves.toBeUndefined() - expect(getAgentSessionAttachmentStore()?.rootDir).toBe(agentSessionAttachmentStoreRoot(blocked)) - warn.mockRestore() - }) }) diff --git a/src/main/runtime/agent-session/structured-agent-session-attachment-wiring.ts b/src/main/runtime/agent-session/installation/structured-agent-session-attachment-wiring.ts similarity index 71% rename from src/main/runtime/agent-session/structured-agent-session-attachment-wiring.ts rename to src/main/runtime/agent-session/installation/structured-agent-session-attachment-wiring.ts index d6cc1c6b7e0..e05a697d638 100644 --- a/src/main/runtime/agent-session/structured-agent-session-attachment-wiring.ts +++ b/src/main/runtime/agent-session/installation/structured-agent-session-attachment-wiring.ts @@ -1,20 +1,20 @@ // Keep chat attachment storage/sweeps beside the journal; its database owns upload claims the sweeps honor. import { mkdirSync } from 'node:fs' -import { AgentSessionAttachmentStore } from '../../native-chat/agent-session-attachments/agent-session-attachment-store' +import { AgentSessionAttachmentStore } from '../../../native-chat/agent-session-attachments/agent-session-attachment-store' import { publishAgentSessionUploadRemoval, setAgentSessionAttachmentStore -} from '../../native-chat/agent-session-attachments/agent-session-attachment-store-registry' +} from '../../../native-chat/agent-session-attachments/agent-session-attachment-store-registry' import { startAgentSessionAttachmentSweeps, type AgentSessionAttachmentSweeper -} from '../../native-chat/agent-session-attachments/agent-session-attachment-sweep' -import { agentSessionAttachmentStoreRoot } from '../../native-chat/agent-session-attachments/agent-session-attachment-references' -import type { JournalSqlDatabase } from '../../native-chat/agent-session-journal/database/journal-sql-database' +} from '../../../native-chat/agent-session-attachments/agent-session-attachment-sweep' +import { agentSessionAttachmentStoreRoot } from '../../../native-chat/agent-session-attachments/agent-session-attachment-references' +import type { JournalSqlDatabase } from '../../../native-chat/agent-session-journal/database/journal-sql-database' import { structuredAgentSessionAttachmentSweepFacts } from './structured-agent-session-attachment-sweep' -import type { StructuredAgentSessionLogger } from '../../native-chat/agent-session-wire/host/structured-agent-session-logger' -import type { AgentSessionRecordStore } from './records/agent-session-record-store' +import type { StructuredAgentSessionLogger } from '../../../native-chat/agent-session-wire/host/structured-agent-session-logger' +import type { AgentSessionRecordStore } from '../records/agent-session-record-store' const FIRST_SWEEP_DELAY_MS = 60 * 1000 const SWEEP_INTERVAL_MS = 6 * 60 * 60 * 1000 diff --git a/src/main/runtime/agent-session/structured-agent-session-held-signal.test.ts b/src/main/runtime/agent-session/installation/structured-agent-session-held-signal.test.ts similarity index 54% rename from src/main/runtime/agent-session/structured-agent-session-held-signal.test.ts rename to src/main/runtime/agent-session/installation/structured-agent-session-held-signal.test.ts index 64243b5ee08..8bbb55302ea 100644 --- a/src/main/runtime/agent-session/structured-agent-session-held-signal.test.ts +++ b/src/main/runtime/agent-session/installation/structured-agent-session-held-signal.test.ts @@ -7,29 +7,29 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { onStructuredAgentSessionsHeldChanged, structuredAgentSessionsHeld -} from '../../native-chat/agent-session-wire/host/structured-agent-session-registry' -import type { StructuredAgentSessionHost } from '../../native-chat/agent-session-wire/host/structured-agent-session-host' -import type { RpcRequest } from '../rpc/core' +} from '../../../native-chat/agent-session-wire/host/structured-agent-session-registry' +import type { StructuredAgentSessionHost } from '../../../native-chat/agent-session-wire/host/structured-agent-session-host' +import type { RpcRequest } from '../../rpc/core' -import { RpcDispatcher } from '../rpc/dispatcher' -import type { OrcaRuntimeService } from '../orca-runtime' +import { RpcDispatcher } from '../../rpc/dispatcher' +import type { OrcaRuntimeService } from '../../orca-runtime' import { stopStructuredAgentSessionRuntime } from './structured-agent-session-runtime' -import { ensureTestStructuredAgentSessionHost as ensureStructuredAgentSessionHost } from './records/agent-session-record-store-test-harness' -import { createStructuredAgentSessionLogger } from '../../native-chat/agent-session-wire/host/structured-agent-session-logger' -import { openAgentSessionRecordStoreOnce } from './records/agent-session-record-store-slot' +import { ensureTestStructuredAgentSessionHost as ensureStructuredAgentSessionHost } from '../records/agent-session-record-store-test-harness' +import { createStructuredAgentSessionLogger } from '../../../native-chat/agent-session-wire/host/structured-agent-session-logger' +import { openAgentSessionRecordStoreOnce } from '../records/agent-session-record-store-slot' import { journalSqlReaderPath, journalSqlWorkerPath -} from '../../native-chat/agent-session-journal/journal-sql-worker-bundle.test-fixture' +} from '../../../native-chat/agent-session-journal/journal-sql-worker-bundle.test-fixture' -vi.mock('../../ai-vault/scan-service/session-scanner-service-spawn', async (importOriginal) => ({ +vi.mock('../../../ai-vault/scan-service/session-scanner-service-spawn', async (importOriginal) => ({ ...(await importOriginal()), scanAiVaultSessionsInService: vi.fn(), resolveAiVaultSessionTitlesInService: vi.fn() })) -const { AI_VAULT_METHODS } = await import('../rpc/methods/history/ai-vault') -await import('../rpc/methods/agent-launch/agent-launch-replay') +const { AI_VAULT_METHODS } = await import('../../rpc/methods/history/ai-vault') +await import('../../rpc/methods/agent-launch/agent-launch-replay') let stateDirectory: string let heldChanges: boolean[] @@ -73,31 +73,6 @@ const runtime = { }) } as unknown as OrcaRuntimeService -function operationId(suffix: string): string { - return `${Date.now()}-${suffix.padStart(32, '0')}` -} - -async function recordChat(host: StructuredAgentSessionHost): Promise { - await host.deps.store.reserveOwner({ - sessionId: 'session-1', - location: { - executionHostId: 'local', - wslDistro: null, - workspaceId: 'workspace-1', - workspaceKind: 'git-worktree' - }, - provider: 'claude', - accountHome: { variable: 'CLAUDE_CONFIG_DIR', path: join(stateDirectory, 'claude') }, - expectedFence: null, - spawnToken: 'spawn-1', - claimKeyId: 'key-1', - handoffOperationId: null, - probe: { outcome: 'indeterminate', reason: 'no answer' }, - operation: { callerKey: 'desktop', operationId: operationId('c1'), fingerprint: 'fp-1' }, - now: Date.now() - }) -} - beforeEach(async () => { stateDirectory = await mkdtemp(join(tmpdir(), 'orca-held-signal-')) heldChanges = [] @@ -120,25 +95,4 @@ describe('whether this machine holds a structured chat', () => { expect(structuredAgentSessionsHeld()).toBe(false) expect(heldChanges).toEqual([]) }) - - it('turns true when the first chat is created here, without a restart', async () => { - const host = await installHost() - expect(structuredAgentSessionsHeld()).toBe(false) - - await recordChat(host) - - expect(structuredAgentSessionsHeld()).toBe(true) - expect(heldChanges).toEqual([true]) - }) - - it('is true as soon as the host restores a saved chat', async () => { - await recordChat(await installHost()) - await stopStructuredAgentSessionRuntime() - heldChanges = [] - - await installHost() - - expect(structuredAgentSessionsHeld()).toBe(true) - expect(heldChanges).toEqual([true]) - }) }) diff --git a/src/main/runtime/agent-session/installation/structured-agent-session-host-assembly.ts b/src/main/runtime/agent-session/installation/structured-agent-session-host-assembly.ts index 5ca49b58601..5db871d89e3 100644 --- a/src/main/runtime/agent-session/installation/structured-agent-session-host-assembly.ts +++ b/src/main/runtime/agent-session/installation/structured-agent-session-host-assembly.ts @@ -10,22 +10,22 @@ import { } from '../../../native-chat/agent-session-wire/providers/structured-agent-session-provider-naming' import { setStructuredAgentSessionHost } from '../../../native-chat/agent-session-wire/host/structured-agent-session-registry' import { scheduleNativeChatVisualsSweep } from '../../../native-chat/conversation-files/native-chat-visuals-sweep' -import type { InstalledRuntime } from '../structured-agent-session-runtime-teardown' +import type { InstalledRuntime } from './structured-agent-session-runtime-teardown' import { AgentSessionRecoveryCapsule } from '../records/agent-session-recovery-capsule' import type { OpenedAgentSessionRecordStore } from '../records/agent-session-record-store-slot' -import { installAgentSessionAttachments } from '../structured-agent-session-attachment-wiring' +import { installAgentSessionAttachments } from './structured-agent-session-attachment-wiring' import { createStructuredAgentSessionOwnerProbe, createStructuredAgentSessionOwnerProbes -} from '../structured-agent-session-owner-probe' +} from '../ownership/structured-agent-session-owner-probe' import type { StructuredAgentAdapterContext } from './structured-agent-runtime-registration-types' import { STRUCTURED_AGENT_RUNTIME_REGISTRATIONS } from './structured-agent-runtime-registrations' -import { createStructuredAgentSessionLifecycleDelivery } from '../structured-agent-session-lifecycle-delivery' -import { createStructuredAgentSessionDispatchFollowUps } from '../structured-agent-session-dispatch-followups' +import { createStructuredAgentSessionLifecycleDelivery } from '../lifecycle/structured-agent-session-lifecycle-delivery' +import { createStructuredAgentSessionDispatchFollowUps } from '../lifecycle/structured-agent-session-dispatch-followups' import type { CatalogOwner } from '../model-catalog/structured-agent-model-catalog-wiring' import type { StructuredAgentSessionRuntimeDeps } from './structured-agent-session-runtime-contract' import type { AgentSessionRecord } from '../../../../shared/agent-session/lifecycle/agent-session-record' -import { observePRWatchCommittedRows } from '../pr-watch-runtime' +import { observePRWatchCommittedRows } from '../lifecycle/pr-watch-runtime' export async function installOnJournal( deps: StructuredAgentSessionRuntimeDeps, diff --git a/src/main/runtime/agent-session/structured-agent-session-host-refusal.ts b/src/main/runtime/agent-session/installation/structured-agent-session-host-refusal.ts similarity index 95% rename from src/main/runtime/agent-session/structured-agent-session-host-refusal.ts rename to src/main/runtime/agent-session/installation/structured-agent-session-host-refusal.ts index 9702b78819d..d780a1e146a 100644 --- a/src/main/runtime/agent-session/structured-agent-session-host-refusal.ts +++ b/src/main/runtime/agent-session/installation/structured-agent-session-host-refusal.ts @@ -1,7 +1,7 @@ import { isAgentSessionRefusalError, type AgentSessionRefusalError -} from '../../../shared/agent-session/failures/agent-session-wire-refusals' +} from '../../../../shared/agent-session/failures/agent-session-wire-refusals' let installRefusal: AgentSessionRefusalError | null = null diff --git a/src/main/runtime/agent-session/structured-agent-session-integration-replay.test.ts b/src/main/runtime/agent-session/installation/structured-agent-session-integration-replay.test.ts similarity index 58% rename from src/main/runtime/agent-session/structured-agent-session-integration-replay.test.ts rename to src/main/runtime/agent-session/installation/structured-agent-session-integration-replay.test.ts index 1dc77eb6b13..61027e0b457 100644 --- a/src/main/runtime/agent-session/structured-agent-session-integration-replay.test.ts +++ b/src/main/runtime/agent-session/installation/structured-agent-session-integration-replay.test.ts @@ -1,20 +1,20 @@ -import { readTestJournalItems } from '../../native-chat/agent-session-journal/journal-observation.test-support' +import { readTestJournalItems } from '../../../native-chat/agent-session-journal/journal-observation.test-support' // Exercise shipped RPC, schemas, capability gate, stores, lease and adapter; only the Codex app-server child is fake. import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import type { AgentJournalRenderItem } from '../../../shared/agent-session/journal/agent-session-journal-types' -import { createTrackedJournalOpener } from '../../native-chat/agent-session-journal/store-lifecycle/journal-host-database-test-support' -import type * as JournalStoreFactory from '../../native-chat/agent-session-journal/journal-store-factory' +import type { AgentJournalRenderItem } from '../../../../shared/agent-session/journal/agent-session-journal-types' +import { createTrackedJournalOpener } from '../../../native-chat/agent-session-journal/store-lifecycle/journal-host-database-test-support' +import type * as JournalStoreFactory from '../../../native-chat/agent-session-journal/journal-store-factory' import { stopStructuredAgentSessionRuntime } from './structured-agent-session-runtime' -import { ensureTestStructuredAgentSessionHost as ensureStructuredAgentSessionHost } from './records/agent-session-record-store-test-harness' +import { ensureTestStructuredAgentSessionHost as ensureStructuredAgentSessionHost } from '../records/agent-session-record-store-test-harness' import { openStructuredCodexRpcHarness, SESSION, THREAD, TURN, type StructuredCodexRpcHarness -} from '../rpc/methods/structured-sessions/structured-codex-session-rpc-test-harness' -import { codexProviderHandle } from '../../../shared/agent-session/lifecycle/provider-handles/agent-session-provider-handle-encoding' +} from '../../rpc/methods/structured-sessions/structured-codex-session-rpc-test-harness' +import { codexProviderHandle } from '../../../../shared/agent-session/lifecycle/provider-handles/agent-session-provider-handle-encoding' const { journalOpenHold } = vi.hoisted(() => { const journalOpenHold: { next: { entered: () => void; released: Promise } | null } = { @@ -24,23 +24,26 @@ const { journalOpenHold } = vi.hoisted(() => { }) // Holds the next journal open midway, so provider events land while the attach binds its journal. -vi.mock('../../native-chat/agent-session-journal/journal-store-factory', async (importOriginal) => { - const actual = await importOriginal() - return { - ...actual, - openAgentSessionJournal: async ( - input: Parameters[0] - ) => { - const hold = journalOpenHold.next - journalOpenHold.next = null - if (hold) { - hold.entered() - await hold.released +vi.mock( + '../../../native-chat/agent-session-journal/journal-store-factory', + async (importOriginal) => { + const actual = await importOriginal() + return { + ...actual, + openAgentSessionJournal: async ( + input: Parameters[0] + ) => { + const hold = journalOpenHold.next + journalOpenHold.next = null + if (hold) { + hold.entered() + await hold.released + } + return actual.openAgentSessionJournal(input) } - return actual.openAgentSessionJournal(input) } } -}) +) const journals = createTrackedJournalOpener() const WORKSPACE = 'workspace-1' @@ -64,32 +67,6 @@ afterEach(async () => { }) describe('a structured codex session over agentSession.*', () => { - it('replays a durable image send without dispatching it twice', async () => { - const created = await harness.ok<{ fence: number }>( - 'agentSession.create', - harness.createIntentParams() - ) - const path = '/tmp/orca-paste-image.png' - const body = { - kind: 'message' as const, - role: 'user' as const, - blocks: [{ type: 'image-ref' as const, path }] - } - const params = { - envelope: harness.envelope('agentSession.send', { body }, created.fence), - body - } - - const turnStarts = () => - harness.codex.live().calls.filter((entry) => entry.method === 'turn/start') - await harness.ok('agentSession.send', params) - await vi.waitFor(() => expect(turnStarts()).toHaveLength(1)) - const replay = await harness.call('agentSession.send', params) - - expect(replay).toMatchObject({ ok: true, result: { ok: true, replayed: true } }) - expect(turnStarts()).toHaveLength(1) - }) - it('joins an acquired attach through journal bind before draining final rows', async () => { await ensureStructuredAgentSessionHost(harness.hostConfig()) const openEntered = Promise.withResolvers() diff --git a/src/main/runtime/agent-session/structured-agent-session-journal-open.ts b/src/main/runtime/agent-session/installation/structured-agent-session-journal-open.ts similarity index 86% rename from src/main/runtime/agent-session/structured-agent-session-journal-open.ts rename to src/main/runtime/agent-session/installation/structured-agent-session-journal-open.ts index 02f355eed39..af7d2b17995 100644 --- a/src/main/runtime/agent-session/structured-agent-session-journal-open.ts +++ b/src/main/runtime/agent-session/installation/structured-agent-session-journal-open.ts @@ -1,7 +1,7 @@ -import { JournalSqlDatabase } from '../../native-chat/agent-session-journal/database/journal-sql-database' -import { journalOpenRefusalError } from '../../native-chat/agent-session-journal/replay/journal-open-failure' +import { JournalSqlDatabase } from '../../../native-chat/agent-session-journal/database/journal-sql-database' +import { journalOpenRefusalError } from '../../../native-chat/agent-session-journal/replay/journal-open-failure' import { recordStructuredAgentSessionHostInstallRefusal } from './structured-agent-session-host-refusal' -import type { StructuredAgentSessionLogger } from '../../native-chat/agent-session-wire/host/structured-agent-session-logger' +import type { StructuredAgentSessionLogger } from '../../../native-chat/agent-session-wire/host/structured-agent-session-logger' // Repeated requests retry journal open; log each distinct failure once, including its stack. let lastLoggedOpenFailure: string | null = null diff --git a/src/main/runtime/agent-session/installation/structured-agent-session-runtime-contract.ts b/src/main/runtime/agent-session/installation/structured-agent-session-runtime-contract.ts index dc9fccd68b9..c6d87d06f15 100644 --- a/src/main/runtime/agent-session/installation/structured-agent-session-runtime-contract.ts +++ b/src/main/runtime/agent-session/installation/structured-agent-session-runtime-contract.ts @@ -1,9 +1,9 @@ import type { StructuredAgentSessionHostDeps } from '../../../native-chat/agent-session-wire/host/structured-agent-session-host-types' import type { AgentSessionAccountKind } from '../../../../shared/agent-session/failures/agent-session-availability' -import type { StructuredAgentSessionTransportOverrides } from '../structured-agent-session-transport-overrides' +import type { StructuredAgentSessionTransportOverrides } from './structured-agent-session-transport-overrides' import type { AgentSessionRecord } from '../../../../shared/agent-session/lifecycle/agent-session-record' import type { AgentSessionAccountHome } from '../../../../shared/agent-session/lifecycle/accounts/agent-session-account-home' -import type { StructuredAttentionMobileDelivery } from '../structured-agent-session-mobile-attention' +import type { StructuredAttentionMobileDelivery } from '../lifecycle/structured-agent-session-mobile-attention' import type { StructuredAgentCommand, StructuredAgentCommandSettings diff --git a/src/main/runtime/agent-session/structured-agent-session-runtime-teardown.ts b/src/main/runtime/agent-session/installation/structured-agent-session-runtime-teardown.ts similarity index 85% rename from src/main/runtime/agent-session/structured-agent-session-runtime-teardown.ts rename to src/main/runtime/agent-session/installation/structured-agent-session-runtime-teardown.ts index 296b9196808..29740eb1a80 100644 --- a/src/main/runtime/agent-session/structured-agent-session-runtime-teardown.ts +++ b/src/main/runtime/agent-session/installation/structured-agent-session-runtime-teardown.ts @@ -1,7 +1,7 @@ -import type { AgentSessionResumeTrigger } from '../../../shared/agent-session/lifecycle/resume/agent-session-resume-marker' -import type { StructuredAgentSessionHost } from '../../native-chat/agent-session-wire/host/structured-agent-session-host' -import type { JournalSqlDatabase } from '../../native-chat/agent-session-journal/database/journal-sql-database' -import { recordAgentSessionRuntimeEnd } from './records/agent-session-runtime-end-record' +import type { AgentSessionResumeTrigger } from '../../../../shared/agent-session/lifecycle/resume/agent-session-resume-marker' +import type { StructuredAgentSessionHost } from '../../../native-chat/agent-session-wire/host/structured-agent-session-host' +import type { JournalSqlDatabase } from '../../../native-chat/agent-session-journal/database/journal-sql-database' +import { recordAgentSessionRuntimeEnd } from '../records/agent-session-runtime-end-record' export type InstalledRuntime = { host: StructuredAgentSessionHost diff --git a/src/main/runtime/agent-session/structured-agent-session-runtime.ts b/src/main/runtime/agent-session/installation/structured-agent-session-runtime.ts similarity index 85% rename from src/main/runtime/agent-session/structured-agent-session-runtime.ts rename to src/main/runtime/agent-session/installation/structured-agent-session-runtime.ts index 82bbf75f484..7046c2b4b7c 100644 --- a/src/main/runtime/agent-session/structured-agent-session-runtime.ts +++ b/src/main/runtime/agent-session/installation/structured-agent-session-runtime.ts @@ -1,33 +1,33 @@ // Install lazily after Electron finalizes the profile path; runtimes without structured requests need no store. Journal-open failures install a refusal. -import { stopPRWatchRuntime, withPRWatchRecovery } from './pr-watch-runtime' -import type { AgentSessionResumeTrigger } from '../../../shared/agent-session/lifecycle/resume/agent-session-resume-marker' +import { stopPRWatchRuntime, withPRWatchRecovery } from '../lifecycle/pr-watch-runtime' +import type { AgentSessionResumeTrigger } from '../../../../shared/agent-session/lifecycle/resume/agent-session-resume-marker' import { structuredAgentSessionTeardownTrigger, tearDownRuntime, type InstalledRuntime } from './structured-agent-session-runtime-teardown' -import type { StructuredAgentSessionHost } from '../../native-chat/agent-session-wire/host/structured-agent-session-host' -import { setStructuredAgentSessionHost } from '../../native-chat/agent-session-wire/host/structured-agent-session-registry' +import type { StructuredAgentSessionHost } from '../../../native-chat/agent-session-wire/host/structured-agent-session-host' +import { setStructuredAgentSessionHost } from '../../../native-chat/agent-session-wire/host/structured-agent-session-registry' import { stopAgentSessionAttachments } from './structured-agent-session-attachment-wiring' import { closeAgentSessionRecordStoreDatabase, openAgentSessionRecordStoreOnce, retireAgentSessionRecordStore -} from './records/agent-session-record-store-slot' -import { agentModelCatalogStore } from '../../native-chat/agent-model-catalog/agent-model-catalog-store' +} from '../records/agent-session-record-store-slot' +import { agentModelCatalogStore } from '../../../native-chat/agent-model-catalog/agent-model-catalog-store' import { neverThrowingStructuredAgentSessionLogger, type StructuredAgentSessionLogger -} from '../../native-chat/agent-session-wire/host/structured-agent-session-logger' -import { migrateLegacyNativeChatVisualsFolders } from '../../native-chat/conversation-files/native-chat-scratch-folder-migration' +} from '../../../native-chat/agent-session-wire/host/structured-agent-session-logger' +import { migrateLegacyNativeChatVisualsFolders } from '../../../native-chat/conversation-files/native-chat-scratch-folder-migration' -import type { StructuredAgentSessionRuntimeDeps } from './installation/structured-agent-session-runtime-contract' +import type { StructuredAgentSessionRuntimeDeps } from './structured-agent-session-runtime-contract' import { ensureStructuredAgentModelCatalogOwner, stopStructuredAgentModelCatalogOwner -} from './model-catalog/structured-agent-model-catalog-wiring' +} from '../model-catalog/structured-agent-model-catalog-wiring' let installing: Promise | null = null let stopping: Promise | null = null @@ -183,6 +183,6 @@ async function install(deps: StructuredAgentSessionRuntimeDeps): Promise & { - closed: boolean - exitVerdict: ClaudeStreamJsonConnection['exitVerdict'] - } - /** The CLI exits on its own: its root is gone, its tree unverifiable. */ - exit: (error: Error) => void - /** The CLI answers initialize now; only meaningful under `initHangs`. */ - answerInit: () => void -} - -export function createScriptedClaudeRuntime(sessionIds: readonly string[]) { - const children: ScriptedClaudeChild[] = [] - const behaviors = new Map() - let releaseStalls = (): void => {} - const stall = new Promise((resolve) => { - releaseStalls = resolve - }) - let root: string | null = null - let host: StructuredAgentSessionHost | null = null - let operations = 0 - - const openConnection: typeof openClaudeStreamJsonConnection = async (launch, handlers = {}) => { - const providerSessionId = String(launch.options.sessionId ?? launch.options.resume) - const sessionId = sessionIds.find( - (candidate) => - claudeSessionIdForOrcaSession( - candidate, - host?.deps.store.getRecord(candidate)?.providerContextBoundary?.operationId - ) === providerSessionId - ) - if (!sessionId) { - throw new Error(`no scripted Claude session for ${providerSessionId}`) - } - const behavior = behaviors.get(sessionId) ?? {} - if (behavior.spawnHangs) { - await stall - } - let failInit = (_error: Error): void => {} - let answerInit = (): void => {} - const answer = (value: T, startup: boolean): Promise => - behavior.stallsControlReads && !startup ? stall.then(() => value) : Promise.resolve(value) - // Untimed unless the behavior sets a deadline; a hang then settles only on the child's exit. - const control = (subtype: string, run: () => Promise): Promise => - runClaudeControl(subtype, run, behavior.controlTimeoutMs ?? null) - const never = (): Promise => new Promise(() => {}) - const optionWrite = (subtype: string): Promise => { - child.calls.push(subtype) - return control(subtype, () => - behavior.optionWritesFail - ? Promise.reject(new Error('Query closed before response received')) - : behavior.optionWritesHang - ? never() - : Promise.resolve() - ) - } - let settingsReads = 0 - const child: ScriptedClaudeChild = { - sessionId, - launch, - calls: [], - initializing: false, - handlers, - exit: (error) => { - child.connection.exitVerdict = { root: 'exited', tree: 'unverifiable' } - failInit(error) - handlers.onExit?.(error) - }, - answerInit: () => answerInit(), - connection: { - pid: 5000 + children.length, - closed: false, - exitVerdict: { root: 'live', tree: 'unverifiable' }, - initializationResult: () => { - child.initializing = true - const initialized = { models: [{ value: 'sonnet', displayName: 'Sonnet' }] } - const announce = (): void => { - if (behavior.sendsNoStartFrame) { - return - } - handlers.onMessage?.({ - type: 'system', - subtype: 'init', - session_id: behavior.initNamesForeignSession ? 'foreign-session' : providerSessionId, - model: 'claude-sonnet-5', - apiKeySource: 'none' - }) - } - if (behavior.initHangs) { - return new Promise((resolve, reject) => { - failInit = reject - answerInit = () => { - announce() - resolve(initialized) - } - }) - } - announce() - return Promise.resolve(initialized) - }, - renameSession: () => Promise.resolve(), - getContextUsage: () => { - child.calls.push('get_context_usage') - return Promise.resolve({}) - }, - getSettings: () => { - child.calls.push('get_settings') - settingsReads += 1 - const startup = settingsReads === 1 - return control('get_settings', () => - behavior.startupSettingsReadHangs && startup - ? never() - : answer({ effective: { effortLevel: 'high' } }, startup) - ) - }, - supportedModels: () => { - child.calls.push('list_models') - return control('list_models', () => - answer( - [ - { value: 'sonnet', displayName: 'Sonnet' }, - { value: 'opus', displayName: 'Opus' } - ], - false - ) - ) - }, - setModel: () => optionWrite('set_model'), - setPermissionMode: () => optionWrite('set_permission_mode'), - applyFlagSettings: () => optionWrite('apply_flag_settings'), - interrupt: async () => undefined, - cancelAsyncMessage: async () => false, - stopTask: async () => {}, - backgroundTask: async () => false, - send: async (_message, beforeDispatch) => { - await beforeDispatch?.() - child.calls.push('send') - }, - close: async () => { - child.connection.closed = true - return !behavior.closeUnproven - } - } - } - children.push(child) - if (behavior.exitsDuringSpawn?.at === 'spawn') { - exitAtSpawn(child, behavior.exitsDuringSpawn.diagnostic) - } - return child.connection - } - const exitAtSpawn = (child: ScriptedClaudeChild, diagnostic: string): void => { - child.connection.closed = true - child.exit(scriptedClaudeExitError(diagnostic)) - } - /** A pid whose process is gone has no start time to read. */ - const readProcessStartTime = async (pid: number): Promise => { - const child = children.find((entry) => entry.connection.pid === pid) - const exits = child ? behaviors.get(child.sessionId)?.exitsDuringSpawn : undefined - if (child && exits?.at === 'start-time-read' && !child.connection.closed) { - exitAtSpawn(child, exits.diagnostic) - return pid * 10 - } - return child?.connection.exitVerdict.root === 'exited' ? null : pid * 10 - } - - return { - behave: (sessionId: string, behavior: ScriptedClaudeBehavior): void => { - behaviors.set(sessionId, behavior) - }, - /** The latest child spawned for `sessionId`. */ - child: (sessionId: string): ScriptedClaudeChild => { - const found = children.findLast((entry) => entry.sessionId === sessionId) - if (!found) { - throw new Error(`no Claude child for ${sessionId}`) - } - return found - }, - children: (sessionId: string): ScriptedClaudeChild[] => - children.filter((entry) => entry.sessionId === sessionId), - install: async (): Promise => { - root ??= await mkdtemp(join(tmpdir(), 'orca-scripted-claude-runtime-')) - await mkdir(join(root, 'claude-home'), { recursive: true }) - const directory = root - host = await ensureStructuredAgentSessionHost({ - logger: createStructuredAgentSessionLogger(), - stateDirectory: directory, - hostId: 'local', - claimKeyId: 'key-1', - resolveWorkspacePath: async () => directory, - resolveClaudeCommand: () => ({ command: '/usr/local/bin/claude', prefixArgs: [] }), - resolveLaunchArgs: () => [], - resolveClaudeAuthPolicy: () => ({ account: 'system' }), - openClaudeConnection: openConnection, - // Production always passes flag support; the scripted CLI is a current Claude Code. - claudeCliFlags: createClaudeCliFlagSupport({ - probe: async () => CURRENT_CLAUDE_CODE_VERSION, - keyOf: async (command, cwd) => `${command}\n${cwd}`, - budgetMs: CLAUDE_CLI_FLAG_PROBE_BUDGET_MS, - now: () => performance.now() - }), - readProcessStartTime - }) - return host - }, - attachParams: ( - sessionId: string, - expectedRuntimeFence: number | null, - overrides: Partial = {} - ) => - hostTestAttachParams(expectedRuntimeFence, { - envelope: { - sessionId, - // The runtime's own clock admits operation ids, so these are minted against it. - clientOperationId: `${Date.now()}-${(++operations).toString(16).padStart(32, '0')}`, - expectedRuntimeFence, - payloadFingerprint: '' - }, - provider: 'claude', - agent: 'claude', - accountHome: { variable: 'CLAUDE_CONFIG_DIR', path: join(root ?? '', 'claude-home') }, - providerHandle: { - kind: 'claude', - sessionId: claudeSessionIdForOrcaSession(sessionId), - leafUuid: null - }, - ...overrides - }), - dispose: async (): Promise => { - releaseStalls() - await stopStructuredAgentSessionRuntime() - if (root) { - await rm(root, { recursive: true, force: true }) - root = null - } - } - } -} diff --git a/src/main/runtime/agent-session/agent-session-launch-directory.test.ts b/src/main/runtime/agent-session/launch/agent-session-launch-directory.test.ts similarity index 86% rename from src/main/runtime/agent-session/agent-session-launch-directory.test.ts rename to src/main/runtime/agent-session/launch/agent-session-launch-directory.test.ts index c0f0f1af3d0..36f506ace02 100644 --- a/src/main/runtime/agent-session/agent-session-launch-directory.test.ts +++ b/src/main/runtime/agent-session/launch/agent-session-launch-directory.test.ts @@ -1,15 +1,15 @@ -import { closeTestJournalHostDatabases } from '../../native-chat/agent-session-journal/store-lifecycle/journal-host-database-test-support' +import { closeTestJournalHostDatabases } from '../../../native-chat/agent-session-journal/store-lifecycle/journal-host-database-test-support' import { mkdir, mkdtemp, rm } from 'node:fs/promises' import type * as NodeFsPromises from 'node:fs/promises' import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import type { AgentSessionExecutionLocation } from '../../../shared/agent-session/lifecycle/agent-session-record' -import { FLOATING_TERMINAL_WORKTREE_ID } from '../../../shared/workspace/identity/floating-workspace-id' +import type { AgentSessionExecutionLocation } from '../../../../shared/agent-session/lifecycle/agent-session-record' +import { FLOATING_TERMINAL_WORKTREE_ID } from '../../../../shared/workspace/identity/floating-workspace-id' import { resolveAgentSessionLaunchDirectory } from './agent-session-launch-directory' -import type { AgentSessionRecordStore } from './records/agent-session-record-store' -import { openTestAgentSessionRecordStore } from './records/agent-session-record-store-test-harness' -import type { AgentSessionReserveRequest } from './ownership/agent-session-reservation-admission' +import type { AgentSessionRecordStore } from '../records/agent-session-record-store' +import { openTestAgentSessionRecordStore } from '../records/agent-session-record-store-test-harness' +import type { AgentSessionReserveRequest } from '../ownership/agent-session-reservation-admission' const statFault = vi.hoisted(() => { const fault: { error: Error | null } = { error: null } diff --git a/src/main/runtime/agent-session/agent-session-launch-directory.ts b/src/main/runtime/agent-session/launch/agent-session-launch-directory.ts similarity index 76% rename from src/main/runtime/agent-session/agent-session-launch-directory.ts rename to src/main/runtime/agent-session/launch/agent-session-launch-directory.ts index 83778d0b244..0f08bb94696 100644 --- a/src/main/runtime/agent-session/agent-session-launch-directory.ts +++ b/src/main/runtime/agent-session/launch/agent-session-launch-directory.ts @@ -1,10 +1,10 @@ import { stat } from 'node:fs/promises' -import type { AgentSessionRecord } from '../../../shared/agent-session/lifecycle/agent-session-record' -import { isDefinitiveAbsence } from '../../../shared/errors/definitive-filesystem-absence' -import { AgentSessionPreSpawnError } from '../../native-chat/agent-session-wire/providers/structured-agent-session-adapter-errors' -import type { AgentSessionRecordStore } from './records/agent-session-record-store' -import { agentSessionPinnedLaunchDirectory } from './records/agent-session-record-launch-directory' -import { isFloatingWorkspaceId } from '../../../shared/workspace/identity/floating-workspace-worktree' +import type { AgentSessionRecord } from '../../../../shared/agent-session/lifecycle/agent-session-record' +import { isDefinitiveAbsence } from '../../../../shared/errors/definitive-filesystem-absence' +import { AgentSessionPreSpawnError } from '../../../native-chat/agent-session-wire/providers/structured-agent-session-adapter-errors' +import type { AgentSessionRecordStore } from '../records/agent-session-record-store' +import { agentSessionPinnedLaunchDirectory } from '../records/agent-session-record-launch-directory' +import { isFloatingWorkspaceId } from '../../../../shared/workspace/identity/floating-workspace-worktree' /** Resuming a missing floating launch directory elsewhere would change the conversation. */ export function agentSessionLaunchFolderMissing( diff --git a/src/main/runtime/agent-session/launch/structured-agent-launch-composition.ts b/src/main/runtime/agent-session/launch/structured-agent-launch-composition.ts index 2a93d9098ae..e3b412bcf65 100644 --- a/src/main/runtime/agent-session/launch/structured-agent-launch-composition.ts +++ b/src/main/runtime/agent-session/launch/structured-agent-launch-composition.ts @@ -12,7 +12,7 @@ import { type NativeChatVisualsLaunch, type PrepareNativeChatVisuals } from '../../../native-chat/conversation-files/native-chat-visuals-delivery' -import { resolveAgentSessionLaunchDirectory } from '../agent-session-launch-directory' +import { resolveAgentSessionLaunchDirectory } from './agent-session-launch-directory' import type { AgentSessionRecordStore } from '../records/agent-session-record-store' import type { StructuredAgentAdapterContext } from '../installation/structured-agent-runtime-registration-types' import { diff --git a/src/main/runtime/agent-session/lifecycle/claude-structured-exit-mid-response.test.ts b/src/main/runtime/agent-session/lifecycle/claude-structured-exit-mid-response.test.ts deleted file mode 100644 index 55b134f8b89..00000000000 --- a/src/main/runtime/agent-session/lifecycle/claude-structured-exit-mid-response.test.ts +++ /dev/null @@ -1,71 +0,0 @@ -import { readTestHostJournal } from '../../../native-chat/agent-session-journal/journal-observation.test-support' -// Script only the CLI; verify self-exit attribution through the production runtime/adapter/store/host. - -import { afterEach, describe, expect, it, vi } from 'vitest' -import { computeAgentSessionPayloadFingerprint } from '../../../../shared/agent-session/lifecycle/operations/agent-session-mutation-envelope' -import { hostTestMessage } from '../../../native-chat/agent-session-wire/host/testing/structured-agent-session-host-test-data.test-fixture' -import type { StructuredAgentSessionHost } from '../../../native-chat/agent-session-wire/host/structured-agent-session-host' -import { waitForStructuredAgentSessionRecovery } from '../structured-agent-session-runtime' -import { - createScriptedClaudeRuntime, - scriptedClaudeExitError -} from '../installation/structured-claude-scripted-runtime-test-support' - -const SESSION = 'claude-exit-mid-response' -const CALLER = { callerKey: 'client-1' } - -let claude = createScriptedClaudeRuntime([SESSION]) -let operations = 0 - -afterEach(async () => { - vi.restoreAllMocks() - await claude.dispose() - claude = createScriptedClaudeRuntime([SESSION]) -}) - -async function send(host: StructuredAgentSessionHost, text: string): Promise { - const body = hostTestMessage(text) - const sent = await host.send(CALLER, { - envelope: { - sessionId: SESSION, - clientOperationId: `${Date.now()}-${(++operations).toString(16).padStart(32, '0')}`, - expectedRuntimeFence: host.deps.store.getRecord(SESSION)?.lease.runtimeFence ?? 0, - payloadFingerprint: computeAgentSessionPayloadFingerprint({ - method: 'agentSession.send', - sessionId: SESSION, - fields: { body } - }) - }, - body - }) - expect(sent, JSON.stringify(sent)).toMatchObject({ ok: true }) -} - -describe('a started Claude CLI that exits while a response is in progress', () => { - it('says Claude stopped, and that the conversation can continue', async () => { - const host = await claude.install() - await expect(host.attach(CALLER, claude.attachParams(SESSION, null))).resolves.toMatchObject({ - ok: true - }) - await send(host, 'hello') - await vi.waitFor(() => expect(claude.child(SESSION).calls).toContain('send')) - - claude.child(SESSION).exit(scriptedClaudeExitError('claude stream-json exited (code 137)')) - await waitForStructuredAgentSessionRecovery() - - await vi.waitFor(async () => - expect( - (await readTestHostJournal(host, SESSION)).items.flatMap((item) => - item.body.kind === 'status' && item.body.failure - ? [{ text: item.body.text, kind: item.body.failure.kind }] - : [] - ) - ).toEqual([ - { - text: 'Claude stopped while this response was in progress. You can continue in this conversation.', - kind: 'providerExited' - } - ]) - ) - }) -}) diff --git a/src/main/runtime/agent-session/lifecycle/claude-structured-failed-start-resume.test.ts b/src/main/runtime/agent-session/lifecycle/claude-structured-failed-start-resume.test.ts deleted file mode 100644 index d479a394271..00000000000 --- a/src/main/runtime/agent-session/lifecycle/claude-structured-failed-start-resume.test.ts +++ /dev/null @@ -1,74 +0,0 @@ -// Unproven first starts have no transcript: retry the same provider id fresh until a start proves its root. - -import { afterEach, describe, expect, it, vi } from 'vitest' -import { claudeSessionIdForOrcaSession } from '../../../claude/structured/claude-structured-session-id' -import { waitForStructuredAgentSessionRecovery } from '../structured-agent-session-runtime' -import { createScriptedClaudeRuntime } from '../installation/structured-claude-scripted-runtime-test-support' - -const SESSION = 'claude-failed-start' -const CALLER = { callerKey: 'client-1' } - -let claude = createScriptedClaudeRuntime([SESSION]) - -afterEach(async () => { - await claude.dispose() - claude = createScriptedClaudeRuntime([SESSION]) -}) - -describe('a Claude chat whose first start died before initialize', () => { - it('resumes on reopen, launching its id fresh and continuing the same chain', async () => { - claude.behave(SESSION, { initHangs: true }) - const host = await claude.install() - await expect(host.attach(CALLER, claude.attachParams(SESSION, null))).resolves.toMatchObject({ - ok: true - }) - await vi.waitFor(() => expect(claude.child(SESSION).initializing).toBe(true)) - claude.child(SESSION).exit(new Error('claude stream-json exited (code 1): not signed in')) - await waitForStructuredAgentSessionRecovery() - const failed = host.deps.store.getRecord(SESSION) - expect(failed?.lease.claimStatus).toBe('released') - - claude.behave(SESSION, {}) - const reopened = await host.attach( - CALLER, - claude.attachParams(SESSION, failed?.lease.runtimeFence ?? null) - ) - - expect(reopened, JSON.stringify(reopened)).toMatchObject({ ok: true }) - await vi.waitFor(() => - expect(host.collaboratorsForTests().sessions.get(SESSION)?.child?.phase).toBe('ready') - ) - const providerSessionId = claudeSessionIdForOrcaSession(SESSION) - // No transcript exists to resume. - expect(claude.child(SESSION).launch.options).toMatchObject({ sessionId: providerSessionId }) - expect(claude.child(SESSION).launch.options.resume).toBeUndefined() - expect( - host.deps.store.getRecord(SESSION)?.providerHandleChain.map((link) => link.origin) - ).toEqual(['created']) - await vi.waitFor(() => - expect(host.deps.store.getRecord(SESSION)?.lease.claimStatus).toBe('live') - ) - }) -}) - -describe('a Claude chat whose CLI exits the moment it is spawned', () => { - // Exit may race spawn or start-time read; both must preserve the CLI verdict. - it.each(['spawn', 'start-time-read'] as const)( - "refuses the create in a sentence, not the CLI's diagnostic, when it exits at %s", - async (at) => { - const diagnostic = 'claude stream-json exited (code 1): claude: not signed in' - claude.behave(SESSION, { exitsDuringSpawn: { diagnostic, at } }) - const host = await claude.install() - - const created = await host.attach(CALLER, claude.attachParams(SESSION, null)) - - expect(created).toMatchObject({ - ok: false, - refusal: { - message: 'Claude stopped before it finished starting. Send your message to try again.', - ownerVerdict: 'exited' - } - }) - } - ) -}) diff --git a/src/main/runtime/agent-session/lifecycle/claude-structured-resumed-start-failure.test.ts b/src/main/runtime/agent-session/lifecycle/claude-structured-resumed-start-failure.test.ts deleted file mode 100644 index b2717108a61..00000000000 --- a/src/main/runtime/agent-session/lifecycle/claude-structured-resumed-start-failure.test.ts +++ /dev/null @@ -1,90 +0,0 @@ -import { readTestHostJournal } from '../../../native-chat/agent-session-journal/journal-observation.test-support' -// Reopened chats publish before initialize; later startup failure must reach the visible transcript. - -import { afterEach, describe, expect, it, vi } from 'vitest' -import { computeAgentSessionPayloadFingerprint } from '../../../../shared/agent-session/lifecycle/operations/agent-session-mutation-envelope' -import type { AgentSessionSubscribeEvent } from '../../../../shared/agent-session/agent-session-wire' -import { hostTestMessage } from '../../../native-chat/agent-session-wire/host/testing/structured-agent-session-host-test-data.test-fixture' -import { waitForStructuredAgentSessionRecovery } from '../structured-agent-session-runtime' -import { - createScriptedClaudeRuntime, - scriptedClaudeExitError -} from '../installation/structured-claude-scripted-runtime-test-support' - -const SESSION = 'claude-resumed-start' -const CALLER = { callerKey: 'client-1' } -const DIAGNOSTIC = 'claude stream-json exited (code 1): claude: not signed in' -const STARTUP_TEXT = 'Claude stopped before it finished starting. Send your message to try again.' - -let claude = createScriptedClaudeRuntime([SESSION]) - -afterEach(async () => { - await claude.dispose() - claude = createScriptedClaudeRuntime([SESSION]) -}) - -function statusTexts(events: AgentSessionSubscribeEvent[]): string[] { - return events.flatMap((event) => { - const items = - event.type === 'batch' ? event.batch.items : event.type === 'snapshot' ? event.page.items : [] - return items.flatMap((item) => (item.body.kind === 'status' ? [item.body.text] : [])) - }) -} - -describe('a reopened Claude chat whose CLI dies before initialize', () => { - it('publishes the startup failure, with the diagnostic, to the open chat', async () => { - const host = await claude.install() - await expect(host.attach(CALLER, claude.attachParams(SESSION, null))).resolves.toMatchObject({ - ok: true - }) - await waitForStructuredAgentSessionRecovery() - await host.close(SESSION, 'evict') - - // Opening starts nothing; the send retries children whose root exits are observed, - // even when descendant cleanup cannot be confirmed. - claude.behave(SESSION, { initHangs: true, closeUnproven: true }) - const events: AgentSessionSubscribeEvent[] = [] - await host.subscribe({ id: 'sub-1', sessionId: SESSION, emit: (event) => events.push(event) }) - const body = hostTestMessage('hello') - const fence = host.deps.store.getRecord(SESSION)?.lease.runtimeFence ?? 0 - const sent = await host.send(CALLER, { - envelope: { - sessionId: SESSION, - clientOperationId: `${Date.now()}-${'f'.repeat(32)}`, - expectedRuntimeFence: fence, - payloadFingerprint: computeAgentSessionPayloadFingerprint({ - method: 'agentSession.send', - sessionId: SESSION, - fields: { body } - }) - }, - body - }) - expect(sent).toMatchObject({ ok: true, value: { submission: { dispatchState: 'pending' } } }) - await vi.waitFor(() => expect(claude.children(SESSION)).toHaveLength(2)) - - for (let count = 2; count <= 6; count++) { - await vi.waitFor(() => expect(claude.children(SESSION)).toHaveLength(count), { - timeout: 10_000 - }) - await vi.waitFor(() => expect(claude.child(SESSION).initializing).toBe(true)) - expect(statusTexts(events)).not.toContain(STARTUP_TEXT) - claude.child(SESSION).exit(scriptedClaudeExitError(DIAGNOSTIC)) - await waitForStructuredAgentSessionRecovery() - await vi.waitFor(() => - expect(host.deps.store.getRecord(SESSION)?.lease.claimStatus).toBe('released') - ) - } - - await vi.waitFor(() => expect(statusTexts(events)).toContainEqual(STARTUP_TEXT)) - const submission = (await readTestHostJournal(host, SESSION)).submissions.find( - (entry) => entry.clientMessageId === (sent.ok && sent.value.clientMessageId) - ) - // Keep stderr in log details, outside the user-facing sentence. - expect(submission).toMatchObject({ - dispatchState: 'rejected', - reason: STARTUP_TEXT, - rejection: { kind: 'providerStartFailed', detail: { text: DIAGNOSTIC, audience: 'log' } } - }) - }) -}) diff --git a/src/main/runtime/agent-session/lifecycle/claude-structured-startup-fault-is-not-an-exit.test.ts b/src/main/runtime/agent-session/lifecycle/claude-structured-startup-fault-is-not-an-exit.test.ts deleted file mode 100644 index 6ee5a9262e0..00000000000 --- a/src/main/runtime/agent-session/lifecycle/claude-structured-startup-fault-is-not-an-exit.test.ts +++ /dev/null @@ -1,123 +0,0 @@ -import { readTestHostJournal } from '../../../native-chat/agent-session-journal/journal-observation.test-support' -// Host-detected startup faults must not be attributed as self-exits without observed CLI exit. - -import { afterEach, describe, expect, it, vi } from 'vitest' -import { computeAgentSessionPayloadFingerprint } from '../../../../shared/agent-session/lifecycle/operations/agent-session-mutation-envelope' -import { hostTestMessage } from '../../../native-chat/agent-session-wire/host/testing/structured-agent-session-host-test-data.test-fixture' -import type { StructuredAgentSessionHost } from '../../../native-chat/agent-session-wire/host/structured-agent-session-host' -import { waitForStructuredAgentSessionRecovery } from '../structured-agent-session-runtime' -import { - createScriptedClaudeRuntime, - scriptedClaudeExitError -} from '../installation/structured-claude-scripted-runtime-test-support' - -const SESSION = 'claude-startup-fault' -const CALLER = { callerKey: 'client-1' } -const DIAGNOSTIC = 'claude stream-json exited (code 1): claude: not signed in (rig)' -const STOPPED_TEXT = 'Claude stopped before it finished starting. Send your message to try again.' - -let claude = createScriptedClaudeRuntime([SESSION]) -let operations = 0 - -afterEach(async () => { - vi.restoreAllMocks() - await claude.dispose() - claude = createScriptedClaudeRuntime([SESSION]) -}) - -function fence(host: StructuredAgentSessionHost): number { - return host.deps.store.getRecord(SESSION)?.lease.runtimeFence ?? 0 -} - -async function send(host: StructuredAgentSessionHost, text: string): Promise { - const body = hostTestMessage(text) - const sent = await host.send(CALLER, { - envelope: { - sessionId: SESSION, - clientOperationId: `${Date.now()}-${(++operations).toString(16).padStart(32, '0')}`, - expectedRuntimeFence: fence(host), - payloadFingerprint: computeAgentSessionPayloadFingerprint({ - method: 'agentSession.send', - sessionId: SESSION, - fields: { body } - }) - }, - body - }) - expect(sent, JSON.stringify(sent)).toMatchObject({ - ok: true, - value: { submission: { dispatchState: 'pending' } } - }) - return sent.ok ? sent.value.clientMessageId : '' -} - -async function failureRows(host: StructuredAgentSessionHost) { - return (await readTestHostJournal(host, SESSION)).items.flatMap((item) => - item.body.kind === 'status' && item.body.failure - ? [{ text: item.body.text, kind: item.body.failure.kind }] - : [] - ) -} - -async function submission(host: StructuredAgentSessionHost, clientMessageId: string) { - return (await readTestHostJournal(host, SESSION)).submissions.find( - (entry) => entry.clientMessageId === clientMessageId - ) -} - -async function released(host: StructuredAgentSessionHost): Promise { - await waitForStructuredAgentSessionRecovery() - await vi.waitFor(() => - expect(host.deps.store.getRecord(SESSION)?.lease.claimStatus).toBe('released') - ) -} - -describe('a Claude start that Orca fails while the CLI is still running', () => { - it('rejects a message held for it as a start that could not happen when init names another session', async () => { - claude.behave(SESSION, { initHangs: true, initNamesForeignSession: true }) - const host = await claude.install() - await expect(host.attach(CALLER, claude.attachParams(SESSION, null))).resolves.toMatchObject({ - ok: true - }) - const held = await send(host, 'hello') - await vi.waitFor(() => expect(claude.child(SESSION).initializing).toBe(true)) - expect(await submission(host, held)).toMatchObject({ dispatchState: 'pending' }) - expect(claude.child(SESSION).calls).not.toContain('send') - - claude.child(SESSION).answerInit() - await released(host) - - await vi.waitFor(async () => - expect(await submission(host, held)).toMatchObject({ - dispatchState: 'rejected', - reason: expect.stringMatching(/^Claude couldn't start\./), - rejection: { kind: 'startFailed' } - }) - ) - expect(await failureRows(host)).toEqual([ - { text: expect.stringMatching(/^Claude couldn't start\./), kind: 'startFailed' } - ]) - expect(claude.child(SESSION).calls).not.toContain('send') - }) - - it('still says Claude stopped when the CLI exits on its own before its start lands', async () => { - claude.behave(SESSION, { initHangs: true }) - const host = await claude.install() - await expect(host.attach(CALLER, claude.attachParams(SESSION, null))).resolves.toMatchObject({ - ok: true - }) - const held = await send(host, 'hello') - - claude.child(SESSION).exit(scriptedClaudeExitError(DIAGNOSTIC)) - await released(host) - - await vi.waitFor(async () => - expect(await submission(host, held)).toMatchObject({ - dispatchState: 'rejected', - reason: STOPPED_TEXT, - rejection: { kind: 'providerStartFailed' } - }) - ) - expect(await failureRows(host)).toEqual([{ text: STOPPED_TEXT, kind: 'providerStartFailed' }]) - }) -}) diff --git a/src/main/runtime/agent-session/pr-watch-runtime.ts b/src/main/runtime/agent-session/lifecycle/pr-watch-runtime.ts similarity index 82% rename from src/main/runtime/agent-session/pr-watch-runtime.ts rename to src/main/runtime/agent-session/lifecycle/pr-watch-runtime.ts index ef9ca48a1ed..cbfd6e53f8c 100644 --- a/src/main/runtime/agent-session/pr-watch-runtime.ts +++ b/src/main/runtime/agent-session/lifecycle/pr-watch-runtime.ts @@ -1,15 +1,15 @@ -import { prWatchStorage } from '../../github/pr-watch/pr-watch-storage' +import { prWatchStorage } from '../../../github/pr-watch/pr-watch-storage' // Owns the host's CI-line watches apart from the chat host: they start once startup settles, so a // PR is watched whether or not any chat was opened. -import { PRWatchService } from '../../github/pr-watch/pr-watch-service' -import type { PRWatchWorkspace } from '../../github/pr-watch/pr-watch-types' -import type { JournalWriterCommit } from '../../native-chat/agent-session-journal/journal-writer-changes' -import type { AgentSessionJournal } from '../../native-chat/agent-session-journal/journal-store' -import type { StructuredAgentSessionLogger } from '../../native-chat/agent-session-wire/host/structured-agent-session-logger' -import { getStructuredAgentSessionHost } from '../../native-chat/agent-session-wire/host/structured-agent-session-registry' -import { openAgentSessionRecordStoreOnce } from './records/agent-session-record-store-slot' -import { isHostShuttingDown } from '../../startup/quit/host-shutdown-state' +import { PRWatchService } from '../../../github/pr-watch/pr-watch-service' +import type { PRWatchWorkspace } from '../../../github/pr-watch/pr-watch-types' +import type { JournalWriterCommit } from '../../../native-chat/agent-session-journal/journal-writer-changes' +import type { AgentSessionJournal } from '../../../native-chat/agent-session-journal/journal-store' +import type { StructuredAgentSessionLogger } from '../../../native-chat/agent-session-wire/host/structured-agent-session-logger' +import { getStructuredAgentSessionHost } from '../../../native-chat/agent-session-wire/host/structured-agent-session-registry' +import { openAgentSessionRecordStoreOnce } from '../records/agent-session-record-store-slot' +import { isHostShuttingDown } from '../../../startup/quit/host-shutdown-state' export type PRWatchRuntimeDeps = { stateDirectory: string diff --git a/src/main/runtime/agent-session/pr-watch-workspace-sources.ts b/src/main/runtime/agent-session/lifecycle/pr-watch-workspace-sources.ts similarity index 73% rename from src/main/runtime/agent-session/pr-watch-workspace-sources.ts rename to src/main/runtime/agent-session/lifecycle/pr-watch-workspace-sources.ts index 68cb91c1172..8b523856a5f 100644 --- a/src/main/runtime/agent-session/pr-watch-workspace-sources.ts +++ b/src/main/runtime/agent-session/lifecycle/pr-watch-workspace-sources.ts @@ -1,9 +1,9 @@ -import type { ExecutionHostId } from '../../../shared/execution-host/execution-host' -import type { Repo } from '../../../shared/repository/repo-types' -import type { PRWatchWorkspace } from '../../github/pr-watch/pr-watch-types' -import { hostedReviewSshConnectionId } from '../../source-control/hosted-review-execution-host' -import type { ProjectRuntimeResolutionStore } from '../../workspaces/execution-host/local-project-runtime-resolution' -import { getLocalProjectWorktreeGitOptions } from '../../workspaces/execution-host/project-runtime-git-options' +import type { ExecutionHostId } from '../../../../shared/execution-host/execution-host' +import type { Repo } from '../../../../shared/repository/repo-types' +import type { PRWatchWorkspace } from '../../../github/pr-watch/pr-watch-types' +import { hostedReviewSshConnectionId } from '../../../source-control/hosted-review-execution-host' +import type { ProjectRuntimeResolutionStore } from '../../../workspaces/execution-host/local-project-runtime-resolution' +import { getLocalProjectWorktreeGitOptions } from '../../../workspaces/execution-host/project-runtime-git-options' import type { PRWatchRuntimeDeps } from './pr-watch-runtime' type WorkspaceSourcesRuntime = { diff --git a/src/main/runtime/agent-session/structured-agent-session-close.ts b/src/main/runtime/agent-session/lifecycle/structured-agent-session-close.ts similarity index 90% rename from src/main/runtime/agent-session/structured-agent-session-close.ts rename to src/main/runtime/agent-session/lifecycle/structured-agent-session-close.ts index 9018e9ff464..c8b76d30075 100644 --- a/src/main/runtime/agent-session/structured-agent-session-close.ts +++ b/src/main/runtime/agent-session/lifecycle/structured-agent-session-close.ts @@ -1,12 +1,12 @@ -import type { StructuredAgentSessionCloseWork } from '../../native-chat/agent-session-wire/termination/structured-agent-session-close-work' -import type { StructuredAgentSessionHost } from '../../native-chat/agent-session-wire/host/structured-agent-session-host' -import { getStructuredAgentSessionHost } from '../../native-chat/agent-session-wire/host/structured-agent-session-registry' -import type { OrcaRuntimeService } from '../orca-runtime' -import type { StructuredAgentSessionCloseCause } from '../../native-chat/agent-session-wire/termination/structured-agent-session-host-lifetime' +import type { StructuredAgentSessionCloseWork } from '../../../native-chat/agent-session-wire/termination/structured-agent-session-close-work' +import type { StructuredAgentSessionHost } from '../../../native-chat/agent-session-wire/host/structured-agent-session-host' +import { getStructuredAgentSessionHost } from '../../../native-chat/agent-session-wire/host/structured-agent-session-registry' +import type { OrcaRuntimeService } from '../../orca-runtime' +import type { StructuredAgentSessionCloseCause } from '../../../native-chat/agent-session-wire/termination/structured-agent-session-host-lifetime' import { observeStructuredSession, structuredSessionCloseSettled -} from '../orchestration/terminal-authority/structured-sessions/structured-worker-authority' +} from '../../orchestration/terminal-authority/structured-sessions/structured-worker-authority' export type StructuredAgentSessionCloseOutcome = { stopped: boolean diff --git a/src/main/runtime/agent-session/structured-agent-session-dispatch-followups.ts b/src/main/runtime/agent-session/lifecycle/structured-agent-session-dispatch-followups.ts similarity index 79% rename from src/main/runtime/agent-session/structured-agent-session-dispatch-followups.ts rename to src/main/runtime/agent-session/lifecycle/structured-agent-session-dispatch-followups.ts index 6aecdf97e29..ce79331a67f 100644 --- a/src/main/runtime/agent-session/structured-agent-session-dispatch-followups.ts +++ b/src/main/runtime/agent-session/lifecycle/structured-agent-session-dispatch-followups.ts @@ -1,5 +1,5 @@ -import type { StructuredAgentSessionHost } from '../../native-chat/agent-session-wire/host/structured-agent-session-host' -import type { StructuredAgentSessionLogger } from '../../native-chat/agent-session-wire/host/structured-agent-session-logger' +import type { StructuredAgentSessionHost } from '../../../native-chat/agent-session-wire/host/structured-agent-session-host' +import type { StructuredAgentSessionLogger } from '../../../native-chat/agent-session-wire/host/structured-agent-session-logger' // Late dispatch settlements run outside their request, so report failures through the logger. type DispatchFollowUpHost = Pick diff --git a/src/main/runtime/agent-session/structured-agent-session-lifecycle-delivery.ts b/src/main/runtime/agent-session/lifecycle/structured-agent-session-lifecycle-delivery.ts similarity index 91% rename from src/main/runtime/agent-session/structured-agent-session-lifecycle-delivery.ts rename to src/main/runtime/agent-session/lifecycle/structured-agent-session-lifecycle-delivery.ts index 68da3e44465..c200cd8f811 100644 --- a/src/main/runtime/agent-session/structured-agent-session-lifecycle-delivery.ts +++ b/src/main/runtime/agent-session/lifecycle/structured-agent-session-lifecycle-delivery.ts @@ -1,8 +1,8 @@ // Track exit recovery through teardown so callbacks cannot write after journal removal. // Starts, option drops and requested-close ends use their own session lane to avoid waiting on another session's reacquisition. -import type { StructuredAgentSessionLifecycleEvent } from '../../native-chat/agent-session-wire/providers/structured-agent-session-adapter' -import type { StructuredAgentSessionLogger } from '../../native-chat/agent-session-wire/host/structured-agent-session-logger' +import type { StructuredAgentSessionLifecycleEvent } from '../../../native-chat/agent-session-wire/providers/structured-agent-session-adapter' +import type { StructuredAgentSessionLogger } from '../../../native-chat/agent-session-wire/host/structured-agent-session-logger' export function createStructuredAgentSessionLifecycleDelivery(input: { handle: (event: StructuredAgentSessionLifecycleEvent) => Promise | undefined diff --git a/src/main/runtime/agent-session/structured-agent-session-mobile-attention.ts b/src/main/runtime/agent-session/lifecycle/structured-agent-session-mobile-attention.ts similarity index 80% rename from src/main/runtime/agent-session/structured-agent-session-mobile-attention.ts rename to src/main/runtime/agent-session/lifecycle/structured-agent-session-mobile-attention.ts index 5fe1be52174..d880d0ca8af 100644 --- a/src/main/runtime/agent-session/structured-agent-session-mobile-attention.ts +++ b/src/main/runtime/agent-session/lifecycle/structured-agent-session-mobile-attention.ts @@ -1,31 +1,31 @@ // Push phone attention from the execution host so headless sessions need no desktop relay. Desktop retains presentation and marks local delivery to avoid duplicate pushes. // Read labels synchronously at the raising commit so alerts cannot outlive prompts; edge ids dedupe delivery and address retirement. -import type { AgentSessionStatusSummary } from '../../../shared/agent-session/agent-session-wire' +import type { AgentSessionStatusSummary } from '../../../../shared/agent-session/agent-session-wire' import { agentSessionAttentionKey, agentSessionAttentionNews, structuredAttentionOrigin, type StructuredAttentionState, type AgentSessionAttentionEdge -} from '../../../shared/agent-session/view/agent-session-attention' -import type { AgentSessionExecutionLocation } from '../../../shared/agent-session/lifecycle/agent-session-record' -import type { AgentStatusOrchestrationContext } from '../../../shared/agent-status/contracts/agent-status-types' -import { isCoordinatorOnlyChatNews } from '../../../shared/orchestration/workers/dispatched-worker-attention' +} from '../../../../shared/agent-session/view/agent-session-attention' +import type { AgentSessionExecutionLocation } from '../../../../shared/agent-session/lifecycle/agent-session-record' +import type { AgentStatusOrchestrationContext } from '../../../../shared/agent-status/contracts/agent-status-types' +import { isCoordinatorOnlyChatNews } from '../../../../shared/orchestration/workers/dispatched-worker-attention' import type { NotificationDispatchRequest, NotificationSettings -} from '../../../shared/notifications/notification-settings-types' +} from '../../../../shared/notifications/notification-settings-types' import { structuredAgentSessionPaneKey, structuredAgentSessionTabId -} from '../../../shared/agent-session/view/structured-agent-session-projection' -import { getRepoIdFromWorktreeId } from '../../../shared/worktree/id' -import { isNotificationSourceEnabled } from '../../../shared/notifications/notification-source-gate' -import { parseWorkspaceKey } from '../../../shared/workspace/identity/workspace-scope' -import { buildNotificationOptions } from '../../ipc/notification-options' -import type { MobileNotificationDispatchEvent } from '../push/notifications/runtime-mobile-notification-controller' -import type { RuntimeStore } from '../construction/runtime-store-contract' -import { getRuntimeDesktopSurface } from '../construction/runtime-desktop-surface' +} from '../../../../shared/agent-session/view/structured-agent-session-projection' +import { getRepoIdFromWorktreeId } from '../../../../shared/worktree/id' +import { isNotificationSourceEnabled } from '../../../../shared/notifications/notification-source-gate' +import { parseWorkspaceKey } from '../../../../shared/workspace/identity/workspace-scope' +import { buildNotificationOptions } from '../../../ipc/notification-options' +import type { MobileNotificationDispatchEvent } from '../../push/notifications/runtime-mobile-notification-controller' +import type { RuntimeStore } from '../../construction/runtime-store-contract' +import { getRuntimeDesktopSurface } from '../../construction/runtime-desktop-surface' export type StructuredAttentionWorkspaceLabels = { repoLabel?: string; worktreeLabel?: string } diff --git a/src/main/runtime/agent-session/lifecycle/structured-agent-session-tab-authority.test-support.ts b/src/main/runtime/agent-session/lifecycle/structured-agent-session-tab-authority.test-support.ts index 234b101b80d..b8741baa8d6 100644 --- a/src/main/runtime/agent-session/lifecycle/structured-agent-session-tab-authority.test-support.ts +++ b/src/main/runtime/agent-session/lifecycle/structured-agent-session-tab-authority.test-support.ts @@ -29,10 +29,10 @@ import { openTestAgentSessionRecordStoreSlot } from '../records/agent-session-re import { seedTestAgentSessionRecordStore } from '../records/agent-session-record-store-persistence.test-fixture' import { createStructuredAgentSessionLogger } from '../../../native-chat/agent-session-wire/host/structured-agent-session-logger' import { OrcaRuntimeService } from '../../orca-runtime' -import { withChatTabChanges } from '../agent-session-tab-layout' +import { withChatTabChanges } from '../../session-tabs/chat/agent-session-tab-layout' import { collectSavedStructuredAgentSessionIds } from './saved-structured-agent-session-restoration' import { chatTabCommandsSettled } from '../../orca-runtime-tests/session-layout-apply.test-fixture' -import { stopStructuredAgentSessionRuntime } from '../structured-agent-session-runtime' +import { stopStructuredAgentSessionRuntime } from '../installation/structured-agent-session-runtime' export const B = 'chat-b-0002', C = 'chat-c-0003', diff --git a/src/main/runtime/agent-session/lifecycle/structured-codex-child-work-runtime.test.ts b/src/main/runtime/agent-session/lifecycle/structured-codex-child-work-runtime.test.ts deleted file mode 100644 index 9ad58a1c57a..00000000000 --- a/src/main/runtime/agent-session/lifecycle/structured-codex-child-work-runtime.test.ts +++ /dev/null @@ -1,153 +0,0 @@ -// The production runtime hands a Codex session's child work to the status sink, under the address -// the session's own row landed under, and ends it with the provider. - -import 'node:fs/promises' -import 'node:os' -import 'node:path' -import { afterEach, describe, expect, it, vi } from 'vitest' - -import { - HOST_TEST_SESSION as SESSION, - hostTestAttachParams -} from '../../../native-chat/agent-session-wire/host/testing/structured-agent-session-host-test-data.test-fixture' -import type { StructuredAgentSessionStatusSink } from '../../../native-chat/agent-session-wire/observations/structured-agent-session-status-ownership' -import { stopStructuredAgentSessionRuntime } from '../structured-agent-session-runtime' -import { ensureTestStructuredAgentSessionHost as ensureStructuredAgentSessionHost } from '../records/agent-session-record-store-test-harness' -import { AgentHookServer } from '../../../agent-hooks/server/agent-hook-server' -import { makeStructuredAgentStatusSubject } from '../../../../shared/agent-status/contracts/agent-status-subject' - -import { AgentSessionRecoveryCapsule } from '../records/agent-session-recovery-capsule' - -import { - openStructuredCodexRpcHarness, - THREAD as RESTART_THREAD, - type StructuredCodexRpcHarness -} from '../../rpc/methods/structured-sessions/structured-codex-session-rpc-test-harness' - -const CHILD = 'thread-runtime-reviewer' - -describe('Codex background-only resume through hook shutdown', () => { - let harness: StructuredCodexRpcHarness | null = null - let server: AgentHookServer | null = null - - afterEach(async () => { - await harness?.dispose() - harness = null - server?.stop() - server = null - }) - - it.each([ - { trigger: 'quit', kind: 'agent', settled: false }, - { trigger: 'update', kind: 'agent', settled: false }, - { trigger: 'quit', kind: 'command', settled: false }, - { trigger: 'update', kind: 'command', settled: false }, - { trigger: 'update', kind: 'command', settled: true } - ] as const)( - '$trigger with a background $kind (settled: $settled)', - async ({ trigger, kind, settled }) => { - const runtime = await openStructuredCodexRpcHarness() - harness = runtime - const store = new AgentHookServer() - server = store - const config = { - ...runtime.hostConfig(), - resolveWorkspacePath: async () => runtime.root, - statusSink: { - publish: (summary, subject) => store.ingestStructuredStatus(summary, subject), - forget: (subject) => store.dropStructuredStatus(subject), - publishChildWork: (subject, evidence, provider) => - store.ingestStructuredChildWork(subject, evidence, provider), - readChildWork: (subject) => store.getStructuredChildWorkViews(subject) - } satisfies StructuredAgentSessionStatusSink - } - const host = await ensureStructuredAgentSessionHost(config) - const params = hostTestAttachParams(null, { - providerHandle: undefined, - location: { - executionHostId: 'local', - wslDistro: null, - workspaceId: 'workspace-1', - workspaceKind: 'folder' - } - }) - params.envelope.clientOperationId = `${Date.now()}-${'1'.padStart(32, '0')}` - expect(await host.attach({ callerKey: 'restart-test' }, params)).toMatchObject({ ok: true }) - await vi.waitFor(() => - expect(host.collaboratorsForTests().sessions.get(SESSION)?.child?.phase).toBe('ready') - ) - const notify = runtime.codex.notify - notify('turn/started', { threadId: RESTART_THREAD, turn: { id: 'lead-turn' } }) - if (kind === 'agent') { - notify('turn/started', { threadId: CHILD, turn: { id: 'child-turn' } }) - notify('item/started', { - threadId: RESTART_THREAD, - turnId: 'lead-turn', - item: { - type: 'subAgentActivity', - id: 'spawn-1', - kind: 'started', - agentThreadId: CHILD, - agentPath: '/root/review' - } - }) - } else { - const command = { - type: 'commandExecution', - id: 'command-1', - command: 'npm run build', - source: 'unifiedExecStartup' - } - notify('item/started', { - threadId: RESTART_THREAD, - turnId: 'lead-turn', - item: { ...command, status: 'inProgress' } - }) - if (settled) { - notify('item/completed', { - threadId: RESTART_THREAD, - turnId: 'lead-turn', - item: { ...command, status: 'completed', exitCode: 0 } - }) - } - } - notify('turn/completed', { - threadId: RESTART_THREAD, - turn: { id: 'lead-turn', status: 'completed' } - }) - await host.flushStreamedEvents(SESSION) - await vi.waitFor(() => - expect(store.getStatusSnapshot().find((entry) => entry.structuredHost)).toMatchObject({ - state: settled ? 'done' : 'working', - mainAgent: { state: 'done' } - }) - ) - // The real quit starts async chat teardown, then synchronously stops hook ingress. - const stopping = stopStructuredAgentSessionRuntime({ trigger }) - store.stop({ keepStatus: true }) - await stopping - expect( - store - .getStructuredChildWorkViews(makeStructuredAgentStatusSubject(params.location, SESSION)) - .filter((child) => child.state !== 'done') - ).toEqual([]) - const activity = { - state: 'done', - prompts: [], - tasks: [{ kind, label: kind === 'agent' ? 'review' : 'npm run build' }] - } - const markers = await new AgentSessionRecoveryCapsule(runtime.root).list(Date.now()) - const restarted = await ensureStructuredAgentSessionHost(config) - const candidates = await restarted.restartResume.list() - if (settled) { - expect(markers).toEqual([]) - expect(candidates).toEqual([]) - } else { - expect(markers).toMatchObject([{ sessionId: SESSION, trigger, activity }]) - expect(candidates).toMatchObject([ - { sessionId: SESSION, agent: 'codex', workspaceKind: 'folder', trigger, activity } - ]) - } - } - ) -}) diff --git a/src/main/runtime/agent-session/naming/structured-agent-session-provider-naming-shutdown.test.ts b/src/main/runtime/agent-session/naming/structured-agent-session-provider-naming-shutdown.test.ts deleted file mode 100644 index 9f2fdc26713..00000000000 --- a/src/main/runtime/agent-session/naming/structured-agent-session-provider-naming-shutdown.test.ts +++ /dev/null @@ -1,168 +0,0 @@ -import type * as ModelCatalogWiring from '../model-catalog/structured-agent-model-catalog-wiring' -import { ChildProcess } from 'node:child_process' -import { mkdtemp, rm } from 'node:fs/promises' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { PassThrough } from 'node:stream' -import { expect, it, vi } from 'vitest' -import { codexProviderHandle } from '../../../../shared/agent-session/lifecycle/provider-handles/agent-session-provider-handle-encoding' -import * as processSpawn from '../../../codex/app-server/codex-app-server-process-tree-kill' -import { closeTestJournalHostDatabase } from '../../../native-chat/agent-session-journal/store-lifecycle/journal-host-database-test-support' -import { agentSessionRecordFixture } from '../../../native-chat/testing/agent-session-record-test-fixture' -import { StructuredAgentSessionAdapterRouter } from '../../../native-chat/agent-session-wire/providers/structured-agent-session-adapter-router' -import { createStructuredAgentSessionLogger } from '../../../native-chat/agent-session-wire/host/structured-agent-session-logger' -import { ensureTestStructuredAgentSessionHost as ensureStructuredAgentSessionHost } from '../records/agent-session-record-store-test-harness' -import { seedTestAgentSessionRecordStore } from '../records/agent-session-record-store-persistence.test-fixture' -import { stopStructuredAgentSessionRuntime } from '../structured-agent-session-runtime' - -vi.mock('../../../provider-process/provider-process-spawn', () => ({ - spawnProviderProcess: (spec: unknown, spawnImpl: (spec: unknown) => unknown) => spawnImpl(spec) -})) - -vi.mock('../model-catalog/structured-agent-model-catalog-wiring', async (importOriginal) => { - const actual = await importOriginal() - return { - ...actual, - ensureStructuredAgentModelCatalogOwner: async ( - ...args: Parameters - ) => ({ - ...(await actual.ensureStructuredAgentModelCatalogOwner(...args)), - modelCatalog: undefined - }) - } -}) - -it('stops naming admission and joins native helper finalization before runtime close', async ({ - onTestFinished -}) => { - const root = await mkdtemp(join(tmpdir(), 'orca-naming-shutdown-')) - const sessionId = 'chat-shutdown-1' - const argumentsReady = Promise.withResolvers() - const stdinEnded = Promise.withResolvers() - const helperExit = Promise.withResolvers() - const order: string[] = [] - const requests: unknown[] = [] - const child = Object.assign(new ChildProcess(), { - stdin: new PassThrough(), - stdout: new PassThrough(), - stderr: new PassThrough() - }) - child.stdin.setEncoding('utf8').on('data', (line: string) => { - const message = JSON.parse(line) - requests.push(message) - if (typeof message.id === 'number') { - child.stdout.write(`${JSON.stringify({ id: message.id, result: {} })}\n`) - } - }) - child.stdin.once('finish', () => { - order.push('helper-stdin-end') - stdinEnded.resolve() - void helperExit.promise.then(() => { - order.push('helper-exit') - child.stdout.end() - child.stderr.end() - child.emit('exit', 0, null) - child.emit('close', 0, null) - }) - }) - const spawn = vi.spyOn(processSpawn, 'spawnCodexAppServerProcess').mockImplementation(() => child) - onTestFinished(async () => { - argumentsReady.resolve([]) - helperExit.resolve() - await stopStructuredAgentSessionRuntime() - await closeTestJournalHostDatabase(root) - vi.restoreAllMocks() - await rm(root, { recursive: true, force: true }) - }) - await seedTestAgentSessionRecordStore(root, { - records: [ - agentSessionRecordFixture({ - sessionId, - provider: 'codex', - accountHome: { variable: 'CODEX_HOME', path: join(root, 'codex-home') }, - providerHandleChain: [ - { - linkId: 'link-1', - handle: codexProviderHandle('thread-1'), - origin: 'created', - mintedAtFence: 1, - observedAt: 0 - } - ], - conversationName: 'Saved name', - conversationNameSource: 'user' - }) - ] - }) - await closeTestJournalHostDatabase(root) - const logger = createStructuredAgentSessionLogger() - const resolveLaunchArgs = vi.fn(() => argumentsReady.promise) - const host = await ensureStructuredAgentSessionHost({ - stateDirectory: root, - hostId: 'local', - claimKeyId: 'key-1', - logger, - resolveWorkspacePath: async () => root, - resolveCodexCommand: () => ({ command: process.execPath, prefixArgs: [] }), - resolveEnvironment: async () => ({}), - resolveLaunchArgs, - resolveClaudeAuthPolicy: () => ({ account: 'managed' }) - }) - expect(host.deps.store.getRecord(sessionId)).toMatchObject({ - sessionId, - provider: 'codex', - conversationName: 'Saved name', - conversationNameSource: 'user' - }) - const adapter = host.deps.adapter - if (!(adapter instanceof StructuredAgentSessionAdapterRouter)) { - throw new Error('expected the installed runtime adapter router') - } - const closeAll = adapter.closeAll.bind(adapter) - const closeAdapters = vi.spyOn(adapter, 'closeAll').mockImplementation(async () => { - order.push('adapter-close') - await closeAll() - }) - const close = host.deps.journalDatabase.close.bind(host.deps.journalDatabase) - const closeDatabase = vi.spyOn(host.deps.journalDatabase, 'close').mockImplementation(() => { - order.push('database-close') - return close() - }) - const stopDelivery = vi.spyOn(host, 'stopDelivery') - host.deps.nameProviderConversation?.(host.deps.store.requireWritableRecord(sessionId)) - await vi.waitFor(() => expect(resolveLaunchArgs).toHaveBeenCalledOnce()) - let stopped = false - const stopping = stopStructuredAgentSessionRuntime().then(() => { - stopped = true - }) - await vi.waitFor(() => expect(stopDelivery).toHaveBeenCalledOnce()) - // A retained callback must neither admit a new push nor coalesce another pass. - host.deps.nameProviderConversation?.(host.deps.store.requireWritableRecord(sessionId)) - expect(stopped).toBe(false) - expect(closeAdapters).not.toHaveBeenCalled() - expect(closeDatabase).not.toHaveBeenCalled() - expect(spawn).not.toHaveBeenCalled() - - argumentsReady.resolve([]) - await stdinEnded.promise - expect(requests).toEqual([ - { - id: 1, - method: 'initialize', - params: { clientInfo: { name: 'orca_desktop', title: 'Orca', version: '0.0.0' } } - }, - { method: 'initialized' }, - { id: 2, method: 'thread/name/set', params: { threadId: 'thread-1', name: 'Saved name' } } - ]) - expect(stopped).toBe(false) - expect(closeAdapters).not.toHaveBeenCalled() - expect(closeDatabase).not.toHaveBeenCalled() - helperExit.resolve() - await stopping - expect(spawn).toHaveBeenCalledOnce() - expect(resolveLaunchArgs).toHaveBeenCalledOnce() - expect(order).toEqual(['helper-stdin-end', 'helper-exit', 'adapter-close', 'database-close']) - expect(closeAdapters).toHaveBeenCalledOnce() - expect(host.deps.journalDatabase.isClosed).toBe(true) - expect(closeDatabase).toHaveBeenCalledOnce() -}) diff --git a/src/main/runtime/agent-session/naming/structured-claude-naming-test-support.ts b/src/main/runtime/agent-session/naming/structured-claude-naming-test-support.ts index f74ee781906..cec4691be56 100644 --- a/src/main/runtime/agent-session/naming/structured-claude-naming-test-support.ts +++ b/src/main/runtime/agent-session/naming/structured-claude-naming-test-support.ts @@ -20,7 +20,7 @@ import { import type { StructuredAgentSessionHost } from '../../../native-chat/agent-session-wire/host/structured-agent-session-host' import { createStructuredAgentSessionLogger } from '../../../native-chat/agent-session-wire/host/structured-agent-session-logger' import { closeTestJournalHostDatabase } from '../../../native-chat/agent-session-journal/store-lifecycle/journal-host-database-test-support' -import { stopStructuredAgentSessionRuntime } from '../structured-agent-session-runtime' +import { stopStructuredAgentSessionRuntime } from '../installation/structured-agent-session-runtime' import { ensureTestStructuredAgentSessionHost as ensureStructuredAgentSessionHost } from '../records/agent-session-record-store-test-harness' import type { StructuredAgentSessionRuntimeDeps } from '../installation/structured-agent-session-runtime-contract' diff --git a/src/main/runtime/agent-session/agent-session-acquisition-exit-transition.ts b/src/main/runtime/agent-session/ownership/agent-session-acquisition-exit-transition.ts similarity index 79% rename from src/main/runtime/agent-session/agent-session-acquisition-exit-transition.ts rename to src/main/runtime/agent-session/ownership/agent-session-acquisition-exit-transition.ts index ef325be041c..7347a3e0fb1 100644 --- a/src/main/runtime/agent-session/agent-session-acquisition-exit-transition.ts +++ b/src/main/runtime/agent-session/ownership/agent-session-acquisition-exit-transition.ts @@ -2,11 +2,11 @@ import { isDeepStrictEqual } from 'node:util' import { agentSessionExecutionLocationsEqual, type AgentSessionRecord -} from '../../../shared/agent-session/lifecycle/agent-session-record' -import { agentSessionLeaseIsReleased } from '../../../shared/agent-session/lifecycle/leases/agent-session-lease-adjudication' -import { nextAgentSessionFence } from '../../../shared/agent-session/lifecycle/leases/agent-session-next-fence' -import type { StructuredAgentSessionAcquisitionReceipt } from '../../native-chat/agent-session-wire/startup/structured-agent-session-startup-attempt-contract' -import { assertFence, withLease } from './ownership/agent-session-lease-transitions' +} from '../../../../shared/agent-session/lifecycle/agent-session-record' +import { agentSessionLeaseIsReleased } from '../../../../shared/agent-session/lifecycle/leases/agent-session-lease-adjudication' +import { nextAgentSessionFence } from '../../../../shared/agent-session/lifecycle/leases/agent-session-next-fence' +import type { StructuredAgentSessionAcquisitionReceipt } from '../../../native-chat/agent-session-wire/startup/structured-agent-session-startup-attempt-contract' +import { assertFence, withLease } from './agent-session-lease-transitions' /** An unpublished start's observed exit belongs to its reservation, never a later owner. */ export function recordAgentSessionAcquisitionExit( diff --git a/src/main/runtime/agent-session/agent-session-acquisition-failure-settlement.ts b/src/main/runtime/agent-session/ownership/agent-session-acquisition-failure-settlement.ts similarity index 91% rename from src/main/runtime/agent-session/agent-session-acquisition-failure-settlement.ts rename to src/main/runtime/agent-session/ownership/agent-session-acquisition-failure-settlement.ts index 4d8a7e28d2a..7fa7c5378c3 100644 --- a/src/main/runtime/agent-session/agent-session-acquisition-failure-settlement.ts +++ b/src/main/runtime/agent-session/ownership/agent-session-acquisition-failure-settlement.ts @@ -2,12 +2,12 @@ import { agentSessionOperationKey, settleAgentSessionOperation, type AgentSessionOperationOutcome -} from '../../../shared/agent-session/lifecycle/operations/agent-session-operation-ledger' -import { nextAgentSessionFence } from '../../../shared/agent-session/lifecycle/leases/agent-session-next-fence' -import type { AgentSessionDeathEvidence } from '../../../shared/agent-session/lifecycle/leases/agent-session-death-evidence' -import type { AgentSessionRecord } from '../../../shared/agent-session/lifecycle/agent-session-record' -import { assertFence, withLease } from './ownership/agent-session-lease-transitions' -import type { AgentSessionStoreState } from './records/agent-session-store-state' +} from '../../../../shared/agent-session/lifecycle/operations/agent-session-operation-ledger' +import { nextAgentSessionFence } from '../../../../shared/agent-session/lifecycle/leases/agent-session-next-fence' +import type { AgentSessionDeathEvidence } from '../../../../shared/agent-session/lifecycle/leases/agent-session-death-evidence' +import type { AgentSessionRecord } from '../../../../shared/agent-session/lifecycle/agent-session-record' +import { assertFence, withLease } from './agent-session-lease-transitions' +import type { AgentSessionStoreState } from '../records/agent-session-store-state' /** Cleanup evidence: exit-proven follows provider tree-close proof (Windows may use stdin EOF/root exit or taskkill /T). * root-exit-observed proves only the lease root died; processless means no process existed. diff --git a/src/main/runtime/agent-session/ownership/agent-session-permission-backfill.test.ts b/src/main/runtime/agent-session/ownership/agent-session-permission-backfill.test.ts index b9d9419624c..bbedcf9da1e 100644 --- a/src/main/runtime/agent-session/ownership/agent-session-permission-backfill.test.ts +++ b/src/main/runtime/agent-session/ownership/agent-session-permission-backfill.test.ts @@ -1,13 +1,5 @@ -import { - ensureStructuredAgentSessionHost, - stopStructuredAgentSessionRuntime -} from '../structured-agent-session-runtime' -import { openAgentSessionRecordStoreOnce } from '../records/agent-session-record-store-slot' -import { - journalSqlReaderPath, - journalSqlWorkerPath -} from '../../../native-chat/agent-session-journal/journal-sql-worker-bundle.test-fixture' -import { recordingStructuredAgentSessionLogger } from '../../../native-chat/agent-session-wire/host/testing/structured-agent-session-logger.test-fixture' +import { stopStructuredAgentSessionRuntime } from '../installation/structured-agent-session-runtime' + import { mkdtemp, rm } from 'node:fs/promises' import { tmpdir } from 'node:os' import { join } from 'node:path' @@ -75,36 +67,3 @@ describe('existing chat permission backfill', () => { expect(store.listRecords().every((row) => row.permissionMode === 'full-access')).toBe(true) }) }) - -it('keeps startup and option reads available when the SQL permission backfill fails', async () => { - await seedTestAgentSessionRecordStore(root, { records: [record('codex')] }) - await withTestAgentSessionDatabase(root, (db) => - db.exec(`CREATE TRIGGER fail_permission_backfill BEFORE UPDATE ON agent_session_records - WHEN json_extract(NEW.record_json,'$.permissionMode') IS NOT json_extract(OLD.record_json,'$.permissionMode') - BEGIN SELECT RAISE(ABORT, 'disk full'); END`) - ) - const logged = recordingStructuredAgentSessionLogger() - await openAgentSessionRecordStoreOnce({ - stateDirectory: root, - hostId: 'local', - logger: logged.logger, - legacySessionTabIds: [], - writerPath: journalSqlWorkerPath(), - readerPath: journalSqlReaderPath(), - onMaintenanceTick: () => {} - }) - const host = await ensureStructuredAgentSessionHost({ - logger: logged.logger, - stateDirectory: root, - hostId: 'local', - claimKeyId: 'key-1', - resolveWorkspacePath: async () => root, - resolveLaunchArgs: () => [], - resolveClaudeAuthPolicy: () => ({ account: 'managed' }), - resolveAgentFullAccess: () => true, - resolveEnvironment: async () => ({}) - }) - expect(host.deps.store.getRecord('session-codex')?.permissionMode).toBeUndefined() - expect((await host.readOptions('session-codex')).current.permissionMode).toBe('ask') - expect(logged.scopes()).toContain('permission-mode-backfill') -}) diff --git a/src/main/runtime/agent-session/agent-session-replaced-runtime.ts b/src/main/runtime/agent-session/ownership/agent-session-replaced-runtime.ts similarity index 90% rename from src/main/runtime/agent-session/agent-session-replaced-runtime.ts rename to src/main/runtime/agent-session/ownership/agent-session-replaced-runtime.ts index 621dcaa0d8d..85485cb00b8 100644 --- a/src/main/runtime/agent-session/agent-session-replaced-runtime.ts +++ b/src/main/runtime/agent-session/ownership/agent-session-replaced-runtime.ts @@ -1,11 +1,11 @@ // The profile lock proves replaced host runtimes lost their pipes, not that provider processes died. // Attribute only runtimes this host replaced; terminal claims and unknown owners provide no such evidence. -import type { AgentSessionOrcaStopCause } from '../../../shared/agent-session/lifecycle/stopping/agent-session-orca-stop' +import type { AgentSessionOrcaStopCause } from '../../../../shared/agent-session/lifecycle/stopping/agent-session-orca-stop' import { listAgentSessionConversations, type AgentSessionStoreState -} from './records/agent-session-store-state' +} from '../records/agent-session-store-state' export type AgentSessionReplacedRuntime = { /** The highest fence a replaced runtime granted; every lower fence was granted before it. */ diff --git a/src/main/runtime/agent-session/ownership/agent-session-reservation-admission.ts b/src/main/runtime/agent-session/ownership/agent-session-reservation-admission.ts index f8a9e16c410..41e7c2acf98 100644 --- a/src/main/runtime/agent-session/ownership/agent-session-reservation-admission.ts +++ b/src/main/runtime/agent-session/ownership/agent-session-reservation-admission.ts @@ -47,7 +47,7 @@ import { agentSessionAccountHomesEqual, type AgentSessionAccountHome } from '../../../../shared/agent-session/lifecycle/accounts/agent-session-account-home' -import { assertReservedTabUnheld } from '../agent-session-tab-table' +import { assertReservedTabUnheld } from '../records/agent-session-tab-table' export type AgentSessionReserveRequest = { forkedFrom?: AgentSessionRecord['forkedFrom'] diff --git a/src/main/runtime/agent-session/structured-agent-session-create-adoption.ts b/src/main/runtime/agent-session/ownership/structured-agent-session-create-adoption.ts similarity index 85% rename from src/main/runtime/agent-session/structured-agent-session-create-adoption.ts rename to src/main/runtime/agent-session/ownership/structured-agent-session-create-adoption.ts index 232c085a15b..d90a11f3fc8 100644 --- a/src/main/runtime/agent-session/structured-agent-session-create-adoption.ts +++ b/src/main/runtime/agent-session/ownership/structured-agent-session-create-adoption.ts @@ -2,40 +2,40 @@ import { stat } from 'node:fs/promises' import { agentSessionRefusalError, isAgentSessionRefusalError -} from '../../../shared/agent-session/failures/agent-session-wire-refusals' -import { prepareCodexAdoption } from '../../native-chat/conversation-adoption/codex-adoption-preparation' -import { isAiVaultTitleAgent } from '../../../shared/ai-vault/contracts/ai-vault-session-title' -import { generatedSessionTitle } from '../../ai-vault/parsing/session-scanner-accumulator' -import { resolveLocalAiVaultSessionTitles } from '../../ai-vault/session-titles/session-title-resolver' -import type { NativeCodexResumePreparation } from '../../codex/history/resume/codex-ai-vault-session-resume' -import type { StructuredAgentSessionResumeSource } from '../../../shared/agent-session/lifecycle/operations/structured-agent-session-create' +} from '../../../../shared/agent-session/failures/agent-session-wire-refusals' +import { prepareCodexAdoption } from '../../../native-chat/conversation-adoption/codex-adoption-preparation' +import { isAiVaultTitleAgent } from '../../../../shared/ai-vault/contracts/ai-vault-session-title' +import { generatedSessionTitle } from '../../../ai-vault/parsing/session-scanner-accumulator' +import { resolveLocalAiVaultSessionTitles } from '../../../ai-vault/session-titles/session-title-resolver' +import type { NativeCodexResumePreparation } from '../../../codex/history/resume/codex-ai-vault-session-resume' +import type { StructuredAgentSessionResumeSource } from '../../../../shared/agent-session/lifecycle/operations/structured-agent-session-create' import type { StructuredAgentCliSourceEvidence, StructuredAgentCliSourceLocator -} from '../../native-chat/conversation-adoption/structured-agent-cli-source' -import type { AgentSessionAccountHome } from '../../../shared/agent-session/lifecycle/accounts/agent-session-account-home' +} from '../../../native-chat/conversation-adoption/structured-agent-cli-source' +import type { AgentSessionAccountHome } from '../../../../shared/agent-session/lifecycle/accounts/agent-session-account-home' import type { AgentSessionProviderHandle, StructuredAgentId -} from '../../../shared/agent-session/lifecycle/provider-handles/agent-session-provider-handle' +} from '../../../../shared/agent-session/lifecycle/provider-handles/agent-session-provider-handle' import { type AgentSessionExecutionLocation, agentSessionExecutionLocationsEqual -} from '../../../shared/agent-session/lifecycle/agent-session-record' -import type { AgentSessionAttachParams } from '../../native-chat/agent-session-wire/acquisition/structured-agent-session-attach' -import type { StructuredAgentSessionHost } from '../../native-chat/agent-session-wire/host/structured-agent-session-host' -import { listStructuredProviderSessionOwnership } from '../../native-chat/agent-session-wire/host/structured-provider-session-ownership' +} from '../../../../shared/agent-session/lifecycle/agent-session-record' +import type { AgentSessionAttachParams } from '../../../native-chat/agent-session-wire/acquisition/structured-agent-session-attach' +import type { StructuredAgentSessionHost } from '../../../native-chat/agent-session-wire/host/structured-agent-session-host' +import { listStructuredProviderSessionOwnership } from '../../../native-chat/agent-session-wire/host/structured-provider-session-ownership' import { findCommittedStructuredAgentSessionAdoptionReplay, findConflictingStructuredAdoption, resolveStructuredAgentSessionAdoption, structuredAdoptionConflictError -} from '../../native-chat/conversation-adoption/structured-agent-session-history-adoption' -import { structuredAgentRuntimeMetadata } from './installation/structured-agent-runtime-metadata' +} from '../../../native-chat/conversation-adoption/structured-agent-session-history-adoption' +import { structuredAgentRuntimeMetadata } from '../installation/structured-agent-runtime-metadata' import type { StructuredAgentTranscriptImport, StructuredAgentTranscriptImportSettings -} from '../../native-chat/conversation-adoption/structured-agent-cli-conversations' +} from '../../../native-chat/conversation-adoption/structured-agent-cli-conversations' export type StructuredAgentSessionCreateIntentInput = { envelope: { sessionId: string; clientOperationId: string } diff --git a/src/main/runtime/agent-session/structured-agent-session-owner-probe.ts b/src/main/runtime/agent-session/ownership/structured-agent-session-owner-probe.ts similarity index 87% rename from src/main/runtime/agent-session/structured-agent-session-owner-probe.ts rename to src/main/runtime/agent-session/ownership/structured-agent-session-owner-probe.ts index 3d92af56c02..20de0eea16c 100644 --- a/src/main/runtime/agent-session/structured-agent-session-owner-probe.ts +++ b/src/main/runtime/agent-session/ownership/structured-agent-session-owner-probe.ts @@ -1,12 +1,12 @@ -import type { AgentSessionOwnerProbe } from '../../../shared/agent-session/lifecycle/leases/agent-session-lease-adjudication' -import type { AgentSessionRecord } from '../../../shared/agent-session/lifecycle/agent-session-record' +import type { AgentSessionOwnerProbe } from '../../../../shared/agent-session/lifecycle/leases/agent-session-lease-adjudication' +import type { AgentSessionRecord } from '../../../../shared/agent-session/lifecycle/agent-session-record' import { probeAgentSessionProcessIdentities, probeAgentSessionProcessIdentity, probeAgentSessionReservation -} from './ownership/agent-session-process-identity-probe' -import { findAgentSessionSpawnTokenProcesses } from './ownership/agent-session-spawn-token-process-scan' -import { readEchoedAgentSessionSpawnToken } from './ownership/agent-session-spawn-token-readback' +} from './agent-session-process-identity-probe' +import { findAgentSessionSpawnTokenProcesses } from './agent-session-spawn-token-process-scan' +import { readEchoedAgentSessionSpawnToken } from './agent-session-spawn-token-readback' /** Probe previous owners with PID-reuse-safe evidence; unresolved ownership remains indeterminate. */ export function createStructuredAgentSessionOwnerProbe( diff --git a/src/main/runtime/agent-session/ownership/structured-agent-session-spawn-token-descendants.test.ts b/src/main/runtime/agent-session/ownership/structured-agent-session-spawn-token-descendants.test.ts index cb8ca7b9c3d..34d24ff6ad9 100644 --- a/src/main/runtime/agent-session/ownership/structured-agent-session-spawn-token-descendants.test.ts +++ b/src/main/runtime/agent-session/ownership/structured-agent-session-spawn-token-descendants.test.ts @@ -10,8 +10,8 @@ import { ORCA_AGENT_SESSION_SPAWN_TOKEN_ENV } from '../../../../shared/agent-ses import type { AgentSessionRecordStore } from '../records/agent-session-record-store' import { openTestAgentSessionRecordStore } from '../records/agent-session-record-store-test-harness' import type { AgentSessionReserveRequest } from './agent-session-reservation-admission' -import { createStructuredAgentSessionOwnerProbe } from '../structured-agent-session-owner-probe' -import { stopStructuredAgentSessionRuntime } from '../structured-agent-session-runtime' +import { createStructuredAgentSessionOwnerProbe } from './structured-agent-session-owner-probe' +import { stopStructuredAgentSessionRuntime } from '../installation/structured-agent-session-runtime' /** pid -> the NUL-separated environment block `/proc//environ` serves. */ const fakeProc = vi.hoisted(() => ({ environs: new Map() })) diff --git a/src/main/runtime/agent-session/pr-watch-runtime.test.ts b/src/main/runtime/agent-session/pr-watch-runtime.test.ts deleted file mode 100644 index a64c7904d2e..00000000000 --- a/src/main/runtime/agent-session/pr-watch-runtime.test.ts +++ /dev/null @@ -1,232 +0,0 @@ -// @orca-isolated-worker -- Watch admission and committed shutdown are process-wide and one-way. -import { mkdtemp, rm, writeFile } from 'node:fs/promises' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { afterEach, beforeAll, beforeEach, expect, it, vi } from 'vitest' -import * as profilePaths from '../../orca-profiles/profile-storage-paths' -import { PRWatchService } from '../../github/pr-watch/pr-watch-service' -import * as refresh from '../../github/pull-requests/refresh/pr-refresh-coordinator' -import { JournalSqlReaderPool } from '../../native-chat/agent-session-journal/journal-sql-reader-pool' -import { JournalSqlDatabase } from '../../native-chat/agent-session-journal/database/journal-sql-database' -import { - journalSqlReaderPath, - journalSqlWorkerPath -} from '../../native-chat/agent-session-journal/journal-sql-worker-bundle.test-fixture' -import { journalDomainDatabasePath } from '../../native-chat/agent-session-journal/database/journal-domain-database' -import { createStructuredAgentSessionLogger } from '../../native-chat/agent-session-wire/host/structured-agent-session-logger' -import { openTestAgentSessionRecordStoreSlot } from './records/agent-session-record-store-test-harness' -import { - closeAgentSessionRecordStoreDatabase, - retireAgentSessionRecordStore -} from './records/agent-session-record-store-slot' -import * as watches from './pr-watch-runtime' -import { recordStructuredAgentSessionHostInstallRefusal } from './structured-agent-session-host-refusal' -import { OrcaRuntimeService } from '../orca-runtime' -import { localAgentSessionRecordStoreLocation } from './records/local-agent-session-record-store-startup-open' -import { markHostShuttingDown } from '../../startup/quit/host-shutdown-state' -import type * as HostRuntime from './structured-agent-session-runtime' - -// The chat host's own installation is covered elsewhere; this exercises what installation does next. -vi.mock('./structured-agent-session-runtime', async (importOriginal) => ({ - ...(await importOriginal()), - ensureStructuredAgentSessionHost: vi.fn(async () => undefined) -})) - -let stateDirectory: string -let runtime: OrcaRuntimeService -let host: typeof HostRuntime - -beforeAll(async () => { - host = await vi.importActual('./structured-agent-session-runtime') -}) - -const location = () => ({ - stateDirectory, - legacySessionTabIds: [], - hostId: 'local', - logger: createStructuredAgentSessionLogger() -}) - -beforeEach(async () => { - stateDirectory = await mkdtemp(join(tmpdir(), 'orca-pr-watch-runtime-')) - vi.spyOn(profilePaths, 'getProfileUserDataPath').mockReturnValue(stateDirectory) - runtime = new OrcaRuntimeService() -}) - -afterEach(async () => { - vi.useRealTimers() - watches.stopPRWatchRuntime() - await retireAgentSessionRecordStore((opened) => - closeAgentSessionRecordStoreDatabase(opened?.journalDatabase) - ) - recordStructuredAgentSessionHostInstallRefusal(null) - vi.restoreAllMocks() - await rm(stateDirectory, { recursive: true, force: true }) -}) - -// Watch admission is process-wide and one-way, so the before-admission case runs first. -it('leaves the first watch start to the serving milestone, not the startup warmup', async () => { - const drained = vi.spyOn(PRWatchService.prototype, 'start') - await openTestAgentSessionRecordStoreSlot(location()) - - // Serve's warmup timer can fire while its post-RPC prerequisites are still pending. - runtime.noteAgentLaunchStartupSettled() - await new Promise((resolve) => setImmediate(resolve)) - expect(drained).not.toHaveBeenCalled() - - runtime.startPullRequestWatches({ admit: true }) - await vi.waitFor(() => expect(drained).toHaveBeenCalledTimes(1)) -}) - -it('starts CI-line watches when a chat installs after the serving milestone start failed', async () => { - const drained = vi.spyOn(PRWatchService.prototype, 'start') - const deps = { ...location(), resolveWorkspace: async () => null } - - // The serving milestone's first start fails to open the journal. - await writeFile(journalDomainDatabasePath(stateDirectory), 'not a database') - runtime.startPullRequestWatches({ admit: true }) - await watches.startPRWatchRuntime(deps) - expect(drained).not.toHaveBeenCalled() - - // Storage recovers and a chat installs, with no teardown; installation retries the watch start. - await rm(journalDomainDatabasePath(stateDirectory)) - await openTestAgentSessionRecordStoreSlot(location()) - await runtime.ensureStructuredAgentSessionHost() - await vi.waitFor(() => expect(drained).toHaveBeenCalledTimes(1)) -}) - -it('keeps one PR outcome observer when a partly started watch service fails and is retried', async () => { - let observers = 0 - const addObserver = refresh.addPRRefreshOutcomeObserver - vi.spyOn(refresh, 'addPRRefreshOutcomeObserver').mockImplementation((observer) => { - const unsubscribe = addObserver(observer) - observers += 1 - return () => { - observers -= 1 - return unsubscribe() - } - }) - const read = JournalSqlReaderPool.prototype.database - let failed = false - vi.spyOn(JournalSqlReaderPool.prototype, 'database').mockImplementation(function ( - this: InstanceType, - operation - ) { - if (!failed && operation.kind === 'pr-watch' && operation.operation.kind === 'watch-chats') { - failed = true - return Promise.reject(new Error('watch read failed once')) - } - return read.call(this, operation) - }) - await openTestAgentSessionRecordStoreSlot(location()) - const deps = { ...location(), resolveWorkspace: async () => null } - - await watches.startPRWatchRuntime(deps, { admit: true }) - expect(failed).toBe(true) - expect(observers).toBe(0) - - await watches.startPRWatchRuntime(deps) - expect(observers).toBe(1) - watches.stopPRWatchRuntime() - expect(observers).toBe(0) -}) - -/** The reviewer's input: the first `watch-chats` read fails once, after the service registered its observer. */ -function failFirstWatchRead(): { failed: () => boolean } { - const read = JournalSqlReaderPool.prototype.database - let failed = false - vi.spyOn(JournalSqlReaderPool.prototype, 'database').mockImplementation(function ( - this: InstanceType, - operation - ) { - if (!failed && operation.kind === 'pr-watch' && operation.operation.kind === 'watch-chats') { - failed = true - return Promise.reject(new Error('watch read failed once')) - } - return read.call(this, operation) - }) - return { failed: () => failed } -} - -/** A saved-chat host's store, opened through the production location so its maintenance pass is wired. */ -async function openInstalledHostStore() { - vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] }) - await openTestAgentSessionRecordStoreSlot(localAgentSessionRecordStoreLocation([])) - return { ...location(), resolveWorkspace: async () => null } -} - -const MAINTENANCE_PASS_MS = 60_000 - -it('does not restart a running watch service on the maintenance pass', async () => { - const started = vi.spyOn(PRWatchService.prototype, 'start') - const deps = await openInstalledHostStore() - - await watches.startPRWatchRuntime(deps, { admit: true }) - await vi.advanceTimersByTimeAsync(MAINTENANCE_PASS_MS) - - expect(started).toHaveBeenCalledTimes(1) -}) - -it('retries a failed first watch start on the maintenance pass, with no chat install or restart', async () => { - const started = vi.spyOn(PRWatchService.prototype, 'start') - const watchRead = failFirstWatchRead() - const deps = await openInstalledHostStore() - - await watches.startPRWatchRuntime(deps, { admit: true }) - expect(watchRead.failed()).toBe(true) - await vi.advanceTimersByTimeAsync(MAINTENANCE_PASS_MS) - - await vi.waitFor(() => expect(started).toHaveBeenCalledTimes(2)) - await expect(started.mock.results[1]?.value).resolves.toBeUndefined() -}) - -it('retries a failed first watch start on the maintenance pass when the chat host opened the store', async () => { - const started = vi.spyOn(PRWatchService.prototype, 'start') - const watchRead = failFirstWatchRead() - vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] }) - // Only the worker bundle differs from production; the host install's own location wins the slot. - const open = JournalSqlDatabase.open - const opened = vi.spyOn(JournalSqlDatabase, 'open').mockImplementation((directory, options) => - open.call(JournalSqlDatabase, directory, { - ...options, - writerPath: journalSqlWorkerPath(), - readerPath: journalSqlReaderPath() - }) - ) - try { - await host.ensureStructuredAgentSessionHost({ - ...location(), - claimKeyId: 'key-1', - resolveWorkspacePath: async () => stateDirectory, - resolveLaunchArgs: () => [], - resolveClaudeAuthPolicy: () => ({ account: 'managed' }), - resolveEnvironment: async () => ({}) - }) - expect(opened).toHaveBeenCalledTimes(1) - - await watches.startPRWatchRuntime( - { ...location(), resolveWorkspace: async () => null }, - { admit: true } - ) - expect(watchRead.failed()).toBe(true) - await vi.advanceTimersByTimeAsync(MAINTENANCE_PASS_MS) - - await vi.waitFor(() => expect(started).toHaveBeenCalledTimes(2)) - await expect(started.mock.results[1]?.value).resolves.toBeUndefined() - } finally { - await host.stopStructuredAgentSessionRuntime() - } -}) - -// Committed shutdown is process-wide and sticky, so this runs last. -it('does not retry a failed watch start on the maintenance pass after shutdown committed', async () => { - const started = vi.spyOn(PRWatchService.prototype, 'start') - failFirstWatchRead() - const deps = await openInstalledHostStore() - - await watches.startPRWatchRuntime(deps, { admit: true }) - markHostShuttingDown() - await vi.advanceTimersByTimeAsync(MAINTENANCE_PASS_MS) - - expect(started).toHaveBeenCalledTimes(1) -}) diff --git a/src/main/runtime/agent-session/agent-session-conversation-receipts.ts b/src/main/runtime/agent-session/records/agent-session-conversation-receipts.ts similarity index 62% rename from src/main/runtime/agent-session/agent-session-conversation-receipts.ts rename to src/main/runtime/agent-session/records/agent-session-conversation-receipts.ts index 82c1d78e274..100a64d5d0f 100644 --- a/src/main/runtime/agent-session/agent-session-conversation-receipts.ts +++ b/src/main/runtime/agent-session/records/agent-session-conversation-receipts.ts @@ -1,7 +1,7 @@ -import type { AgentSessionForkedFrom } from '../../../shared/agent-session/lifecycle/agent-session-record' -import type { AgentSessionStoreTransactions } from './records/agent-session-store-transactions' -import type { AgentSessionConversationClear } from './records/agent-session-conversation-command-record' -import type { AgentSessionRewindRecord } from '../../../shared/agent-session/lifecycle/rewind/agent-session-rewind' +import type { AgentSessionForkedFrom } from '../../../../shared/agent-session/lifecycle/agent-session-record' +import type { AgentSessionStoreTransactions } from './agent-session-store-transactions' +import type { AgentSessionConversationClear } from './agent-session-conversation-command-record' +import type { AgentSessionRewindRecord } from '../../../../shared/agent-session/lifecycle/rewind/agent-session-rewind' export function createAgentSessionConversationReceipts( transactions: Pick diff --git a/src/main/runtime/agent-session/records/agent-session-founding-admission.ts b/src/main/runtime/agent-session/records/agent-session-founding-admission.ts index 9d33b7e0ff9..36a8a550a45 100644 --- a/src/main/runtime/agent-session/records/agent-session-founding-admission.ts +++ b/src/main/runtime/agent-session/records/agent-session-founding-admission.ts @@ -13,7 +13,7 @@ import { type AgentSessionReserveRequest, type AgentSessionReserveResult } from '../ownership/agent-session-reservation-admission' -import { assertReservedTabUnheld, setAgentSessionTabVisibility } from '../agent-session-tab-table' +import { assertReservedTabUnheld, setAgentSessionTabVisibility } from './agent-session-tab-table' import { selectWritableAgentSessionRecord, requireWritableAgentSessionRecord, diff --git a/src/main/runtime/agent-session/records/agent-session-inventory-scale.test.ts b/src/main/runtime/agent-session/records/agent-session-inventory-scale.test.ts deleted file mode 100644 index b9996e011b4..00000000000 --- a/src/main/runtime/agent-session/records/agent-session-inventory-scale.test.ts +++ /dev/null @@ -1,200 +0,0 @@ -import { describe, expect, it } from 'vitest' -import '../../../../shared/ai-vault/search/ai-vault-search-test-fixture' -import '../../../ai-vault/structured-sessions/structured-session-ownership.test-support' -import '../../../ai-vault/structured-sessions/structured-session-ownership' -import { hostTestState } from '../../../native-chat/agent-session-wire/host/testing/structured-agent-session-host.test-fixture' -import { StructuredAgentSessionHost } from '../../../native-chat/agent-session-wire/host/structured-agent-session-host' -import { setStructuredAgentSessionHost } from '../../../native-chat/agent-session-wire/host/structured-agent-session-registry' -import { scaleDirectory, scaleRecord } from './agent-session-scale.test-fixture' -import { createReferenceAgentIndex } from '../../workspaces/references/runtime-reference-agents' -import { - openTestAgentSessionRecordStore, - openTestAgentSessionDatabase -} from './agent-session-record-store-test-harness' -import { seedTestAgentSessionRecordStore } from './agent-session-record-store-persistence.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 { structuredSessionMailReach } from '../../orchestration/mailbox/routing/structured-session-mail-address' -import { resolveOrcaSessionParty } from '../../orchestration/addressing/orchestration-party' -import { testOrcaSessionId } from '../../../../shared/agent-session/identity/orca-session-address-test-fixture' -import { - mintStructuredWorkerHandle, - mintStructuredWorkerPaneKey, - structuredWorkerIdentities, - structuredWorkerProcessIncarnation -} from '../../orchestration/terminal-authority/structured-sessions/structured-worker-identity' -import { - openAgentSessionRecordStoreOnce, - retireAgentSessionRecordStore -} from './agent-session-record-store-slot' -import { createStructuredAgentSessionLogger } from '../../../native-chat/agent-session-wire/host/structured-agent-session-logger' -import type { AgentSessionRecord } from '../../../../shared/agent-session/lifecycle/agent-session-record' -import { conversationRecordReader } from '../../orchestration/addressing/session-lineage/structured-session-lineage' -import '../structured-agent-session-create-adoption' -import { - journalSqlReaderPath, - journalSqlWorkerPath -} from '../../../native-chat/agent-session-journal/journal-sql-worker-bundle.test-fixture' - -const referenceRuntime = { - getOrchestrationFleetAgentStatusSnapshot: () => [], - getAgentProviderSessionRows: () => [], - getTerminalLivenessVerdict: () => null -} - -function clearedRecord(sessionId: string, successor: string): AgentSessionRecord { - return { - ...scaleRecord(sessionId), - conversationCommand: { - command: 'clear', - state: 'completed', - replacementSessionId: successor, - operationId: `clear-${sessionId}`, - callerKey: 'client', - phase: 'committed' - } - } -} - -describe('persisted conversation inventory identity', () => { - it('keeps global worker identity separate from candidate inventory and retains closure/loop outcomes', async () => { - const rootId = testOrcaSessionId('global-root') - const successor = testOrcaSessionId('visible-successor') - const globalRoot = await scaleDirectory() - const candidateRoot = await scaleDirectory() - const rows = [ - scaleRecord(successor), - scaleRecord('closed-chat'), - clearedRecord('loop-one', 'loop-two'), - clearedRecord('loop-two', 'loop-one') - ] - const sessionTabs = [ - { tabId: 'successor-tab', sessionId: successor }, - { tabId: 'loop-tab', sessionId: 'loop-one' } - ] - await seedTestAgentSessionRecordStore(globalRoot, { - records: [clearedRecord(rootId, successor), ...rows], - sessionTabs - }) - await seedTestAgentSessionRecordStore(candidateRoot, { records: rows, sessionTabs }) - const globalStore = await openTestAgentSessionRecordStore(globalRoot) - const candidateStore = await openTestAgentSessionRecordStore(candidateRoot) - const host = new StructuredAgentSessionHost({ - ...hostTestState().host.deps, - store: globalStore, - journalDatabase: await openTestAgentSessionDatabase(globalRoot) - }) - setStructuredAgentSessionHost(host) - const db = new OrchestrationDb(':memory:') - const handle = mintStructuredWorkerHandle() - const paneKey = mintStructuredWorkerPaneKey(rootId) - try { - const run = db.createRun({ - objective: 'identity control', - coordinatorHandle: null, - coordinatorPaneKey: null - }) - const dispatch = db.createDispatchContext({ - taskId: db.createTask({ runId: run.id, spec: 'saved worker' }).id, - assigneeHandle: handle, - assigneePaneKey: paneKey, - processIncarnation: structuredWorkerProcessIncarnation(rootId), - creator: { kind: 'system' }, - maxDepth: Number.MAX_SAFE_INTEGER - }) - expect(db.getDispatchContextById(dispatch.id)?.assignee_orca_session_id).toBe(rootId) - const reader = conversationRecordReader(candidateStore) - const found = () => - [...createReferenceAgentIndex(referenceRuntime, db, reader).values()].flat() - expect(candidateStore.getConversation(rootId)).toBeNull() - expect(found()).toMatchObject([{ sessionId: successor, liveness: 'unverifiable' }]) - expect(found()[0]?.mailbox).toBeUndefined() - expect( - structuredSessionMailReach(reader, candidateStore.getConversation(successor)!, db) - ).toEqual({ kind: 'ended', reason: 'worker-identity-lost' }) - structuredWorkerIdentities.register({ - handle, - paneKey, - sessionId: rootId, - agent: 'claude', - processIncarnation: structuredWorkerProcessIncarnation(rootId), - worktreeId: 'workspace-1', - hostScope: { kind: 'local', hostId: 'local' } - }) - expect(resolveOrcaSessionParty(successor, db)).toMatchObject({ - orcaSessionId: rootId, - terminalHandle: handle - }) - expect(found()[0]?.mailbox).toBe(`orca_session_id:${successor}`) - expect( - structuredSessionMailReach(reader, candidateStore.getConversation('closed-chat')!, db) - ).toEqual({ kind: 'ended', reason: 'closed' }) - expect( - structuredSessionMailReach(reader, candidateStore.getConversation('loop-one')!, db) - ).toMatchObject({ kind: 'unverifiable', reason: expect.stringContaining('loops') }) - await candidateStore.setSessionTabVisibility(successor, false) - expect(found()).toEqual([]) - } finally { - structuredWorkerIdentities.forget(handle) - db.close() - } - }) - - it('uses the opened cold inventory without importing its predecessor into absent global identity', async () => { - const root = await scaleDirectory() - const predecessor = testOrcaSessionId('cold-root') - const successor = testOrcaSessionId('cold-successor') - await seedTestAgentSessionRecordStore(root, { - records: [clearedRecord(predecessor, successor), scaleRecord(successor)], - sessionTabs: [{ tabId: 'cold-tab', sessionId: successor }] - }) - const opened = await openAgentSessionRecordStoreOnce({ - legacySessionTabIds: [], - stateDirectory: root, - hostId: 'local', - logger: createStructuredAgentSessionLogger(), - writerPath: journalSqlWorkerPath(), - readerPath: journalSqlReaderPath(), - onMaintenanceTick: () => {} - }) - const db = new OrchestrationDb(':memory:') - try { - const run = db.createRun({ - objective: 'cold identity', - coordinatorHandle: null, - coordinatorPaneKey: null - }) - db.createDispatchContext({ - taskId: db.createTask({ runId: run.id, spec: 'predecessor' }).id, - assigneeHandle: mintStructuredWorkerHandle(), - processIncarnation: structuredWorkerProcessIncarnation(predecessor), - creator: { kind: 'system' }, - maxDepth: Number.MAX_SAFE_INTEGER - }) - for (const index of [ - createReferenceAgentIndex(referenceRuntime, db), - createReferenceAgentIndex(referenceRuntime, db, conversationRecordReader(opened.store)) - ]) { - expect([...index.values()].flat()).toMatchObject([ - { - sessionId: successor, - mailbox: `orca_session_id:${successor}`, - liveness: 'unverifiable' - } - ]) - } - expect(resolveOrcaSessionParty(successor, db)).toMatchObject({ - orcaSessionId: successor, - terminalHandle: null - }) - } finally { - db.close() - await retireAgentSessionRecordStore(async (released) => { - await released?.journalDatabase.close() - }) - } - }) -}) diff --git a/src/main/runtime/agent-session/agent-session-operation-receipt.ts b/src/main/runtime/agent-session/records/agent-session-operation-receipt.ts similarity index 64% rename from src/main/runtime/agent-session/agent-session-operation-receipt.ts rename to src/main/runtime/agent-session/records/agent-session-operation-receipt.ts index d4eb449cc0b..55d8b0c3134 100644 --- a/src/main/runtime/agent-session/agent-session-operation-receipt.ts +++ b/src/main/runtime/agent-session/records/agent-session-operation-receipt.ts @@ -1,11 +1,11 @@ -import type { JournalOperationReceipt } from '../../native-chat/agent-session-journal/writing/journal-row-writer' -import type { AgentSessionOperationOutcome } from '../../../shared/agent-session/lifecycle/operations/agent-session-operation-ledger' +import type { JournalOperationReceipt } from '../../../native-chat/agent-session-journal/writing/journal-row-writer' +import type { AgentSessionOperationOutcome } from '../../../../shared/agent-session/lifecycle/operations/agent-session-operation-ledger' import type { settleAgentSessionOperationInto, AgentSessionOperationAcceptance -} from './ownership/agent-session-operation-admission' -import type { AgentSessionRecordAcceptance } from './records/agent-session-store-mutation' -import type { AgentSessionStoreTransactions } from './records/agent-session-store-transactions' +} from '../ownership/agent-session-operation-admission' +import type { AgentSessionRecordAcceptance } from './agent-session-store-mutation' +import type { AgentSessionStoreTransactions } from './agent-session-store-transactions' export type AgentSessionOperationReceiptInput = ( | Parameters[1] diff --git a/src/main/runtime/agent-session/records/agent-session-record-command.ts b/src/main/runtime/agent-session/records/agent-session-record-command.ts index b81758e356e..0109394b3d0 100644 --- a/src/main/runtime/agent-session/records/agent-session-record-command.ts +++ b/src/main/runtime/agent-session/records/agent-session-record-command.ts @@ -8,7 +8,7 @@ import { import type { AgentSessionRewindRecord } from '../../../../shared/agent-session/lifecycle/rewind/agent-session-rewind' import type { AgentSessionLastTurn } from '../../../../shared/agent-session/lifecycle/records/agent-session-last-turn' import type { createAgentSessionOwnerProof } from '../ownership/agent-session-owner-proof' -import { recordAgentSessionAcquisitionExit } from '../agent-session-acquisition-exit-transition' +import { recordAgentSessionAcquisitionExit } from '../ownership/agent-session-acquisition-exit-transition' import { commitAgentSessionProcessIdentity, evictAgentSessionOwner, diff --git a/src/main/runtime/agent-session/records/agent-session-record-rows.ts b/src/main/runtime/agent-session/records/agent-session-record-rows.ts index 83e0292a7b7..29396794ec9 100644 --- a/src/main/runtime/agent-session/records/agent-session-record-rows.ts +++ b/src/main/runtime/agent-session/records/agent-session-record-rows.ts @@ -20,7 +20,7 @@ import { isReadableAgentSessionStoreTab, isReadableRetiredAgentSessionClaimKey } from './agent-session-store-row-rules' -import { AgentSessionTabTable, type PersistedAgentSessionTab } from '../agent-session-tab-table' +import { AgentSessionTabTable, type PersistedAgentSessionTab } from './agent-session-tab-table' /** Never-recorded differs from recorded-empty; legacy fallback cannot infer this from row count (#17439). */ export const AGENT_SESSION_TABS_RECORDED = 'session_tabs_recorded' diff --git a/src/main/runtime/agent-session/records/agent-session-record-store-slot.ts b/src/main/runtime/agent-session/records/agent-session-record-store-slot.ts index f4329ad21e4..27f687992a6 100644 --- a/src/main/runtime/agent-session/records/agent-session-record-store-slot.ts +++ b/src/main/runtime/agent-session/records/agent-session-record-store-slot.ts @@ -7,7 +7,7 @@ import { journalDomainDatabasePath } from '../../../native-chat/agent-session-jo import { journalDatabaseHoldsAgentSessions } from '../../../native-chat/agent-session-journal/database/journal-database' import { AgentSessionRecordStore } from './agent-session-record-store' import type { JournalSqlDatabase } from '../../../native-chat/agent-session-journal/database/journal-sql-database' -import { openStructuredAgentSessionSqlJournalDatabase } from '../structured-agent-session-journal-open' +import { openStructuredAgentSessionSqlJournalDatabase } from '../installation/structured-agent-session-journal-open' import type { StructuredAgentSessionLogger } from '../../../native-chat/agent-session-wire/host/structured-agent-session-logger' export type AgentSessionRecordStoreLocation = { diff --git a/src/main/runtime/agent-session/records/agent-session-record-store-test-harness.ts b/src/main/runtime/agent-session/records/agent-session-record-store-test-harness.ts index c86900728c7..a0688243bce 100644 --- a/src/main/runtime/agent-session/records/agent-session-record-store-test-harness.ts +++ b/src/main/runtime/agent-session/records/agent-session-record-store-test-harness.ts @@ -12,7 +12,7 @@ import { } from '../../../native-chat/agent-session-journal/journal-sql-worker-bundle.test-fixture' import { AgentSessionRecordStore } from './agent-session-record-store' import { openAgentSessionRecordStoreOnce } from './agent-session-record-store-slot' -import { ensureStructuredAgentSessionHost } from '../structured-agent-session-runtime' +import { ensureStructuredAgentSessionHost } from '../installation/structured-agent-session-runtime' const TEST_HOST_ID = 'local' diff --git a/src/main/runtime/agent-session/records/agent-session-record-store.ts b/src/main/runtime/agent-session/records/agent-session-record-store.ts index 0e5d32fdd0f..98e17623773 100644 --- a/src/main/runtime/agent-session/records/agent-session-record-store.ts +++ b/src/main/runtime/agent-session/records/agent-session-record-store.ts @@ -2,7 +2,7 @@ import { clearSuccessor } from './agent-session-sender-identity-revision' import type * as usageLimitContinue from '../../../../shared/agent-session/lifecycle/stopping/agent-session-usage-limit-continue' import type { createAgentSessionOwnerProof } from '../ownership/agent-session-owner-proof' import { backfillAgentSessionPermissionModes } from '../ownership/agent-session-permission-backfill' -import { createAgentSessionConversationReceipts } from '../agent-session-conversation-receipts' +import { createAgentSessionConversationReceipts } from './agent-session-conversation-receipts' import { agentSessionOperationKey, type AgentSessionOperationDecision, @@ -29,7 +29,7 @@ import type { AgentSessionProcessIdentityCommit } from '../ownership/agent-sessi import type { AgentSessionFailedAcquisitionSettlement, AgentSessionFailedPostAcquisitionAttachmentSettlement -} from '../agent-session-acquisition-failure-settlement' +} from '../ownership/agent-session-acquisition-failure-settlement' import type { AgentSessionLeaseRenewal } from '../ownership/agent-session-lease-renewal' import { collectAgentSessionRestartProbes, @@ -48,10 +48,10 @@ import { heldAgentSessionIds, type AgentSessionStoreState } from './agent-session-store-state' -import { AgentSessionRecordTabs } from '../agent-session-tab-table' +import { AgentSessionRecordTabs } from './agent-session-tab-table' import type { JournalSqlDatabase } from '../../../native-chat/agent-session-journal/database/journal-sql-database' import type { JournalOperationReceipt } from '../../../native-chat/agent-session-journal/writing/journal-row-writer' -import { agentSessionOperationOutcomeReceipt } from '../agent-session-operation-receipt' +import { agentSessionOperationOutcomeReceipt } from './agent-session-operation-receipt' import { AgentSessionStoreTransactions } from './agent-session-store-transactions' import { createAgentSessionFoundingStore } from './agent-session-founding-store' import type { diff --git a/src/main/runtime/agent-session/agent-session-rewind-completion.ts b/src/main/runtime/agent-session/records/agent-session-rewind-completion.ts similarity index 77% rename from src/main/runtime/agent-session/agent-session-rewind-completion.ts rename to src/main/runtime/agent-session/records/agent-session-rewind-completion.ts index 7b0ddd51bc5..8f87eb34354 100644 --- a/src/main/runtime/agent-session/agent-session-rewind-completion.ts +++ b/src/main/runtime/agent-session/records/agent-session-rewind-completion.ts @@ -1,17 +1,17 @@ import { cancelAgentSessionUsageLimitContinue, type UsageLimitContinueIdentity -} from '../../../shared/agent-session/lifecycle/stopping/agent-session-usage-limit-continue' -import type { AgentJournalCursor } from '../../../shared/agent-session/journal/agent-session-journal-identity' -import type { AgentSessionRewindRecord } from '../../../shared/agent-session/lifecycle/rewind/agent-session-rewind' -import type { AgentSessionStoreState } from './records/agent-session-store-state' -import { settleAgentSessionOperationInto } from './ownership/agent-session-operation-admission' +} from '../../../../shared/agent-session/lifecycle/stopping/agent-session-usage-limit-continue' +import type { AgentJournalCursor } from '../../../../shared/agent-session/journal/agent-session-journal-identity' +import type { AgentSessionRewindRecord } from '../../../../shared/agent-session/lifecycle/rewind/agent-session-rewind' +import type { AgentSessionStoreState } from './agent-session-store-state' +import { settleAgentSessionOperationInto } from '../ownership/agent-session-operation-admission' import { agentSessionProviderHandleChainHead, appendAgentSessionProviderHandleLink -} from '../../../shared/agent-session/lifecycle/provider-handles/agent-session-provider-handle' -import { agentSessionProviderHandleKey } from '../../../shared/agent-session/lifecycle/provider-handles/agent-session-provider-handle-encoding' -import type { AgentSessionRecord } from '../../../shared/agent-session/lifecycle/agent-session-record' +} from '../../../../shared/agent-session/lifecycle/provider-handles/agent-session-provider-handle' +import { agentSessionProviderHandleKey } from '../../../../shared/agent-session/lifecycle/provider-handles/agent-session-provider-handle-encoding' +import type { AgentSessionRecord } from '../../../../shared/agent-session/lifecycle/agent-session-record' function rewindProviderChain( record: AgentSessionRecord, diff --git a/src/main/runtime/agent-session/agent-session-runtime-attribution.ts b/src/main/runtime/agent-session/records/agent-session-runtime-attribution.ts similarity index 92% rename from src/main/runtime/agent-session/agent-session-runtime-attribution.ts rename to src/main/runtime/agent-session/records/agent-session-runtime-attribution.ts index a655dceee68..f5556c09396 100644 --- a/src/main/runtime/agent-session/agent-session-runtime-attribution.ts +++ b/src/main/runtime/agent-session/records/agent-session-runtime-attribution.ts @@ -2,8 +2,8 @@ // Unknown/older-build/terminal owners retain generic guidance instead of an invented cause. import { randomUUID } from 'node:crypto' -import type { AgentSessionRecord } from '../../../shared/agent-session/lifecycle/agent-session-record' -import type { AgentSessionStoreState } from './records/agent-session-store-state' +import type { AgentSessionRecord } from '../../../../shared/agent-session/lifecycle/agent-session-record' +import type { AgentSessionStoreState } from './agent-session-store-state' let incarnation = randomUUID() diff --git a/src/main/runtime/agent-session/records/agent-session-runtime-end-record.test.ts b/src/main/runtime/agent-session/records/agent-session-runtime-end-record.test.ts index 86ca76a33f5..f6ebcfba9ed 100644 --- a/src/main/runtime/agent-session/records/agent-session-runtime-end-record.test.ts +++ b/src/main/runtime/agent-session/records/agent-session-runtime-end-record.test.ts @@ -24,13 +24,12 @@ vi.mock('../../../filesystem/durable-file-write', async (importOriginal) => { import { beginAgentSessionRuntimeRecord, readAgentSessionRuntimeEnds, - recordAgentSessionRuntimeEnd, - recordAgentSessionRuntimeEndOnExit + recordAgentSessionRuntimeEnd } from './agent-session-runtime-end-record' import { tearDownRuntime, type InstalledRuntime -} from '../structured-agent-session-runtime-teardown' +} from '../installation/structured-agent-session-runtime-teardown' const RUNTIME_A = '0000000a-0000-4000-8000-000000000000' const RUNTIME_B = '0000000b-0000-4000-8000-000000000000' @@ -110,15 +109,6 @@ describe('what a runtime records about itself', () => { recordAgentSessionRuntimeEnd('quit', 2) expect(readAgentSessionRuntimeEnds(directory)?.has(RUNTIME_A)).toBe(false) }) - - it('reads a clean process exit nothing else recorded as a quit, and any other exit as nothing', () => { - beginAgentSessionRuntimeRecord(directory, RUNTIME_A, 1) - expect(process.listeners('exit')).toContain(recordAgentSessionRuntimeEndOnExit) - recordAgentSessionRuntimeEndOnExit(1) - expect(readAgentSessionRuntimeEnds(directory)?.get(RUNTIME_A)).toBe('crash') - recordAgentSessionRuntimeEndOnExit(0) - expect(readAgentSessionRuntimeEnds(directory)?.get(RUNTIME_A)).toBe('quit') - }) }) describe('a quit', () => { diff --git a/src/main/runtime/agent-session/records/agent-session-store-cache.ts b/src/main/runtime/agent-session/records/agent-session-store-cache.ts index 52e8ee64c24..2b418b31af8 100644 --- a/src/main/runtime/agent-session/records/agent-session-store-cache.ts +++ b/src/main/runtime/agent-session/records/agent-session-store-cache.ts @@ -1,7 +1,7 @@ import { decodePersistedAgentSessionRecord } from '../../../../shared/agent-session/lifecycle/records/agent-session-record-stored-form' import { isDeepStrictEqual } from 'node:util' import { sessionCrewChanges } from '../../orchestration/crew/crew-changes' -import { AgentSessionTabTable } from '../agent-session-tab-table' +import { AgentSessionTabTable } from './agent-session-tab-table' import type { AgentSessionStoreRowWrites } from '../../../native-chat/agent-session-journal/journal-writer-store-row-changes' import type { AgentSessionStoreState } from './agent-session-store-state' import { agentSessionStoreRowChanges } from '../../../native-chat/agent-session-journal/journal-writer-store-row-changes' diff --git a/src/main/runtime/agent-session/records/agent-session-store-command.ts b/src/main/runtime/agent-session/records/agent-session-store-command.ts index 37df534c8ae..e057905ab7b 100644 --- a/src/main/runtime/agent-session/records/agent-session-store-command.ts +++ b/src/main/runtime/agent-session/records/agent-session-store-command.ts @@ -32,13 +32,13 @@ import { settleFailedAgentSessionAcquisition, settleFailedAgentSessionPostAcquisitionAttachment, type AgentSessionFailedAcquisitionSettlement -} from '../agent-session-acquisition-failure-settlement' +} from '../ownership/agent-session-acquisition-failure-settlement' import { initializeAgentSessionTabs, effectiveAgentSessionTabs, setAgentSessionTabVisibility, showAgentSessionTabs -} from '../agent-session-tab-table' +} from './agent-session-tab-table' import { commitAgentSessionFounding } from './agent-session-founding-admission' import type { AgentSessionStoreState } from './agent-session-store-state' diff --git a/src/main/runtime/agent-session/records/agent-session-store-mutation.ts b/src/main/runtime/agent-session/records/agent-session-store-mutation.ts index b7a9d99876e..ecacf2d092e 100644 --- a/src/main/runtime/agent-session/records/agent-session-store-mutation.ts +++ b/src/main/runtime/agent-session/records/agent-session-store-mutation.ts @@ -1,4 +1,4 @@ -import { commitAgentSessionRewindCompletion } from '../agent-session-rewind-completion' +import { commitAgentSessionRewindCompletion } from './agent-session-rewind-completion' import type { AgentSessionRewindRecord } from '../../../../shared/agent-session/lifecycle/rewind/agent-session-rewind' import type { AgentJournalCursor } from '../../../../shared/agent-session/journal/agent-session-journal-identity' import { diff --git a/src/main/runtime/agent-session/records/agent-session-store-row-rules.ts b/src/main/runtime/agent-session/records/agent-session-store-row-rules.ts index 5589005dbc5..c8628fd6c94 100644 --- a/src/main/runtime/agent-session/records/agent-session-store-row-rules.ts +++ b/src/main/runtime/agent-session/records/agent-session-store-row-rules.ts @@ -12,7 +12,7 @@ import { import type { PersistedAgentSessionRecord } from '../../../../shared/agent-session/lifecycle/leases/agent-session-legacy-handoff-lease' import { isAgentSessionSurfaceTabId } from '../../../../shared/agent-session/view/agent-session-surface-tab-id' import type { RetiredAgentSessionClaimKey } from './agent-session-store-state' -import type { PersistedAgentSessionTab } from '../agent-session-tab-table' +import type { PersistedAgentSessionTab } from './agent-session-tab-table' export function isReadableAgentSessionStoreRecord( sessionId: string, diff --git a/src/main/runtime/agent-session/records/agent-session-store-state.ts b/src/main/runtime/agent-session/records/agent-session-store-state.ts index 8380abf6969..492ce77b155 100644 --- a/src/main/runtime/agent-session/records/agent-session-store-state.ts +++ b/src/main/runtime/agent-session/records/agent-session-store-state.ts @@ -6,7 +6,7 @@ import { agentSessionRefusalError } from '../../../../shared/agent-session/failu import type { AgentSessionOperationRow } from '../../../../shared/agent-session/lifecycle/operations/agent-session-operation-ledger' import type { AgentSessionRecord } from '../../../../shared/agent-session/lifecycle/agent-session-record' import type { AgentSessionOrcaStopCause } from '../../../../shared/agent-session/lifecycle/stopping/agent-session-orca-stop' -import type { AgentSessionTabTable } from '../agent-session-tab-table' +import type { AgentSessionTabTable } from './agent-session-tab-table' export type RetiredAgentSessionClaimKey = { keyId: string; retiredAt: number } diff --git a/src/main/runtime/agent-session/records/agent-session-store-transactions.ts b/src/main/runtime/agent-session/records/agent-session-store-transactions.ts index 7ddeb8a0df7..889be2485e8 100644 --- a/src/main/runtime/agent-session/records/agent-session-store-transactions.ts +++ b/src/main/runtime/agent-session/records/agent-session-store-transactions.ts @@ -17,7 +17,7 @@ import type { CommandReceiptScope } from '../../../native-chat/agent-session-jou import { agentSessionRuntimeIncarnation, attributeAgentSessionRuntime -} from '../agent-session-runtime-attribution' +} from './agent-session-runtime-attribution' import { beginAgentSessionRuntimeRecord, readAgentSessionRuntimeEnds @@ -25,7 +25,7 @@ import { import { agentSessionReplacedRuntimes, type AgentSessionReplacedRuntime -} from '../agent-session-replaced-runtime' +} from '../ownership/agent-session-replaced-runtime' import { agentSessionStoreRowChanges, type AgentSessionStoreRowWrites diff --git a/src/main/runtime/agent-session/agent-session-tab-table.ts b/src/main/runtime/agent-session/records/agent-session-tab-table.ts similarity index 93% rename from src/main/runtime/agent-session/agent-session-tab-table.ts rename to src/main/runtime/agent-session/records/agent-session-tab-table.ts index f8b9162c2de..0675fa7e9b4 100644 --- a/src/main/runtime/agent-session/agent-session-tab-table.ts +++ b/src/main/runtime/agent-session/records/agent-session-tab-table.ts @@ -1,12 +1,12 @@ -import { AgentSessionRecordPublication } from './records/agent-session-record-publication' -import { isAgentSessionSurfaceTabId } from '../../../shared/agent-session/view/agent-session-surface-tab-id' -import type { AgentSessionReserveRequest } from './ownership/agent-session-reservation-admission' -import { agentSessionRefusalError } from '../../../shared/agent-session/failures/agent-session-wire-refusals' -import { structuredAgentSessionTabId } from '../../../shared/agent-session/view/structured-agent-session-projection' +import { AgentSessionRecordPublication } from './agent-session-record-publication' +import { isAgentSessionSurfaceTabId } from '../../../../shared/agent-session/view/agent-session-surface-tab-id' +import type { AgentSessionReserveRequest } from '../ownership/agent-session-reservation-admission' +import { agentSessionRefusalError } from '../../../../shared/agent-session/failures/agent-session-wire-refusals' +import { structuredAgentSessionTabId } from '../../../../shared/agent-session/view/structured-agent-session-projection' import { hasAgentSessionConversation, type AgentSessionStoreState -} from './records/agent-session-store-state' +} from './agent-session-store-state' /** Tab membership defines visibility; tab and session ids form a one-to-one mapping. */ export class AgentSessionTabTable { diff --git a/src/main/runtime/agent-session/agent-session-unsaved-creation-supersession.test.ts b/src/main/runtime/agent-session/records/agent-session-unsaved-creation-supersession.test.ts similarity index 84% rename from src/main/runtime/agent-session/agent-session-unsaved-creation-supersession.test.ts rename to src/main/runtime/agent-session/records/agent-session-unsaved-creation-supersession.test.ts index 40087e54536..7a06982e98e 100644 --- a/src/main/runtime/agent-session/agent-session-unsaved-creation-supersession.test.ts +++ b/src/main/runtime/agent-session/records/agent-session-unsaved-creation-supersession.test.ts @@ -1,13 +1,13 @@ -import { closeTestJournalHostDatabases } from '../../native-chat/agent-session-journal/store-lifecycle/journal-host-database-test-support' +import { closeTestJournalHostDatabases } from '../../../native-chat/agent-session-journal/store-lifecycle/journal-host-database-test-support' import { mkdtemp, rm } from 'node:fs/promises' import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, beforeEach, describe, expect, it } from 'vitest' -import type { AgentSessionProviderHandleLink } from '../../../shared/agent-session/lifecycle/provider-handles/agent-session-provider-handle' -import { codexProviderHandleLink } from '../../codex/structured/acquisition/codex-structured-owner-identity' -import type { AgentSessionRecordStore } from './records/agent-session-record-store' -import { openTestAgentSessionRecordStore } from './records/agent-session-record-store-test-harness' -import type { AgentSessionReserveRequest } from './ownership/agent-session-reservation-admission' +import type { AgentSessionProviderHandleLink } from '../../../../shared/agent-session/lifecycle/provider-handles/agent-session-provider-handle' +import { codexProviderHandleLink } from '../../../codex/structured/acquisition/codex-structured-owner-identity' +import type { AgentSessionRecordStore } from './agent-session-record-store' +import { openTestAgentSessionRecordStore } from './agent-session-record-store-test-harness' +import type { AgentSessionReserveRequest } from '../ownership/agent-session-reservation-admission' const NOW = 1_800_000_000_000 const SESSION = 'session-codex' diff --git a/src/main/runtime/agent-session/records/local-agent-session-record-store-startup-open.ts b/src/main/runtime/agent-session/records/local-agent-session-record-store-startup-open.ts index e765a38d2af..83b027322e1 100644 --- a/src/main/runtime/agent-session/records/local-agent-session-record-store-startup-open.ts +++ b/src/main/runtime/agent-session/records/local-agent-session-record-store-startup-open.ts @@ -1,5 +1,5 @@ import { LOCAL_EXECUTION_HOST_ID } from '../../../../shared/execution-host/execution-host' -import { withPRWatchRecovery } from '../pr-watch-runtime' +import { withPRWatchRecovery } from '../lifecycle/pr-watch-runtime' import { getProfileUserDataPath } from '../../../orca-profiles/profile-storage-paths' import { createStructuredAgentSessionLogger, diff --git a/src/main/runtime/agent-session/records/structured-agent-session-mobile-restore.test.ts b/src/main/runtime/agent-session/records/structured-agent-session-mobile-restore.test.ts deleted file mode 100644 index aef732b0a87..00000000000 --- a/src/main/runtime/agent-session/records/structured-agent-session-mobile-restore.test.ts +++ /dev/null @@ -1,139 +0,0 @@ -import { openTestChats } from '../../../native-chat/agent-session-wire/host/testing/structured-agent-session-open-test-chats.test-fixture' -import { abandonStructuredAgentSessionHost } from '../../../native-chat/agent-session-wire/host/testing/structured-agent-session-host-test-abandon.test-fixture' -import { describe, expect, it } from 'vitest' -import { - hostTestState, - adapter, - attach, - seedApproval, - envelope, - CALLER, - hostTestRecoveryCapsuleSettled -} from '../../../native-chat/agent-session-wire/host/testing/structured-agent-session-host.test-fixture' -import { - HOST_TEST_SESSION as SESSION, - HOST_TEST_NOW as NOW, - hostTestMessage -} from '../../../native-chat/agent-session-wire/host/testing/structured-agent-session-host-test-data.test-fixture' -import { StructuredAgentSessionHost } from '../../../native-chat/agent-session-wire/host/structured-agent-session-host' -import { claudeAndCodexDeclared } from '../../../native-chat/agent-session-wire/providers/testing/structured-agent-session-adapter-router.test-fixture' -import { - openTestAgentSessionRecordStore, - openTestAgentSessionDatabase -} from './agent-session-record-store-test-harness' -import { - RuntimeMobileNotificationController, - type MobileNotificationEvent -} from '../../push/notifications/runtime-mobile-notification-controller' -import { createStructuredAttentionMobileDelivery } from '../structured-agent-session-mobile-attention' -import { MobileNotificationDismissalStore } from '../../push/notifications/mobile-notification-dismissal-store' - -function wire(host: StructuredAgentSessionHost, controller: RuntimeMobileNotificationController) { - const delivery = createStructuredAttentionMobileDelivery({ - readNotificationSettings: () => ({ - enabled: true, - agentTaskComplete: true, - agentNeedsInput: true, - terminalBell: true, - suppressWhenFocused: false, - customSoundId: 'system', - customSoundPath: null, - customSoundVolume: 1, - mutedNotificationSourceIds: [], - notifyHiddenWorkspaces: true - }), - readWorkspaceLabels: () => ({}), - isWorkspaceMuted: () => false, - readOrchestration: () => undefined, - dispatch: (event) => controller.dispatch(event), - reconcile: (state) => controller.reconcileStructuredPromptAttention(state), - now: () => NOW - }) - return host.subscribeTurnCompletions({ - id: 'host-attention-delivery', - includePrompts: true, - emit: (event) => { - if (event.type !== 'end') { - delivery.deliver(event, host.readStatusSummary(SESSION)) - } - }, - onState: delivery.reconcile - }) -} - -describe('prompt delivery after host recovery', () => { - it('withdraws a recovered cancellation before the first attention baseline', async () => { - const h = hostTestState() - await attach() - const original = new RuntimeMobileNotificationController() - original.configureDismissalStore(h.root) - const sent: MobileNotificationEvent[] = [] - original.onDispatched((event) => sent.push(event)) - const unsubscribe = wire(h.host, original) - const body = hostTestMessage('Work') - expect( - await h.host.send(CALLER, { envelope: envelope('agentSession.send', { body }), body }) - ).toMatchObject({ ok: true }) - const prompt = await seedApproval() - const delivered = sent.find((event) => event.type === 'notification') - if ( - !delivered?.notificationId || - !delivered.notificationEpoch || - delivered.notificationSeq === undefined - ) { - throw new Error('pending approval was not delivered') - } - const identity = { - notificationId: delivered.notificationId, - notificationEpoch: delivered.notificationEpoch, - notificationSeq: delivered.notificationSeq - } - unsubscribe() - await original.closeDismissals() - await abandonStructuredAgentSessionHost(h.host) - // A restarted process starts after the old one's capsule writes finished or died with it. - await hostTestRecoveryCapsuleSettled() - const restarted = new RuntimeMobileNotificationController() - restarted.configureDismissalStore(h.root) - const events: MobileNotificationEvent[] = [] - restarted.onDispatched((event) => events.push(event)) - const store = await openTestAgentSessionRecordStore(h.root) - const host = new StructuredAgentSessionHost({ - agents: claudeAndCodexDeclared(), - logger: h.log.logger, - store, - adapter: adapter(), - journalDatabase: await openTestAgentSessionDatabase(h.root), - claimKeyId: 'key-1', - mintSpawnToken: () => 'spawn-b', - probeOwner: async () => ({ outcome: 'pid-absent' }), - now: () => NOW - }) - const stop = wire(host, restarted) - try { - await host.reconcileRestartLeases() - await openTestChats(host) - const history = await host.history({ sessionId: SESSION, direction: 'tail' }) - expect(history.ok).toBe(true) - expect( - history.ok ? history.page.items.find((item) => item.itemId === prompt.itemId)?.body : null - ).toMatchObject({ resolution: { state: 'cancelled' } }) - expect(events.filter((event) => event.type === 'notification')).toEqual([]) - expect(events.filter((event) => event.type === 'dismiss')).toEqual([ - expect.objectContaining({ dismissedDelivery: identity }) - ]) - await restarted.flushDismissals() - expect( - new MobileNotificationDismissalStore(h.root) - .liveDeliveries() - .filter((delivery) => delivery.notificationId === identity.notificationId) - ).toEqual([]) - expect(restarted.reconcileDismissedPushes([identity])).toEqual([identity]) - await openTestChats(host) - expect(events.filter((event) => event.type === 'dismiss')).toHaveLength(1) - } finally { - stop() - await host.flushAllStreamedEvents() - } - }) -}) diff --git a/src/main/runtime/agent-session/records/structured-agent-session-startup-tab-restore.test.ts b/src/main/runtime/agent-session/records/structured-agent-session-startup-tab-restore.test.ts deleted file mode 100644 index b9e967d2638..00000000000 --- a/src/main/runtime/agent-session/records/structured-agent-session-startup-tab-restore.test.ts +++ /dev/null @@ -1,421 +0,0 @@ -import { readTestHostJournal } from '../../../native-chat/agent-session-journal/journal-observation.test-support' -import { partialRuntimeStore } from '../../orca-runtime-tests/runtime-store-partial-fixture' -import type { WorkspaceSessionState } from '../../../../shared/workspace-session/workspace-session-state-types' -import { mkdtemp, rm } from 'node:fs/promises' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import type { AgentSessionRecord } from '../../../../shared/agent-session/lifecycle/agent-session-record' -import { - agentSessionLeaseFixture, - agentSessionRecordFixture -} from '../../../../shared/agent-session/lifecycle/records/agent-session-record.test-fixture' -import { journalDatabasePath } from '../../../native-chat/agent-session-journal/database/journal-host-database' -import { - closeTestJournalHostDatabase, - closeTestJournalHostDatabases, - insertTestJournalRowJson, - openTestJournalHostDatabase -} from '../../../native-chat/agent-session-journal/store-lifecycle/journal-host-database-test-support' -import * as journalFactory from '../../../native-chat/agent-session-journal/journal-store-factory' -import { publishJournalSessionEpoch } from '../../../native-chat/agent-session-journal/durable-rows/journal-row-table' -import { createQueuedRigProvider } from '../../../native-chat/agent-session-wire/host/testing/structured-agent-session-queued-message-rig-provider.test-fixture' -import { createStructuredSessionObservationClock } from '../../../native-chat/agent-session-wire/host/testing/structured-agent-session-observation-clock.test-fixture' -import type { StructuredAgentSessionHost } from '../../../native-chat/agent-session-wire/host/structured-agent-session-host' -import type { AgentJournalMessageItem } from '../../../../shared/agent-session/journal/agent-session-journal-types' -import { computeAgentSessionPayloadFingerprint } from '../../../../shared/agent-session/lifecycle/operations/agent-session-mutation-envelope' -import { mintAgentSessionOperationId } from '../../orchestration/mailbox/structured-pointer/structured-pointer-operation-id' -import { journalIdentityFor } from '../../../native-chat/agent-session-wire/acquisition/structured-agent-session-attach' -import { attachParamsForRecord } from '../../../native-chat/agent-session-wire/host/structured-agent-session-conversation-open' -import { getStructuredAgentSessionHost } from '../../../native-chat/agent-session-wire/host/structured-agent-session-registry' -import type * as AgentSessionRecordRows from './agent-session-record-rows' -import { - ensureTestStructuredAgentSessionHost as ensureStructuredAgentSessionHost, - openTestAgentSessionDatabase, - seedTestAgentSessionStoreFromNewerBuild -} from './agent-session-record-store-test-harness' -import { seedTestAgentSessionRecordStore } from './agent-session-record-store-persistence.test-fixture' -import { OrcaRuntimeService } from '../../orca-runtime' -import { stopStructuredAgentSessionRuntime } from '../structured-agent-session-runtime' -import { recordingStructuredAgentSessionLogger } from '../../../native-chat/agent-session-wire/host/testing/structured-agent-session-logger.test-fixture' -import { codexProviderHandle } from '../../../../shared/agent-session/lifecycle/provider-handles/agent-session-provider-handle-encoding' -import { structuredAgentSessionTabId } from '../../../../shared/agent-session/view/structured-agent-session-projection' - -// `failing` fails every record write; `grants` lets that many more through, then fails. -const writes = vi.hoisted(() => ({ failing: false, grants: Infinity, refused: 0 })) - -vi.mock('./agent-session-record-rows', async (importOriginal) => { - const actual = await importOriginal() - return { - ...actual, - writeAgentSessionStoreRows: (...args: Parameters) => { - if (writes.failing || writes.grants <= 0) { - writes.refused += 1 - throw new Error('disk I/O error') - } - writes.grants -= 1 - return actual.writeAgentSessionStoreRows(...args) - } - } -}) - -const PROMPT = 'add a retry' - -let root: string - -beforeEach(async () => { - root = await mkdtemp(join(tmpdir(), 'orca-startup-tab-restore-')) -}) - -afterEach(async () => { - Object.assign(writes, { failing: false, grants: Infinity, refused: 0 }) - await stopStructuredAgentSessionRuntime().catch(() => undefined) - await closeTestJournalHostDatabases() - vi.restoreAllMocks() - await rm(root, { recursive: true, force: true }) -}) - -/** A released chat, so no startup probe looks for a live owner. */ -function chatRecord( - sessionId: string, - options: { codex?: boolean; clearedInto?: string } = {} -): AgentSessionRecord { - const record = agentSessionRecordFixture( - agentSessionLeaseFixture({ - sessionId, - ownerProcess: null, - reservedSpawnToken: null, - claimStatus: 'released' - }) - ) - const codex = options.codex - ? { - provider: 'codex' as const, - providerHandleChain: record.providerHandleChain.map((link) => ({ - ...link, - handle: codexProviderHandle(`thread-${sessionId}`) - })), - accountHome: { variable: 'CODEX_HOME' as const, path: join(root, 'codex-home') } - } - : {} - const clear = options.clearedInto - ? { - conversationCommand: { - command: 'clear' as const, - state: 'completed' as const, - phase: 'committed' as const, - operationId: `clear-${sessionId}`, - callerKey: 'client-1', - replacementSessionId: options.clearedInto - } - } - : {} - return { ...record, ...codex, ...clear } -} - -/** Seed released records and one accepted prompt each; visible is absent for legacy profiles, newer stamps a later database version. */ -async function seedProfile( - records: AgentSessionRecord[], - options: { newer?: boolean; visible?: string[]; history?: AgentSessionRecord[] } = {} -) { - await seedTestAgentSessionRecordStore(root, { - records, - ...(options.visible - ? { - sessionTabs: options.visible.map((sessionId) => ({ - tabId: structuredAgentSessionTabId(sessionId), - sessionId - })) - } - : {}) - }) - const database = await openTestAgentSessionDatabase(root) - for (const record of options.history ?? records) { - const fence = record.lease.runtimeFence - const journal = await journalFactory.openAgentSessionJournal({ - identity: journalIdentityFor( - record, - attachParamsForRecord(record, { clientOperationId: 'seed', expectedRuntimeFence: fence }) - ), - database - }) - await journal.appendSubmission({ - clientMessageId: 'client-1', - payloadFingerprint: 'fp-1', - body: { kind: 'message', role: 'user', blocks: [{ type: 'text', text: PROMPT }] }, - fence, - handoverRecorded: true - }) - await journal.resolveDispatch({ - clientMessageId: 'client-1', - fence, - state: 'accepted', - providerIdentity: null - }) - await journal.close() - } - await closeTestJournalHostDatabase(root) - if (options.newer) { - await seedTestAgentSessionStoreFromNewerBuild(root) - } - return { path: journalDatabasePath(root) } -} - -function startupRuntime(options: { afterInstall?: () => void; profileChats?: string[] } = {}) { - const log = recordingStructuredAgentSessionLogger() - // A legacy profile's saved chat tabs, which a store with no tab index restores from. - const profile: WorkspaceSessionState = { - activeRepoId: null, - activeWorktreeId: 'workspace-1', - activeTabId: null, - tabsByWorktree: {}, - terminalLayoutsByTabId: {}, - unifiedTabs: { - 'workspace-1': (options.profileChats ?? []).map((sessionId, index) => ({ - id: `agent-session:${sessionId}`, - entityId: sessionId, - groupId: 'group-1', - worktreeId: 'workspace-1', - contentType: 'agent-session', - label: 'Codex Chat', - customLabel: null, - color: null, - sortOrder: index, - createdAt: 1 - })) - } - } - class StartupRuntime extends OrcaRuntimeService { - protected override hasPersistedStructuredAgentSessionStore() { - return true - } - protected override async refreshMobileSessionPtyRecords() { - return new Set() - } - override async ensureStructuredAgentSessionHost() { - await ensureStructuredAgentSessionHost({ - logger: log.logger, - stateDirectory: root, - hostId: 'local', - claimKeyId: 'key-1', - legacySessionTabIds: this.legacyStructuredSessionTabIds, - resolveWorkspacePath: async () => root, - resolveEnvironment: async () => ({}), - resolveLaunchArgs: () => [], - resolveClaudeAuthPolicy: () => ({ account: 'managed' }) - }) - options.afterInstall?.() - } - } - const runtime = new StartupRuntime(partialRuntimeStore({ getWorkspaceSession: () => profile })) - return { - runtime, - log, - published: () => runtime.mobileSessionTabsByWorktree.get('workspace-1')?.tabs ?? [] - } -} - -describe('restoring the chat tabs open at quit', () => { - it('keeps recorded Codex queue admission through startup and physical reopen until Steer', async () => { - const sessionId = 'codex_921935f3_cbca_41e4_8b82_220245b3ecd4' - const epoch = '13c4e01d-1d1f-41bc-932a-629bf803c4a1' - const messageId = '1793285151845-19784765711d4fa6aa7a71b754b8574d' - const body: AgentJournalMessageItem = { - kind: 'message', - role: 'user', - blocks: [{ type: 'text', text: 'Reply exactly QA3231_CODEX_KEPT_REPLY1_OK' }] - } - // codex-main79-immutable-raw.json SHA25645767f7ef2a1ae7d44767fd4c79b4d9717c73f3548dc15205449a5812e4ba067: original rows from the stopped upgraded DB. - // Select the committed admission before seq3 handover, not an observed kept card or pre-upgrade DB snapshot. - const recordedRows = [ - { - seq: 1, - ts: 1793285143624, - json: '{"kind":"epoch","reason":"session_created","providerHandle":{"kind":"opaque","agent":"codex","value":"pending"},"v":2,"epoch":"13c4e01d-1d1f-41bc-932a-629bf803c4a1","seq":1,"fence":0,"ts":1793285143624}' - }, - { - seq: 2, - ts: 1793285151851, - json: '{"kind":"submission","clientMessageId":"1793285151845-19784765711d4fa6aa7a71b754b8574d","payloadFingerprint":"8d7b18e93fb35212a3f33ebb3781abf2708cace17a461933ad7c235cef55e7fd","providerHandle":{"kind":"opaque","agent":"codex","value":"pending"},"body":{"kind":"message","role":"user","blocks":[{"type":"text","text":"Reply exactly QA3231_CODEX_KEPT_REPLY1_OK"}]},"v":2,"epoch":"13c4e01d-1d1f-41bc-932a-629bf803c4a1","seq":2,"fence":1,"ts":1793285151851,"handoverRecorded":true,"origin":"client","source":{"kind":"user"},"options":{}}' - } - ] - const record = chatRecord(sessionId, { codex: true }) - // Companion record/profile are fixtures; only these two raw journal rows are recorded state. - await seedProfile([record], { visible: [sessionId], history: [] }) - const database = openTestJournalHostDatabase(root) - publishJournalSessionEpoch( - database.db, - { sessionId, workspaceId: record.location.workspaceId }, - epoch - ) - for (const row of recordedRows) { - insertTestJournalRowJson(database.db, sessionId, row.seq, row.json, row.ts) - } - await closeTestJournalHostDatabase(root) - - const installs: { - host: StructuredAgentSessionHost - provider: ReturnType - }[] = [] - const installProvider = () => { - const host = getStructuredAgentSessionHost() - if (!host) { - throw new Error('production runtime did not install its host') - } - if (installs.some((installed) => installed.host === host)) { - return - } - const provider = createQueuedRigProvider(host.deps.store, { restartable: true }, () => host) - Object.assign(host.deps.adapter, provider.adapter, { disposeSession: provider.closeSession }) - installs.push({ host, provider }) - } - const current = () => { - const installed = installs.at(-1) - if (!installed) { - throw new Error('no installed test provider') - } - return installed - } - const clock = createStructuredSessionObservationClock(() => current().host, sessionId) - const expectWaitingCard = async (host: StructuredAgentSessionHost) => { - const history = await host.history({ sessionId, direction: 'tail' }) - if (!history.ok) { - throw new Error('recorded conversation history refused') - } - expect(history.page.queuedMessages).toEqual([ - { messageId, position: 0, state: 'waiting', body } - ]) - const original = (await readTestHostJournal(host, sessionId)).submissions - expect(original).toHaveLength(1) - expect(original[0]).toMatchObject({ - clientMessageId: messageId, - acceptedSequence: 2, - dispatchState: 'rejected', - keptAsQueuedMessageId: messageId, - handoverRecorded: true, - origin: 'client', - source: { kind: 'user' }, - options: {} - }) - expect(original[0]?.handedOverAt).toBeUndefined() - } - const now = 1_793_285_160_000 - try { - const opens = vi.spyOn(journalFactory, 'openAgentSessionJournal') - const firstRuntime = startupRuntime({ - profileChats: [sessionId], - afterInstall: installProvider - }) - await firstRuntime.runtime.restoreStructuredAgentSessionTabs() - const first = current() - expect(firstRuntime.published().map((tab) => tab.id)).toEqual([`agent-session:${sessionId}`]) - expect(opens).not.toHaveBeenCalled() - expect(first.provider.starts).not.toHaveBeenCalled() - expect(first.provider.dispatch).not.toHaveBeenCalled() - await expect(first.host.revealSession(sessionId)).resolves.toMatchObject({ - sessionId, - readable: true - }) - expect(opens).toHaveBeenCalledOnce() - await expectWaitingCard(first.host) - clock.start() - vi.setSystemTime(now) - await clock.observe(100) - expect(first.provider.starts).not.toHaveBeenCalled() - expect(first.provider.dispatch).not.toHaveBeenCalled() - - const firstDatabase = first.host.deps.journalDatabase - clock.restore() - await stopStructuredAgentSessionRuntime() - expect(firstDatabase.isClosed).toBe(true) - await closeTestJournalHostDatabases() - opens.mockClear() - const nextRuntime = startupRuntime({ - profileChats: [sessionId], - afterInstall: installProvider - }) - await nextRuntime.runtime.restoreStructuredAgentSessionTabs() - const next = current() - expect(next.host).not.toBe(first.host) - expect(next.host.deps.store).not.toBe(first.host.deps.store) - expect(next.host.deps.journalDatabase).not.toBe(firstDatabase) - expect(nextRuntime.published().map((tab) => tab.id)).toEqual([`agent-session:${sessionId}`]) - expect(opens).not.toHaveBeenCalled() - expect(next.provider.starts).not.toHaveBeenCalled() - expect(next.provider.dispatch).not.toHaveBeenCalled() - await expect(next.host.revealSession(sessionId)).resolves.toMatchObject({ - sessionId, - readable: true - }) - expect(opens).toHaveBeenCalledOnce() - await expectWaitingCard(next.host) - clock.start() - vi.setSystemTime(now) - await clock.observe(100) - expect(next.provider.starts).not.toHaveBeenCalled() - expect(next.provider.dispatch).not.toHaveBeenCalled() - - const operationId = mintAgentSessionOperationId(now) - const liveRecord = next.host.deps.store.getRecord(sessionId) - if (!liveRecord) { - throw new Error('recorded conversation disappeared') - } - const sent = await next.host.queuedMessageSend( - { callerKey: 'client-1' }, - { - envelope: { - sessionId, - clientOperationId: operationId, - expectedRuntimeFence: liveRecord.lease.runtimeFence, - payloadFingerprint: computeAgentSessionPayloadFingerprint({ - method: 'agentSession.queuedMessageSend', - sessionId, - fields: { messageId } - }) - }, - messageId - } - ) - expect(sent).toMatchObject({ - ok: true, - value: { clientMessageId: operationId, submission: { queuedMessageId: messageId } } - }) - expect(operationId).not.toBe(messageId) - await vi.waitFor(() => expect(next.provider.dispatch).toHaveBeenCalledTimes(1)) - expect(next.provider.starts).toHaveBeenCalledOnce() - expect(next.provider.dispatch).toHaveBeenCalledWith( - expect.objectContaining({ - sessionId, - clientMessageId: operationId, - body, - executionOptions: {} - }) - ) - const delivered = await next.host.history({ sessionId, direction: 'tail' }) - if (!delivered.ok) { - throw new Error('delivered conversation history refused') - } - expect(delivered.page.queuedMessages).toEqual([]) - expect( - (await readTestHostJournal(next.host, sessionId)).submissions.filter( - (entry) => entry.queuedMessageId === messageId - ) - ).toEqual([ - expect.objectContaining({ - clientMessageId: operationId, - queuedMessageId: messageId, - origin: 'client', - options: {} - }) - ]) - await clock.observe(100) - expect(next.provider.dispatch).toHaveBeenCalledTimes(1) - expect(first.provider.dispatch).not.toHaveBeenCalled() - clock.restore() - await stopStructuredAgentSessionRuntime() - expect(next.host.deps.journalDatabase.isClosed).toBe(true) - } finally { - clock.restore() - } - }) -}) diff --git a/src/main/runtime/agent-session/structured-agent-session-close.test.ts b/src/main/runtime/agent-session/structured-agent-session-close.test.ts deleted file mode 100644 index 03f5cb78d08..00000000000 --- a/src/main/runtime/agent-session/structured-agent-session-close.test.ts +++ /dev/null @@ -1,182 +0,0 @@ -import { - agentSessionLeaseFixture, - agentSessionRecordFixture -} from '../../../shared/agent-session/lifecycle/records/agent-session-record.test-fixture' -import { agentSessionConversationView } from '../../../shared/agent-session/lifecycle/leases/agent-session-conversation-view' -// Child exit proof precedes advisory tab cleanup; failed stops retain the original surface. - -import { beforeEach, describe, expect, it, vi } from 'vitest' -import type { StructuredAgentSessionCloseCause } from '../../native-chat/agent-session-wire/termination/structured-agent-session-host-lifetime' -import type { AgentSessionRecord } from '../../../shared/agent-session/lifecycle/agent-session-record' -import { recordingStructuredAgentSessionLogger } from '../../native-chat/agent-session-wire/host/testing/structured-agent-session-logger.test-fixture' - -const hostRef: { current: unknown } = { current: null } - -vi.mock('../../native-chat/agent-session-wire/host/structured-agent-session-registry', () => ({ - getStructuredAgentSessionHost: () => hostRef.current -})) - -const { closeStructuredAgentSessionChild } = await import('./structured-agent-session-close') - -const SESSION = 'session-1' -const TAB_ID = 'tab-of-session-1' - -function record(sessionId: string): AgentSessionRecord { - const record = agentSessionRecordFixture(agentSessionLeaseFixture({ sessionId, runtimeFence: 1 })) - return { - ...record, - location: { ...record.location, workspaceId: 'repo_1::/tmp/wt-a', workspaceKind: 'folder' } - } -} - -type HostOptions = { - alreadyReleased?: boolean - skipAdmission?: boolean - /** Sessions the host keeps holding through a close, so the post-close observation is `live`. */ - stuck?: boolean - /** Rejects the close, without the child going. */ - closeThrows?: Error - /** The child dies and is recorded dead, but the close then fails past that proof. */ - settledThenThrows?: boolean - /** Rejects the visibility write itself, so the hide never lands. */ - visibilityThrows?: Error - /** Sessions already in the persisted visible-tab index. */ - visible?: string[] - /** Blows up the index read, so the rollback cannot prove the tab was ever visible. */ - indexThrows?: boolean -} -void [SESSION, false, undefined, { deferHiddenNotice: true, check: expect.any(Function) }] - -function installHost(options: HostOptions = {}) { - const entry = record(SESSION) - if (options.alreadyReleased) { - entry.lease.claimStatus = 'released' - entry.lease.deathEvidence = { kind: 'exit-observed', detail: 'natural exit', observedAt: 1 } - } - const held = new Set(options.alreadyReleased ? [] : [SESSION]) - const visible = new Set(options.visible ?? [SESSION]) - const setSessionTabVisibility = vi.fn(async (sessionId: string, isVisible: boolean) => { - if (options.visibilityThrows) { - throw options.visibilityThrows - } - if (isVisible) { - visible.add(sessionId) - } else { - visible.delete(sessionId) - } - }) - const notifySessionTabHidden = vi.fn() - const close = vi.fn( - async (sessionId: string, _cause: StructuredAgentSessionCloseCause, admit?: () => boolean) => { - if (!options.skipAdmission && admit && !admit()) { - throw new Error('The user kept this chat open.') - } - if (options.closeThrows) { - throw options.closeThrows - } - if (options.stuck) { - return - } - held.delete(sessionId) - entry.lease.claimStatus = 'released' - entry.lease.deathEvidence = { kind: 'exit-observed', detail: 'closed', observedAt: 1 } - if (options.settledThenThrows) { - throw new Error('the event sink could not be flushed') - } - } - ) - const log = recordingStructuredAgentSessionLogger() - hostRef.current = { - deps: { - logger: log.logger, - store: { - getConversation: (id: string) => - id === SESSION ? agentSessionConversationView(entry) : null, - getSessionTabId: (id: string) => { - if (options.indexThrows) { - throw new Error('visible tab index unreadable') - } - return visible.has(id) ? TAB_ID : null - } - } - }, - getSessionTabId: (id: string) => { - if (options.indexThrows) { - throw new Error('unreadable') - } - return visible.has(id) ? TAB_ID : null - }, - isSessionTabVisible: (id: string) => visible.has(id), - hasSession: (sessionId: string) => held.has(sessionId), - setSessionTabVisibility, - notifySessionTabHidden, - close - } - return { close, setSessionTabVisibility, notifySessionTabHidden, visible, log } -} - -function runtimeFor(retire = vi.fn(() => true)) { - let raw: { worktreeId: string; tabId: string } | null = { - worktreeId: 'repo_1::/tmp/wt-a', - tabId: 'raw-retry' - } - return { - currentLocalStructuredSessionPresentation: () => raw, - captureStructuredAgentSessionPresentation: () => ({ raw, saved: [] }), - retireStructuredAgentSessionTabFromSnapshot: (...args: Parameters) => { - raw = null - return retire(...args) - }, - removeCapturedStructuredSessionSavedTabs: vi.fn() - } -} - -describe('closeStructuredAgentSessionChild admitted surface', () => { - beforeEach(() => { - hostRef.current = null - vi.restoreAllMocks() - }) - - it.each(['false', 'throws', 'unreached'] as const)( - 'does not turn %s admission into success from independent exit proof', - async (mode) => { - const host = installHost({ alreadyReleased: true, skipAdmission: mode === 'unreached' }) - const runtime = runtimeFor() - const afterClose = vi.fn() - const admitClose = vi.fn(() => { - if (mode === 'throws') { - throw new Error('Admission failed') - } - return false - }) - expect( - await closeStructuredAgentSessionChild(SESSION, { runtime, afterClose, admitClose }) - ).toMatchObject({ - stopped: false, - closeAttempted: true - }) - expect(admitClose).toHaveBeenCalledTimes(mode === 'unreached' ? 0 : 1) - expect(afterClose).not.toHaveBeenCalled() - expect(host.visible.has(SESSION)).toBe(true) - expect(host.setSessionTabVisibility).not.toHaveBeenCalled() - expect(runtime.currentLocalStructuredSessionPresentation()).not.toBeNull() - expect(runtime.removeCapturedStructuredSessionSavedTabs).not.toHaveBeenCalled() - } - ) -}) - -it('protects a newer actual raw Retry spelling even while the durable table id is unchanged', async () => { - const host = installHost({ visible: [] }) - const runtime = runtimeFor() - const raw = { worktreeId: 'repo_1::/tmp/wt-a', tabId: 'newer-raw-retry' } - const close = host.close.getMockImplementation()! - host.close.mockImplementation(async (...args) => { - await close(...args) - runtime.currentLocalStructuredSessionPresentation = () => raw - }) - expect(await closeStructuredAgentSessionChild(SESSION, { runtime })).toMatchObject({ - stopped: true - }) - expect(host.setSessionTabVisibility).not.toHaveBeenCalled() - expect(runtime.removeCapturedStructuredSessionSavedTabs).not.toHaveBeenCalled() -}) diff --git a/src/main/runtime/agent-session/structured-agent-session-held-identity-start-failure.test.ts b/src/main/runtime/agent-session/structured-agent-session-held-identity-start-failure.test.ts deleted file mode 100644 index ac9c120b990..00000000000 --- a/src/main/runtime/agent-session/structured-agent-session-held-identity-start-failure.test.ts +++ /dev/null @@ -1,357 +0,0 @@ -import { randomUUID } from 'node:crypto' -import { mkdirSync, writeFileSync } from 'node:fs' -import type { - ClaudeStreamJsonConnection, - ClaudeStreamJsonLaunch, - openClaudeStreamJsonConnection -} from '../../claude/claude-stream-json-connection' -import { readTestHostJournal } from '../../native-chat/agent-session-journal/journal-observation.test-support' -import { scriptedClaudeExitError } from './installation/structured-claude-scripted-runtime-test-support' -import { mkdtemp, rm } from 'node:fs/promises' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import type * as TimersPromises from 'node:timers/promises' -import { afterEach, beforeEach, expect, it, vi } from 'vitest' -import { readWholeAgentSessionFailureFact } from '../../../shared/agent-session/failures/agent-session-failure' -import { computeAgentSessionPayloadFingerprint } from '../../../shared/agent-session/lifecycle/operations/agent-session-mutation-envelope' -import { - hostTestAttachParams, - hostTestMessage, - HOST_TEST_SESSION as SESSION -} from '../../native-chat/agent-session-wire/host/testing/structured-agent-session-host-test-data.test-fixture' -import { createStructuredAgentSessionLogger } from '../../native-chat/agent-session-wire/host/structured-agent-session-logger' -import { piScriptedChild } from '../../pi/rpc/pi-scripted-child.test-fixture' -import { codexScriptedChild } from '../../codex/structured/session-lifecycle/codex-scripted-child.test-fixture' -import type { - ScriptedAgentChild, - ScriptedAgentChildFactory -} from './installation/structured-agent-scripted-child.test-fixture' -import { stopStructuredAgentSessionRuntime } from './structured-agent-session-runtime' -import { ensureTestStructuredAgentSessionHost as ensureStructuredAgentSessionHost } from './records/agent-session-record-store-test-harness' - -// The start retry backoff's promise delay must use the fake clock this suite jumps. -vi.mock('node:timers/promises', async (importOriginal) => ({ - ...(await importOriginal()), - // ast-grep-ignore: test-no-real-time-wait -- Backed by the fake setTimeout installed per test. - setTimeout: (ms?: number) => new Promise((resolve) => setTimeout(resolve, ms)) -})) - -let directory: string | undefined -let operations = 0 -const operationId = () => `${Date.now()}-${(++operations).toString(16).padStart(32, '0')}` -const caller = { callerKey: 'adapter-start-failure-test' } - -beforeEach(() => { - // Real time still passes, so file and database work settles; waits jump the clock. - vi.useFakeTimers({ shouldAdvanceTime: true, toFake: ['setTimeout', 'clearTimeout'] }) -}) - -afterEach(async () => { - vi.useRealTimers() - await stopStructuredAgentSessionRuntime() - if (directory) { - await rm(directory, { recursive: true, force: true }) - directory = undefined - } -}) - -async function failedStart( - agent: 'pi' | 'codex' | 'grok' | 'claude', - script: ScriptedAgentChild, - unanswered = false -) { - directory = await mkdtemp(join(tmpdir(), 'orca-adapter-start-failure-')) - const root = directory - const host = await ensureStructuredAgentSessionHost({ - logger: createStructuredAgentSessionLogger(), - stateDirectory: root, - hostId: 'local', - claimKeyId: 'key-1', - resolveWorkspacePath: async () => root, - resolveClaudeAuthPolicy: () => ({ account: 'managed' }), - resolveLaunchArgs: () => [], - resolveEnvironment: async () => ({ PATH: '' }), - ...script.deps - }) - const expectedAttempts = unanswered || agent === 'grok' || agent === 'claude' ? 5 : 1 - const identities = Array.from({ length: expectedAttempts }, () => ({ - entered: Promise.withResolvers(), - released: Promise.withResolvers() - })) - let recording = 0 - const commitProcessIdentity = host.deps.store.commitProcessIdentity.bind(host.deps.store) - vi.spyOn(host.deps.store, 'commitProcessIdentity').mockImplementation(async (input) => { - const identity = identities[recording++] - if (!identity) { - throw new Error('an unexpected child tried to record its identity') - } - const recorded = commitProcessIdentity(input) - identity.entered.resolve() - await identity.released.promise - return await recorded - }) - const params = hostTestAttachParams( - null, - agent === 'codex' - ? { providerHandle: undefined } - : { - provider: agent, - agent, - providerHandle: undefined, - accountHome: - agent === 'claude' - ? { variable: 'CLAUDE_CONFIG_DIR', path: root } - : agent === 'pi' - ? { variable: 'PI_CODING_AGENT_DIR', path: root } - : { variable: 'GROK_HOME', path: root }, - location: { - executionHostId: 'local', - wslDistro: null, - workspaceId: 'folder-1', - workspaceKind: 'folder' - } - } - ) - params.envelope.clientOperationId = operationId() - const attached = await host.create(caller, params) - if (!attached.ok) { - throw new Error(JSON.stringify(attached.refusal)) - } - const body = hostTestMessage('held during start') - const sent = await host.send(caller, { - envelope: { - sessionId: SESSION, - clientOperationId: operationId(), - expectedRuntimeFence: attached.value.fence, - payloadFingerprint: computeAgentSessionPayloadFingerprint({ - method: 'agentSession.send', - sessionId: SESSION, - fields: { body } - }) - }, - body - }) - if (!sent.ok) { - throw new Error(JSON.stringify(sent.refusal)) - } - for (let attempt = 1; attempt <= expectedAttempts; attempt++) { - // Retries back off 100·2^n ms (800 ms before the fifth spawn); each poll jumps 100 ms. - await vi.waitFor( - () => { - vi.advanceTimersByTime(100) - expect(script.spawns()).toBe(attempt) - }, - { timeout: 5_000, interval: 10 } - ) - const fail = unanswered ? script.exitHandshake : script.failHandshake - if (!fail) { - throw new Error('fixture has no unanswered exit') - } - const identity = identities[attempt - 1]! - await identity.entered.promise - try { - fail('provider config is invalid: bad key') - } finally { - identity.released.resolve() - } - } - const submission = async () => { - await host.flushStreamedEvents(SESSION) - return (await readTestHostJournal(host, SESSION)).submissions.find( - (entry) => entry.clientMessageId === sent.value.clientMessageId - ) - } - await vi.waitFor(async () => expect((await submission())?.dispatchState).toBe('rejected'), { - timeout: 5_000 - }) - const settled = await submission() - const snapshot = await readTestHostJournal(host, SESSION) - const failureKind = agent === 'codex' && !unanswered ? 'startFailed' : 'providerStartFailed' - expect(readWholeAgentSessionFailureFact(settled?.rejection)).toMatchObject({ - kind: failureKind, - detail: { text: 'provider config is invalid: bad key' } - }) - expect( - snapshot.items.filter( - (item) => - item.body.kind === 'status' && - readWholeAgentSessionFailureFact(item.body.failure)?.kind === failureKind - ) - ).toHaveLength(1) - expect(script.prompts()).toEqual([]) - expect(script.spawns()).toBe(expectedAttempts) -} - -it('Claude keeps unanswered early exits within five attempts', async () => { - await failedStart('claude', claudeScriptedChild()) -}) -it('Codex keeps unanswered early exits within five attempts', async () => { - await failedStart('codex', codexScriptedChild(), true) -}) -it('Pi keeps unanswered early exits within five attempts', async () => { - await failedStart('pi', piScriptedChild(), true) -}) - -type Spawned = { - connection: Omit & { - closed: boolean - exitVerdict: ClaudeStreamJsonConnection['exitVerdict'] - } - answer: () => void - fail: (message: string) => void -} - -function promptText(message: Record): string { - const inner = message.message - const content = - inner && typeof inner === 'object' && 'content' in inner ? inner.content : undefined - const blocks = Array.isArray(content) ? content : [] - return blocks - .map((block: unknown) => - block && typeof block === 'object' && 'text' in block ? String(block.text) : '' - ) - .join('') -} - -/** The CLI writes its transcript as a conversation's first message lands; a later start resumes it. */ -function writeTranscript(launch: ClaudeStreamJsonLaunch, providerSessionId: string): void { - const home = launch.env?.CLAUDE_CONFIG_DIR - if (!home) { - return - } - const folder = join(home, 'projects', 'scripted') - mkdirSync(folder, { recursive: true }) - writeFileSync(join(folder, `${providerSessionId}.jsonl`), '{}\n') -} - -const claudeScriptedChild: ScriptedAgentChildFactory = () => { - const spawned: Spawned[] = [] - const prompts: string[] = [] - let resumes = 0 - let closes = 0 - const openConnection: typeof openClaudeStreamJsonConnection = async (launch, handlers = {}) => { - if (launch.options.resume !== undefined) { - resumes += 1 - } - const providerSessionId = String(launch.options.sessionId ?? launch.options.resume) - const initialized = { models: [{ value: 'sonnet', displayName: 'Sonnet' }] } - let answer = (): void => {} - let reject = (_error: Error): void => {} - const init = new Promise((resolve, fail) => { - answer = () => { - handlers.onMessage?.({ - type: 'system', - subtype: 'init', - session_id: providerSessionId, - model: 'claude-sonnet-5', - apiKeySource: 'none' - }) - resolve(initialized) - } - reject = fail - }) - if (!child.holdHandshakes) { - answer() - } - const connection: Spawned['connection'] = { - pid: 7000 + spawned.length, - closed: false, - exitVerdict: { root: 'live', tree: 'unverifiable' }, - initializationResult: () => init, - getContextUsage: async () => ({}), - renameSession: async () => {}, - getSettings: async () => ({ effective: {} }), - supportedModels: async () => [{ value: 'sonnet', displayName: 'Sonnet' }], - setModel: async () => {}, - setPermissionMode: async () => {}, - applyFlagSettings: async () => {}, - interrupt: async () => undefined, - cancelAsyncMessage: async () => false, - stopTask: async () => {}, - backgroundTask: async () => false, - send: async (message, beforeDispatch) => { - await beforeDispatch?.() - prompts.push(promptText(message)) - writeTranscript(launch, providerSessionId) - // The CLI echoes each message it takes under the client's uuid: Orca's proof of delivery. - handlers.onMessage?.({ - type: 'user', - session_id: providerSessionId, - parent_tool_use_id: null, - uuid: message.uuid, - isReplay: true, - message: message.message - }) - if (child.completeTurns) { - const id = randomUUID() - handlers.onMessage?.({ - type: 'assistant', - parent_tool_use_id: null, - message: { - id: `msg-${id}`, - role: 'assistant', - content: [{ type: 'text', text: 'done' }] - }, - session_id: providerSessionId - }) - handlers.onMessage?.({ - type: 'result', - subtype: 'success', - is_error: false, - session_id: providerSessionId, - uuid: id - }) - } - }, - close: async () => { - if (!connection.closed) { - connection.closed = true - closes += 1 - connection.exitVerdict = { root: 'exited', tree: 'exited' } - handlers.onExit?.(new Error('closed by Orca')) - } - return true - } - } - spawned.push({ - connection, - answer, - fail: (message) => { - const error = scriptedClaudeExitError(message) - connection.closed = true - connection.exitVerdict = { root: 'exited', tree: 'unverifiable' } - reject(error) - handlers.onExit?.(error) - } - }) - return connection - } - const newest = (): Spawned => { - const latest = spawned.at(-1) - if (!latest) { - throw new Error('no Claude child was spawned') - } - return latest - } - const child: ScriptedAgentChild = { - deps: { - openClaudeConnection: openConnection, - readProcessStartTime: async (pid) => - spawned.find((entry) => entry.connection.pid === pid)?.connection.exitVerdict.root === - 'exited' - ? null - : pid * 10, - resolveClaudeCommand: () => ({ command: '/nonexistent/scripted-claude', prefixArgs: [] }), - resolveClaudeAuthPolicy: () => ({ account: 'system' }) - }, - holdHandshakes: true, - releaseHandshake: () => newest().answer(), - failHandshake: (message) => newest().fail(message), - completeTurns: true, - prompts: () => prompts, - spawns: () => spawned.length, - resumes: () => resumes, - closes: () => closes - } - return child -} diff --git a/src/main/runtime/agent-session/structured-agent-session-host-refusal.test.ts b/src/main/runtime/agent-session/structured-agent-session-host-refusal.test.ts deleted file mode 100644 index 48e37213d87..00000000000 --- a/src/main/runtime/agent-session/structured-agent-session-host-refusal.test.ts +++ /dev/null @@ -1,91 +0,0 @@ -// Journal-open refusal leaves the file intact and other runtime work available. - -import { createHash } from 'node:crypto' -import { existsSync } from 'node:fs' -import { mkdtemp, readFile, rm, unlink, writeFile } from 'node:fs/promises' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { isAgentSessionRefusalError } from '../../../shared/agent-session/failures/agent-session-wire-refusals' -import { journalDatabasePath } from '../../native-chat/agent-session-journal/database/journal-host-database' -import { requireStructuredHost } from '../rpc/methods/structured-sessions/creation/structured-agent-session-gate' -import type { RpcContext } from '../rpc/core' -import { stopStructuredAgentSessionRuntime } from './structured-agent-session-runtime' -import { ensureTestStructuredAgentSessionHost as ensureStructuredAgentSessionHost } from './records/agent-session-record-store-test-harness' -import { recordingStructuredAgentSessionLogger } from '../../native-chat/agent-session-wire/host/testing/structured-agent-session-logger.test-fixture' -import { closeTestJournalHostDatabases } from '../../native-chat/agent-session-journal/store-lifecycle/journal-host-database-test-support' - -let root: string -let log = recordingStructuredAgentSessionLogger() - -// An in-process caller: the same build as the host, so the gate asks it for no capability. -// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the gate reads only `clientKind` and `clientCapabilities`. -const IN_PROCESS = {} as RpcContext - -function install(): ReturnType { - return ensureStructuredAgentSessionHost({ - logger: log.logger, - stateDirectory: root, - hostId: 'local', - claimKeyId: 'key-1', - resolveWorkspacePath: async () => root, - resolveEnvironment: async () => ({}), - resolveLaunchArgs: () => [], - resolveClaudeAuthPolicy: () => ({ account: 'managed' }) - }) -} - -/** The refusal as the gate throws it for every structured request. */ -function gateRefusal(): { reason: unknown; message: string } { - try { - requireStructuredHost(IN_PROCESS) - } catch (error) { - if (isAgentSessionRefusalError(error)) { - return { reason: error.refusal.details?.reason, message: error.refusal.message } - } - throw error - } - throw new Error('the gate admitted the request') -} - -async function digest(path: string): Promise { - return createHash('sha256') - .update(await readFile(path)) - .digest('hex') -} - -beforeEach(async () => { - root = await mkdtemp(join(tmpdir(), 'orca-journal-host-refusal-')) - log = recordingStructuredAgentSessionLogger() -}) - -afterEach(async () => { - await stopStructuredAgentSessionRuntime().catch(() => undefined) - vi.restoreAllMocks() - await closeTestJournalHostDatabases() - await rm(root, { recursive: true, force: true }) -}) - -describe('a process whose journal will not open', () => { - it('refuses every chat and leaves a damaged file exactly as it is', async () => { - const path = journalDatabasePath(root) - await writeFile(path, 'not a database '.repeat(512)) - const before = await digest(path) - vi.spyOn(console, 'warn').mockImplementation(() => undefined) - - await expect(install()).rejects.toMatchObject({ - refusal: { message: 'Unable to load this chat.', details: { reason: 'journalCorrupt' } } - }) - expect(gateRefusal()).toEqual({ - reason: 'journalCorrupt', - message: 'Unable to load this chat.' - }) - expect(await digest(path)).toBe(before) - expect(existsSync(`${path}-wal`)).toBe(false) - expect(existsSync(`${path}-shm`)).toBe(false) - - await unlink(path) - await expect(install()).resolves.toBeDefined() - expect(gateRefusal).toThrow('the gate admitted the request') - }) -}) diff --git a/src/main/runtime/agent-session/structured-agent-session-legacy-send-behind-command.test.ts b/src/main/runtime/agent-session/structured-agent-session-legacy-send-behind-command.test.ts deleted file mode 100644 index 4311d8a0c03..00000000000 --- a/src/main/runtime/agent-session/structured-agent-session-legacy-send-behind-command.test.ts +++ /dev/null @@ -1,107 +0,0 @@ -import { readTestHostJournal } from '../../native-chat/agent-session-journal/journal-observation.test-support' -// Clients without accepted-send support wait for handover; sends queued behind compact must answer when queued to avoid the phone timeout. - -import { afterEach, beforeEach, expect, it, vi } from 'vitest' -import type { AgentSessionSendResult } from '../../../shared/agent-session/agent-session-wire' -import { ensureTestStructuredAgentSessionHost as ensureStructuredAgentSessionHost } from './records/agent-session-record-store-test-harness' -import { - openStructuredCodexRpcHarness, - SESSION, - THREAD, - type FakeCodexConnection, - type StructuredCodexRpcHarness -} from '../rpc/methods/structured-sessions/structured-codex-session-rpc-test-harness' - -const COMPACTION_TURN = 'compaction-turn' -// Far under the phone's 15 s send timeout, and far over a handover that is already due. -const PROMPT_REPLY_MS = 2_000 - -let harness: StructuredCodexRpcHarness - -beforeEach(async () => { - // The harness's default client is the phone's: pending replies, but not accepted-send. - harness = await openStructuredCodexRpcHarness() -}) - -afterEach(async () => { - await harness.dispose() -}) - -function calls(method: string): FakeCodexConnection[] { - return harness.codex.connections.flatMap((connection) => - connection.calls.filter((entry) => entry.method === method).map(() => connection) - ) -} - -function send(text: string): Promise { - const body = { kind: 'message' as const, role: 'user' as const, blocks: [{ type: 'text', text }] } - return harness.ok('agentSession.send', { - envelope: harness.envelope('agentSession.send', { body }, null), - body - }) -} - -function promptly(reply: Promise): Promise { - return Promise.race([ - reply, - new Promise((_, reject) => - setTimeout(() => reject(new Error('the send reply waited out the command')), PROMPT_REPLY_MS) - ) - ]) -} - -it('answers a send queued behind /compact at once, and delivers it once after the compaction', async () => { - const created = await harness.ok<{ fence: number }>( - 'agentSession.create', - harness.createIntentParams() - ) - await harness.ok('agentSession.conversationCommand', { - command: 'compact', - envelope: harness.envelope( - 'agentSession.conversationCommand', - { command: 'compact' }, - created.fence - ) - }) - await vi.waitFor(() => expect(calls('thread/compact/start')).toHaveLength(1)) - - const answer = await promptly(send('after the compaction')) - expect(answer).toMatchObject({ queued: { state: 'waiting' } }) - if (!('queued' in answer)) { - throw new Error('expected a queued send') - } - expect(calls('turn/start')).toHaveLength(0) - - harness.codex.notify('turn/started', { threadId: THREAD, turn: { id: COMPACTION_TURN } }) - harness.codex.notify('item/completed', { - threadId: THREAD, - turnId: COMPACTION_TURN, - item: { type: 'contextCompaction', id: 'compaction' } - }) - harness.codex.notify('turn/completed', { - threadId: THREAD, - turn: { id: COMPACTION_TURN, status: 'completed' } - }) - - await vi.waitFor(() => expect(calls('turn/start')).toHaveLength(1)) - const journal = await readTestHostJournal( - await ensureStructuredAgentSessionHost(harness.hostConfig()), - SESSION - ) - expect( - journal.submissions.filter((entry) => entry.queuedMessageId === answer.queued.messageId) - ).toEqual([expect.objectContaining({ handedOverAt: expect.any(Number) })]) - await new Promise((resolve) => setTimeout(resolve, 50)) - expect(calls('turn/start')).toHaveLength(1) -}) - -it('still holds the reply of a send that no command is holding until it is handed over', async () => { - await harness.ok('agentSession.create', harness.createIntentParams()) - - const answer = await promptly(send('first message')) - if (!('submission' in answer)) { - throw new Error('expected a direct send') - } - expect(answer.submission.handedOverAt).toEqual(expect.any(Number)) - await vi.waitFor(() => expect(calls('turn/start')).toHaveLength(1)) -}) diff --git a/src/main/runtime/agent-session/structured-agent-session-runtime-provider-started.test.ts b/src/main/runtime/agent-session/structured-agent-session-runtime-provider-started.test.ts deleted file mode 100644 index 00366382d9d..00000000000 --- a/src/main/runtime/agent-session/structured-agent-session-runtime-provider-started.test.ts +++ /dev/null @@ -1,92 +0,0 @@ -// Record Claude startup evidence already held by the adapter; never block session operations on another start or a stalled CLI control read. - -import { afterEach, describe, expect, it, vi } from 'vitest' -import { waitForStructuredAgentSessionRecovery } from './structured-agent-session-runtime' -import { createScriptedClaudeRuntime } from './installation/structured-claude-scripted-runtime-test-support' - -const STALLED = 'claude-started-stalled' -const HEALTHY = 'claude-started-healthy' -const CALLER = { callerKey: 'client-1' } - -let claude = createScriptedClaudeRuntime([STALLED, HEALTHY]) - -afterEach(async () => { - vi.restoreAllMocks() - await claude.dispose() - claude = createScriptedClaudeRuntime([STALLED, HEALTHY]) -}) - -describe('a Claude child proving its start', () => { - it("never holds another session's start, or its own close, on a CLI read", async () => { - claude.behave(STALLED, { stallsControlReads: true }) - const host = await claude.install() - - await expect(host.attach(CALLER, claude.attachParams(HEALTHY, null))).resolves.toMatchObject({ - ok: true - }) - await waitForStructuredAgentSessionRecovery() - - // This child answers startup, then never answers another control read. - await expect(host.attach(CALLER, claude.attachParams(STALLED, null))).resolves.toMatchObject({ - ok: true - }) - await vi.waitFor(() => expect(claude.child(STALLED).calls).toContain('get_settings')) - await vi.waitFor(() => - expect(host.collaboratorsForTests().sessions.get(STALLED)?.child?.phase).toBe('ready') - ) - - claude.child(HEALTHY).exit(new Error('claude stream-json exited (code 1): crashed')) - await vi.waitFor(() => - expect(host.deps.store.getRecord(HEALTHY)?.lease.claimStatus).toBe('released') - ) - - await vi.waitFor(() => - expect(host.collaboratorsForTests().sessions.get(STALLED)?.child?.phase).toBe('ready') - ) - expect(host.deps.store.getRecord(STALLED)?.options).toBeUndefined() - expect(host.deps.store.getRecord(STALLED)?.providerHandleChain).toHaveLength(1) - expect(claude.child(STALLED).calls).toEqual(['get_settings']) - - let closed = false - void host.close(STALLED, 'evict').then(() => { - closed = true - }) - await vi.waitFor(() => expect(closed).toBe(true)) - }) - - it("flips to ready while another session's start is still acquiring", async () => { - const host = await claude.install() - // This start never returns from its spawn, so its lease stays reserved with no child. - claude.behave(HEALTHY, { spawnHangs: true }) - void host.attach(CALLER, claude.attachParams(HEALTHY, null)).catch(() => undefined) - await vi.waitFor(() => - expect(host.deps.store.getRecord(HEALTHY)?.lease.claimStatus).toBe('reserved') - ) - const childrenWhileHung = claude.children(HEALTHY).length - - await expect(host.attach(CALLER, claude.attachParams(STALLED, null))).resolves.toMatchObject({ - ok: true - }) - await vi.waitFor(() => - expect(host.collaboratorsForTests().sessions.get(STALLED)?.child?.phase).toBe('ready') - ) - expect(host.deps.store.getRecord(HEALTHY)?.lease.claimStatus).toBe('reserved') - expect(claude.children(HEALTHY)).toHaveLength(childrenWhileHung) - }) - - it('records the proven start without overwriting saved choices with provider reports', async () => { - const host = await claude.install() - const replaceOptions = vi.spyOn(host.deps.store, 'replaceSessionOptions') - const saved = { model: 'opus', effort: 'low' } - await expect( - host.attach(CALLER, claude.attachParams(HEALTHY, null, { options: saved })) - ).resolves.toMatchObject({ ok: true }) - await vi.waitFor(() => - expect(host.collaboratorsForTests().sessions.get(HEALTHY)?.child?.phase).toBe('ready') - ) - - expect(host.deps.store.getRecord(HEALTHY)?.providerHandleChain).toHaveLength(1) - expect(host.deps.store.getRecord(HEALTHY)?.options).toEqual(saved) - expect(replaceOptions).not.toHaveBeenCalled() - }) -}) diff --git a/src/main/runtime/agent-session/structured-agent-session-runtime.test.ts b/src/main/runtime/agent-session/structured-agent-session-runtime.test.ts deleted file mode 100644 index b3993228074..00000000000 --- a/src/main/runtime/agent-session/structured-agent-session-runtime.test.ts +++ /dev/null @@ -1,110 +0,0 @@ -import { readFileSync } from 'node:fs' -import { mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises' -import { tmpdir } from 'node:os' -import { basename, join } from 'node:path' -import { afterEach, describe, expect, it, vi } from 'vitest' -import type { AgentSessionRecord } from '../../../shared/agent-session/lifecycle/agent-session-record' - -import { - ensureStructuredAgentSessionHost, - stopStructuredAgentSessionRuntime -} from './structured-agent-session-runtime' -import { seedTestAgentSessionRecordStore } from './records/agent-session-record-store-persistence.test-fixture' -import { nativeChatScratchFolderFor } from '../../native-chat/conversation-files/native-chat-scratch-folder' -import { foundAgentSessionRecord } from './records/agent-session-record-founding' -import { closeTestJournalHostDatabases } from '../../native-chat/agent-session-journal/store-lifecycle/journal-host-database-test-support' -import { recordingStructuredAgentSessionLogger } from '../../native-chat/agent-session-wire/host/testing/structured-agent-session-logger.test-fixture' -import { onStructuredAgentSessionsHeldChanged } from '../../native-chat/agent-session-wire/host/structured-agent-session-registry' -import { openAgentSessionRecordStoreOnce } from './records/agent-session-record-store-slot' -import { - journalSqlReaderPath, - journalSqlWorkerPath -} from '../../native-chat/agent-session-journal/journal-sql-worker-bundle.test-fixture' - -const HOST_ID = 'local' - -describe('structured agent-session runtime install', () => { - let stateDirectory: string | null = null - - afterEach(async () => { - await stopStructuredAgentSessionRuntime() - if (stateDirectory) { - await closeTestJournalHostDatabases() - await rm(stateDirectory, { recursive: true, force: true }) - stateDirectory = null - } - vi.restoreAllMocks() - }) - - function oldChat(provider: 'claude' | 'codex'): AgentSessionRecord { - return foundAgentSessionRecord( - { - sessionId: `old-${provider}`, - provider, - location: { - executionHostId: HOST_ID, - workspaceId: 'folder-1', - workspaceKind: 'folder', - wslDistro: null - }, - accountHome: { - variable: provider === 'claude' ? 'CLAUDE_CONFIG_DIR' : 'CODEX_HOME', - path: '/account' - } - }, - { claimKeyId: 'key-1', now: 1 } - ) - } - - async function installOver( - fullAccessAgents: readonly string[], - logger = recordingStructuredAgentSessionLogger().logger - ) { - await openAgentSessionRecordStoreOnce({ - stateDirectory: stateDirectory!, - hostId: HOST_ID, - logger, - legacySessionTabIds: [], - writerPath: journalSqlWorkerPath(), - readerPath: journalSqlReaderPath(), - onMaintenanceTick: () => {} - }) - return await ensureStructuredAgentSessionHost({ - logger, - stateDirectory: stateDirectory!, - hostId: HOST_ID, - claimKeyId: 'key-1', - resolveWorkspacePath: async () => stateDirectory!, - resolveLaunchArgs: () => [], - resolveClaudeAuthPolicy: () => ({ account: 'managed' }), - resolveAgentFullAccess: (agent) => fullAccessAgents.includes(agent), - resolveEnvironment: async () => ({}) - }) - } - - it('moves pre-rename chat visuals under the current root before the host is readable', async () => { - stateDirectory = await mkdtemp(join(tmpdir(), 'orca-structured-runtime-visuals-')) - await seedTestAgentSessionRecordStore(stateDirectory, { records: [oldChat('codex')] }) - const current = nativeChatScratchFolderFor(stateDirectory, 'old-codex') - const legacy = join(stateDirectory, 'native-chat-visuals', basename(current)) - await mkdir(legacy, { recursive: true }) - await writeFile(join(legacy, 'chart.html'), '

chart

') - - let readableAtPublication = false - const stopListening = onStructuredAgentSessionsHeldChanged((held) => { - if (held) { - readableAtPublication = readFileSync(join(current, 'chart.html'), 'utf8') === '

chart

' - } - }) - try { - const host = await installOver(['codex']) - expect(host.deps.store.getRecord('old-codex')?.permissionMode).toBe('full-access') - expect((await host.readOptions('old-codex')).current.permissionMode).toBe('full-access') - } finally { - stopListening() - } - - expect(readableAtPublication).toBe(true) - expect(await readFile(join(current, 'chart.html'), 'utf8')).toBe('

chart

') - }) -}) diff --git a/src/main/runtime/agent-session/structured-agent-session-startup-reconcile.test.ts b/src/main/runtime/agent-session/structured-agent-session-startup-reconcile.test.ts deleted file mode 100644 index 1be8dc83231..00000000000 --- a/src/main/runtime/agent-session/structured-agent-session-startup-reconcile.test.ts +++ /dev/null @@ -1,113 +0,0 @@ -// Newer records reconcile read-only in memory. - -import { readFile, mkdtemp, rm, writeFile } from 'node:fs/promises' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { afterEach, beforeEach, expect, it, vi } from 'vitest' -import { agentSessionRecordFixture } from '../../../shared/agent-session/lifecycle/records/agent-session-record.test-fixture' -import { journalDomainDatabasePath } from '../../native-chat/agent-session-journal/database/journal-domain-database' -import { JournalSqlDatabase } from '../../native-chat/agent-session-journal/database/journal-sql-database' -import { getStructuredAgentSessionHost } from '../../native-chat/agent-session-wire/host/structured-agent-session-registry' -import { - ensureTestStructuredAgentSessionHost as ensureStructuredAgentSessionHost, - openTestAgentSessionRecordStoreSlot, - seedTestAgentSessionStoreFromNewerBuild -} from './records/agent-session-record-store-test-harness' -import { seedTestAgentSessionRecordStore } from './records/agent-session-record-store-persistence.test-fixture' -import { closeTestJournalHostDatabases } from '../../native-chat/agent-session-journal/store-lifecycle/journal-host-database-test-support' -import { OrcaRuntimeService } from '../orca-runtime' -import { stopStructuredAgentSessionRuntime } from './structured-agent-session-runtime' -import { - recordStructuredAgentSessionHostInstallRefusal, - structuredAgentSessionHostRefusal -} from './structured-agent-session-host-refusal' -import { recordingStructuredAgentSessionLogger } from '../../native-chat/agent-session-wire/host/testing/structured-agent-session-logger.test-fixture' - -let root: string - -beforeEach(async () => { - root = await mkdtemp(join(tmpdir(), 'orca-startup-reconcile-')) -}) - -afterEach(async () => { - vi.restoreAllMocks() - recordStructuredAgentSessionHostInstallRefusal(null) - await stopStructuredAgentSessionRuntime().catch(() => undefined) - await closeTestJournalHostDatabases() - await rm(root, { recursive: true, force: true }) -}) - -/** A profile with one chat whose last owner is gone; `newer` stamps it as a newer Orca's. */ -async function seedChat(options: { newer?: boolean } = {}) { - const record = agentSessionRecordFixture() - await seedTestAgentSessionRecordStore(root, { records: [record] }) - if (options.newer) { - await seedTestAgentSessionStoreFromNewerBuild(root) - } - await closeTestJournalHostDatabases() - return { path: journalDomainDatabasePath(root), sessionId: record.sessionId } -} - -function startupRuntime(log = recordingStructuredAgentSessionLogger()) { - const runtime = new OrcaRuntimeService() - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: these are the runtime's own protected members; the test roots the host at `root` and stubs the PTY daemon. - const internal = runtime as unknown as { - hasPersistedStructuredAgentSessionStore(): boolean - ensureStructuredAgentSessionHost(): Promise - refreshMobileSessionPtyRecords(): Promise | null> - } - internal.hasPersistedStructuredAgentSessionStore = () => true - internal.ensureStructuredAgentSessionHost = () => - ensureStructuredAgentSessionHost({ - logger: log.logger, - stateDirectory: root, - hostId: 'local', - claimKeyId: 'key-1', - resolveWorkspacePath: async () => root, - resolveEnvironment: async () => ({}), - resolveLaunchArgs: () => [], - resolveClaudeAuthPolicy: () => ({ account: 'managed' }) - }) - internal.refreshMobileSessionPtyRecords = async () => new Set() - return runtime -} - -it('finishes startup over records a newer Orca wrote, reads them, and writes nothing', async () => { - const { path, sessionId } = await seedChat({ newer: true }) - const bytes = await readFile(path) - const log = recordingStructuredAgentSessionLogger() - const runtime = startupRuntime(log) - - await expect(runtime.prepareStructuredAgentSessionStartupRestoration()).resolves.toBeUndefined() - - expect(log.entries).toEqual([]) - const host = getStructuredAgentSessionHost() - expect(host?.sessionAgent(sessionId)).toBe('claude') - // Adjudicated in memory only: the verdict is re-derived at the next start. - expect(host?.deps.store.getRecord(sessionId)?.lease.unreconciled).toBe(false) - await stopStructuredAgentSessionRuntime() - expect(await readFile(path)).toEqual(bytes) -}) - -it('does not open the journal again before RPC after this startup refused it', async () => { - await writeFile(journalDomainDatabasePath(root), 'not a database') - const open = vi.spyOn(JournalSqlDatabase, 'open') - const opened = openTestAgentSessionRecordStoreSlot({ - stateDirectory: root, - legacySessionTabIds: [], - hostId: 'local', - logger: recordingStructuredAgentSessionLogger().logger - }) - opened.catch(() => {}) - const runtime = startupRuntime() - runtime.beginStructuredAgentSessionStartupOpen(Promise.resolve(), { - legacySessionTabIds: [], - persisted: true, - opened - }) - - await expect(runtime.prepareStructuredAgentSessionStartupRestoration()).resolves.toBeUndefined() - - expect(structuredAgentSessionHostRefusal()).not.toBeNull() - expect(open).toHaveBeenCalledTimes(1) -}) diff --git a/src/main/runtime/browser/tabs/browser-session-tab-selection-snapshot.ts b/src/main/runtime/browser/tabs/browser-session-tab-selection-snapshot.ts index 0523af2f7e4..02a13e64edb 100644 --- a/src/main/runtime/browser/tabs/browser-session-tab-selection-snapshot.ts +++ b/src/main/runtime/browser/tabs/browser-session-tab-selection-snapshot.ts @@ -1,5 +1,5 @@ import type { RuntimeMobileSessionTabsSnapshot } from '../../../../shared/remote-runtime/session-graph/runtime-session-contracts' -import { selectMobileSessionTab } from '../../session-tabs/mobile-session-tab-selection' +import { selectMobileSessionTab } from '../../session-tabs/layout/mobile-session-tab-selection' type SessionTabGroup = NonNullable[number] diff --git a/src/main/runtime/construction/runtime-identity-state.ts b/src/main/runtime/construction/runtime-identity-state.ts index ec1f384efaf..7fc4da99701 100644 --- a/src/main/runtime/construction/runtime-identity-state.ts +++ b/src/main/runtime/construction/runtime-identity-state.ts @@ -1,6 +1,6 @@ import type { TerminalIdentitySource } from '../terminal/identity/terminal-identity-source' import * as savedChatOpen from '../agent-session/records/local-agent-session-record-store-startup-open' -import type { SessionTitlePublisher } from '../session-tabs/session-title-publisher' +import type { SessionTitlePublisher } from '../session-tabs/publication/session-title-publisher' import { randomUUID } from 'node:crypto' import { mainBindsUnendedTerminal } from '../terminal/surface/main-pane-verdict' import type { TuiAgent } from '../../../shared/agent-launch/catalog/tui-agent' diff --git a/src/main/runtime/files/paths/markdown-tab-disk-documents.ts b/src/main/runtime/files/paths/markdown-tab-disk-documents.ts index 50a33de59ef..9abe253e466 100644 --- a/src/main/runtime/files/paths/markdown-tab-disk-documents.ts +++ b/src/main/runtime/files/paths/markdown-tab-disk-documents.ts @@ -19,7 +19,7 @@ import type { PersistedOpenFile, WorkspaceSessionState } from '../../../../shared/workspace-session/workspace-session-state-types' -import { findListedEditorFile } from '../../session-tabs/headless-editor-tabs' +import { findListedEditorFile } from '../../session-tabs/restoration/headless-editor-tabs' export type MarkdownDiskFile = { content: string; byteLength: number } diff --git a/src/main/runtime/files/paths/runtime-markdown-tab-operations.ts b/src/main/runtime/files/paths/runtime-markdown-tab-operations.ts index 9d4f65381a0..a26c1b68128 100644 --- a/src/main/runtime/files/paths/runtime-markdown-tab-operations.ts +++ b/src/main/runtime/files/paths/runtime-markdown-tab-operations.ts @@ -1,4 +1,4 @@ -import type { OrcaRuntimeWithScheduleMobileSessionTabsChanged } from '../../session-tabs/session-tabs-change-publication' +import type { OrcaRuntimeWithScheduleMobileSessionTabsChanged } from '../../session-tabs/publication/session-tabs-change-publication' import type { RuntimeMarkdownReadTabResult, RuntimeMarkdownSaveTabResult @@ -12,7 +12,7 @@ import { type MarkdownTabDiskHost } from './markdown-tab-disk-documents' import { createMarkdownTabDiskHost } from './markdown-tab-disk-host' -import { RuntimeMobileSessionTabOrder } from '../../session-tabs/mobile-session-tab-order' +import { RuntimeMobileSessionTabOrder } from '../../session-tabs/layout/mobile-session-tab-order' export abstract class RuntimeMarkdownTabOperations extends RuntimeMobileSessionTabOrder { abstract resolveRuntimeFileTarget(worktreeSelector: string): Promise<{ worktree: ResolvedWorktree 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 b5f5a0db42b..cb666318f84 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 @@ -90,7 +90,7 @@ import { addWorktree } from '../../git/worktrees/creation/worktree-add' import { advertisedUrlWatcher } from '../../ports/advertised-url-watcher' import { afterAll, afterEach, beforeAll, beforeEach, vi, type MockInstance } from 'vitest' import { initOrcaProfilePaths } from '../../orca-profiles/profile-storage-paths' -import { stopStructuredAgentSessionRuntime } from '../agent-session/structured-agent-session-runtime' +import { stopStructuredAgentSessionRuntime } from '../agent-session/installation/structured-agent-session-runtime' import { assertWorktreeCleanForRemoval } from '../../git/worktrees/removal/worktree-removal-preflight' import { __cancelLegacyWorkerTerminalRecoveryRetriesForTests as cancelLegacyWorkerTerminalRecoveryRetriesForTests } from '../orchestration/terminal-authority/runtime-legacy-worker-terminal-recovery-controller' import { clearConfiguredWorktreeSharedDirectoriesCacheForTests } from '../../git/worktrees/content-paths/worktree-shared-directories' diff --git a/src/main/runtime/orchestration/terminal-authority/legacy-worker-runtime-recovery.ts b/src/main/runtime/orchestration/terminal-authority/legacy-worker-runtime-recovery.ts index ea1b2c395c3..e75a88491eb 100644 --- a/src/main/runtime/orchestration/terminal-authority/legacy-worker-runtime-recovery.ts +++ b/src/main/runtime/orchestration/terminal-authority/legacy-worker-runtime-recovery.ts @@ -3,7 +3,7 @@ import type { LegacyWorkerTerminalRecoveryPlan } from './release/orchestration-l import type { LegacyWorkerTerminalRecoveryResult } from './structured-sessions/runtime-legacy-worker-terminal-recovery-types' import { RuntimeWorkspaceSessionFlush } from '../../workspaces/session-hosts/runtime-workspace-session-flush' import { StartupWorkerAuthorityRestore } from './startup-worker-authority-restore' -import type { OrcaRuntimeWithGetStructuredAgentSessionCreateSupport as StructuredSessionStartup } from '../../session-tabs/structured-session-create-support' +import type { OrcaRuntimeWithGetStructuredAgentSessionCreateSupport as StructuredSessionStartup } from '../../session-tabs/chat/structured-session-create-support' export abstract class LegacyWorkerRuntimeRecovery extends RuntimeWorkspaceSessionFlush { protected abstract getResolvedWorktreeMap(): Promise> diff --git a/src/main/runtime/orchestration/terminal-authority/release/worker-terminal-release-runtime.ts b/src/main/runtime/orchestration/terminal-authority/release/worker-terminal-release-runtime.ts index 1ae95fe6a16..b97410a9b08 100644 --- a/src/main/runtime/orchestration/terminal-authority/release/worker-terminal-release-runtime.ts +++ b/src/main/runtime/orchestration/terminal-authority/release/worker-terminal-release-runtime.ts @@ -1,5 +1,5 @@ import type { OrcaRuntimeService } from '../../../orca-runtime' -import type { StructuredSessionSurfaceRuntime } from '../../../agent-session/structured-agent-session-close' +import type { StructuredSessionSurfaceRuntime } from '../../../agent-session/lifecycle/structured-agent-session-close' export type WorkerTerminalReleaseRuntime = StructuredSessionSurfaceRuntime & Pick< diff --git a/src/main/runtime/orchestration/terminal-authority/structured-sessions/structured-chat-coordinator-mail-rig.test-fixture.ts b/src/main/runtime/orchestration/terminal-authority/structured-sessions/structured-chat-coordinator-mail-rig.test-fixture.ts index 1f3fef043e7..4abcee17be2 100644 --- a/src/main/runtime/orchestration/terminal-authority/structured-sessions/structured-chat-coordinator-mail-rig.test-fixture.ts +++ b/src/main/runtime/orchestration/terminal-authority/structured-sessions/structured-chat-coordinator-mail-rig.test-fixture.ts @@ -23,7 +23,7 @@ import { OrchestrationDb } from '../../db/orchestration-db' import { RpcDispatcher } from '../../../rpc/dispatcher' import { ORCHESTRATION_METHODS } from '../../../rpc/methods/orchestration/orchestration' import { idOf, resultOf } from '../../../rpc/orchestration/callers/session.test-fixture' -import { stopStructuredAgentSessionRuntime } from '../../../agent-session/structured-agent-session-runtime' +import { stopStructuredAgentSessionRuntime } from '../../../agent-session/installation/structured-agent-session-runtime' import { ensureTestStructuredAgentSessionHost as ensureStructuredAgentSessionHost } from '../../../agent-session/records/agent-session-record-store-test-harness' import { createCoordinatorMailObservationClock } from './structured-chat-coordinator-observation-clock.test-fixture' import { diff --git a/src/main/runtime/orchestration/terminal-authority/structured-sessions/structured-chat-coordinator-observation-clock.test-fixture.ts b/src/main/runtime/orchestration/terminal-authority/structured-sessions/structured-chat-coordinator-observation-clock.test-fixture.ts index 5e407b9fcd0..e4ea025565a 100644 --- a/src/main/runtime/orchestration/terminal-authority/structured-sessions/structured-chat-coordinator-observation-clock.test-fixture.ts +++ b/src/main/runtime/orchestration/terminal-authority/structured-sessions/structured-chat-coordinator-observation-clock.test-fixture.ts @@ -3,7 +3,7 @@ import type { StructuredAgentSessionHost } from '../../../../native-chat/agent-s import { OrchestrationStructuredMailboxPointerDelivery } from '../../mailbox/structured-pointer/structured-mailbox-pointer-delivery' import { StructuredAgentSessionStatusFeed } from '../../../../native-chat/agent-session-wire/observations/structured-agent-session-status-feed' import type { OrcaRuntimeService } from '../../../orca-runtime' -import { waitForStructuredAgentSessionRecovery } from '../../../agent-session/structured-agent-session-runtime' +import { waitForStructuredAgentSessionRecovery } from '../../../agent-session/installation/structured-agent-session-runtime' import { awakeNow, createAwakeClock, type AwakeClock } from '../../../../power/awake-clock' import type * as AwakeClockModule from '../../../../power/awake-clock' diff --git a/src/main/runtime/orchestration/terminal-authority/structured-sessions/structured-chat-dispatch-worker-lifecycle.test.ts b/src/main/runtime/orchestration/terminal-authority/structured-sessions/structured-chat-dispatch-worker-lifecycle.test.ts deleted file mode 100644 index dbef33aaea6..00000000000 --- a/src/main/runtime/orchestration/terminal-authority/structured-sessions/structured-chat-dispatch-worker-lifecycle.test.ts +++ /dev/null @@ -1,236 +0,0 @@ -import { execFile } from 'node:child_process' -import { createRequire } from 'node:module' -import { join } from 'node:path' -import { pathToFileURL } from 'node:url' -import { promisify } from 'node:util' -import '../../../rpc/dispatch/testing/unused-default-rpc-methods.test-fixture' - -import { describe, expect, it, vi } from 'vitest' -import { formatOrcaSessionAddress } from '../../../../../shared/agent-session/identity/orca-session-address' -import { testOrcaSessionId } from '../../../../../shared/agent-session/identity/orca-session-address-test-fixture' -import { idOf } from '../../../rpc/orchestration/callers/session.test-fixture' -import { closeStructuredAgentSessionChild } from '../../../agent-session/structured-agent-session-close' -import { OrcaRuntimeRpcServer } from '../../../rpc/server/runtime-rpc' -import { ORCHESTRATION_METHODS } from '../../../rpc/methods/orchestration/orchestration' -import type { FakeConnection } from './structured-chat-coordinator-fake-codex-fixture' -import { - COORDINATOR, - PEER_CHAT, - WAIT, - call, - coordinatorRunAndTask, - db, - host, - openChat, - sendUserMessage, - settleTurn, - codex, - runtime, - root -} from './structured-chat-coordinator-mail-rig.test-fixture' - -const WORKER = formatOrcaSessionAddress(testOrcaSessionId(PEER_CHAT)) - -const cliPath = join(process.cwd(), 'src/cli/index.ts') -const tsxLoader = pathToFileURL(createRequire(import.meta.url).resolve('tsx')).href - -async function readWorkerThroughCli(dispatchId: string): Promise { - const env = { ...process.env } - for (const name of [ - 'HOME', - 'USERPROFILE', - 'APPDATA', - 'LOCALAPPDATA', - 'XDG_CONFIG_HOME', - 'XDG_CACHE_HOME', - 'XDG_DATA_HOME', - 'XDG_STATE_HOME', - 'XDG_RUNTIME_DIR', - 'CLAUDE_CONFIG_DIR', - 'CODEX_HOME', - 'ORCA_E2E_HOME_DIR', - 'ORCA_E2E_USER_DATA_DIR', - 'ORCA_USER_DATA_PATH' - ]) { - env[name] = root - } - for (const name of [ - 'ORCA_ENVIRONMENT', - 'ORCA_PAIRING_CODE', - 'ORCA_REMOTE_PAIRING', - 'ORCA_RUNTIME_SOURCE_ID', - 'ORCA_RUNTIME_SOURCE_INCARNATION', - 'ORCA_RUNTIME_SOURCE_PROFILE_PATH', - 'ORCA_TERMINAL_HANDLE', - 'ORCA_PANE_KEY', - 'ORCA_AGENT_LAUNCH_TOKEN', - 'ORCA_STRUCTURED_SESSION' - ]) { - env[name] = '' - } - env.ORCA_AGENT_SESSION_ID = COORDINATOR - env.ORCA_BACKGROUND_LAUNCH = '1' - env.ORCA_DISABLE_MACOS_LOGIN_SHELL = '1' - // execFile owns its child handle, bounds its lifetime, and awaits exit before server cleanup. - const { stdout } = await promisify(execFile)( - process.execPath, - [ - '--import', - tsxLoader, - '--conditions=orca-source', - cliPath, - 'orchestration', - 'worker-read', - '--dispatch', - dispatchId, - '--source', - 'transcript' - ], - { cwd: root, env, timeout: 15_000, windowsHide: true, encoding: 'utf8' } - ) - return stdout -} - -/** A Dispatch of the coordinator's task to the peer chat, both chats open. */ -async function dispatchToChat(): Promise<{ - taskId: string - dispatchId: string - worker: FakeConnection -}> { - await openChat(COORDINATOR) - const worker = await openChat(PEER_CHAT) - const { taskId } = await coordinatorRunAndTask() - const { dispatch } = await call( - 'orchestration.dispatch', - { task: taskId, to: WORKER }, - { sessionId: COORDINATOR } - ) - return { taskId, dispatchId: idOf(dispatch), worker } -} - -function workerDone(taskId: string, dispatchId: string) { - return { - subject: 'Done', - type: 'worker_done', - payload: JSON.stringify({ taskId, dispatchId, outcome: 'succeeded' }) - } -} - -/** The chat is still open: its conversation attached and its tab listed. */ -function expectChatOpen(sessionId: string): void { - expect(host.hasSession(sessionId)).toBe(true) - expect(host.deps.store.getVisibleSessionTabIndex().sessionIds).toContain(sessionId) -} - -describe("a chat assignee's report", () => { - it("is refused from a terminal that carries the chat's Dispatch under its own handle", async () => { - const { taskId, dispatchId } = await dispatchToChat() - - const receipt = await call('orchestration.send', { - ...workerDone(taskId, dispatchId), - from: 'term_worker' - }) - - expect(receipt).toMatchObject({ lifecycle: { action: 'rejected' } }) - expect(db.getDispatchContextById(dispatchId)?.status).toBe('dispatched') - expect(db.getTask(taskId)?.status).toBe('dispatched') - }) -}) - -describe("a chat assignee's liveness, stop and close", () => { - it('fails its Dispatch when the chat is closed, as a closed terminal does, and reads exited', async () => { - const { taskId, dispatchId } = await dispatchToChat() - - // As the close RPC does when the person closes the chat's tab. - await host.setSessionTabVisibility(PEER_CHAT, false) - - expect(db.getDispatchContextById(dispatchId)).toMatchObject({ - status: 'failed', - termination_reason: 'operator_close' - }) - expect(db.getTask(taskId)?.status).not.toBe('dispatched') - expect(await call('orchestration.workerShow', { dispatch: dispatchId })).toMatchObject({ - observation: { status: 'exited' } - }) - }) - - it('keeps its Dispatch while a close remains unproven, and fails it once a close is proven', async () => { - const { dispatchId } = await dispatchToChat() - vi.spyOn(host, 'close').mockRejectedValueOnce(new Error('the agent would not stop')) - - // As a refusable worktree removal closes each chat in it. - const outcome = await closeStructuredAgentSessionChild(PEER_CHAT) - - expect(outcome).toMatchObject({ stopped: false, closeAttempted: true }) - expectChatOpen(PEER_CHAT) - expect(db.getDispatchContextById(dispatchId)?.status).toBe('dispatched') - - expect(await closeStructuredAgentSessionChild(PEER_CHAT)).toMatchObject({ stopped: true }) - expect(db.getDispatchContextById(dispatchId)).toMatchObject({ - status: 'failed', - termination_reason: 'operator_close' - }) - }) - - it("keeps its Dispatch when another chat's close lands while its own close remains unproven", async () => { - const { dispatchId } = await dispatchToChat() - let refuseClose: (error: Error) => void = () => undefined - const close = vi - .spyOn(host, 'close') - .mockImplementationOnce(() => new Promise((_resolve, reject) => (refuseClose = reject))) - const closing = closeStructuredAgentSessionChild(PEER_CHAT) - await vi.waitFor(() => expect(close).toHaveBeenCalled(), WAIT) - - // Its tab stays visible pending the close when the other chat's notice re-derives. - await host.setSessionTabVisibility(COORDINATOR, false) - expect(db.getDispatchContextById(dispatchId)?.status).toBe('dispatched') - refuseClose(new Error('the agent would not stop')) - - expect(await closing).toMatchObject({ stopped: false, closeAttempted: true }) - expectChatOpen(PEER_CHAT) - expect(db.getDispatchContextById(dispatchId)?.status).toBe('dispatched') - }) - - it("reads the chat's transcript for worker-read", async () => { - const { dispatchId, worker } = await dispatchToChat() - expect(await sendUserMessage(PEER_CHAT, 'working on it')).toMatchObject({ ok: true }) - await vi.waitFor(() => expect(worker.turns).toHaveLength(1), WAIT) - await settleTurn(PEER_CHAT, 0) - - const journal = host.collaboratorsForTests().sessions.get(PEER_CHAT)?.journal - if (!journal) { - throw new Error('Worker conversation was not opened') - } - const prefix = journal.cursor() - await host.close(PEER_CHAT, 'evict') - expect(host.hasSession(PEER_CHAT)).toBe(false) - const saved = await journal.reads.cursor() - expect(saved.sequence).toBeGreaterThanOrEqual(prefix.sequence) - const acquisitions = codex.connections.length - const server = new OrcaRuntimeRpcServer({ - runtime, - userDataPath: root, - enableWebSocket: false, - methods: ORCHESTRATION_METHODS - }) - try { - await server.start() - const output = await readWorkerThroughCli(dispatchId) - expect(output).toContain('Source: transcript (provider=codex)') - expect(output).toContain('working on it') - expect(host.hasSession(PEER_CHAT)).toBe(true) - expect(codex.connections).toHaveLength(acquisitions) - - const read = await call('orchestration.workerRead', { dispatch: dispatchId }) - - expect(read).toMatchObject({ - source: 'transcript', - status: { liveness: 'live' }, - projection: { dispatchId } - }) - expect(JSON.stringify(read.transcript)).toContain('working on it') - } finally { - await server.stop() - } - }) -}) diff --git a/src/main/runtime/orchestration/terminal-authority/structured-sessions/structured-worker-at-rest.test.ts b/src/main/runtime/orchestration/terminal-authority/structured-sessions/structured-worker-at-rest.test.ts deleted file mode 100644 index 3657c582f14..00000000000 --- a/src/main/runtime/orchestration/terminal-authority/structured-sessions/structured-worker-at-rest.test.ts +++ /dev/null @@ -1,259 +0,0 @@ -import { agentSessionConversationView } from '../../../../../shared/agent-session/lifecycle/leases/agent-session-conversation-view' -import { - agentSessionLeaseFixture, - agentSessionRecordFixture -} from '../../../../../shared/agent-session/lifecycle/records/agent-session-record.test-fixture' -import { codexProviderHandle } from '../../../../../shared/agent-session/lifecycle/provider-handles/agent-session-provider-handle-encoding' -// Open Dispatches retain active work; chats at rest remain mail recipients until tab retirement. Process liveness and close proof remain separate. - -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import type { AgentSessionRecord } from '../../../../../shared/agent-session/lifecycle/agent-session-record' -import { OrchestrationDb } from '../../db/orchestration-db' -import '../../db/contract-constants' -import '../../db/messages/mailbox-routing-page' -import '../../db/dispatch-row-writer' -import '../../db/attempt-outcome-projection' - -const hostRef: { current: unknown } = { current: null } - -vi.mock( - '../../../../native-chat/agent-session-wire/host/structured-agent-session-registry', - () => ({ - getStructuredAgentSessionHost: () => hostRef.current - }) -) - -const { observeStructuredWorker, resolveStructuredWorkerAuthority } = - await import('./structured-worker-authority') -const { structuredWorkerOwesWork } = await import('./structured-worker-custody') -const { - mintStructuredWorkerHandle, - mintStructuredWorkerPaneKey, - structuredWorkerIdentities, - structuredWorkerProcessIncarnation -} = await import('./structured-worker-identity') -const { listAddressableStructuredWorkers } = - await import('../../addressing/groups/structured-worker-group-addressing') -await import('../../../agent-session/structured-agent-session-close') -const { resolveGroupAddress } = await import('../../addressing/groups/group-addressing') -const { createRestTestRig, foundRestTestChat, sweepTicks } = - await import('../../../../native-chat/agent-session-wire/host/testing/structured-agent-session-rest-test-rig.test-fixture') -const { STRUCTURED_AGENT_SESSION_IDLE_MS: IDLE_MS } = - await import('../../../../native-chat/agent-session-wire/termination/structured-agent-session-idle-sweep') -const { HOST_TEST_SESSION: REST_TEST_SESSION } = - await import('../../../../native-chat/agent-session-wire/host/testing/structured-agent-session-host-test-data.test-fixture') - -const SESSION = 'a1b2c3d4-e5f6-4a7b-8c9d-0e1f2a3b4c5d' -const LOCAL = JSON.stringify({ kind: 'local', hostId: 'local' }) - -function record(lease: Partial): AgentSessionRecord { - const base = agentSessionRecordFixture( - agentSessionLeaseFixture({ sessionId: SESSION, runtimeFence: 3, ...lease }) - ) - return { - ...base, - provider: 'codex', - accountHome: { variable: 'CODEX_HOME', path: '/tmp/codex-home' }, - providerHandleChain: base.providerHandleChain.map((link) => ({ - ...link, - handle: codexProviderHandle('at-rest') - })), - location: { ...base.location, workspaceId: 'wt_1' } - } -} - -function installHost(current: AgentSessionRecord | null, tabs: string[]) { - const host = { - deps: { - logger: { warn: vi.fn() }, - store: { - getRecord: () => current, - getConversation: () => (current ? agentSessionConversationView(current) : null), - listConversations: () => (current ? [agentSessionConversationView(current)] : []), - getVisibleSessionTabIndex: () => ({ present: true, sessionIds: tabs }) - } - }, - getSessionTabId: (id: string) => (tabs.includes(id) ? `agent-session:${id}` : null), - hasSession: () => false, - getPersistedVisibleSessionTabIndex: () => ({ present: true, sessionIds: tabs }), - setSessionTabVisibility: vi.fn(async (_id: string, visible: boolean) => { - tabs.splice(0, tabs.length, ...(visible ? [SESSION] : [])) - }), - close: vi.fn(async () => undefined) - } - hostRef.current = host - return host -} - -beforeEach(() => { - structuredWorkerIdentities.clear() - hostRef.current = null -}) - -describe('an open dispatch keeps its worker running (P2-19 i)', () => { - let db: OrchestrationDb - beforeEach(() => { - db = new OrchestrationDb(':memory:') - }) - afterEach(() => db.close()) - - function dispatchWorker(hostScope = LOCAL) { - const task = db.createTask({ runId: 'run_legacy_local', spec: 'structured work' }) - const { dispatch } = db.createStartingWorkerDispatch({ - taskId: task.id, - startOptions: {}, - creator: { kind: 'system' }, - maxDepth: 9 - }) - db.prepareStartingWorkerAuthority({ - dispatchId: dispatch.id, - handle: mintStructuredWorkerHandle(), - paneKey: mintStructuredWorkerPaneKey(SESSION), - processIncarnation: structuredWorkerProcessIncarnation(SESSION), - worktreeId: 'wt_1', - effects: [], - setupState: 'not_configured', - hostScope, - terminalOwnership: 'created' - }) - return dispatch - } - - it('keeps a worker at rest after its dispatch settles a group recipient, until its tab goes (P2-19 ii)', () => { - const dispatch = dispatchWorker() - db.markWorkerDispatchReady(dispatch.id) - db.beginWorkerStop(dispatch.id, 'epoch_home') - db.settleWorkerStop(dispatch.id) - // Settlement forgets the in-memory entry; only the durable row and the record remain. - structuredWorkerIdentities.clear() - const tabs = [SESSION] - installHost( - record({ - claimStatus: 'released', - deathEvidence: { kind: 'exit-observed', detail: 'stopped by the sweep', observedAt: 1 } - }), - tabs - ) - const handle = db.getWorkerTerminalResourceByOwner(dispatch.id)!.terminal_handle - const recipients = () => listAddressableStructuredWorkers(db) - - expect(recipients()).toEqual([{ handle, worktreeId: 'wt_1', agentIdentity: 'codex' }]) - expect(resolveGroupAddress('@codex', 'term_sender', recipients(), () => 'idle')).toEqual([ - handle - ]) - expect(resolveGroupAddress('@claude', 'term_sender', recipients(), () => 'idle')).toEqual([]) - // Direct mail resolves the same worker through the same ownership answer. - expect(resolveStructuredWorkerAuthority(handle, db)?.identity.handle).toBe(handle) - - tabs.length = 0 - expect(recipients()).toEqual([]) - expect(resolveStructuredWorkerAuthority(handle, db)).toBeNull() - }) - - it('stops routing to a worker its coordinator abandoned and then released, and keeps its tab', () => { - const dispatch = dispatchWorker() - db.markWorkerDispatchReady(dispatch.id) - structuredWorkerIdentities.clear() - const tabs = [SESSION] - installHost( - record({ - claimStatus: 'released', - deathEvidence: { kind: 'exit-observed', detail: 'stopped by the sweep', observedAt: 1 } - }), - tabs - ) - const resource = db.getWorkerTerminalResourceByOwner(dispatch.id)! - const handle = resource.terminal_handle - const recipients = () => listAddressableStructuredWorkers(db) - // At rest, its dispatch abandoned: still a recipient, as a terminal worker left running is. - db.abandonWorkerDispatch(dispatch.id, 'epoch_test') - const worktreeGroup = () => - resolveGroupAddress('@worktree:wt_1', 'term_sender', recipients(), () => 'idle') - expect(worktreeGroup()).toEqual([handle]) - expect(resolveStructuredWorkerAuthority(handle, db)).not.toBeNull() - - // The release finds the agent at rest, so it settles as released. - expect(db.requestWorkerTerminalRelease(dispatch.id)).toMatchObject({ disposition: 'retained' }) - expect( - db.settleDeadWorkerTerminalRelease({ - requestingDispatchId: dispatch.id, - resourceId: resource.id, - processIncarnation: resource.process_incarnation! - }) - ).toMatchObject({ disposition: 'released' }) - - expect(tabs).toEqual([SESSION]) - expect(worktreeGroup()).toEqual([]) - // Direct mail routes through the same answer. - expect(resolveStructuredWorkerAuthority(handle, db)).toBeNull() - }) -}) - -describe('a task dispatched into a worker whose own dispatch settled', () => { - it('keeps the worker running while that task is open, and lets it rest once the task settles', async () => { - const db = new OrchestrationDb(':memory:') - const rig = await createRestTestRig({ - hasOpenDispatch: (current) => structuredWorkerOwesWork(db, current) - }) - try { - hostRef.current = rig.host - await foundRestTestChat(rig) - const incarnation = structuredWorkerProcessIncarnation(REST_TEST_SESSION) - const handle = mintStructuredWorkerHandle() - const workerPane = mintStructuredWorkerPaneKey(REST_TEST_SESSION) - const first = db.createTask({ runId: 'run_legacy_local', spec: 'first task' }) - const { dispatch: started } = db.createStartingWorkerDispatch({ - taskId: first.id, - startOptions: {}, - creator: { kind: 'system' }, - maxDepth: 9 - }) - db.prepareStartingWorkerAuthority({ - dispatchId: started.id, - handle, - paneKey: workerPane, - processIncarnation: incarnation, - worktreeId: 'wt_1', - effects: [], - setupState: 'not_configured', - hostScope: LOCAL, - terminalOwnership: 'created' - }) - db.markWorkerDispatchReady(started.id) - expect( - db.settleWorkerReport({ - taskId: first.id, - dispatchId: started.id, - outcome: 'succeeded', - result: 'done' - }) - ).toMatchObject({ action: 'settled' }) - // The coordinator hands the same worker its next task: a dispatch with no worker row. - const second = db.createTask({ runId: 'run_legacy_local', spec: 'second task' }) - const handedOn = db.createDispatchContext({ - taskId: second.id, - assigneeHandle: handle, - assigneePaneKey: workerPane, - processIncarnation: incarnation, - creator: { kind: 'system' }, - maxDepth: 9 - }) - rig.clock.now += 2 * IDLE_MS - - await sweepTicks(12) - expect(rig.adapter.closeSession).not.toHaveBeenCalled() - expect(observeStructuredWorker({ sessionId: REST_TEST_SESSION }).status).toBe('live') - - db.completeDispatch(handedOn.id) - rig.clock.now += IDLE_MS + 1 - await vi.waitFor(() => - expect(observeStructuredWorker({ sessionId: REST_TEST_SESSION }).status).toBe('exited') - ) - expect(rig.adapter.closeSession).toHaveBeenCalledWith(REST_TEST_SESSION, undefined) - } finally { - hostRef.current = null - await rig.dispose() - db.close() - } - }) -}) diff --git a/src/main/runtime/orchestration/workers/turn-stops/chat-worker-request-failure-rig.test-fixture.ts b/src/main/runtime/orchestration/workers/turn-stops/chat-worker-request-failure-rig.test-fixture.ts index 6396798f4cd..e5744d792fd 100644 --- a/src/main/runtime/orchestration/workers/turn-stops/chat-worker-request-failure-rig.test-fixture.ts +++ b/src/main/runtime/orchestration/workers/turn-stops/chat-worker-request-failure-rig.test-fixture.ts @@ -12,7 +12,7 @@ import type { StructuredAgentSessionAdapter } from '../../../../native-chat/agen import { codexProviderHandle } from '../../../../../shared/agent-session/lifecycle/provider-handles/agent-session-provider-handle-encoding' import { formatOrcaSessionAddress } from '../../../../../shared/agent-session/identity/orca-session-address' import { testOrcaSessionId } from '../../../../../shared/agent-session/identity/orca-session-address-test-fixture' -import { openStructuredAgentSessionSqlJournalDatabase } from '../../../agent-session/structured-agent-session-journal-open' +import { openStructuredAgentSessionSqlJournalDatabase } from '../../../agent-session/installation/structured-agent-session-journal-open' import { SqlAgentSessionJournal } from '../../../../native-chat/agent-session-journal/journal-sql-store' import type { JournalSqlDatabase } from '../../../../native-chat/agent-session-journal/database/journal-sql-database' import { diff --git a/src/main/runtime/rpc/methods/history/ai-vault.ts b/src/main/runtime/rpc/methods/history/ai-vault.ts index 45ebfeb7415..e8dad7db1fc 100644 --- a/src/main/runtime/rpc/methods/history/ai-vault.ts +++ b/src/main/runtime/rpc/methods/history/ai-vault.ts @@ -26,7 +26,7 @@ import { import { ensureStructuredAgentSessionHostUnlessRefused, tryEnsureStructuredAgentSessionHostForResume -} from '../../../agent-session/structured-agent-session-host-refusal' +} from '../../../agent-session/installation/structured-agent-session-host-refusal' import { clientOpensStructuredChatFromHistory, supportsStructuredAgentSessions diff --git a/src/main/runtime/rpc/methods/orchestration/structured-workers/orchestration-structured-worker-close.test-fixture.ts b/src/main/runtime/rpc/methods/orchestration/structured-workers/orchestration-structured-worker-close.test-fixture.ts deleted file mode 100644 index ff34a8bc7a3..00000000000 --- a/src/main/runtime/rpc/methods/orchestration/structured-workers/orchestration-structured-worker-close.test-fixture.ts +++ /dev/null @@ -1,73 +0,0 @@ -import { expect, vi } from 'vitest' -import { - hostTestAttachParams, - hostTestOperationId -} from '../../../../../native-chat/agent-session-wire/host/testing/structured-agent-session-host-test-data.test-fixture' -import type { JournalSqlReads } from '../../../../../native-chat/agent-session-journal/journal-sql-reads' -import type { SqlAgentSessionJournal } from '../../../../../native-chat/agent-session-journal/journal-sql-store' -import { hostTestState } from '../../../../../native-chat/agent-session-wire/host/testing/structured-agent-session-host.test-fixture' - -export function holdClose(sessionId: string) { - const { host } = hostTestState() - const lane = Promise.withResolvers() - const entered = Promise.withResolvers() - const held = host.collaboratorsForTests().serialize(sessionId, () => lane.promise) - const close = host.close - vi.spyOn(host, 'close').mockImplementation((...args) => { - entered.resolve() - return close(...args) - }) - return { - entered: entered.promise, - release: async () => { - lane.resolve() - await held - } - } -} - -export function holdAdmissionReply(journal: SqlAgentSessionJournal) { - const entered = Promise.withResolvers() - const reply = Promise.withResolvers() - const ordered = journal.readInOrder.bind(journal) - let held = true - vi.spyOn(journal, 'readInOrder').mockImplementation(function ( - run: (reads: JournalSqlReads) => T | Promise - ): Promise { - return ordered((reads) => - run({ - ...reads, - work: async (input) => { - const answer = await reads.work(input) - if (held) { - held = false - entered.resolve() - await reply.promise - } - return answer - } - }) - ) - }) - return { - entered: entered.promise, - release: () => reply.resolve(), - fail: () => reply.reject(new Error('work reader unavailable')) - } -} - -export async function reattach(sessionId: string) { - const { host, store } = hostTestState() - const result = await host.attach( - { callerKey: 'redrive-test' }, - hostTestAttachParams(store.requireWritableRecord(sessionId).lease.runtimeFence, { - envelope: { - sessionId, - clientOperationId: hostTestOperationId(), - expectedRuntimeFence: store.requireWritableRecord(sessionId).lease.runtimeFence, - payloadFingerprint: '0'.repeat(64) - } - }) - ) - expect(result.ok).toBe(true) -} diff --git a/src/main/runtime/rpc/methods/orchestration/structured-workers/orchestration-structured-worker-lifecycle.ts b/src/main/runtime/rpc/methods/orchestration/structured-workers/orchestration-structured-worker-lifecycle.ts index e6014443ad2..94b41d4da7b 100644 --- a/src/main/runtime/rpc/methods/orchestration/structured-workers/orchestration-structured-worker-lifecycle.ts +++ b/src/main/runtime/rpc/methods/orchestration/structured-workers/orchestration-structured-worker-lifecycle.ts @@ -36,7 +36,7 @@ import { releaseStructuredWorkerSession } from './orchestration-structured-worke import { closeStructuredAgentSessionChild, type StructuredSessionSurfaceRuntime -} from '../../../../agent-session/structured-agent-session-close' +} from '../../../../agent-session/lifecycle/structured-agent-session-close' import { chatAssigneeJournal, type StructuredJournalSource diff --git a/src/main/runtime/rpc/methods/orchestration/structured-workers/orchestration-structured-worker-session.ts b/src/main/runtime/rpc/methods/orchestration/structured-workers/orchestration-structured-worker-session.ts index b9d626ac04f..1f3c24a7f1a 100644 --- a/src/main/runtime/rpc/methods/orchestration/structured-workers/orchestration-structured-worker-session.ts +++ b/src/main/runtime/rpc/methods/orchestration/structured-workers/orchestration-structured-worker-session.ts @@ -1,7 +1,7 @@ import { closeStructuredAgentSessionChild, type StructuredAgentSessionCloseOptions -} from '../../../../agent-session/structured-agent-session-close' +} from '../../../../agent-session/lifecycle/structured-agent-session-close' /** Create structured workers directly; attach is not readiness, so hold the preamble until the agent takes it. * Open dispatches retain agents through the idle sweep; settled workers rest and restart on mail. The preamble is a turn, never keystrokes. */ diff --git a/src/main/runtime/rpc/methods/orchestration/worker/follow-up/worker-follow-up-placement.ts b/src/main/runtime/rpc/methods/orchestration/worker/follow-up/worker-follow-up-placement.ts index d2b869979d6..d0cccb58f57 100644 --- a/src/main/runtime/rpc/methods/orchestration/worker/follow-up/worker-follow-up-placement.ts +++ b/src/main/runtime/rpc/methods/orchestration/worker/follow-up/worker-follow-up-placement.ts @@ -11,7 +11,7 @@ import { structuredWorkerSession } from '../../../../../orchestration/terminal-authority/structured-sessions/structured-worker-authority' import type { WorkerFollowUpPlacement } from './worker-follow-up-choice' -import { publishChatTabInBackground } from '../../../../../session-tabs/background-chat-tab-publication' +import { publishChatTabInBackground } from '../../../../../session-tabs/chat/background-chat-tab-publication' /** What a follow-up continues, and for a closed worker how it comes back once the follow-up holds its Dispatch. */ export type WorkerFollowUp = { diff --git a/src/main/runtime/rpc/methods/orchestration/worker/release/worker-auto-release-turns.test.ts b/src/main/runtime/rpc/methods/orchestration/worker/release/worker-auto-release-turns.test.ts deleted file mode 100644 index 56df92ae69d..00000000000 --- a/src/main/runtime/rpc/methods/orchestration/worker/release/worker-auto-release-turns.test.ts +++ /dev/null @@ -1,75 +0,0 @@ -import '../../structured-workers/orchestration-structured-worker-close.test-fixture' -import '../../../../../../native-chat/agent-session-journal/journal-observation.test-support' -import '../../../../../../../shared/orca-profiles/constants' -import '../../../../../orca-runtime-tests/runtime-store-partial-fixture' -import '../../../../../agent-session/agent-session-tab-layout' -import '../../../../../../../shared/agent-session/journal/agent-session-journal-types' -import '../../../../../../native-chat/agent-session-wire/publication/history/agent-session-history-page' -import '../../../../../../native-chat/agent-session-wire/publication/subscribers/agent-session-subscriber-frame-fields' -import { hostTestState } from '../../../../../../native-chat/agent-session-wire/host/testing/structured-agent-session-host.test-fixture' -import { createTestParams } from '../../../../../../native-chat/agent-session-wire/host/testing/structured-agent-session-create.test-fixture' -import { hostTestOperationId } from '../../../../../../native-chat/agent-session-wire/host/testing/structured-agent-session-host-test-data.test-fixture' -import '../../../../../../native-chat/agent-session-wire/host/structured-agent-session-registry' -import '../../../../../orchestration/terminal-authority/structured-sessions/structured-worker-identity' -import '../../rpc-test-harness' -import '../../structured-workers/orchestration-structured-worker-session' -import '../start/placement/worker-placement-topology' -import './worker-release-completion' - -vi.mock('../../../structured-sessions/creation/structured-agent-session-create', () => ({ - createStructuredAgentSessionForWorktree: async (args: { envelope: { sessionId: string } }) => { - const { host } = hostTestState() - return host.create( - { callerKey: 'redrive-test' }, - createTestParams(undefined, { - envelope: { - ...args.envelope, - clientOperationId: hostTestOperationId(), - expectedRuntimeFence: null, - payloadFingerprint: '0'.repeat(64) - } - }) - ) - } -})) - -import { afterEach, describe, expect, it, vi } from 'vitest' -import { getWorkerTerminalAutoReleaseScheduler } from '../../../../../orchestration/terminal-authority/release/worker-terminal-auto-release-scheduler' -import '../../../../../orchestration/terminal-authority/release/worker-auto-release-activity' - -import { createOrchestrationWorkerReleaseHarness } from '../testing/worker-release.test-support' - -describe('orchestration worker automatic release across turns and settings', () => { - const h = createOrchestrationWorkerReleaseHarness() - - afterEach(() => { - getWorkerTerminalAutoReleaseScheduler(h.runtime).clear() - h.cleanup() - vi.useRealTimers() - }) - - function setupWithFakeClock(): void { - vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'Date'] }) - vi.setSystemTime(new Date('2026-10-27T12:00:00Z')) - h.setup() - } - - it('refuses to stop a kept worker without touching it, and stops it once auto-close is allowed', async () => { - setupWithFakeClock() - const { dispatchId } = await h.startWorker() - const keepOpen = (keep: boolean) => - h.call('orchestration.workerKeepOpen', { paneKey: h.workerPaneKey, keep }) - await keepOpen(true) - - await expect( - h.call('orchestration.workerStop', { dispatch: dispatchId }) - ).rejects.toMatchObject({ code: 'terminal_kept_open' }) - expect(h.db.getWorkerDispatch(dispatchId)?.state).toBe('ready') - expect(h.db.getDispatchContextById(dispatchId)?.capability_revoked_at).toBeNull() - - await keepOpen(false) - await expect( - h.call('orchestration.workerStop', { dispatch: dispatchId }) - ).resolves.toMatchObject({ state: 'stopped' }) - }) -}) diff --git a/src/main/runtime/rpc/methods/orchestration/worker/start/readiness/failed-worker-start-teardown.ts b/src/main/runtime/rpc/methods/orchestration/worker/start/readiness/failed-worker-start-teardown.ts index 85212bff6bd..fec31141a10 100644 --- a/src/main/runtime/rpc/methods/orchestration/worker/start/readiness/failed-worker-start-teardown.ts +++ b/src/main/runtime/rpc/methods/orchestration/worker/start/readiness/failed-worker-start-teardown.ts @@ -1,4 +1,4 @@ -import { closeStructuredAgentSessionChild } from '../../../../../../agent-session/structured-agent-session-close' +import { closeStructuredAgentSessionChild } from '../../../../../../agent-session/lifecycle/structured-agent-session-close' import { OrchestrationError } from '../../../../../../orchestration/orchestration-error' import type { OrcaRuntimeService } from '../../../../../../orca-runtime' import { diff --git a/src/main/runtime/rpc/methods/session-tabs/session-tab-mutation-methods.ts b/src/main/runtime/rpc/methods/session-tabs/session-tab-mutation-methods.ts index d7ea9641953..dac1a496e47 100644 --- a/src/main/runtime/rpc/methods/session-tabs/session-tab-mutation-methods.ts +++ b/src/main/runtime/rpc/methods/session-tabs/session-tab-mutation-methods.ts @@ -1,8 +1,8 @@ import { resolveRuntimeNavigationTarget } from '../../../../../shared/remote-runtime/session-graph/runtime-navigation' -import { resolveChatTabActivation } from '../../../agent-session/agent-session-tab-identity' +import { resolveChatTabActivation } from '../../../session-tabs/chat/agent-session-tab-identity' import { commitLeafMoveAndRekey } from '../../../../ipc/pty/ipc/leaf-move' import type { OrcaRuntimeService } from '../../../orca-runtime' -import type { MovedPanePlacement } from '../../../session-tabs/headless-pane-move-to-new-tab' +import type { MovedPanePlacement } from '../../../session-tabs/layout/headless-pane-move-to-new-tab' import { defineMethod } from '../../core' import { assertProjectedSessionTabVisible, diff --git a/src/main/runtime/rpc/methods/session-tabs/structured-chat-tab-table.test-fixture.ts b/src/main/runtime/rpc/methods/session-tabs/structured-chat-tab-table.test-fixture.ts index 0459251051f..c66dda08b05 100644 --- a/src/main/runtime/rpc/methods/session-tabs/structured-chat-tab-table.test-fixture.ts +++ b/src/main/runtime/rpc/methods/session-tabs/structured-chat-tab-table.test-fixture.ts @@ -1,4 +1,4 @@ -import { availableRevealWorkspace } from '../../../session-tabs/structured-workspace-authority.test-fixture' +import { availableRevealWorkspace } from '../../../session-tabs/chat/structured-workspace-authority.test-fixture' /** Drive chat tab pointers through real disk records, structured host, runtime and RPC; fake only the provider. */ import { mkdtemp, rm } from 'node:fs/promises' diff --git a/src/main/runtime/rpc/methods/structured-sessions/conversation/structured-agent-session-close-method.ts b/src/main/runtime/rpc/methods/structured-sessions/conversation/structured-agent-session-close-method.ts index 66464aceec7..0a48e992cf1 100644 --- a/src/main/runtime/rpc/methods/structured-sessions/conversation/structured-agent-session-close-method.ts +++ b/src/main/runtime/rpc/methods/structured-sessions/conversation/structured-agent-session-close-method.ts @@ -13,7 +13,7 @@ import { noteStructuredAgentSessionClose } from '../creation/structured-agent-se import { captureStructuredSessionSurface, retireCapturedStructuredSessionSurface -} from '../../../../agent-session/structured-agent-session-close' +} from '../../../../agent-session/lifecycle/structured-agent-session-close' export const STRUCTURED_AGENT_SESSION_CLOSE_METHOD = defineMethod({ // Close only provider/in-memory state, preserving record/journal for future attachment. diff --git a/src/main/runtime/rpc/methods/structured-sessions/conversation/structured-agent-session-reveal.ts b/src/main/runtime/rpc/methods/structured-sessions/conversation/structured-agent-session-reveal.ts index ae64992fab8..4cc9b2e5a6e 100644 --- a/src/main/runtime/rpc/methods/structured-sessions/conversation/structured-agent-session-reveal.ts +++ b/src/main/runtime/rpc/methods/structured-sessions/conversation/structured-agent-session-reveal.ts @@ -1,5 +1,5 @@ import { getStructuredAgentSessionHost } from '../../../../../native-chat/agent-session-wire/host/structured-agent-session-registry' -import { StructuredWorkspaceUnavailable } from '../../../../session-tabs/structured-workspace-authority' +import { StructuredWorkspaceUnavailable } from '../../../../session-tabs/chat/structured-workspace-authority' import type { StructuredSessionWorkspaceRemovedDetails } from '../../../../../../shared/agent-session/view/open-structured-agent-session' // Republish an existing host-owned record's tab for history entries holding only session id; unpublished tabs disappear on sync. // Unlike ensure, read workspace/provider from host state so callers cannot redirect publication. @@ -22,7 +22,7 @@ import { import { structuredSessionSurfaceIsCurrent, type StructuredSessionSurface -} from '../../../../agent-session/structured-agent-session-close' +} from '../../../../agent-session/lifecycle/structured-agent-session-close' import { RevealParams } from '../../../../../../shared/rpc-contract/structured-agent-session/structured-agent-session-params' import '../../../../../../shared/rpc-contract/structured-agent-session/structured-agent-session-continue-params' import '../../../../../../shared/rpc-contract/structured-agent-session/structured-agent-session-rename-params' diff --git a/src/main/runtime/rpc/methods/structured-sessions/creation/structured-agent-session-close-before-create.ts b/src/main/runtime/rpc/methods/structured-sessions/creation/structured-agent-session-close-before-create.ts index 1250cacfbdb..4a6a6f15ea1 100644 --- a/src/main/runtime/rpc/methods/structured-sessions/creation/structured-agent-session-close-before-create.ts +++ b/src/main/runtime/rpc/methods/structured-sessions/creation/structured-agent-session-close-before-create.ts @@ -9,7 +9,7 @@ import type { RpcContext } from '../../../core' import { type StructuredSessionSurface, closeCapturedStructuredSession -} from '../../../../agent-session/structured-agent-session-close' +} from '../../../../agent-session/lifecycle/structured-agent-session-close' // Per-launch ids prevent cross-create matches; cap entries whose create never arrives. const MAX_CLOSED_BEFORE_CREATE = 256 diff --git a/src/main/runtime/rpc/methods/structured-sessions/creation/structured-agent-session-create-handler.ts b/src/main/runtime/rpc/methods/structured-sessions/creation/structured-agent-session-create-handler.ts index 664bf9d4bab..f72f4b260ce 100644 --- a/src/main/runtime/rpc/methods/structured-sessions/creation/structured-agent-session-create-handler.ts +++ b/src/main/runtime/rpc/methods/structured-sessions/creation/structured-agent-session-create-handler.ts @@ -1,4 +1,4 @@ -import type { StructuredSessionSurface } from '../../../../agent-session/structured-agent-session-close' +import type { StructuredSessionSurface } from '../../../../agent-session/lifecycle/structured-agent-session-close' import { AGENT_CHAT_PERMISSION_MODE_OPTION_ID } from '../../../../../../shared/agent-launch/permissions/agent-chat-permission-mode-option-id' import type { z } from 'zod' import { agentSessionRefusalError } from '../../../../../../shared/agent-session/failures/agent-session-wire-refusals' diff --git a/src/main/runtime/rpc/methods/structured-sessions/creation/structured-agent-session-create.ts b/src/main/runtime/rpc/methods/structured-sessions/creation/structured-agent-session-create.ts index 2944052715c..c1adf6d1919 100644 --- a/src/main/runtime/rpc/methods/structured-sessions/creation/structured-agent-session-create.ts +++ b/src/main/runtime/rpc/methods/structured-sessions/creation/structured-agent-session-create.ts @@ -1,4 +1,4 @@ -import type { StructuredSessionSurface } from '../../../../agent-session/structured-agent-session-close' +import type { StructuredSessionSurface } from '../../../../agent-session/lifecycle/structured-agent-session-close' import { structuredAgentSessionTabId } from '../../../../../../shared/agent-session/view/structured-agent-session-projection' import { seededPermissionMode } from '../../../../../../shared/native-chat/input/session-options/native-chat-session-option-defaults' // Resolve the host launch identity, then commit an at-rest create or the compatible acquired path. @@ -38,7 +38,7 @@ import type { StructuredAgentId } from '../../../../../../shared/agent-session/l import { resolveUncommittedStructuredCreate } from './structured-agent-session-precommit-refusal' import { ORCA_LAYOUT_OWNER_IS_MAIN } from '../../../../../../shared/workspace-layout/layout-owner-switch' import { structuredAgentSessionClosedBeforeCreate } from './structured-agent-session-close-before-create' -import type { ChatTabPlacement } from '../../../../agent-session/agent-session-tab-layout' +import type { ChatTabPlacement } from '../../../../session-tabs/chat/agent-session-tab-layout' export type PreparedStructuredAgentSessionCreate = { host: StructuredAgentSessionHost diff --git a/src/main/runtime/rpc/methods/structured-sessions/creation/structured-agent-session-gate.ts b/src/main/runtime/rpc/methods/structured-sessions/creation/structured-agent-session-gate.ts index c26e48ed465..0ad1f4dd736 100644 --- a/src/main/runtime/rpc/methods/structured-sessions/creation/structured-agent-session-gate.ts +++ b/src/main/runtime/rpc/methods/structured-sessions/creation/structured-agent-session-gate.ts @@ -9,7 +9,7 @@ import type { StructuredAgentSessionHost } from '../../../../../native-chat/agen import type { StructuredAgentSessionCaller } from '../../../../../native-chat/agent-session-wire/host/structured-agent-session-host-types' import type { RpcContext } from '../../../core' import { rpcCallerOperationKey } from '../../../callers/rpc-caller-identity' -import { structuredAgentSessionHostRefusal } from '../../../../agent-session/structured-agent-session-host-refusal' +import { structuredAgentSessionHostRefusal } from '../../../../agent-session/installation/structured-agent-session-host-refusal' import { createSupportFollowsHostSetting, clientReadsStructuredSessionAgent, diff --git a/src/main/runtime/rpc/methods/structured-sessions/protocol/structured-agent-session-at-rest-options.test.ts b/src/main/runtime/rpc/methods/structured-sessions/protocol/structured-agent-session-at-rest-options.test.ts deleted file mode 100644 index 60531887e00..00000000000 --- a/src/main/runtime/rpc/methods/structured-sessions/protocol/structured-agent-session-at-rest-options.test.ts +++ /dev/null @@ -1,137 +0,0 @@ -import { readTestHostJournal } from '../../../../../native-chat/agent-session-journal/journal-observation.test-support' -import '../../../dispatch/testing/unused-default-rpc-methods.test-fixture' -vi.mock('node:fs/promises', { spy: true }) -import { AGENT_JOURNAL_THREAD_SCOPE } from '../../../../../../shared/agent-session/journal/agent-session-journal-types' -import { expect, it, vi } from 'vitest' -import { computeAgentSessionPayloadFingerprint } from '../../../../../../shared/agent-session/lifecycle/operations/agent-session-mutation-envelope' -import { activeStructuredAgentSessionTurnId } from '../../../../../../shared/agent-session/view/structured-agent-session-live-turn' -import { - hostTestOperationId, - HOST_TEST_SESSION as SESSION, - HOST_TEST_THREAD as REST_TEST_THREAD -} from '../../../../../native-chat/agent-session-wire/host/testing/structured-agent-session-host-test-data.test-fixture' -import { - foundRestTestChat, - REST_TEST_CALLER as CALLER, - restTestSend -} from '../../../../../native-chat/agent-session-wire/host/testing/structured-agent-session-rest-test-rig.test-fixture' - -import { closeStructuredAgentSessionChild } from '../../../../agent-session/structured-agent-session-close' -import { discardStructuredWorkerSession } from '../../orchestration/structured-workers/orchestration-structured-worker-session' - -import { fixture, call, restingChat } from './structured-agent-session-rest-contract-test-fixture' - -it('records a pick as intent and replays it at the next start (P2-16)', async () => { - await restingChat() - const fields = { key: 'model', value: 'gpt-picked' } - const [picked] = await call('agentSession.setOption', { - envelope: { - sessionId: SESSION, - clientOperationId: hostTestOperationId(), - expectedRuntimeFence: fixture.rig.store.getRecord(SESSION)!.lease.runtimeFence, - payloadFingerprint: computeAgentSessionPayloadFingerprint({ - method: 'agentSession.setOption', - sessionId: SESSION, - fields - }) - }, - ...fields - }) - expect(picked).toMatchObject({ ok: true, result: { ok: true } }) - expect(fixture.rig.store.getRecord(SESSION)?.options).toMatchObject({ model: 'gpt-picked' }) - expect(fixture.rig.adapter.acquire).not.toHaveBeenCalled() - - const fence = fixture.rig.store.getRecord(SESSION)!.lease.runtimeFence - await fixture.rig.host.send(CALLER, restTestSend('use the new model', fence)) - await vi.waitFor(() => expect(fixture.rig.adapter.acquire).toHaveBeenCalledOnce()) - expect(fixture.rig.adapter.acquire.mock.calls[0]?.[0]).toMatchObject({ - options: expect.objectContaining({ model: 'gpt-picked' }) - }) -}) - -it('whose settlement write failed is settled by the next send, which is delivered', async () => { - await foundRestTestChat(fixture.rig) - const open = fixture.rig.host.collaboratorsForTests().sessions.get(SESSION)! - const running = open.child! - // A turn in flight, so the exit has something to settle. - fixture.rig.adapter.acquire.mock.calls - .at(-1)?.[0] - .events?.appendItem( - { provider: 'codex', threadId: REST_TEST_THREAD, turnId: 'working', ordinal: 50 }, - { kind: 'turn', turnId: 'working', state: 'running' }, - { turnScope: AGENT_JOURNAL_THREAD_SCOPE } - ) - await fixture.rig.host.flushStreamedEvents(SESSION) - // Refuse both the exit write and its queued retry to test retained death evidence. - vi.spyOn(open.journal, 'appendLifecycleBatch') - .mockRejectedValueOnce(new Error('disk full')) - .mockRejectedValueOnce(new Error('disk full')) - await fixture.rig.host.handleAdapterEvent({ - type: 'ended', - sessionId: SESSION, - reason: 'killed', - cause: 'unexpected-exit', - fence: running.fence, - acquisitionGeneration: running.generation! - }) - // Released with its death evidence, not latched: the next acquire settles from that evidence. - await vi.waitFor(() => - expect(fixture.rig.store.getRecord(SESSION)?.lease).toMatchObject({ - claimStatus: 'released', - deathEvidence: { kind: 'exit-observed' } - }) - ) - await fixture.rig.host.collaboratorsForTests().serialize(SESSION, async () => {}) - - const sent = await fixture.rig.host.send( - CALLER, - restTestSend('again', fixture.rig.store.getRecord(SESSION)!.lease.runtimeFence) - ) - - if (!sent.ok) { - throw new Error(`send refused: ${sent.refusal.code}`) - } - await fixture.rig.host.waitForSendSettlement(SESSION, sent.value.clientMessageId) - expect(fixture.rig.adapter.dispatch).toHaveBeenCalledTimes(2) - expect( - activeStructuredAgentSessionTurnId((await readTestHostJournal(fixture.rig.host, SESSION)).items) - ).not.toBe('working') -}) - -it.each([ - ['the close RPC', async () => void (await call('agentSession.close', { sessionId: SESSION }))], - ['the runtime chat close', async () => void (await closeStructuredAgentSessionChild(SESSION))], - [ - 'a discarded worker', - () => - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the discard reads only this runtime member. - discardStructuredWorkerSession(SESSION, { - retireStructuredAgentSessionTabFromSnapshot: () => undefined - } as never) - ] -])('%s rejects a message accepted before any start, and starts nothing', async (_, close) => { - await restingChat() - const { loop } = fixture.rig.host.collaboratorsForTests().conversationDelivery - vi.spyOn(loop, 'wake').mockImplementation(() => Promise.resolve()) - const reader: unknown[] = [] - await fixture.rig.host.subscribe({ - id: 'reader', - sessionId: SESSION, - emit: (event) => reader.push(event) - }) - const fence = fixture.rig.store.getRecord(SESSION)!.lease.runtimeFence - expect( - (await fixture.rig.host.send(CALLER, restTestSend('closed before it went', fence))).ok - ).toBe(true) - - await close() - // A close's rejection is a sentence with its fact beside it, never a marker. - await vi.waitFor(() => - expect(JSON.stringify(reader)).toContain( - '"reason":"The chat closed before this message was sent.","submittedAt"' - ) - ) - expect(JSON.stringify(reader)).toContain('"rejection":{"kind":"chatClosed"}') - expect(fixture.rig.host.hasSession(SESSION)).toBe(false) - expect(fixture.rig.adapter.acquire).not.toHaveBeenCalled() -}) diff --git a/src/main/runtime/rpc/methods/structured-sessions/protocol/structured-agent-session-rest-contract-test-fixture.ts b/src/main/runtime/rpc/methods/structured-sessions/protocol/structured-agent-session-rest-contract-test-fixture.ts deleted file mode 100644 index 675f2cc46bf..00000000000 --- a/src/main/runtime/rpc/methods/structured-sessions/protocol/structured-agent-session-rest-contract-test-fixture.ts +++ /dev/null @@ -1,104 +0,0 @@ -import { afterEach, beforeEach, vi } from 'vitest' -import { STRUCTURED_AGENT_SESSION_RUNTIME_CAPABILITY } from '../../../../../../shared/agent-session/capabilities/agent-session-runtime-capabilities' -import { setStructuredAgentSessionHost } from '../../../../../native-chat/agent-session-wire/host/structured-agent-session-registry' -import { - createRestTestRig, - foundRestTestChat -} from '../../../../../native-chat/agent-session-wire/host/testing/structured-agent-session-rest-test-rig.test-fixture' - -import { HOST_TEST_SESSION as SESSION } from '../../../../../native-chat/agent-session-wire/host/testing/structured-agent-session-host-test-data.test-fixture' -import type { RestTestRig } from '../../../../../native-chat/agent-session-wire/host/testing/structured-agent-session-rest-test-rig.test-fixture' -import { OrcaRuntimeService } from '../../../../orca-runtime' -import type { RpcResponse } from '../../../core' -import { RpcDispatcher } from '../../../dispatcher' -import type { RpcDispatchStreamingOptions } from '../../../dispatch/dispatcher-stream-options' -import { STRUCTURED_AGENT_SESSION_METHODS } from '../structured-agent-session' -import type * as fileOperations from 'node:fs/promises' -import * as contextSnapshots from '../../../../../native-chat/conversation-context/agent-session-context-snapshots' - -vi.mock('node:fs/promises', { spy: true }) -export const actualFiles = await vi.importActual('node:fs/promises') - -export const CLIENT = { - clientId: 'device-1', - clientKind: 'runtime' as const, - clientCapabilities: [STRUCTURED_AGENT_SESSION_RUNTIME_CAPABILITY], - connectionId: 'connection-1' -} - -let rig: RestTestRig - -let dispatcher: RpcDispatcher - -let requests = 0 - -export async function call( - method: string, - params: unknown, - client: RpcDispatchStreamingOptions = CLIENT -): Promise { - const replies: RpcResponse[] = [] - requests += 1 - await dispatcher.dispatchStreaming( - { id: `request-${requests}`, authToken: 'token', method, params }, - (raw) => replies.push(JSON.parse(raw) as RpcResponse), - client - ) - return replies -} - -/** A chat that once ran, reopened by a fresh host: nothing of it is in memory. */ - -export async function restingChat(): Promise { - await foundRestTestChat(rig) - await rig.store.replaceSessionOptions({ - sessionId: SESSION, - fence: rig.store.getRecord(SESSION)!.lease.runtimeFence, - options: { model: 'gpt-saved', effort: 'high' }, - now: rig.clock.now - }) - await rig.restart() - setStructuredAgentSessionHost(rig.host) - rig.adapter.acquire.mockClear() - rig.adapter.dispatch.mockClear() - rig.adapter.readOptions.mockClear() -} - -beforeEach(async () => { - requests = 0 - rig = await createRestTestRig({ idleSweep: { intervalMs: 3_600_000 } }) - setStructuredAgentSessionHost(rig.host) - const runtime = new OrcaRuntimeService() - dispatcher = new RpcDispatcher({ runtime, methods: STRUCTURED_AGENT_SESSION_METHODS }) -}) - -afterEach(async () => { - vi.restoreAllMocks() - setStructuredAgentSessionHost(null) - await rig.dispose() - await actualFiles.rm(contextSnapshots.agentSessionContextSnapshotRoot(rig.root), { - recursive: true, - force: true - }) -}) - -export const fixture = { - get dispatcher() { - return dispatcher - }, - set dispatcher(value: typeof dispatcher) { - dispatcher = value - }, - get requests() { - return requests - }, - set requests(value: typeof requests) { - requests = value - }, - get rig() { - return rig - }, - set rig(value: typeof rig) { - rig = value - } -} diff --git a/src/main/runtime/rpc/methods/structured-sessions/protocol/structured-agent-session-rpc.test-fixture.ts b/src/main/runtime/rpc/methods/structured-sessions/protocol/structured-agent-session-rpc.test-fixture.ts index 4a6486ed6a8..d5a71b773aa 100644 --- a/src/main/runtime/rpc/methods/structured-sessions/protocol/structured-agent-session-rpc.test-fixture.ts +++ b/src/main/runtime/rpc/methods/structured-sessions/protocol/structured-agent-session-rpc.test-fixture.ts @@ -6,7 +6,7 @@ import { OPERATION, request } from './structured-agent-session-rpc-client.test-fixture' -import { availableRevealWorkspace } from '../../../../session-tabs/structured-workspace-authority.test-fixture' +import { availableRevealWorkspace } from '../../../../session-tabs/chat/structured-workspace-authority.test-fixture' import { EVERY_AGENT_CHAT } from '../../../../../../shared/native-chat/every-agent-chat.test-fixture' import { vi } from 'vitest' import type { StructuredAgentSessionHost } from '../../../../../native-chat/agent-session-wire/host/structured-agent-session-host' diff --git a/src/main/runtime/agent-session/structured-agent-session-paired-caller.test.ts b/src/main/runtime/rpc/methods/structured-sessions/structured-agent-session-paired-caller.test.ts similarity index 92% rename from src/main/runtime/agent-session/structured-agent-session-paired-caller.test.ts rename to src/main/runtime/rpc/methods/structured-sessions/structured-agent-session-paired-caller.test.ts index b75a58e016a..757e199d6d4 100644 --- a/src/main/runtime/agent-session/structured-agent-session-paired-caller.test.ts +++ b/src/main/runtime/rpc/methods/structured-sessions/structured-agent-session-paired-caller.test.ts @@ -4,11 +4,11 @@ import { readdir, readFile } from 'node:fs/promises' import { join } from 'node:path' import { afterEach, describe, expect, it, vi } from 'vitest' -import { stopStructuredAgentSessionRuntime } from './structured-agent-session-runtime' +import { stopStructuredAgentSessionRuntime } from '../../../agent-session/installation/structured-agent-session-runtime' import { openStructuredCodexRpcHarness, type StructuredCodexRpcHarness -} from '../rpc/methods/structured-sessions/structured-codex-session-rpc-test-harness' +} from './structured-codex-session-rpc-test-harness' const CREDENTIAL = 'paired-bearer-credential-0f3c9a71' const DEVICE = 'device-7d2e41' diff --git a/src/main/runtime/rpc/methods/structured-sessions/structured-codex-session-rpc-test-harness.ts b/src/main/runtime/rpc/methods/structured-sessions/structured-codex-session-rpc-test-harness.ts index 4f578011fe1..4e5b629da45 100644 --- a/src/main/runtime/rpc/methods/structured-sessions/structured-codex-session-rpc-test-harness.ts +++ b/src/main/runtime/rpc/methods/structured-sessions/structured-codex-session-rpc-test-harness.ts @@ -21,7 +21,7 @@ import type { OrcaRuntimeService } from '../../../orca-runtime' import type { RpcRequest, RpcResponse } from '../../core' import { RpcDispatcher } from '../../dispatcher' import { STRUCTURED_AGENT_SESSION_METHODS } from './structured-agent-session' -import { stopStructuredAgentSessionRuntime } from '../../../agent-session/structured-agent-session-runtime' +import { stopStructuredAgentSessionRuntime } from '../../../agent-session/installation/structured-agent-session-runtime' import { ensureTestStructuredAgentSessionHost as ensureStructuredAgentSessionHost } from '../../../agent-session/records/agent-session-record-store-test-harness' import { createStructuredAgentSessionLogger } from '../../../../native-chat/agent-session-wire/host/structured-agent-session-logger' import { scriptedCodexTransport } from '../../../orca-runtime-tests/scripted-codex-transport.test-fixture' diff --git a/src/main/runtime/session-construction/agent-session/get-agent-session-execution-namespace.ts b/src/main/runtime/session-construction/agent-session/get-agent-session-execution-namespace.ts index 9bade41d54c..2b90b03988e 100644 --- a/src/main/runtime/session-construction/agent-session/get-agent-session-execution-namespace.ts +++ b/src/main/runtime/session-construction/agent-session/get-agent-session-execution-namespace.ts @@ -16,7 +16,7 @@ import { isTuiAgentEnabled } from '../../../../shared/agent-launch/catalog/tui-a import { buildAgentResumeStartupPlan } from '../../../../shared/agent-launch/startup/tui-agent-resume-startup' import { agentLaunchQuotingShell } from '../../../../shared/agent-launch/startup/agent-launch-runtime' import { OrchestrationError } from '../../orchestration/orchestration-error' -import { withAgentSessionAccountEnv } from '../../agent-session/agent-session-account-env' +import { withAgentSessionAccountEnv } from '../../agent-session/environment/agent-session-account-env' import { resolveWslHostAgentResumeInputs } from '../../terminal/launch/wsl-host-agent-terminal-launch' import type { SleepingAgentLaunchConfig } from '../../../../shared/agent-session/lifecycle/agent-session-resume' import { isTerminalLeafId, makePaneKey } from '../../../../shared/workspace-layout/stable-pane-id' diff --git a/src/main/runtime/session-graph/session-graph-promotion.ts b/src/main/runtime/session-graph/session-graph-promotion.ts index 174317f19e5..a735ebe8b2c 100644 --- a/src/main/runtime/session-graph/session-graph-promotion.ts +++ b/src/main/runtime/session-graph/session-graph-promotion.ts @@ -1,22 +1,22 @@ import type { OrcaRuntimeWithResolveExitWaiters as ResolveExitWaitersMethods } from '../terminal/wait/terminal-wait-settlements' import type { OrcaRuntimeWithHasTerminalsForWorktree as HasTerminalsForWorktreeMethods } from './session-graph-reload-lifecycle' import type { OrcaRuntimeWithBindPtyIncarnationHandle as BindPtyIncarnationHandleMethods } from '../terminal/identity/terminal-handle-bindings' -import type { OrcaRuntimeWithCollectMobileVisibleGraphChangedWorktrees as CollectMobileVisibleGraphChangedWorktreesMethods } from '../session-tabs/session-tabs-inventory' +import type { OrcaRuntimeWithCollectMobileVisibleGraphChangedWorktrees as CollectMobileVisibleGraphChangedWorktreesMethods } from '../session-tabs/inventory/session-tabs-inventory' import type { OrcaRuntimeWithGetPtyRecordForPaneKey as GetPtyRecordForPaneKeyMethods } from '../orchestration/mailbox/routing/terminal-pane-mail-routing' import type { OrcaRuntimeWithMarkPtyLivenessUnverifiable as MarkPtyLivenessUnverifiableMethods } from '../terminal/layout/terminal-input-floor' import type { OrcaRuntimeWithRecordPtyWorktree as RecordPtyWorktreeMethods } from '../terminal/identity/pty-worktree-record' -import type { RuntimeSessionTabsInventoryPublication as SessionTabsInventoryPublicationMethods } from '../session-tabs/session-tabs-inventory-publication' +import type { RuntimeSessionTabsInventoryPublication as SessionTabsInventoryPublicationMethods } from '../session-tabs/inventory/session-tabs-inventory-publication' import type { OrcaRuntimeWithRefreshFloatingWorkspacePtyLiveness as RefreshFloatingWorkspacePtyLivenessMethods } from '../terminal/lifecycle/floating-session-liveness' -import type { OrcaRuntimeWithTouchMobileSessionTabsForWorktree as TouchMobileSessionTabsForWorktreeMethods } from '../session-tabs/mobile-session-membership' -import type { OrcaRuntimeWithScheduleMobileSessionTabsChanged as ScheduleMobileSessionTabsChangedMethods } from '../session-tabs/session-tabs-change-publication' -import type { OrcaRuntimeWithSyncMobileSessionTabs as SyncMobileSessionTabsMethods } from '../session-tabs/mobile-session-reconciliation' +import type { OrcaRuntimeWithTouchMobileSessionTabsForWorktree as TouchMobileSessionTabsForWorktreeMethods } from '../session-tabs/restoration/mobile-session-membership' +import type { OrcaRuntimeWithScheduleMobileSessionTabsChanged as ScheduleMobileSessionTabsChangedMethods } from '../session-tabs/publication/session-tabs-change-publication' +import type { OrcaRuntimeWithSyncMobileSessionTabs as SyncMobileSessionTabsMethods } from '../session-tabs/restoration/mobile-session-reconciliation' import { OrcaRuntimeWithNotifySshStateChanged } from '../workspaces/workspace-host-notifications' import { HEADLESS_RUNTIME_WINDOW_ID } from '../../../shared/remote-runtime/session-graph/runtime-session-contracts' import { ActiveGroupViewFacts } from '../view-facts/active-group-view-facts' import type { ExecutionHostId } from '../../../shared/execution-host/execution-host' import type { WorkspaceSessionState } from '../../../shared/workspace-session/workspace-session-state-types' import type { RuntimePtyWorktreeRecord } from '../terminal/records/runtime-terminal-state-records' -import type { SessionTitleAuthority } from '../session-tabs/session-title-publisher' +import type { SessionTitleAuthority } from '../session-tabs/publication/session-title-publisher' export abstract class OrcaRuntimeWithAttachWindow extends OrcaRuntimeWithNotifySshStateChanged { protected abstract captureSessionTitleAuthority(): SessionTitleAuthority diff --git a/src/main/runtime/session-graph/session-graph-reload-lifecycle.ts b/src/main/runtime/session-graph/session-graph-reload-lifecycle.ts index 981f5771076..1e20d4d08b6 100644 --- a/src/main/runtime/session-graph/session-graph-reload-lifecycle.ts +++ b/src/main/runtime/session-graph/session-graph-reload-lifecycle.ts @@ -1,6 +1,6 @@ import type { OrcaRuntimeWithTransitionGraphReloadToTerminalState as TransitionGraphReloadToTerminalStateMethods } from './session-graph-authority' import type { OrcaRuntimeWithBindPtyIncarnationHandle as BindPtyIncarnationHandleMethods } from '../terminal/identity/terminal-handle-bindings' -import { OrcaRuntimeWithSessionTitleAuthority } from '../session-tabs/session-title-publisher' +import { OrcaRuntimeWithSessionTitleAuthority } from '../session-tabs/publication/session-title-publisher' import type { RuntimeRendererReloadFence } from './renderer-reload-fence' import { ORCA_LAYOUT_OWNER_IS_MAIN } from '../../../shared/workspace-layout/layout-owner-switch' import { HEADLESS_RUNTIME_WINDOW_ID } from '../../../shared/remote-runtime/session-graph/runtime-session-contracts' diff --git a/src/main/runtime/session-graph/session-window-graph.ts b/src/main/runtime/session-graph/session-window-graph.ts index f8c93e35855..1d874b23807 100644 --- a/src/main/runtime/session-graph/session-window-graph.ts +++ b/src/main/runtime/session-graph/session-window-graph.ts @@ -10,7 +10,7 @@ import { HEADLESS_RUNTIME_WINDOW_ID } from '../../../shared/remote-runtime/sessi import type { RuntimeLeafRecord } from '../terminal/records/runtime-terminal-state-records' import { ORCA_LAYOUT_OWNER_IS_MAIN } from '../../../shared/workspace-layout/layout-owner-switch' -import { assertBrowserPageInventoryFrames } from '../session-tabs/mobile-session-inventory-base' +import { assertBrowserPageInventoryFrames } from '../session-tabs/inventory/mobile-session-inventory-base' type Graph = RuntimeSyncWindowGraph diff --git a/src/main/runtime/session-lifecycle/close/close-mobile-row-in-main-layout.ts b/src/main/runtime/session-lifecycle/close/close-mobile-row-in-main-layout.ts index 49c56df230c..fe476d8ce8d 100644 --- a/src/main/runtime/session-lifecycle/close/close-mobile-row-in-main-layout.ts +++ b/src/main/runtime/session-lifecycle/close/close-mobile-row-in-main-layout.ts @@ -6,8 +6,8 @@ import { startedMainTerminalSurfaces } from '../../terminal/surface/main-termina import { closeInMainLayout, type MainLayoutClose -} from '../../session-tabs/main-layout-close-command' -import type { ExplicitCloseStop } from '../../session-tabs/explicit-terminal-close-pty-stops' +} from '../../session-tabs/layout/main-layout-close-command' +import type { ExplicitCloseStop } from '../../session-tabs/terminal-retirement/explicit-terminal-close-pty-stops' import { retireTerminalSurfacesFromSnapshot } from '../../terminal/surface/mobile-session-terminal-retirement' export abstract class OrcaRuntimeWithCloseMobileRowInMainLayout extends OrcaRuntimeWithRefuseUnattributedMobileSessionTabClose { diff --git a/src/main/runtime/session-lifecycle/close/close-mobile-session-tab.ts b/src/main/runtime/session-lifecycle/close/close-mobile-session-tab.ts index a5fee067e75..adf357ec47f 100644 --- a/src/main/runtime/session-lifecycle/close/close-mobile-session-tab.ts +++ b/src/main/runtime/session-lifecycle/close/close-mobile-session-tab.ts @@ -15,11 +15,11 @@ import { import { getRuntimeBrowserPageRegistry } from '../../browser/client-pages/runtime-browser-page-registry' import type { RuntimeEdgeCommandSurface } from '../../construction/runtime-edge-command-controller' import { rendererPublicationThrottle } from '../../../window/visibility/renderer-publication-throttle' -import { retireHeadlessMobileSessionEditorTab } from '../../session-tabs/headless-editor-tabs' +import { retireHeadlessMobileSessionEditorTab } from '../../session-tabs/restoration/headless-editor-tabs' import { LOCAL_EXECUTION_HOST_ID } from '../../../../shared/execution-host/execution-host' import { ORCA_LAYOUT_OWNER_IS_MAIN } from '../../../../shared/workspace-layout/layout-owner-switch' -import { closeMobileStructuredSessionPresentation } from '../../session-tabs/structured-session-tab-presentation' -import type { OrcaRuntimeWithCloseStructuredAgentSessionTab as ChatPresentation } from '../../session-tabs/structured-session-tab-close' +import { closeMobileStructuredSessionPresentation } from '../../session-tabs/chat/structured-session-tab-presentation' +import type { OrcaRuntimeWithCloseStructuredAgentSessionTab as ChatPresentation } from '../../session-tabs/chat/structured-session-tab-close' export abstract class OrcaRuntimeWithCloseMobileSessionTab extends OrcaRuntimeWithCloseMobileRowInMainLayout { abstract retireStructuredAgentSessionTabFromSnapshot( diff --git a/src/main/runtime/session-lifecycle/close/has-live-or-persisted-serve-or-ssh-owned-pty-binding.ts b/src/main/runtime/session-lifecycle/close/has-live-or-persisted-serve-or-ssh-owned-pty-binding.ts index 215ae6931dd..ba6079743fb 100644 --- a/src/main/runtime/session-lifecycle/close/has-live-or-persisted-serve-or-ssh-owned-pty-binding.ts +++ b/src/main/runtime/session-lifecycle/close/has-live-or-persisted-serve-or-ssh-owned-pty-binding.ts @@ -1,8 +1,8 @@ -import type { OrcaRuntimeWithRestoreLivePairedRendererSessionOwnedMobileTerminals as RendererTerminalRescue } from '../../session-tabs/renderer-session-terminal-rescue' -import type { OrcaRuntimeWithCloseStructuredAgentSessionTab as StructuredSessionClose } from '../../session-tabs/structured-session-tab-close' +import type { OrcaRuntimeWithRestoreLivePairedRendererSessionOwnedMobileTerminals as RendererTerminalRescue } from '../../session-tabs/restoration/renderer-session-terminal-rescue' +import type { OrcaRuntimeWithCloseStructuredAgentSessionTab as StructuredSessionClose } from '../../session-tabs/chat/structured-session-tab-close' import type { OrcaRuntimeWithTransitionGraphReloadToTerminalState as SessionGraphAuthority } from '../../session-graph/session-graph-authority' import type { OrcaRuntimeWithWaitForMobileTerminalSurface as MobileTerminalSurface } from '../../terminal/view/mobile-terminal-surface' -import type { OrcaRuntimeWithCloseHeadlessMobileTerminalTab as HeadlessTerminalClose } from '../../session-tabs/headless-terminal-tab-close' +import type { OrcaRuntimeWithCloseHeadlessMobileTerminalTab as HeadlessTerminalClose } from '../../session-tabs/terminal-retirement/headless-terminal-tab-close' import { OrcaRuntimeWithReconcileHeadlessMobileSessionBrowserTabs } from '../projection/reconcile-headless-mobile-session-browser-tabs' import type { RuntimeMobileSessionTabsSnapshot } from '../../../../shared/remote-runtime/session-graph/runtime-session-contracts' import type { RuntimeMobileSessionTerminalTab } from '../../../../shared/remote-runtime/session-graph/runtime-mobile-session-tab-contracts' diff --git a/src/main/runtime/session-lifecycle/projection/apply-mobile-session-tab-navigation.ts b/src/main/runtime/session-lifecycle/projection/apply-mobile-session-tab-navigation.ts index c1f14780227..7d038ff1bb4 100644 --- a/src/main/runtime/session-lifecycle/projection/apply-mobile-session-tab-navigation.ts +++ b/src/main/runtime/session-lifecycle/projection/apply-mobile-session-tab-navigation.ts @@ -1,7 +1,7 @@ import { HEADLESS_RUNTIME_WINDOW_ID } from '../../../../shared/remote-runtime/session-graph/runtime-session-contracts' -import { selectMobileSessionTab } from '../../session-tabs/mobile-session-tab-selection' -import type { OrcaRuntimeWithScheduleMobileSessionTabsChanged as MobileSessionPublication } from '../../session-tabs/session-tabs-change-publication' -import type { OrcaRuntimeWithStoredMobileSnapshotHasStalePreservedTab as MobileSessionPreservation } from '../../session-tabs/mobile-session-publication-preservation' +import { selectMobileSessionTab } from '../../session-tabs/layout/mobile-session-tab-selection' +import type { OrcaRuntimeWithScheduleMobileSessionTabsChanged as MobileSessionPublication } from '../../session-tabs/publication/session-tabs-change-publication' +import type { OrcaRuntimeWithStoredMobileSnapshotHasStalePreservedTab as MobileSessionPreservation } from '../../session-tabs/restoration/mobile-session-publication-preservation' import { OrcaRuntimeWithPerformMobileSessionPtyRecordsRefresh } from './perform-mobile-session-pty-records-refresh' import type { RuntimeMobileSessionTabsResult, diff --git a/src/main/runtime/session-lifecycle/projection/build-headless-mobile-session-browser-tabs.ts b/src/main/runtime/session-lifecycle/projection/build-headless-mobile-session-browser-tabs.ts index edbb386ecc7..7e2d7a4637b 100644 --- a/src/main/runtime/session-lifecycle/projection/build-headless-mobile-session-browser-tabs.ts +++ b/src/main/runtime/session-lifecycle/projection/build-headless-mobile-session-browser-tabs.ts @@ -1,7 +1,7 @@ import { buildRuntimeClientBrowserTabs } from './build-runtime-client-browser-tabs' import { getBrowserHostLeaseRegistry } from '../../browser-host/leases/browser-host-lease-registry-instance' -import type { OrcaRuntimeWithStoredMobileSnapshotHasStalePreservedTab as BrowserOwnership } from '../../session-tabs/mobile-session-publication-preservation' -import { OrcaRuntimeWithPersistTerminalSurfaceRetirements } from '../../session-tabs/terminal-surface-retirements' +import type { OrcaRuntimeWithStoredMobileSnapshotHasStalePreservedTab as BrowserOwnership } from '../../session-tabs/restoration/mobile-session-publication-preservation' +import { OrcaRuntimeWithPersistTerminalSurfaceRetirements } from '../../session-tabs/terminal-retirement/terminal-surface-retirements' import type { RuntimeMobileSessionBrowserTab, RuntimeMobileSessionTerminalTab @@ -12,7 +12,7 @@ import type { } from '../../../../shared/remote-runtime/session-graph/runtime-session-contracts' import { parseAppSshPtyId } from '../../../../shared/remote-runtime/ssh/ssh-pty-id' import { getRuntimeBrowserPageRegistry } from '../../browser/client-pages/runtime-browser-page-registry' -import { holdAgentSessionInventory } from '../../agent-session/structured-agent-session-inventory-hold' +import { holdAgentSessionInventory } from '../../session-tabs/inventory/structured-agent-session-inventory-hold' import type { Tab } from '../../../../shared/workspace-layout/tab-groups/tab-types' import { captureTerminalCloseRequest, diff --git a/src/main/runtime/session-lifecycle/projection/mobile-session-browser-group-projection.ts b/src/main/runtime/session-lifecycle/projection/mobile-session-browser-group-projection.ts index d4d1c811d84..e7e78b5f0c0 100644 --- a/src/main/runtime/session-lifecycle/projection/mobile-session-browser-group-projection.ts +++ b/src/main/runtime/session-lifecycle/projection/mobile-session-browser-group-projection.ts @@ -3,7 +3,7 @@ import type { RuntimeMobileSessionTabsSnapshot } from '../../../../shared/remote-runtime/session-graph/runtime-session-contracts' import type { RuntimeMobileSessionSnapshotTab } from '../../../../shared/remote-runtime/session-graph/runtime-mobile-session-tab-contracts' -import { retireMobileSessionTabSelection } from '../../session-tabs/mobile-session-tab-selection' +import { retireMobileSessionTabSelection } from '../../session-tabs/layout/mobile-session-tab-selection' // Terminal-only rebuilds drop browser ids; restore their prior group, assigning only new browsers to target/first group. export function appendBrowserTabOrder( diff --git a/src/main/runtime/session-lifecycle/projection/perform-mobile-session-pty-records-refresh.ts b/src/main/runtime/session-lifecycle/projection/perform-mobile-session-pty-records-refresh.ts index 6f8a15ace95..6ae68c64927 100644 --- a/src/main/runtime/session-lifecycle/projection/perform-mobile-session-pty-records-refresh.ts +++ b/src/main/runtime/session-lifecycle/projection/perform-mobile-session-pty-records-refresh.ts @@ -24,7 +24,7 @@ import { isWorktreeTerminalsSleepingError } from '../../../../shared/workspace/l import { paneHoldsSession } from '../../terminal/surface/main-terminal-surfaces' import { recordShownTerminalUserOpen } from '../../terminal/lifecycle/run-terminal-client-use' -import { resolveChatTabActivation } from '../../agent-session/agent-session-tab-identity' +import { resolveChatTabActivation } from '../../session-tabs/chat/agent-session-tab-identity' export abstract class OrcaRuntimeWithPerformMobileSessionPtyRecordsRefresh extends OrcaRuntimeWithRestoredPaneStart { protected abstract toMobileSessionTabsResult( snapshot: RuntimeMobileSessionTabsSnapshot diff --git a/src/main/runtime/session-lifecycle/projection/prune-mobile-session-tab-group-layout.ts b/src/main/runtime/session-lifecycle/projection/prune-mobile-session-tab-group-layout.ts index 3687beff462..2b018caa79f 100644 --- a/src/main/runtime/session-lifecycle/projection/prune-mobile-session-tab-group-layout.ts +++ b/src/main/runtime/session-lifecycle/projection/prune-mobile-session-tab-group-layout.ts @@ -1,6 +1,6 @@ import { rendererStatusReplica } from '../../session-graph/renderer-status-replica' import { selectFreshAgentRowForMobileTab } from '../../workspaces/process-listing/runtime-hook-agent-row-selection' -import { OrcaRuntimeWithSavedConversationTitlePublication } from '../../session-tabs/saved-conversation-title-publication' +import { OrcaRuntimeWithSavedConversationTitlePublication } from '../../session-tabs/chat/saved-conversation-title-publication' import type { TabGroupLayoutNode } from '../../../../shared/workspace-layout/tab-groups/tab-types' import type { RuntimeMobileSessionSnapshotTab, @@ -30,7 +30,7 @@ import { structuredWorkerHandleAgentStatus } from '../../orchestration/addressin import { retitleStructuredConversationTabs, titleStructuredConversationTabs -} from '../../session-tabs/structured-conversation-tab-title' +} from '../../session-tabs/chat/structured-conversation-tab-title' import { structuredChatDisplayName } from '../../../../shared/agent-session/view/structured-chat-row-name' import { agentSessionRecordShownName } from '../../agent-session/records/agent-session-record-shown-name' diff --git a/src/main/runtime/session-lifecycle/projection/reconcile-headless-mobile-session-browser-tabs.ts b/src/main/runtime/session-lifecycle/projection/reconcile-headless-mobile-session-browser-tabs.ts index 0c80b9c4797..d24b5ec0768 100644 --- a/src/main/runtime/session-lifecycle/projection/reconcile-headless-mobile-session-browser-tabs.ts +++ b/src/main/runtime/session-lifecycle/projection/reconcile-headless-mobile-session-browser-tabs.ts @@ -1,11 +1,11 @@ -import type { OrcaRuntimeWithStoredMobileSnapshotHasStalePreservedTab as BrowserOwnership } from '../../session-tabs/mobile-session-publication-preservation' +import type { OrcaRuntimeWithStoredMobileSnapshotHasStalePreservedTab as BrowserOwnership } from '../../session-tabs/restoration/mobile-session-publication-preservation' import type { OrcaRuntimeWithPruneMobileSessionTabGroupLayout as MobileSessionProjection } from './prune-mobile-session-tab-group-layout' -import type { OrcaRuntimeWithCloseStructuredAgentSessionTab as StructuredSessionClose } from '../../session-tabs/structured-session-tab-close' +import type { OrcaRuntimeWithCloseStructuredAgentSessionTab as StructuredSessionClose } from '../../session-tabs/chat/structured-session-tab-close' import type { OrcaRuntimeWithPerformMobileSessionPtyRecordsRefresh as MobileSessionRefresh } from './perform-mobile-session-pty-records-refresh' import type { RuntimeWorkspaceCatalog as WorkspaceCatalog } from '../../workspaces/catalog/workspace-catalog' import type { OrcaRuntimeWithResolveMobileSessionTerminalCommand as MobileTerminalStartup } from '../../terminal/launch/mobile-terminal-startup' import type { OrcaRuntimeWithCreateRuntimeOwnedMobileSessionTerminal as OwnedMobileTerminalCreate } from '../../terminal/launch/mobile-terminal-owned-create' -import { OrcaRuntimeWithHydrateHeadlessMobileSessionTabsFromWorkspaceSession } from '../../session-tabs/mobile-session-hydration' +import { OrcaRuntimeWithHydrateHeadlessMobileSessionTabsFromWorkspaceSession } from '../../session-tabs/restoration/mobile-session-hydration' import type { RuntimeMobileSessionBrowserTab, RuntimeMobileSessionSnapshotTab, diff --git a/src/main/runtime/session-lifecycle/projection/runtime-mobile-session-result-finalization.ts b/src/main/runtime/session-lifecycle/projection/runtime-mobile-session-result-finalization.ts index 6e181790b35..82345951658 100644 --- a/src/main/runtime/session-lifecycle/projection/runtime-mobile-session-result-finalization.ts +++ b/src/main/runtime/session-lifecycle/projection/runtime-mobile-session-result-finalization.ts @@ -1,4 +1,4 @@ -import { normalizeMobileSessionTabSelection } from '../../session-tabs/mobile-session-tab-selection' +import { normalizeMobileSessionTabSelection } from '../../session-tabs/layout/mobile-session-tab-selection' import type { RuntimeMobileSessionTabsResult } from '../../../../shared/remote-runtime/session-graph/runtime-session-contracts' import { dropRetirementProofsForLiveSurfaces } from '../../../../shared/workspace-layout/terminal-surfaces/terminal-retirement-proof-ledger' import { orderMobileSessionTabsByGroups } from './mobile-session-tab-merge' diff --git a/src/main/runtime/session-tabs/acknowledged-terminal-tab-retirement-main-close.test.ts b/src/main/runtime/session-tabs/acknowledged-terminal-tab-retirement-main-close.test.ts deleted file mode 100644 index 5db32018c85..00000000000 --- a/src/main/runtime/session-tabs/acknowledged-terminal-tab-retirement-main-close.test.ts +++ /dev/null @@ -1,65 +0,0 @@ -// Main-owned counterparts to acknowledged-terminal-tab-retirement.test.ts: close waits for layout durability without a window-ack race. -import { afterEach, expect, it, vi } from 'vitest' -import { - ACK_LEAF, - ACK_SECOND_LEAF, - ACK_TAB, - createAcknowledgedTabRetirementFixture -} from './acknowledged-terminal-tab-retirement-fixture' -import '../../persistence/terminal-topology/pane-ownership/terminal-topology-membership' -import { _resetClosedPaneFencesForTests } from '../../persistence/terminal-topology/pane-ownership/closed-pane-binding-fence' - -vi.mock('../../../shared/workspace-layout/layout-owner-switch', () => ({ - ORCA_LAYOUT_OWNER_IS_MAIN: true -})) - -const fixtures: Awaited>[] = [] -afterEach(async () => { - for (const fixture of fixtures.splice(0)) { - await fixture.dispose() - } - vi.restoreAllMocks() - // Reused tab ids must not inherit an earlier test's close fence. - _resetClosedPaneFencesForTests() -}) -async function fixture(bound = false) { - const result = await createAcknowledgedTabRetirementFixture(bound) - fixtures.push(result) - const stopped: string[] = [] - result.runtime.setPtyController({ - write: () => true, - kill: (ptyId: string) => { - stopped.push(ptyId) - return true - }, - getForegroundProcess: async () => null - }) - return { ...result, stopped } -} - -it("stops a sibling a partial mobile snapshot omitted, from main's own panes", async () => { - const f = await fixture(true) - await f.publish(true, 2, [ACK_LEAF]) - await expect(f.close()).resolves.toEqual({ closed: true, retirementConfirmed: true }) - expect(f.stopped).toEqual(expect.arrayContaining(['pty-a', 'pty-b'])) - expect( - f.store.getWorkspaceSession().terminalLayoutsByTabId[ACK_TAB]?.ptyIdsByLeafId?.[ACK_SECOND_LEAF] - ).toBeUndefined() -}) - -// Main-owned close waits for durable layout, matching window-owned retirement's acknowledgement boundary. -it("answers the close only once main's layout write is durable", async () => { - const f = await fixture(true) - await f.store.flushPendingOrThrowAsync() - const gate = f.authority.pause() - let answered = false - const closing = f.close().then((result) => { - answered = true - return result - }) - await gate.started.promise - expect(answered).toBe(false) - gate.finish.resolve() - await expect(closing).resolves.toEqual({ closed: true, retirementConfirmed: true }) - expect(f.hasTab()).toBe(false) -}) diff --git a/src/main/runtime/agent-session/agent-session-tab-identity.ts b/src/main/runtime/session-tabs/chat/agent-session-tab-identity.ts similarity index 91% rename from src/main/runtime/agent-session/agent-session-tab-identity.ts rename to src/main/runtime/session-tabs/chat/agent-session-tab-identity.ts index 3b2a305a6c5..623c2c7f536 100644 --- a/src/main/runtime/agent-session/agent-session-tab-identity.ts +++ b/src/main/runtime/session-tabs/chat/agent-session-tab-identity.ts @@ -1,9 +1,9 @@ -import { normalizeMobileSessionTabSelection } from '../session-tabs/mobile-session-tab-selection' -import { isReopenedChatTabId } from '../../../shared/agent-session/view/structured-agent-session-host-tab-id' +import { normalizeMobileSessionTabSelection } from '../layout/mobile-session-tab-selection' +import { isReopenedChatTabId } from '../../../../shared/agent-session/view/structured-agent-session-host-tab-id' import { randomUUID } from 'node:crypto' -import { isAgentSessionSurfaceTabId } from '../../../shared/agent-session/view/agent-session-surface-tab-id' -import type { RuntimeMobileSessionTabsSnapshot } from '../../../shared/remote-runtime/session-graph/runtime-session-contracts' -import { getStructuredAgentSessionHost } from '../../native-chat/agent-session-wire/host/structured-agent-session-registry' +import { isAgentSessionSurfaceTabId } from '../../../../shared/agent-session/view/agent-session-surface-tab-id' +import type { RuntimeMobileSessionTabsSnapshot } from '../../../../shared/remote-runtime/session-graph/runtime-session-contracts' +import { getStructuredAgentSessionHost } from '../../../native-chat/agent-session-wire/host/structured-agent-session-registry' const REOPENED_TAB_PREFIX = 'agent-chat-tab-v1-' diff --git a/src/main/runtime/agent-session/agent-session-tab-layout-queue.ts b/src/main/runtime/session-tabs/chat/agent-session-tab-layout-queue.ts similarity index 91% rename from src/main/runtime/agent-session/agent-session-tab-layout-queue.ts rename to src/main/runtime/session-tabs/chat/agent-session-tab-layout-queue.ts index f94bc7f605f..62a4ab3cb87 100644 --- a/src/main/runtime/agent-session/agent-session-tab-layout-queue.ts +++ b/src/main/runtime/session-tabs/chat/agent-session-tab-layout-queue.ts @@ -1,7 +1,7 @@ -import { savedSessionId } from './lifecycle/saved-structured-agent-session-restoration' -import type { ExecutionHostId } from '../../../shared/execution-host/execution-host' -import type { LayoutApplyReply } from '../../../shared/workspace-layout/workspace-layout-command-types' -import type { WorkspaceSessionState } from '../../../shared/workspace-session/workspace-session-state-types' +import { savedSessionId } from '../../agent-session/lifecycle/saved-structured-agent-session-restoration' +import type { ExecutionHostId } from '../../../../shared/execution-host/execution-host' +import type { LayoutApplyReply } from '../../../../shared/workspace-layout/workspace-layout-command-types' +import type { WorkspaceSessionState } from '../../../../shared/workspace-session/workspace-session-state-types' import { chatTabLayoutCommand, loadChatTabLayout, diff --git a/src/main/runtime/agent-session/agent-session-tab-layout.test.ts b/src/main/runtime/session-tabs/chat/agent-session-tab-layout.test.ts similarity index 80% rename from src/main/runtime/agent-session/agent-session-tab-layout.test.ts rename to src/main/runtime/session-tabs/chat/agent-session-tab-layout.test.ts index e8246510c55..61f8ed0746f 100644 --- a/src/main/runtime/agent-session/agent-session-tab-layout.test.ts +++ b/src/main/runtime/session-tabs/chat/agent-session-tab-layout.test.ts @@ -1,10 +1,10 @@ import { describe, expect, it, vi } from 'vitest' -import type { Tab } from '../../../shared/workspace-layout/tab-groups/tab-types' -import type { WorkspaceSessionState } from '../../../shared/workspace-session/workspace-session-state-types' +import type { Tab } from '../../../../shared/workspace-layout/tab-groups/tab-types' +import type { WorkspaceSessionState } from '../../../../shared/workspace-session/workspace-session-state-types' import { withChatTabChanges, type ChatTabChange } from './agent-session-tab-layout' // rollback build (switch-off) — delete with the switch-off code post-flip -vi.mock('../../../shared/workspace-layout/layout-owner-switch', () => ({ +vi.mock('../../../../shared/workspace-layout/layout-owner-switch', () => ({ ORCA_LAYOUT_OWNER_IS_MAIN: false })) @@ -31,22 +31,6 @@ function change(session: WorkspaceSessionState, changes: ChatTabChange[]): Works } describe('a windowless host’s chat tab saves', () => { - it('open a chat in a freshly minted group once the last one closed', () => { - const first = change(EMPTY, [open('chat-a')]) - const firstGroup = first.tabGroups?.[WT]?.[0]?.id - const closed = change(first, [{ close: 'chat-a', tabId: 'structured-agent-session-chat-a' }]) - const remembering = { - ...closed, - activeGroupIdByWorktree: { ...closed.activeGroupIdByWorktree, [WT]: firstGroup! } - } - expect(remembering.tabGroups?.[WT] ?? []).toEqual([]) - const reopened = change(remembering, [open('chat-b')]) - const groups = reopened.tabGroups?.[WT] ?? [] - expect(firstGroup).toBeTruthy() - expect(groups).toHaveLength(1) - expect(groups[0]?.id).not.toBe(firstGroup) - }) - it('save a chat opened with no client place at the end of the remembered active group', () => { const tab = (sessionId: string, groupId: string): Tab => ({ id: `structured-agent-session-${sessionId}`, diff --git a/src/main/runtime/agent-session/agent-session-tab-layout.ts b/src/main/runtime/session-tabs/chat/agent-session-tab-layout.ts similarity index 80% rename from src/main/runtime/agent-session/agent-session-tab-layout.ts rename to src/main/runtime/session-tabs/chat/agent-session-tab-layout.ts index 5e1a593f546..30fbfc07b47 100644 --- a/src/main/runtime/agent-session/agent-session-tab-layout.ts +++ b/src/main/runtime/session-tabs/chat/agent-session-tab-layout.ts @@ -1,18 +1,18 @@ // Persist windowless chat tabs too, so the host layout remains complete. -import type { AgentType } from '../../../shared/agent-status/contracts/agent-status-types' -import type { ExecutionHostId } from '../../../shared/execution-host/execution-host' -import { applyLayoutCommand } from '../../../shared/workspace-layout/workspace-layout-commands' -import { loadWorkspaceLayout } from '../../../shared/workspace-layout/persistence/workspace-layout-load' -import { nameBasedLoadContext } from '../../../shared/workspace-layout/persistence/workspace-layout-minted-ids' -import type { CommandOf } from '../../../shared/workspace-layout/workspace-layout-command-types' -import type { WorkspaceLayout } from '../../../shared/workspace-layout/workspace-layout-model' -import { saveWorkspaceLayout } from '../../../shared/workspace-layout/persistence/workspace-layout-save' -import type { WorkspaceSessionState } from '../../../shared/workspace-session/workspace-session-state-types' +import type { AgentType } from '../../../../shared/agent-status/contracts/agent-status-types' +import type { ExecutionHostId } from '../../../../shared/execution-host/execution-host' +import { applyLayoutCommand } from '../../../../shared/workspace-layout/workspace-layout-commands' +import { loadWorkspaceLayout } from '../../../../shared/workspace-layout/persistence/workspace-layout-load' +import { nameBasedLoadContext } from '../../../../shared/workspace-layout/persistence/workspace-layout-minted-ids' +import type { CommandOf } from '../../../../shared/workspace-layout/workspace-layout-command-types' +import type { WorkspaceLayout } from '../../../../shared/workspace-layout/workspace-layout-model' +import { saveWorkspaceLayout } from '../../../../shared/workspace-layout/persistence/workspace-layout-save' +import type { WorkspaceSessionState } from '../../../../shared/workspace-session/workspace-session-state-types' import { randomUUID } from 'node:crypto' -import { getStructuredAgentSessionHost } from '../../native-chat/agent-session-wire/host/structured-agent-session-registry' -import { structuredAgentSessionTabId } from '../../../shared/agent-session/view/structured-agent-session-projection' -import { isReopenedChatTabId } from '../../../shared/agent-session/view/structured-agent-session-host-tab-id' +import { getStructuredAgentSessionHost } from '../../../native-chat/agent-session-wire/host/structured-agent-session-registry' +import { structuredAgentSessionTabId } from '../../../../shared/agent-session/view/structured-agent-session-projection' +import { isReopenedChatTabId } from '../../../../shared/agent-session/view/structured-agent-session-host-tab-id' import { resolveChatTabActivation } from './agent-session-tab-identity' /** Placement in the creating client's host-owned group/tab ids. */ diff --git a/src/main/runtime/session-tabs/background-chat-tab-publication.ts b/src/main/runtime/session-tabs/chat/background-chat-tab-publication.ts similarity index 74% rename from src/main/runtime/session-tabs/background-chat-tab-publication.ts rename to src/main/runtime/session-tabs/chat/background-chat-tab-publication.ts index 9c2c82336c9..d3237e08bd2 100644 --- a/src/main/runtime/session-tabs/background-chat-tab-publication.ts +++ b/src/main/runtime/session-tabs/chat/background-chat-tab-publication.ts @@ -1,5 +1,5 @@ -import type { OrcaRuntimeService } from '../orca-runtime' -import type { StructuredAgentSessionHost } from '../../native-chat/agent-session-wire/host/structured-agent-session-host' +import type { OrcaRuntimeService } from '../../orca-runtime' +import type { StructuredAgentSessionHost } from '../../../native-chat/agent-session-wire/host/structured-agent-session-host' /** Reveals a chat session and publishes its tab without taking focus. */ export async function publishChatTabInBackground( diff --git a/src/main/runtime/session-tabs/restored-chat-tab-changes.ts b/src/main/runtime/session-tabs/chat/restored-chat-tab-changes.ts similarity index 83% rename from src/main/runtime/session-tabs/restored-chat-tab-changes.ts rename to src/main/runtime/session-tabs/chat/restored-chat-tab-changes.ts index b8e8f5ddc97..d5b90517ea0 100644 --- a/src/main/runtime/session-tabs/restored-chat-tab-changes.ts +++ b/src/main/runtime/session-tabs/chat/restored-chat-tab-changes.ts @@ -1,11 +1,11 @@ -import { OrcaRuntimeWithCloseMobileSessionTab } from '../session-lifecycle/close/close-mobile-session-tab' -import { getStructuredAgentSessionHost } from '../../native-chat/agent-session-wire/host/structured-agent-session-registry' -import type { RuntimeMobileSessionTabsSnapshot } from '../../../shared/remote-runtime/session-graph/runtime-session-contracts' -import { LOCAL_EXECUTION_HOST_ID } from '../../../shared/execution-host/execution-host' -import { retireStructuredAgentSessionTabFrom } from '../agent-session/structured-agent-session-tab-retirement' -import { chatTabChangesMatchingIndex } from '../agent-session/structured-agent-session-tab-index-seed' -import { chatTabId, type ChatTabChange } from '../agent-session/agent-session-tab-layout' -import { structuredSessionTabRetired } from '../orchestration/terminal-authority/structured-sessions/structured-worker-custody' +import { OrcaRuntimeWithCloseMobileSessionTab } from '../../session-lifecycle/close/close-mobile-session-tab' +import { getStructuredAgentSessionHost } from '../../../native-chat/agent-session-wire/host/structured-agent-session-registry' +import type { RuntimeMobileSessionTabsSnapshot } from '../../../../shared/remote-runtime/session-graph/runtime-session-contracts' +import { LOCAL_EXECUTION_HOST_ID } from '../../../../shared/execution-host/execution-host' +import { retireStructuredAgentSessionTabFrom } from './structured-agent-session-tab-retirement' +import { chatTabChangesMatchingIndex } from './structured-agent-session-tab-index-seed' +import { chatTabId, type ChatTabChange } from './agent-session-tab-layout' +import { structuredSessionTabRetired } from '../../orchestration/terminal-authority/structured-sessions/structured-worker-custody' type ChatTabOpen = Extract['open'] diff --git a/src/main/runtime/session-tabs/saved-conversation-title-publication.ts b/src/main/runtime/session-tabs/chat/saved-conversation-title-publication.ts similarity index 86% rename from src/main/runtime/session-tabs/saved-conversation-title-publication.ts rename to src/main/runtime/session-tabs/chat/saved-conversation-title-publication.ts index d5d0aefa282..dd5f684ad27 100644 --- a/src/main/runtime/session-tabs/saved-conversation-title-publication.ts +++ b/src/main/runtime/session-tabs/chat/saved-conversation-title-publication.ts @@ -1,13 +1,13 @@ -import { OrcaRuntimeWithScheduleMobileSessionTabsChanged } from './session-tabs-change-publication' +import { OrcaRuntimeWithScheduleMobileSessionTabsChanged } from '../publication/session-tabs-change-publication' import { StructuredConversationLabelChanges } from './structured-conversation-label-changes' import { retitleStructuredConversationTabs } from './structured-conversation-tab-title' -import { savedWorkspaceCatalog } from '../../persistence/profile-save-domains' -import { getStructuredAgentSessionHost } from '../../native-chat/agent-session-wire/host/structured-agent-session-registry' -import { ORCA_LAYOUT_OWNER_IS_MAIN } from '../../../shared/workspace-layout/layout-owner-switch' -import { structuredChatDisplayName } from '../../../shared/agent-session/view/structured-chat-row-name' -import { agentSessionRecordShownName } from '../agent-session/records/agent-session-record-shown-name' -import type { ExecutionHostId } from '../../../shared/execution-host/execution-host' -import type { RuntimeMobileSessionTabsSnapshot } from '../../../shared/remote-runtime/session-graph/runtime-session-contracts' +import { savedWorkspaceCatalog } from '../../../persistence/profile-save-domains' +import { getStructuredAgentSessionHost } from '../../../native-chat/agent-session-wire/host/structured-agent-session-registry' +import { ORCA_LAYOUT_OWNER_IS_MAIN } from '../../../../shared/workspace-layout/layout-owner-switch' +import { structuredChatDisplayName } from '../../../../shared/agent-session/view/structured-chat-row-name' +import { agentSessionRecordShownName } from '../../agent-session/records/agent-session-record-shown-name' +import type { ExecutionHostId } from '../../../../shared/execution-host/execution-host' +import type { RuntimeMobileSessionTabsSnapshot } from '../../../../shared/remote-runtime/session-graph/runtime-session-contracts' export abstract class OrcaRuntimeWithSavedConversationTitlePublication extends OrcaRuntimeWithScheduleMobileSessionTabsChanged { private labelChangesTracker?: StructuredConversationLabelChanges diff --git a/src/main/runtime/agent-session/structured-agent-session-tab-close-cause.ts b/src/main/runtime/session-tabs/chat/structured-agent-session-tab-close-cause.ts similarity index 59% rename from src/main/runtime/agent-session/structured-agent-session-tab-close-cause.ts rename to src/main/runtime/session-tabs/chat/structured-agent-session-tab-close-cause.ts index a2bdeaaab7b..16ba5a07f23 100644 --- a/src/main/runtime/agent-session/structured-agent-session-tab-close-cause.ts +++ b/src/main/runtime/session-tabs/chat/structured-agent-session-tab-close-cause.ts @@ -1,5 +1,5 @@ -import type { RuntimeSessionTabCloseReason } from '../../../shared/remote-runtime/session-graph/runtime-session-contracts' -import type { StructuredAgentSessionCloseCause } from '../../native-chat/agent-session-wire/termination/structured-agent-session-host-lifetime' +import type { RuntimeSessionTabCloseReason } from '../../../../shared/remote-runtime/session-graph/runtime-session-contracts' +import type { StructuredAgentSessionCloseCause } from '../../../native-chat/agent-session-wire/termination/structured-agent-session-host-lifetime' /** Missing reason means an older client's user close; lifecycle echoes do not represent user intent. */ export function structuredAgentSessionTabCloseCause( diff --git a/src/main/runtime/agent-session/structured-agent-session-tab-index-seed.ts b/src/main/runtime/session-tabs/chat/structured-agent-session-tab-index-seed.ts similarity index 84% rename from src/main/runtime/agent-session/structured-agent-session-tab-index-seed.ts rename to src/main/runtime/session-tabs/chat/structured-agent-session-tab-index-seed.ts index b0c8f869c19..eb37f14b34f 100644 --- a/src/main/runtime/agent-session/structured-agent-session-tab-index-seed.ts +++ b/src/main/runtime/session-tabs/chat/structured-agent-session-tab-index-seed.ts @@ -1,6 +1,6 @@ -import type { Tab } from '../../../shared/workspace-layout/tab-groups/tab-types' +import type { Tab } from '../../../../shared/workspace-layout/tab-groups/tab-types' import type { ChatTabChange } from './agent-session-tab-layout' -import { savedSessionId } from './lifecycle/saved-structured-agent-session-restoration' +import { savedSessionId } from '../../agent-session/lifecycle/saved-structured-agent-session-restoration' /** Match windowless saved tabs to the index: add legacy missing tabs and remove closed leftovers only while both records exist. */ export function chatTabChangesMatchingIndex( diff --git a/src/main/runtime/agent-session/structured-agent-session-tab-retirement.ts b/src/main/runtime/session-tabs/chat/structured-agent-session-tab-retirement.ts similarity index 82% rename from src/main/runtime/agent-session/structured-agent-session-tab-retirement.ts rename to src/main/runtime/session-tabs/chat/structured-agent-session-tab-retirement.ts index 9f85e7ba517..98ec698445c 100644 --- a/src/main/runtime/agent-session/structured-agent-session-tab-retirement.ts +++ b/src/main/runtime/session-tabs/chat/structured-agent-session-tab-retirement.ts @@ -1,9 +1,9 @@ -import { retireMobileSessionTabSelection } from '../session-tabs/mobile-session-tab-selection' +import { retireMobileSessionTabSelection } from '../layout/mobile-session-tab-selection' /** Share tab retirement between user close and orchestration settlement so dead tabs cannot reattach sessions. */ -import type { RuntimeMobileSessionSnapshotTab } from '../../../shared/remote-runtime/session-graph/runtime-mobile-session-tab-contracts' -import type { RuntimeMobileSessionTabsSnapshot } from '../../../shared/remote-runtime/session-graph/runtime-session-contracts' -import { structuredAgentSessionTabId } from '../../../shared/agent-session/view/structured-agent-session-projection' +import type { RuntimeMobileSessionSnapshotTab } from '../../../../shared/remote-runtime/session-graph/runtime-mobile-session-tab-contracts' +import type { RuntimeMobileSessionTabsSnapshot } from '../../../../shared/remote-runtime/session-graph/runtime-session-contracts' +import { structuredAgentSessionTabId } from '../../../../shared/agent-session/view/structured-agent-session-projection' export function findStructuredAgentSessionTab( snapshot: RuntimeMobileSessionTabsSnapshot, diff --git a/src/main/runtime/session-tabs/structured-conversation-label-changes.ts b/src/main/runtime/session-tabs/chat/structured-conversation-label-changes.ts similarity index 91% rename from src/main/runtime/session-tabs/structured-conversation-label-changes.ts rename to src/main/runtime/session-tabs/chat/structured-conversation-label-changes.ts index f2c4438234c..d9dd4b5b345 100644 --- a/src/main/runtime/session-tabs/structured-conversation-label-changes.ts +++ b/src/main/runtime/session-tabs/chat/structured-conversation-label-changes.ts @@ -1,7 +1,7 @@ -import type { ExecutionHostId } from '../../../shared/execution-host/execution-host' -import type { WorkspaceSessionState } from '../../../shared/workspace-session/workspace-session-state-types' -import type { RuntimeStore } from '../construction/runtime-store-contract' -import { partitionHoldsWorktree } from '../workspaces/session-hosts/twin-repo-session-host' +import type { ExecutionHostId } from '../../../../shared/execution-host/execution-host' +import type { WorkspaceSessionState } from '../../../../shared/workspace-session/workspace-session-state-types' +import type { RuntimeStore } from '../../construction/runtime-store-contract' +import { partitionHoldsWorktree } from '../../workspaces/session-hosts/twin-repo-session-host' type LabelBaseline = { hostId: ExecutionHostId | null diff --git a/src/main/runtime/session-tabs/structured-conversation-tab-title.ts b/src/main/runtime/session-tabs/chat/structured-conversation-tab-title.ts similarity index 86% rename from src/main/runtime/session-tabs/structured-conversation-tab-title.ts rename to src/main/runtime/session-tabs/chat/structured-conversation-tab-title.ts index aa4245b77ce..ed6a9314131 100644 --- a/src/main/runtime/session-tabs/structured-conversation-tab-title.ts +++ b/src/main/runtime/session-tabs/chat/structured-conversation-tab-title.ts @@ -1,6 +1,6 @@ -import { defaultAgentChatLabel } from '../../../shared/agent-session/conversation-naming/agent-session-chat-label' -import type { RuntimeMobileSessionAgentTab } from '../../../shared/remote-runtime/session-graph/runtime-mobile-session-tab-contracts' -import type { RuntimeMobileSessionTabsSnapshot } from '../../../shared/remote-runtime/session-graph/runtime-session-contracts' +import { defaultAgentChatLabel } from '../../../../shared/agent-session/conversation-naming/agent-session-chat-label' +import type { RuntimeMobileSessionAgentTab } from '../../../../shared/remote-runtime/session-graph/runtime-mobile-session-tab-contracts' +import type { RuntimeMobileSessionTabsSnapshot } from '../../../../shared/remote-runtime/session-graph/runtime-session-contracts' /** Whether a chat is a fork on this host, so phones draw its fork mark. */ export type StructuredConversationForked = (sessionId: string) => boolean diff --git a/src/main/runtime/session-tabs/structured-session-account-home.ts b/src/main/runtime/session-tabs/chat/structured-session-account-home.ts similarity index 83% rename from src/main/runtime/session-tabs/structured-session-account-home.ts rename to src/main/runtime/session-tabs/chat/structured-session-account-home.ts index 17b81c9db81..f41fa3c2000 100644 --- a/src/main/runtime/session-tabs/structured-session-account-home.ts +++ b/src/main/runtime/session-tabs/chat/structured-session-account-home.ts @@ -1,11 +1,11 @@ -import type { StructuredAgentId } from '../../../shared/agent-session/lifecycle/provider-handles/agent-session-provider-handle' -import { structuredAgentRuntimeMetadata } from '../agent-session/installation/structured-agent-runtime-metadata' -import { getProfileUserDataPath } from '../../orca-profiles/profile-storage-paths' -import { resolveHostStructuredAgentLaunchEnvironment } from '../agent-session/launch/structured-agent-launch-support' -import { agentWorkspaceTrustDecisionForWorkspace } from '../../agent-launch/trust/agent-workspace-trust-spawn' +import type { StructuredAgentId } from '../../../../shared/agent-session/lifecycle/provider-handles/agent-session-provider-handle' +import { structuredAgentRuntimeMetadata } from '../../agent-session/installation/structured-agent-runtime-metadata' +import { getProfileUserDataPath } from '../../../orca-profiles/profile-storage-paths' +import { resolveHostStructuredAgentLaunchEnvironment } from '../../agent-session/launch/structured-agent-launch-support' +import { agentWorkspaceTrustDecisionForWorkspace } from '../../../agent-launch/trust/agent-workspace-trust-spawn' import { OrcaRuntimeWithStructuredSessionCliWriterHost } from './structured-session-cli-writer-host' -import type { AgentSessionAccountHome } from '../../../shared/agent-session/lifecycle/accounts/agent-session-account-home' -import type { AgentSessionRecord } from '../../../shared/agent-session/lifecycle/agent-session-record' +import type { AgentSessionAccountHome } from '../../../../shared/agent-session/lifecycle/accounts/agent-session-account-home' +import type { AgentSessionRecord } from '../../../../shared/agent-session/lifecycle/agent-session-record' export abstract class OrcaRuntimeWithStructuredSessionAccountHome extends OrcaRuntimeWithStructuredSessionCliWriterHost { /** Resolve account home through this host's agent registration; null means unregistered and create refuses. */ diff --git a/src/main/runtime/session-tabs/structured-session-cli-writer-host.ts b/src/main/runtime/session-tabs/chat/structured-session-cli-writer-host.ts similarity index 75% rename from src/main/runtime/session-tabs/structured-session-cli-writer-host.ts rename to src/main/runtime/session-tabs/chat/structured-session-cli-writer-host.ts index 7b508cb4f79..048abcc0746 100644 --- a/src/main/runtime/session-tabs/structured-session-cli-writer-host.ts +++ b/src/main/runtime/session-tabs/chat/structured-session-cli-writer-host.ts @@ -1,16 +1,16 @@ import { terminalLaunchFacts, type TerminalLaunchResult -} from '../../../shared/agent-session/lifecycle/agent-session-resume' -import { LOCAL_EXECUTION_HOST_ID } from '../../../shared/execution-host/execution-host' -import type { StructuredAgentId } from '../../../shared/agent-session/lifecycle/provider-handles/agent-session-provider-handle' -import { assertCliConversationWritersExited } from '../agent-session/lifecycle/structured-agent-cli-writers' -import type { EnrichedAgentHookEventPayload } from '../../agent-hooks/server/server-types' -import type { AgentSessionRecord } from '../../../shared/agent-session/lifecycle/agent-session-record' -import { CLI_CONVERSATION_ADOPTING_AGENTS } from '../../../shared/agent-session/view/structured-agent-cli-conversation-adoption' -import { recordConversationKey } from '../../native-chat/conversation-adoption/structured-conversation-key' -import type { StructuredAgentCliSourceRoute } from '../../native-chat/conversation-adoption/structured-agent-cli-source' -import { OrcaRuntimeWithGetWorktreePs } from '../workspaces/process-listing/workspace-process-listing' +} from '../../../../shared/agent-session/lifecycle/agent-session-resume' +import { LOCAL_EXECUTION_HOST_ID } from '../../../../shared/execution-host/execution-host' +import type { StructuredAgentId } from '../../../../shared/agent-session/lifecycle/provider-handles/agent-session-provider-handle' +import { assertCliConversationWritersExited } from '../../agent-session/lifecycle/structured-agent-cli-writers' +import type { EnrichedAgentHookEventPayload } from '../../../agent-hooks/server/server-types' +import type { AgentSessionRecord } from '../../../../shared/agent-session/lifecycle/agent-session-record' +import { CLI_CONVERSATION_ADOPTING_AGENTS } from '../../../../shared/agent-session/view/structured-agent-cli-conversation-adoption' +import { recordConversationKey } from '../../../native-chat/conversation-adoption/structured-conversation-key' +import type { StructuredAgentCliSourceRoute } from '../../../native-chat/conversation-adoption/structured-agent-cli-source' +import { OrcaRuntimeWithGetWorktreePs } from '../../workspaces/process-listing/workspace-process-listing' export abstract class OrcaRuntimeWithStructuredSessionCliWriterHost extends OrcaRuntimeWithGetWorktreePs { getStructuredAgentCliSourceRoute(source: { diff --git a/src/main/runtime/session-tabs/structured-session-create-support.ts b/src/main/runtime/session-tabs/chat/structured-session-create-support.ts similarity index 86% rename from src/main/runtime/session-tabs/structured-session-create-support.ts rename to src/main/runtime/session-tabs/chat/structured-session-create-support.ts index 26020a323a3..0375911c62c 100644 --- a/src/main/runtime/session-tabs/structured-session-create-support.ts +++ b/src/main/runtime/session-tabs/chat/structured-session-create-support.ts @@ -1,35 +1,35 @@ -import { AGENT_CHAT_PERMISSION_MODE_OPTION_ID } from '../../../shared/agent-launch/permissions/agent-chat-permission-mode' -import { resolveStructuredAgentSessionForkIntent } from '../../native-chat/agent-session-wire/acquisition/structured-agent-session-fork-intent' +import { AGENT_CHAT_PERMISSION_MODE_OPTION_ID } from '../../../../shared/agent-launch/permissions/agent-chat-permission-mode' +import { resolveStructuredAgentSessionForkIntent } from '../../../native-chat/agent-session-wire/acquisition/structured-agent-session-fork-intent' import { captureStructuredAgentCliSource, structuredAgentCliSourceFromEvidence -} from '../../native-chat/conversation-adoption/structured-agent-cli-source' +} from '../../../native-chat/conversation-adoption/structured-agent-cli-source' import type { OrcaRuntimeWithRestoreStructuredAgentSessionTabsOnce as RestoreStructuredAgentSessionTabsOnceMethods } from './structured-session-tab-restoration' -import { agentSessionRefusalError } from '../../../shared/agent-session/failures/agent-session-wire-refusals' +import { agentSessionRefusalError } from '../../../../shared/agent-session/failures/agent-session-wire-refusals' import { StructuredSessionWorkspaceScope } from './structured-session-workspace-scope' -import { getStructuredAgentSessionHost } from '../../native-chat/agent-session-wire/host/structured-agent-session-registry' +import { getStructuredAgentSessionHost } from '../../../native-chat/agent-session-wire/host/structured-agent-session-registry' import { resolveCommittedStructuredAgentSessionAdoptionIntent, requireUnownedStructuredAgentSessionAdoption, resolveStructuredAgentSessionAdoptionForCreate, structuredAgentSessionAdoptAttach, type StructuredAgentSessionCreateIntentInput -} from '../agent-session/structured-agent-session-create-adoption' -import type { AgentSessionAttachParams } from '../../native-chat/agent-session-wire/acquisition/structured-agent-session-attach' +} from '../../agent-session/ownership/structured-agent-session-create-adoption' +import type { AgentSessionAttachParams } from '../../../native-chat/agent-session-wire/acquisition/structured-agent-session-attach' import { resolveHostStructuredAgentCreateSupport, resolveHostStructuredAgentLaunchEnvironment -} from '../agent-session/launch/structured-agent-launch-support' -import { structuredAgentRuntimeMetadata } from '../agent-session/installation/structured-agent-runtime-metadata' -import { structuredAgentChatProgramNeedsInstall } from '../agent-session/launch/structured-agent-availability' -import { structuredLaunchSeedOptions } from '../../../shared/native-chat/input/session-options/native-chat-session-option-defaults' -import { hasPersistedStructuredAgentSessionStore as hasPersistedStructuredAgentSessionStoreOnDisk } from '../agent-session/records/agent-session-record-store-slot' -import { ensureStructuredAgentSessionHostUnlessRefused } from '../agent-session/structured-agent-session-host-refusal' -import { getProfileUserDataPath } from '../../orca-profiles/profile-storage-paths' -import { isFloatingWorkspaceSelector } from '../../../shared/workspace/identity/floating-workspace-worktree' -import type { AgentSessionAccountHome } from '../../../shared/agent-session/lifecycle/accounts/agent-session-account-home' -import type { StructuredAgentId } from '../../../shared/agent-session/lifecycle/provider-handles/agent-session-provider-handle' -import type { StructuredAgentCreateSupportReply } from '../../../shared/agent-session/lifecycle/operations/structured-agent-create-support-reply' +} from '../../agent-session/launch/structured-agent-launch-support' +import { structuredAgentRuntimeMetadata } from '../../agent-session/installation/structured-agent-runtime-metadata' +import { structuredAgentChatProgramNeedsInstall } from '../../agent-session/launch/structured-agent-availability' +import { structuredLaunchSeedOptions } from '../../../../shared/native-chat/input/session-options/native-chat-session-option-defaults' +import { hasPersistedStructuredAgentSessionStore as hasPersistedStructuredAgentSessionStoreOnDisk } from '../../agent-session/records/agent-session-record-store-slot' +import { ensureStructuredAgentSessionHostUnlessRefused } from '../../agent-session/installation/structured-agent-session-host-refusal' +import { getProfileUserDataPath } from '../../../orca-profiles/profile-storage-paths' +import { isFloatingWorkspaceSelector } from '../../../../shared/workspace/identity/floating-workspace-worktree' +import type { AgentSessionAccountHome } from '../../../../shared/agent-session/lifecycle/accounts/agent-session-account-home' +import type { StructuredAgentId } from '../../../../shared/agent-session/lifecycle/provider-handles/agent-session-provider-handle' +import type { StructuredAgentCreateSupportReply } from '../../../../shared/agent-session/lifecycle/operations/structured-agent-create-support-reply' export abstract class OrcaRuntimeWithGetStructuredAgentSessionCreateSupport extends StructuredSessionWorkspaceScope { protected abstract restoreStructuredAgentSessionTabsOnce( diff --git a/src/main/runtime/agent-session/structured-session-renderer-close.ts b/src/main/runtime/session-tabs/chat/structured-session-renderer-close.ts similarity index 83% rename from src/main/runtime/agent-session/structured-session-renderer-close.ts rename to src/main/runtime/session-tabs/chat/structured-session-renderer-close.ts index 2db8ce1f539..37b24941a0e 100644 --- a/src/main/runtime/agent-session/structured-session-renderer-close.ts +++ b/src/main/runtime/session-tabs/chat/structured-session-renderer-close.ts @@ -1,4 +1,4 @@ -import { SESSION_TAB_NOT_FOUND_ERROR } from '../../../shared/workspace-layout/client-views/session-tab-close' +import { SESSION_TAB_NOT_FOUND_ERROR } from '../../../../shared/workspace-layout/client-views/session-tab-close' /** A renderer that already removed the captured tab has acknowledged the close. */ export async function closeRenderedStructuredSessionTab( diff --git a/src/main/runtime/session-tabs/structured-session-tab-close.ts b/src/main/runtime/session-tabs/chat/structured-session-tab-close.ts similarity index 86% rename from src/main/runtime/session-tabs/structured-session-tab-close.ts rename to src/main/runtime/session-tabs/chat/structured-session-tab-close.ts index 29680f3be92..e07902aec73 100644 --- a/src/main/runtime/session-tabs/structured-session-tab-close.ts +++ b/src/main/runtime/session-tabs/chat/structured-session-tab-close.ts @@ -1,34 +1,30 @@ -import { retireMobileSessionTabSelection } from './mobile-session-tab-selection' -import { LOCAL_EXECUTION_HOST_ID } from '../../../shared/execution-host/execution-host' -import type { OrcaRuntimeWithStoredMobileSnapshotHasStalePreservedTab as BrowserOwnership } from './mobile-session-publication-preservation' -import type { OrcaRuntimeWithPruneMobileSessionTabGroupLayout as PruneMobileSessionTabGroupLayoutMethods } from '../session-lifecycle/projection/prune-mobile-session-tab-group-layout' -import type { RuntimeHeadlessTabGroups as HeadlessTabGroupsMethods } from './headless-tab-group-moves' +import { retireMobileSessionTabSelection } from '../layout/mobile-session-tab-selection' +import { LOCAL_EXECUTION_HOST_ID } from '../../../../shared/execution-host/execution-host' +import type { OrcaRuntimeWithStoredMobileSnapshotHasStalePreservedTab as BrowserOwnership } from '../restoration/mobile-session-publication-preservation' +import type { OrcaRuntimeWithPruneMobileSessionTabGroupLayout as PruneMobileSessionTabGroupLayoutMethods } from '../../session-lifecycle/projection/prune-mobile-session-tab-group-layout' +import type { RuntimeHeadlessTabGroups as HeadlessTabGroupsMethods } from '../layout/headless-tab-group-moves' import { OrcaRuntimeWithStructuredSessionTabProjection } from './restored-chat-tab-changes' -import type { BrowserTabInfo } from '../../../shared/browser/runtime/runtime-browser-contracts' +import type { BrowserTabInfo } from '../../../../shared/browser/runtime/runtime-browser-contracts' import type { RuntimeMobileSessionAgentTab, RuntimeMobileSessionBrowserTab, RuntimeMobileSessionTerminalTab -} from '../../../shared/remote-runtime/session-graph/runtime-mobile-session-tab-contracts' +} from '../../../../shared/remote-runtime/session-graph/runtime-mobile-session-tab-contracts' import type { RuntimeMobileSessionRetiredTerminalSurface, RuntimeMobileSessionTabsSnapshot -} from '../../../shared/remote-runtime/session-graph/runtime-session-contracts' -import type { RuntimePtyWorktreeRecord } from '../terminal/records/runtime-terminal-state-records' -import type { BrowserSessionTabSelectionOptions } from '../browser/tabs/browser-tab-create-publication' -import { getRuntimeBrowserPageRegistry } from '../browser/client-pages/runtime-browser-page-registry' -import { applyBrowserSessionTabSelection } from '../browser/tabs/browser-session-tab-selection-snapshot' -import { getStructuredAgentSessionHost } from '../../native-chat/agent-session-wire/host/structured-agent-session-registry' -import type { StructuredAgentSessionCloseCause } from '../../native-chat/agent-session-wire/termination/structured-agent-session-host-lifetime' -import { - chatTabId, - withChatTabChanges, - type ChatTabChange -} from '../agent-session/agent-session-tab-layout' -import { createChatTabLayoutQueue } from '../agent-session/agent-session-tab-layout-queue' -import type * as LayoutCommands from '../terminal/layout/runtime-layout-apply' -import { ORCA_LAYOUT_OWNER_IS_MAIN } from '../../../shared/workspace-layout/layout-owner-switch' -import type { LayoutApplyReply } from '../../../shared/workspace-layout/workspace-layout-command-types' +} from '../../../../shared/remote-runtime/session-graph/runtime-session-contracts' +import type { RuntimePtyWorktreeRecord } from '../../terminal/records/runtime-terminal-state-records' +import type { BrowserSessionTabSelectionOptions } from '../../browser/tabs/browser-tab-create-publication' +import { getRuntimeBrowserPageRegistry } from '../../browser/client-pages/runtime-browser-page-registry' +import { applyBrowserSessionTabSelection } from '../../browser/tabs/browser-session-tab-selection-snapshot' +import { getStructuredAgentSessionHost } from '../../../native-chat/agent-session-wire/host/structured-agent-session-registry' +import type { StructuredAgentSessionCloseCause } from '../../../native-chat/agent-session-wire/termination/structured-agent-session-host-lifetime' +import { chatTabId, withChatTabChanges, type ChatTabChange } from './agent-session-tab-layout' +import { createChatTabLayoutQueue } from './agent-session-tab-layout-queue' +import type * as LayoutCommands from '../../terminal/layout/runtime-layout-apply' +import { ORCA_LAYOUT_OWNER_IS_MAIN } from '../../../../shared/workspace-layout/layout-owner-switch' +import type { LayoutApplyReply } from '../../../../shared/workspace-layout/workspace-layout-command-types' import { captureStructuredSessionPresentation, capturedStructuredSessionSavedTabChanges, @@ -38,7 +34,7 @@ import type { StructuredSessionTabPublicationInput as ChatPublication } from './ import { closeCapturedStructuredSession, type StructuredSessionSurface -} from '../agent-session/structured-agent-session-close' +} from '../../agent-session/lifecycle/structured-agent-session-close' export abstract class OrcaRuntimeWithCloseStructuredAgentSessionTab extends OrcaRuntimeWithStructuredSessionTabProjection { protected abstract isHeadlessOwnedMobileBrowserTab( diff --git a/src/main/runtime/session-tabs/structured-session-tab-presentation.ts b/src/main/runtime/session-tabs/chat/structured-session-tab-presentation.ts similarity index 80% rename from src/main/runtime/session-tabs/structured-session-tab-presentation.ts rename to src/main/runtime/session-tabs/chat/structured-session-tab-presentation.ts index 1ddd601d05c..f8135016ae9 100644 --- a/src/main/runtime/session-tabs/structured-session-tab-presentation.ts +++ b/src/main/runtime/session-tabs/chat/structured-session-tab-presentation.ts @@ -1,20 +1,20 @@ import type { RuntimeMobileSessionTabsSnapshot, RuntimeSessionTabCloseReason -} from '../../../shared/remote-runtime/session-graph/runtime-session-contracts' -import type { RuntimeMobileSessionAgentTab } from '../../../shared/remote-runtime/session-graph/runtime-mobile-session-tab-contracts' -import { closeRenderedStructuredSessionTab } from '../agent-session/structured-session-renderer-close' +} from '../../../../shared/remote-runtime/session-graph/runtime-session-contracts' +import type { RuntimeMobileSessionAgentTab } from '../../../../shared/remote-runtime/session-graph/runtime-mobile-session-tab-contracts' +import { closeRenderedStructuredSessionTab } from './structured-session-renderer-close' import { captureInstalledStructuredSessionSurface, closeCapturedStructuredSession, type StructuredSessionSurfaceRuntime -} from '../agent-session/structured-agent-session-close' -import { getStructuredAgentSessionHost } from '../../native-chat/agent-session-wire/host/structured-agent-session-registry' -import { structuredAgentSessionTabCloseCause } from '../agent-session/structured-agent-session-tab-close-cause' -import { isReopenedChatTabId } from '../../../shared/agent-session/view/structured-agent-session-host-tab-id' -import type { WorkspaceSessionState } from '../../../shared/workspace-session/workspace-session-state-types' -import { savedSessionId } from '../agent-session/lifecycle/saved-structured-agent-session-restoration' -import type { QueuedChatTabChange } from '../agent-session/agent-session-tab-layout-queue' +} from '../../agent-session/lifecycle/structured-agent-session-close' +import { getStructuredAgentSessionHost } from '../../../native-chat/agent-session-wire/host/structured-agent-session-registry' +import { structuredAgentSessionTabCloseCause } from './structured-agent-session-tab-close-cause' +import { isReopenedChatTabId } from '../../../../shared/agent-session/view/structured-agent-session-host-tab-id' +import type { WorkspaceSessionState } from '../../../../shared/workspace-session/workspace-session-state-types' +import { savedSessionId } from '../../agent-session/lifecycle/saved-structured-agent-session-restoration' +import type { QueuedChatTabChange } from './agent-session-tab-layout-queue' type Surface = { worktreeId: string; tabId: string } diff --git a/src/main/runtime/session-tabs/structured-session-tab-publication.ts b/src/main/runtime/session-tabs/chat/structured-session-tab-publication.ts similarity index 86% rename from src/main/runtime/session-tabs/structured-session-tab-publication.ts rename to src/main/runtime/session-tabs/chat/structured-session-tab-publication.ts index a1427b4178b..a84f03cc62c 100644 --- a/src/main/runtime/session-tabs/structured-session-tab-publication.ts +++ b/src/main/runtime/session-tabs/chat/structured-session-tab-publication.ts @@ -1,25 +1,25 @@ import { normalizeMobileSessionTabSelection, selectMobileSessionTab -} from './mobile-session-tab-selection' -import type { OrcaRuntimeService } from '../orca-runtime' -import type { RuntimeMobileSessionAgentTab } from '../../../shared/remote-runtime/session-graph/runtime-mobile-session-tab-contracts' -import type { RuntimeMobileSessionTabsSnapshot } from '../../../shared/remote-runtime/session-graph/runtime-session-contracts' -import { defaultAgentChatLabel } from '../../../shared/agent-session/conversation-naming/agent-session-chat-label' -import { getHeadlessMobileSessionGroupId } from '../terminal/surface/mobile-session-layout-projection' -import type { StructuredSessionSurface } from '../agent-session/structured-agent-session-close' -import type { StructuredAgentId } from '../../../shared/agent-session/lifecycle/provider-handles/agent-session-provider-handle' -import { insertTabIdIntoOrder } from '../../../shared/workspace-layout/tab-groups/tab-order' +} from '../layout/mobile-session-tab-selection' +import type { OrcaRuntimeService } from '../../orca-runtime' +import type { RuntimeMobileSessionAgentTab } from '../../../../shared/remote-runtime/session-graph/runtime-mobile-session-tab-contracts' +import type { RuntimeMobileSessionTabsSnapshot } from '../../../../shared/remote-runtime/session-graph/runtime-session-contracts' +import { defaultAgentChatLabel } from '../../../../shared/agent-session/conversation-naming/agent-session-chat-label' +import { getHeadlessMobileSessionGroupId } from '../../terminal/surface/mobile-session-layout-projection' +import type { StructuredSessionSurface } from '../../agent-session/lifecycle/structured-agent-session-close' +import type { StructuredAgentId } from '../../../../shared/agent-session/lifecycle/provider-handles/agent-session-provider-handle' +import { insertTabIdIntoOrder } from '../../../../shared/workspace-layout/tab-groups/tab-order' import { chatTabId, resolveChatTabPlacement, type ChatTabPlacement -} from '../agent-session/agent-session-tab-layout' -import { getStructuredAgentSessionHost } from '../../native-chat/agent-session-wire/host/structured-agent-session-registry' -import { mobileChatTabId, newReopenedChatTabId } from '../agent-session/agent-session-tab-identity' -import { isReopenedChatTabId } from '../../../shared/agent-session/view/structured-agent-session-host-tab-id' -import type { MainSessionTabRows } from './main-session-tab-rows' -import { withMainTabOrder } from './main-session-tab-order' +} from './agent-session-tab-layout' +import { getStructuredAgentSessionHost } from '../../../native-chat/agent-session-wire/host/structured-agent-session-registry' +import { mobileChatTabId, newReopenedChatTabId } from './agent-session-tab-identity' +import { isReopenedChatTabId } from '../../../../shared/agent-session/view/structured-agent-session-host-tab-id' +import type { MainSessionTabRows } from '../layout/main-session-tab-rows' +import { withMainTabOrder } from '../layout/main-session-tab-order' export type StructuredSessionTabPublicationInput = { workspaceId: string diff --git a/src/main/runtime/session-tabs/structured-session-tab-rename.ts b/src/main/runtime/session-tabs/chat/structured-session-tab-rename.ts similarity index 83% rename from src/main/runtime/session-tabs/structured-session-tab-rename.ts rename to src/main/runtime/session-tabs/chat/structured-session-tab-rename.ts index 15bf9fb9b50..21546609caf 100644 --- a/src/main/runtime/session-tabs/structured-session-tab-rename.ts +++ b/src/main/runtime/session-tabs/chat/structured-session-tab-rename.ts @@ -1,5 +1,5 @@ -import { getStructuredAgentSessionHost } from '../../native-chat/agent-session-wire/host/structured-agent-session-registry' -import type { RuntimeMobileSessionTabsSnapshot } from '../../../shared/remote-runtime/session-graph/runtime-session-contracts' +import { getStructuredAgentSessionHost } from '../../../native-chat/agent-session-wire/host/structured-agent-session-registry' +import type { RuntimeMobileSessionTabsSnapshot } from '../../../../shared/remote-runtime/session-graph/runtime-session-contracts' export type SessionTabProps = { tabId: string diff --git a/src/main/runtime/session-tabs/structured-session-tab-restoration.ts b/src/main/runtime/session-tabs/chat/structured-session-tab-restoration.ts similarity index 87% rename from src/main/runtime/session-tabs/structured-session-tab-restoration.ts rename to src/main/runtime/session-tabs/chat/structured-session-tab-restoration.ts index 25494c81f60..7d838ced27a 100644 --- a/src/main/runtime/session-tabs/structured-session-tab-restoration.ts +++ b/src/main/runtime/session-tabs/chat/structured-session-tab-restoration.ts @@ -4,33 +4,33 @@ import { type StructuredSessionRawPublicationInput, type StructuredSessionTabPublicationInput } from './structured-session-tab-publication' -import type { OrcaRuntimeWithScheduleMobileSessionTabsChanged as ScheduleMobileSessionTabsChangedMethods } from './session-tabs-change-publication' +import type { OrcaRuntimeWithScheduleMobileSessionTabsChanged as ScheduleMobileSessionTabsChangedMethods } from '../publication/session-tabs-change-publication' import { OrcaRuntimeWithGetStructuredAgentSessionCreateSupport } from './structured-session-create-support' -import { getStructuredAgentSessionHost } from '../../native-chat/agent-session-wire/host/structured-agent-session-registry' -import { LOCAL_EXECUTION_HOST_ID } from '../../../shared/execution-host/execution-host' +import { getStructuredAgentSessionHost } from '../../../native-chat/agent-session-wire/host/structured-agent-session-registry' +import { LOCAL_EXECUTION_HOST_ID } from '../../../../shared/execution-host/execution-host' import { restoredChatTabChanges } from './restored-chat-tab-changes' -import { ORCA_LAYOUT_OWNER_IS_MAIN } from '../../../shared/workspace-layout/layout-owner-switch' -import type { RuntimeRepoSearchRefs } from '../../../shared/worktree/catalog/runtime-worktree-contracts' -import { REPO_SEARCH_REFS_DEFAULT_LIMIT as DEFAULT_REPO_SEARCH_REFS_LIMIT } from '../../../shared/git/refs/repo-search-limits' -import type { Repo } from '../../../shared/repository/repo-types' -import type { GitAdmissionTier } from '../../../shared/rpc-contract/source-control/git-admission-tier-params' +import { ORCA_LAYOUT_OWNER_IS_MAIN } from '../../../../shared/workspace-layout/layout-owner-switch' +import type { RuntimeRepoSearchRefs } from '../../../../shared/worktree/catalog/runtime-worktree-contracts' +import { REPO_SEARCH_REFS_DEFAULT_LIMIT as DEFAULT_REPO_SEARCH_REFS_LIMIT } from '../../../../shared/git/refs/repo-search-limits' +import type { Repo } from '../../../../shared/repository/repo-types' +import type { GitAdmissionTier } from '../../../../shared/rpc-contract/source-control/git-admission-tier-params' import { getLocalProjectGhExecOptions, type LocalProjectGhExecOptions -} from '../../workspaces/execution-host/project-runtime-git-options' +} from '../../../workspaces/execution-host/project-runtime-git-options' import { agentLaunchPlatformForScope, newWorktreeLaunchScope, resolveAgentLaunchRuntime, resolveStartupAgentLaunchRuntime -} from '../terminal/launch/agent-launch-scope-runtime' -import type { TuiAgent } from '../../../shared/agent-launch/catalog/tui-agent' -import type { AgentLaunchRuntime } from '../../../shared/agent-launch/startup/agent-launch-runtime' -import type { TerminalWorkspaceLaunchScope } from '../orchestration/terminal-authority/structured-sessions/runtime-legacy-worker-terminal-recovery-types' -import { parseAppSshPtyId } from '../../../shared/remote-runtime/ssh/ssh-pty-id' -import type { TerminalProcessInspection as PtyProcessInspection } from '../../../shared/terminal/pty/lifecycle/terminal-process-inspection' -import type { MainSessionTabRows } from './main-session-tab-rows' -import { isReopenedChatTabId } from '../../../shared/agent-session/view/structured-agent-session-host-tab-id' +} from '../../terminal/launch/agent-launch-scope-runtime' +import type { TuiAgent } from '../../../../shared/agent-launch/catalog/tui-agent' +import type { AgentLaunchRuntime } from '../../../../shared/agent-launch/startup/agent-launch-runtime' +import type { TerminalWorkspaceLaunchScope } from '../../orchestration/terminal-authority/structured-sessions/runtime-legacy-worker-terminal-recovery-types' +import { parseAppSshPtyId } from '../../../../shared/remote-runtime/ssh/ssh-pty-id' +import type { TerminalProcessInspection as PtyProcessInspection } from '../../../../shared/terminal/pty/lifecycle/terminal-process-inspection' +import type { MainSessionTabRows } from '../layout/main-session-tab-rows' +import { isReopenedChatTabId } from '../../../../shared/agent-session/view/structured-agent-session-host-tab-id' export type AgentLaunchScope = Parameters< OrcaRuntimeWithRestoreStructuredAgentSessionTabsOnce['getAgentLaunchPlatformForWorkspace'] diff --git a/src/main/runtime/session-tabs/structured-session-workspace-scope.ts b/src/main/runtime/session-tabs/chat/structured-session-workspace-scope.ts similarity index 84% rename from src/main/runtime/session-tabs/structured-session-workspace-scope.ts rename to src/main/runtime/session-tabs/chat/structured-session-workspace-scope.ts index 332e8dd5b01..29ddd51de13 100644 --- a/src/main/runtime/session-tabs/structured-session-workspace-scope.ts +++ b/src/main/runtime/session-tabs/chat/structured-session-workspace-scope.ts @@ -1,27 +1,27 @@ import { prepareStructuredWorkspaceAuthority } from './structured-workspace-authority' -import type { AgentSessionExecutionLocation } from '../../../shared/agent-session/lifecycle/agent-session-record' +import type { AgentSessionExecutionLocation } from '../../../../shared/agent-session/lifecycle/agent-session-record' import { OrcaRuntimeWithStructuredSessionAccountHome } from './structured-session-account-home' import { isNativeLocalLocation, LOCAL_EXECUTION_HOST_ID, getConnectionExecutionHostId, getRepoExecutionHostId -} from '../../../shared/execution-host/execution-host' -import { getLocalProjectWorktreeGitOptions } from '../../workspaces/execution-host/project-runtime-git-options' +} from '../../../../shared/execution-host/execution-host' +import { getLocalProjectWorktreeGitOptions } from '../../../workspaces/execution-host/project-runtime-git-options' import { isFloatingWorkspaceId, isFloatingWorkspaceSelector -} from '../../../shared/workspace/identity/floating-workspace-worktree' -import { parseWslUncPath } from '../../../shared/file-access/wsl-paths' -import { parseWorkspaceKey } from '../../../shared/workspace/identity/workspace-scope' -import { composeWorktreeId, splitWorktreeIdForFilesystem } from '../../../shared/worktree/id' -import { resolveWorktreeHostRouting } from '../workspaces/catalog/worktree-launch-host-repo' -import type { RuntimeWorkspaceFileTargets } from '../workspaces/workspace-file-session-targets' -import type { OrcaRuntimeWithTransitionGraphReloadToTerminalState } from '../session-graph/session-graph-authority' -import type { RuntimeWorkspaceCatalog } from '../workspaces/catalog/workspace-catalog' -import type { RuntimeWorkspaceSelectors } from '../workspaces/workspace-selectors' -import { getStructuredAgentSessionHost } from '../../native-chat/agent-session-wire/host/structured-agent-session-registry' -import type { NotificationAttentionAcknowledgement } from '../../../shared/notifications/notification-settings-types' +} from '../../../../shared/workspace/identity/floating-workspace-worktree' +import { parseWslUncPath } from '../../../../shared/file-access/wsl-paths' +import { parseWorkspaceKey } from '../../../../shared/workspace/identity/workspace-scope' +import { composeWorktreeId, splitWorktreeIdForFilesystem } from '../../../../shared/worktree/id' +import { resolveWorktreeHostRouting } from '../../workspaces/catalog/worktree-launch-host-repo' +import type { RuntimeWorkspaceFileTargets } from '../../workspaces/workspace-file-session-targets' +import type { OrcaRuntimeWithTransitionGraphReloadToTerminalState } from '../../session-graph/session-graph-authority' +import type { RuntimeWorkspaceCatalog } from '../../workspaces/catalog/workspace-catalog' +import type { RuntimeWorkspaceSelectors } from '../../workspaces/workspace-selectors' +import { getStructuredAgentSessionHost } from '../../../native-chat/agent-session-wire/host/structured-agent-session-registry' +import type { NotificationAttentionAcknowledgement } from '../../../../shared/notifications/notification-settings-types' export abstract class StructuredSessionWorkspaceScope extends OrcaRuntimeWithStructuredSessionAccountHome { protected abstract resolveFolderWorkspaceSelector( diff --git a/src/main/runtime/session-tabs/structured-workspace-authority.test-fixture.ts b/src/main/runtime/session-tabs/chat/structured-workspace-authority.test-fixture.ts similarity index 79% rename from src/main/runtime/session-tabs/structured-workspace-authority.test-fixture.ts rename to src/main/runtime/session-tabs/chat/structured-workspace-authority.test-fixture.ts index 690adf8c02a..396f144d57e 100644 --- a/src/main/runtime/session-tabs/structured-workspace-authority.test-fixture.ts +++ b/src/main/runtime/session-tabs/chat/structured-workspace-authority.test-fixture.ts @@ -1,4 +1,4 @@ -import type { OrcaRuntimeService } from '../orca-runtime' +import type { OrcaRuntimeService } from '../../orca-runtime' export const availableRevealWorkspace: OrcaRuntimeService['prepareStructuredAgentSessionRevealWorkspace'] = async () => ({ diff --git a/src/main/runtime/session-tabs/structured-workspace-authority.ts b/src/main/runtime/session-tabs/chat/structured-workspace-authority.ts similarity index 79% rename from src/main/runtime/session-tabs/structured-workspace-authority.ts rename to src/main/runtime/session-tabs/chat/structured-workspace-authority.ts index ad05d57a68c..79a5490db15 100644 --- a/src/main/runtime/session-tabs/structured-workspace-authority.ts +++ b/src/main/runtime/session-tabs/chat/structured-workspace-authority.ts @@ -2,36 +2,36 @@ import { dirname } from 'node:path' import type { AgentSessionExecutionLocation, AgentSessionWorkspaceKind -} from '../../../shared/agent-session/lifecycle/agent-session-record' +} from '../../../../shared/agent-session/lifecycle/agent-session-record' import { getRepoExecutionHostId, getRepoSshConnectionId, LOCAL_EXECUTION_HOST_ID -} from '../../../shared/execution-host/execution-host' -import { resolveQualifiedFolderWorkspaceResult } from '../../../shared/folder-workspaces/folder-workspace-execution-host' -import { isFloatingWorkspaceId } from '../../../shared/workspace/identity/floating-workspace-worktree' -import { isFolderRepo } from '../../../shared/repository/repo-kind' -import type { Repo } from '../../../shared/repository/repo-types' -import { withTimeout } from '../../../shared/concurrency/promise-timeout-fallback' -import { parseWorkspaceKey } from '../../../shared/workspace/identity/workspace-scope' -import { splitWorktreeIdForFilesystem } from '../../../shared/worktree/id' -import { beginWatcherInstall } from '../../workspaces/removal/watcher-removal-gate' -import { areWorktreePathsEqual } from '../../git/worktrees/catalog/worktree-path-comparison' -import { resolveFloatingWorkspacePath } from '../../persistence/restoring-sessions/floating-workspace-normalization' -import { getAppEnvironment } from '../../../shared/app-lifecycle/app-environment' -import { resolveLocalProjectRuntimeForRepo } from '../../workspaces/execution-host/local-project-runtime-resolution' -import { localWorktreePathPresence } from '../../workspaces/catalog/local-worktree-path-presence' +} from '../../../../shared/execution-host/execution-host' +import { resolveQualifiedFolderWorkspaceResult } from '../../../../shared/folder-workspaces/folder-workspace-execution-host' +import { isFloatingWorkspaceId } from '../../../../shared/workspace/identity/floating-workspace-worktree' +import { isFolderRepo } from '../../../../shared/repository/repo-kind' +import type { Repo } from '../../../../shared/repository/repo-types' +import { withTimeout } from '../../../../shared/concurrency/promise-timeout-fallback' +import { parseWorkspaceKey } from '../../../../shared/workspace/identity/workspace-scope' +import { splitWorktreeIdForFilesystem } from '../../../../shared/worktree/id' +import { beginWatcherInstall } from '../../../workspaces/removal/watcher-removal-gate' +import { areWorktreePathsEqual } from '../../../git/worktrees/catalog/worktree-path-comparison' +import { resolveFloatingWorkspacePath } from '../../../persistence/restoring-sessions/floating-workspace-normalization' +import { getAppEnvironment } from '../../../../shared/app-lifecycle/app-environment' +import { resolveLocalProjectRuntimeForRepo } from '../../../workspaces/execution-host/local-project-runtime-resolution' +import { localWorktreePathPresence } from '../../../workspaces/catalog/local-worktree-path-presence' import { readAllWorktreeMetaForHost, readWorktreeMetaForHost -} from '../../persistence/host-qualified-worktree-meta' +} from '../../../persistence/host-qualified-worktree-meta' import { isRuntimeFolderWorkspaceIdForRepo, getRuntimeFolderWorkspaceRootId -} from '../workspaces/catalog/runtime-folder-workspace' -import { scanRuntimeWorktreesUntilNotOvertaken } from '../workspaces/catalog/runtime-witnessed-worktree-scan' -import type { RuntimeStore } from '../construction/runtime-store-contract' -import type { RuntimeWorktreeScanResult } from '../workspaces/catalog/repo-worktree-resolution-scan' +} from '../../workspaces/catalog/runtime-folder-workspace' +import { scanRuntimeWorktreesUntilNotOvertaken } from '../../workspaces/catalog/runtime-witnessed-worktree-scan' +import type { RuntimeStore } from '../../construction/runtime-store-contract' +import type { RuntimeWorktreeScanResult } from '../../workspaces/catalog/repo-worktree-resolution-scan' export class StructuredWorkspaceUnavailable extends Error { constructor( diff --git a/src/main/runtime/session-tabs/graph-sync-mobile-snapshot-gating.test.ts b/src/main/runtime/session-tabs/graph-sync-mobile-snapshot-gating.test.ts deleted file mode 100644 index 83fabbe5728..00000000000 --- a/src/main/runtime/session-tabs/graph-sync-mobile-snapshot-gating.test.ts +++ /dev/null @@ -1,158 +0,0 @@ -/** Preserve serve/browser rows through hydration while emitting real changes and suppressing no-op syncs. */ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import type { - RuntimeMobileSessionTabsResult, - RuntimeMobileSessionTabsSnapshot -} from '../../../shared/remote-runtime/session-graph/runtime-session-contracts' -import type { WorkspaceSessionState } from '../../../shared/workspace-session/workspace-session-state-types' -import { OrcaRuntimeService } from '../orca-runtime' - -const WT = 'repo-1::/tmp/worktree-a' - -const storeBase = { - getRepo: () => ({ - id: 'repo-1', - path: '/tmp/repo', - displayName: 'repo', - badgeColor: 'blue', - addedAt: 1 - }), - getRepos: () => [storeBase.getRepo()], - addRepo: () => {}, - updateRepo: () => undefined as never, - getAllWorktreeMeta: () => ({}), - getWorktreeMeta: () => undefined, - getGitHubCache: () => ({ pr: {}, issue: {} }), - setWorktreeMeta: () => undefined as never, - removeWorktreeMeta: () => {}, - getRetiredWorktreeNameRegistry: () => ({ exhaustedTiers: 0, names: [] }), - addRetiredWorktreeName: () => {}, - mergeRetiredWorktreeNames: () => false, - getSettings: () => ({ - workspaceDir: '/tmp/workspaces', - nestWorkspaces: false, - refreshLocalBaseRefOnWorktreeCreate: false, - branchPrefix: 'none', - branchPrefixCustom: '' - }) -} - -function makeSession(overrides: Partial = {}): WorkspaceSessionState { - return { - activeRepoId: 'repo-1', - activeWorktreeId: WT, - activeTabId: null, - tabsByWorktree: {}, - terminalLayoutsByTabId: {}, - ...overrides - } -} - -function createRuntime(initialSession: WorkspaceSessionState) { - let session = initialSession - const runtime = new OrcaRuntimeService({ - ...storeBase, - getWorkspaceSession: () => session, - setWorkspaceSession: (next: WorkspaceSessionState) => { - session = next - } - }) - const events: RuntimeMobileSessionTabsResult[] = [] - const unsubscribe = runtime.onMobileSessionTabsChanged( - (snapshot) => events.push(snapshot), - undefined, - 'mobile' - ) - const setSession = (next: WorkspaceSessionState): void => { - session = next - } - const sync = async ( - mobileSessionTabs?: RuntimeMobileSessionTabsSnapshot[], - graph: { tabs?: unknown[]; leaves?: unknown[] } = {} - ): Promise => { - await runtime.syncWindowGraph(1, { - tabs: (graph.tabs ?? []) as never, - leaves: (graph.leaves ?? []) as never, - mobileSessionTabs - }) - } - return { runtime, events, sync, setSession, unsubscribe } -} - -function makeRendererSnapshot(args: { - worktree?: string - version: number - epoch?: string - title?: string - ptyId?: string -}): RuntimeMobileSessionTabsSnapshot { - const worktree = args.worktree ?? WT - return { - worktree, - publicationEpoch: args.epoch ?? 'renderer:test-epoch', - snapshotVersion: args.version, - activeGroupId: 'group-1', - activeTabId: 'tab-1::leaf-1', - activeTabType: 'terminal', - tabs: [ - { - type: 'terminal', - id: 'tab-1::leaf-1', - parentTabId: 'tab-1', - leafId: 'leaf-1', - title: args.title ?? 'Terminal 1', - ...(args.ptyId ? { ptyId: args.ptyId } : {}), - isActive: true - } - ] - } -} - -describe('graph-sync mobile snapshot gating', () => { - beforeEach(() => { - vi.useFakeTimers() - }) - - afterEach(() => { - vi.useRealTimers() - }) - - it('drains a pending notify to existing subscribers instead of replaying it to a new one', async () => { - const { runtime, events, sync } = createRuntime(makeSession()) - - await sync([makeRendererSnapshot({ version: 1 })]) - vi.advanceTimersByTime(20) - expect(events).toHaveLength(0) - - const lateEvents: RuntimeMobileSessionTabsResult[] = [] - runtime.onMobileSessionTabsChanged((snapshot) => lateEvents.push(snapshot), undefined, 'mobile') - const drainedOnSubscribe = events.length - - vi.advanceTimersByTime(500) - // Subscribe includes armed state in its initial snapshot; do not replay it as a stale update. - expect(lateEvents).toEqual([]) - // Drain rather than cancel so existing subscribers receive the pending change. - expect(drainedOnSubscribe).toBe(1) - expect(events).toHaveLength(1) - }) - - it('keeps a drained desktop frame with the subscribers present when it was scheduled', async () => { - const { runtime, events, sync } = createRuntime(makeSession()) - const delivered = new Promise((resolve) => { - runtime.onMobileSessionTabsChanged(() => resolve(), undefined, 'runtime') - }) - await sync([makeRendererSnapshot({ version: 1 })]) - vi.advanceTimersByTime(20) - - const lateEvents: RuntimeMobileSessionTabsResult[] = [] - runtime.onMobileSessionTabsChanged( - (snapshot) => lateEvents.push(snapshot), - undefined, - 'runtime' - ) - await delivered - - expect(events).toHaveLength(1) - expect(lateEvents).toEqual([]) - }) -}) diff --git a/src/main/runtime/session-tabs/host-terminal-close-persistence-durability.test.ts b/src/main/runtime/session-tabs/host-terminal-close-persistence-durability.test.ts deleted file mode 100644 index 55d536f967e..00000000000 --- a/src/main/runtime/session-tabs/host-terminal-close-persistence-durability.test.ts +++ /dev/null @@ -1,73 +0,0 @@ -/** Persisting a host binding must not arm topology authority; otherwise renderer close becomes stale - * and de-persist depends on a later PTY exit, which can fail. Guard currentRevision <= 0 without split authority. */ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { mkdtempSync, rmSync } from 'node:fs' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import type { WorkspaceSessionState } from '../../../shared/workspace-session/workspace-session-state-types' -import { createStore, testState } from '../../persistence/persistence-test-harness' - -vi.mock('electron', () => ({ - app: { getPath: () => testStateDirRef.dir, getName: () => 'orca', getVersion: () => '0.0.0' }, - BrowserWindow: { fromId: () => null, getAllWindows: () => [] }, - webContents: { fromId: () => null }, - ipcMain: { on: () => {}, handle: () => {}, removeListener: () => {} }, - safeStorage: { isEncryptionAvailable: () => false } -})) - -const testStateDirRef = vi.hoisted(() => ({ dir: '' })) - -const REPO_ID = 'repo-1' -const WT = `${REPO_ID}::/tmp/wt-cli` -const TAB = 'cli-tab-1' -const LEAF = '11111111-1111-4111-8111-111111111111' -const PTY = `${WT}@@a1b2c3d4` - -function rendererWriteWithout( - session: WorkspaceSessionState, - tabId: string -): WorkspaceSessionState { - const next: WorkspaceSessionState = { - ...session, - tabsByWorktree: { - ...session.tabsByWorktree, - [WT]: (session.tabsByWorktree?.[WT] ?? []).filter((tab) => tab.id !== tabId) - } - } - delete (next as { terminalTopologyRevisionByRepoId?: unknown }).terminalTopologyRevisionByRepoId - return next -} - -async function makeStore() { - return createStore() -} - -describe('host-created terminal close durability', () => { - beforeEach(() => { - testState.dir = mkdtempSync(join(tmpdir(), 'orca-close-durability-')) - testStateDirRef.dir = testState.dir - }) - - afterEach(() => { - rmSync(testState.dir, { recursive: true, force: true }) - }) - - it('a renderer close write durably removes the row it persisted', async () => { - const store = await makeStore() - await store.persistPtyBinding({ worktreeId: WT, tabId: TAB, leafId: LEAF, ptyId: PTY }) - store.setWorkspaceSession(rendererWriteWithout(store.getWorkspaceSession(), TAB)) - expect(store.getWorkspaceSession().tabsByWorktree?.[WT] ?? []).toEqual([]) - }) - - it('pre-existing host-authoritative membership rebases the close away (not ours)', async () => { - const store = await makeStore() - store.setWorkspaceSession({ - ...store.getWorkspaceSession(), - terminalTopologyRevisionByRepoId: { [REPO_ID]: 1 } - }) - await store.persistPtyBinding({ worktreeId: WT, tabId: TAB, leafId: LEAF, ptyId: PTY }) - store.setWorkspaceSession(rendererWriteWithout(store.getWorkspaceSession(), TAB)) - // Existing armed-fence behavior retains omitted rows until exit retirement, independently of CLI creates. - expect(store.getWorkspaceSession().tabsByWorktree?.[WT]?.map((t) => t.id)).toContain(TAB) - }) -}) diff --git a/src/main/runtime/session-tabs/mobile-session-inventory-base.ts b/src/main/runtime/session-tabs/inventory/mobile-session-inventory-base.ts similarity index 93% rename from src/main/runtime/session-tabs/mobile-session-inventory-base.ts rename to src/main/runtime/session-tabs/inventory/mobile-session-inventory-base.ts index 68211066111..bd86369de9a 100644 --- a/src/main/runtime/session-tabs/mobile-session-inventory-base.ts +++ b/src/main/runtime/session-tabs/inventory/mobile-session-inventory-base.ts @@ -1,11 +1,11 @@ import { browserPageInventorySchema, type BrowserPageInventoryEntry -} from '../../../shared/browser/runtime/browser-page-inventory' +} from '../../../../shared/browser/runtime/browser-page-inventory' import type { RuntimeMobileSessionTabsPublication, RuntimeMobileSessionTabsSnapshot -} from '../../../shared/remote-runtime/session-graph/runtime-session-contracts' +} from '../../../../shared/remote-runtime/session-graph/runtime-session-contracts' type AcceptedInventoryBase = { publicationEpoch: string diff --git a/src/main/runtime/session-tabs/session-tabs-inventory-publication.ts b/src/main/runtime/session-tabs/inventory/session-tabs-inventory-publication.ts similarity index 92% rename from src/main/runtime/session-tabs/session-tabs-inventory-publication.ts rename to src/main/runtime/session-tabs/inventory/session-tabs-inventory-publication.ts index 041c5a10fda..4a2b303ece8 100644 --- a/src/main/runtime/session-tabs/session-tabs-inventory-publication.ts +++ b/src/main/runtime/session-tabs/inventory/session-tabs-inventory-publication.ts @@ -1,5 +1,5 @@ -import type { PtyControllerInventory } from '../terminal/lifecycle/runtime-pty-controller-contract' -import { parseExecutionHostId } from '../../../shared/execution-host/execution-host' +import type { PtyControllerInventory } from '../../terminal/lifecycle/runtime-pty-controller-contract' +import { parseExecutionHostId } from '../../../../shared/execution-host/execution-host' import { OrcaRuntimeWithCollectMobileVisibleGraphChangedWorktrees } from './session-tabs-inventory' export abstract class RuntimeSessionTabsInventoryPublication extends OrcaRuntimeWithCollectMobileVisibleGraphChangedWorktrees { diff --git a/src/main/runtime/session-tabs/session-tabs-inventory.ts b/src/main/runtime/session-tabs/inventory/session-tabs-inventory.ts similarity index 89% rename from src/main/runtime/session-tabs/session-tabs-inventory.ts rename to src/main/runtime/session-tabs/inventory/session-tabs-inventory.ts index d7397cd69d4..e3621f16512 100644 --- a/src/main/runtime/session-tabs/session-tabs-inventory.ts +++ b/src/main/runtime/session-tabs/inventory/session-tabs-inventory.ts @@ -1,32 +1,32 @@ -import { ORCA_LAYOUT_OWNER_IS_MAIN } from '../../../shared/workspace-layout/layout-owner-switch' -import { visibleGraphChangedWorktrees } from '../session-graph/visible-graph-changed-worktrees' +import { ORCA_LAYOUT_OWNER_IS_MAIN } from '../../../../shared/workspace-layout/layout-owner-switch' +import { visibleGraphChangedWorktrees } from '../../session-graph/visible-graph-changed-worktrees' import type { RuntimeSessionTabsInventoryPublication as SessionTabsInventoryPublicationMethods } from './session-tabs-inventory-publication' -import type { OrcaRuntimeWithScheduleMobileSessionTabsChanged as ScheduleMobileSessionTabsChangedMethods } from './session-tabs-change-publication' -import type { OrcaRuntimeWithResolveBrowserNetworkExecutionHostForWorktree as ResolveBrowserNetworkExecutionHostForWorktreeMethods } from '../terminal/launch/terminal-workspace-scope' -import type { OrcaRuntimeWithHydrateHeadlessMobileSessionTabsFromWorkspaceSession as HydrateHeadlessMobileSessionTabsFromWorkspaceSessionMethods } from './mobile-session-hydration' -import type { OrcaRuntimeWithBuildHeadlessMobileSessionBrowserTabs as BuildHeadlessMobileSessionBrowserTabsMethods } from '../session-lifecycle/projection/build-headless-mobile-session-browser-tabs' -import type { OrcaRuntimeWithRestoreLivePairedRendererSessionOwnedMobileTerminals as RestoreLivePairedRendererSessionOwnedMobileTerminalsMethods } from './renderer-session-terminal-rescue' -import type { OrcaRuntimeWithTouchMobileSessionTabsForWorktree as TouchMobileSessionTabsForWorktreeMethods } from './mobile-session-membership' -import type { OrcaRuntimeWithPruneMobileSessionTabGroupLayout as PruneMobileSessionTabGroupLayoutMethods } from '../session-lifecycle/projection/prune-mobile-session-tab-group-layout' -import { OrcaRuntimeWithSyncWindowGraph } from '../session-graph/session-window-graph' -import { mainTerminalSurfaces } from '../terminal/surface/main-terminal-surfaces' -import type { MainTerminalSurfacesHost } from '../terminal/surface/main-terminal-surfaces-host' -import type { WorkspaceLayoutReads } from '../terminal/surface/workspace-layout-stream' -import type { MainSessionTabRows } from './main-session-tab-rows' +import type { OrcaRuntimeWithScheduleMobileSessionTabsChanged as ScheduleMobileSessionTabsChangedMethods } from '../publication/session-tabs-change-publication' +import type { OrcaRuntimeWithResolveBrowserNetworkExecutionHostForWorktree as ResolveBrowserNetworkExecutionHostForWorktreeMethods } from '../../terminal/launch/terminal-workspace-scope' +import type { OrcaRuntimeWithHydrateHeadlessMobileSessionTabsFromWorkspaceSession as HydrateHeadlessMobileSessionTabsFromWorkspaceSessionMethods } from '../restoration/mobile-session-hydration' +import type { OrcaRuntimeWithBuildHeadlessMobileSessionBrowserTabs as BuildHeadlessMobileSessionBrowserTabsMethods } from '../../session-lifecycle/projection/build-headless-mobile-session-browser-tabs' +import type { OrcaRuntimeWithRestoreLivePairedRendererSessionOwnedMobileTerminals as RestoreLivePairedRendererSessionOwnedMobileTerminalsMethods } from '../restoration/renderer-session-terminal-rescue' +import type { OrcaRuntimeWithTouchMobileSessionTabsForWorktree as TouchMobileSessionTabsForWorktreeMethods } from '../restoration/mobile-session-membership' +import type { OrcaRuntimeWithPruneMobileSessionTabGroupLayout as PruneMobileSessionTabGroupLayoutMethods } from '../../session-lifecycle/projection/prune-mobile-session-tab-group-layout' +import { OrcaRuntimeWithSyncWindowGraph } from '../../session-graph/session-window-graph' +import { mainTerminalSurfaces } from '../../terminal/surface/main-terminal-surfaces' +import type { MainTerminalSurfacesHost } from '../../terminal/surface/main-terminal-surfaces-host' +import type { WorkspaceLayoutReads } from '../../terminal/surface/workspace-layout-stream' +import type { MainSessionTabRows } from '../layout/main-session-tab-rows' import type { RuntimeMobileSessionTabsResult, RuntimeSyncedTab, RuntimeSyncWindowGraph -} from '../../../shared/remote-runtime/session-graph/runtime-session-contracts' -import type { RuntimeLeafRecord } from '../terminal/records/runtime-terminal-state-records' -import type { PtyControllerInventory } from '../terminal/lifecycle/runtime-pty-controller-contract' -import type { PaneStartStatuses } from '../terminal/surface/pane-start-statuses' +} from '../../../../shared/remote-runtime/session-graph/runtime-session-contracts' +import type { RuntimeLeafRecord } from '../../terminal/records/runtime-terminal-state-records' +import type { PtyControllerInventory } from '../../terminal/lifecycle/runtime-pty-controller-contract' +import type { PaneStartStatuses } from '../../terminal/surface/pane-start-statuses' import { paneOfPty, type PtyPane, type PtyPaneSource, type PtyPaneOf -} from '../terminal/surface/pty-pane-query' +} from '../../terminal/surface/pty-pane-query' export abstract class OrcaRuntimeWithCollectMobileVisibleGraphChangedWorktrees extends OrcaRuntimeWithSyncWindowGraph { abstract get workspaceLayoutReads(): WorkspaceLayoutReads diff --git a/src/main/runtime/agent-session/structured-agent-session-inventory-hold.ts b/src/main/runtime/session-tabs/inventory/structured-agent-session-inventory-hold.ts similarity index 100% rename from src/main/runtime/agent-session/structured-agent-session-inventory-hold.ts rename to src/main/runtime/session-tabs/inventory/structured-agent-session-inventory-hold.ts diff --git a/src/main/runtime/session-tabs/headless-pane-move-to-new-tab.ts b/src/main/runtime/session-tabs/layout/headless-pane-move-to-new-tab.ts similarity index 91% rename from src/main/runtime/session-tabs/headless-pane-move-to-new-tab.ts rename to src/main/runtime/session-tabs/layout/headless-pane-move-to-new-tab.ts index 967bebc4a6d..5452106aa44 100644 --- a/src/main/runtime/session-tabs/headless-pane-move-to-new-tab.ts +++ b/src/main/runtime/session-tabs/layout/headless-pane-move-to-new-tab.ts @@ -1,19 +1,19 @@ import type { RuntimeHeadlessTabGroups as HeadlessTabGroupsMethods } from './headless-tab-group-moves' -import { OrcaRuntimeWithCloseHeadlessMobileTerminalTab } from './headless-terminal-tab-close' +import { OrcaRuntimeWithCloseHeadlessMobileTerminalTab } from '../terminal-retirement/headless-terminal-tab-close' import { recordPtySurface, spawnSurfaceClaimSequence -} from '../terminal/surface/pty-recorded-surface-topology' +} from '../../terminal/surface/pty-recorded-surface-topology' import { withSelectedTabs } from './headless-tab-group-selection' -import type { RuntimeMobileSessionTabGroup } from '../../../shared/remote-runtime/session-graph/runtime-session-contracts' -import { makePaneKey } from '../../../shared/workspace-layout/stable-pane-id' -import { isValidHostTerminalTabId } from '../../../shared/workspace-layout/terminal-surfaces/terminal-tab-id' -import { ORCA_LAYOUT_OWNER_IS_MAIN } from '../../../shared/workspace-layout/layout-owner-switch' +import type { RuntimeMobileSessionTabGroup } from '../../../../shared/remote-runtime/session-graph/runtime-session-contracts' +import { makePaneKey } from '../../../../shared/workspace-layout/stable-pane-id' +import { isValidHostTerminalTabId } from '../../../../shared/workspace-layout/terminal-surfaces/terminal-tab-id' +import { ORCA_LAYOUT_OWNER_IS_MAIN } from '../../../../shared/workspace-layout/layout-owner-switch' import { isTerminalLeafMoveRequest, type TerminalLeafMoveRequest, type TerminalLeafMoveResult -} from '../../../shared/workspace-layout/terminal-topology/terminal-leaf-move' +} from '../../../../shared/workspace-layout/terminal-topology/terminal-leaf-move' /** Where the client dropped the new tab, in the host's group ids. */ export type MovedPanePlacement = { targetGroupId: string; index?: number } diff --git a/src/main/runtime/session-tabs/headless-tab-group-moves.ts b/src/main/runtime/session-tabs/layout/headless-tab-group-moves.ts similarity index 96% rename from src/main/runtime/session-tabs/headless-tab-group-moves.ts rename to src/main/runtime/session-tabs/layout/headless-tab-group-moves.ts index dba44b215f2..bc2108416b8 100644 --- a/src/main/runtime/session-tabs/headless-tab-group-moves.ts +++ b/src/main/runtime/session-tabs/layout/headless-tab-group-moves.ts @@ -5,16 +5,16 @@ import type { RuntimeMobileSessionTabMove, RuntimeMobileSessionTabMoveResult, RuntimeMobileSessionTabsSnapshot -} from '../../../shared/remote-runtime/session-graph/runtime-session-contracts' +} from '../../../../shared/remote-runtime/session-graph/runtime-session-contracts' import { buildHeadlessTabGroupMove, buildHeadlessTabGroupSplit -} from '../../../shared/workspace-layout/tab-groups/tab-group-moves' +} from '../../../../shared/workspace-layout/tab-groups/tab-group-moves' import { randomUUID } from 'node:crypto' import { withSelectedTabs } from './headless-tab-group-selection' -import type { TabGroupLayoutNode } from '../../../shared/workspace-layout/tab-groups/tab-types' +import type { TabGroupLayoutNode } from '../../../../shared/workspace-layout/tab-groups/tab-types' import type { RuntimeMobileSessionTabOrder } from './mobile-session-tab-order' -import type { OrcaRuntimeWithPruneMobileSessionTabGroupLayout } from '../session-lifecycle/projection/prune-mobile-session-tab-group-layout' +import type { OrcaRuntimeWithPruneMobileSessionTabGroupLayout } from '../../session-lifecycle/projection/prune-mobile-session-tab-group-layout' export abstract class RuntimeHeadlessTabGroups extends RuntimeHeadlessTabProperties { protected abstract resolveMobileSessionHostTabId( diff --git a/src/main/runtime/session-tabs/headless-tab-group-selection.ts b/src/main/runtime/session-tabs/layout/headless-tab-group-selection.ts similarity index 76% rename from src/main/runtime/session-tabs/headless-tab-group-selection.ts rename to src/main/runtime/session-tabs/layout/headless-tab-group-selection.ts index 4ccf1ff8f30..12a7473dea5 100644 --- a/src/main/runtime/session-tabs/headless-tab-group-selection.ts +++ b/src/main/runtime/session-tabs/layout/headless-tab-group-selection.ts @@ -1,7 +1,7 @@ // Preserve per-group selection across shared membership moves; removed selections fall back to the first tab. -import type { RuntimeMobileSessionTabGroup } from '../../../shared/remote-runtime/session-graph/runtime-session-contracts' -import type { LayoutGroup } from '../../../shared/workspace-layout/workspace-layout-model' +import type { RuntimeMobileSessionTabGroup } from '../../../../shared/remote-runtime/session-graph/runtime-session-contracts' +import type { LayoutGroup } from '../../../../shared/workspace-layout/workspace-layout-model' export function withSelectedTabs( before: readonly RuntimeMobileSessionTabGroup[], diff --git a/src/main/runtime/session-tabs/headless-tab-properties.ts b/src/main/runtime/session-tabs/layout/headless-tab-properties.ts similarity index 93% rename from src/main/runtime/session-tabs/headless-tab-properties.ts rename to src/main/runtime/session-tabs/layout/headless-tab-properties.ts index a5bff14246a..b53f1986707 100644 --- a/src/main/runtime/session-tabs/headless-tab-properties.ts +++ b/src/main/runtime/session-tabs/layout/headless-tab-properties.ts @@ -1,18 +1,21 @@ -import { renameStructuredSessionTab, type SessionTabProps } from './structured-session-tab-rename' +import { + renameStructuredSessionTab, + type SessionTabProps +} from '../chat/structured-session-tab-rename' import { OrcaRuntimeWithHeadlessPaneMoveToNewTab } from './headless-pane-move-to-new-tab' -import type { WorkspaceSessionState } from '../../../shared/workspace-session/workspace-session-state-types' -import type { RuntimeMobileSessionTabsSnapshot } from '../../../shared/remote-runtime/session-graph/runtime-session-contracts' -import type { RuntimeMobileSessionSnapshotTab } from '../../../shared/remote-runtime/session-graph/runtime-mobile-session-tab-contracts' +import type { WorkspaceSessionState } from '../../../../shared/workspace-session/workspace-session-state-types' +import type { RuntimeMobileSessionTabsSnapshot } from '../../../../shared/remote-runtime/session-graph/runtime-session-contracts' +import type { RuntimeMobileSessionSnapshotTab } from '../../../../shared/remote-runtime/session-graph/runtime-mobile-session-tab-contracts' import type { TerminalLayoutSnapshot, TerminalPaneLayoutNode -} from '../../../shared/workspace-layout/terminal-tab-types' -import { ORCA_LAYOUT_OWNER_IS_MAIN } from '../../../shared/workspace-layout/layout-owner-switch' -import { cloneTerminalLayoutSnapshot } from '../terminal/surface/mobile-session-layout-projection' +} from '../../../../shared/workspace-layout/terminal-tab-types' +import { ORCA_LAYOUT_OWNER_IS_MAIN } from '../../../../shared/workspace-layout/layout-owner-switch' +import { cloneTerminalLayoutSnapshot } from '../../terminal/surface/mobile-session-layout-projection' import { sameStringRecord, terminalLayoutNodeEqual -} from '../../../shared/workspace-layout/terminal-topology/terminal-layout-equality' +} from '../../../../shared/workspace-layout/terminal-topology/terminal-layout-equality' type HeadlessPaneLayoutEdit = { tabId: string diff --git a/src/main/runtime/session-tabs/main-handle-close.ts b/src/main/runtime/session-tabs/layout/main-handle-close.ts similarity index 85% rename from src/main/runtime/session-tabs/main-handle-close.ts rename to src/main/runtime/session-tabs/layout/main-handle-close.ts index 2b4def3e160..ba69354c861 100644 --- a/src/main/runtime/session-tabs/main-handle-close.ts +++ b/src/main/runtime/session-tabs/layout/main-handle-close.ts @@ -1,10 +1,10 @@ // Main-owned handle close commits pane/tab retirement before stopping ended terminals; no window or phone row is required. -import type { RuntimeTerminalClose } from '../../../shared/terminal/runtime/runtime-terminal-contracts' -import type { LayoutApplyReply } from '../../../shared/workspace-layout/workspace-layout-command-types' -import type { WindowLayoutCommand } from '../terminal/layout/runtime-layout-apply' -import { startedMainTerminalSurfaces } from '../terminal/surface/main-terminal-surfaces' -import type { ExplicitCloseStop } from './explicit-terminal-close-pty-stops' +import type { RuntimeTerminalClose } from '../../../../shared/terminal/runtime/runtime-terminal-contracts' +import type { LayoutApplyReply } from '../../../../shared/workspace-layout/workspace-layout-command-types' +import type { WindowLayoutCommand } from '../../terminal/layout/runtime-layout-apply' +import { startedMainTerminalSurfaces } from '../../terminal/surface/main-terminal-surfaces' +import type { ExplicitCloseStop } from '../terminal-retirement/explicit-terminal-close-pty-stops' import { closeInMainLayout } from './main-layout-close-command' type HandleTarget = { worktreeId: string; ptyId: string | null; tabId?: string; leafId?: string } diff --git a/src/main/runtime/session-tabs/main-layout-agent-launch-tabs.ts b/src/main/runtime/session-tabs/layout/main-layout-agent-launch-tabs.ts similarity index 88% rename from src/main/runtime/session-tabs/main-layout-agent-launch-tabs.ts rename to src/main/runtime/session-tabs/layout/main-layout-agent-launch-tabs.ts index 5e0066d7839..2d990389120 100644 --- a/src/main/runtime/session-tabs/main-layout-agent-launch-tabs.ts +++ b/src/main/runtime/session-tabs/layout/main-layout-agent-launch-tabs.ts @@ -1,15 +1,15 @@ // Main-owned early launch tabs are written before launch and withdrawn through main close; paired-runtime workspaces retain window relay. -import { OrcaRuntimeWithCloseStructuredAgentSessionTab } from './structured-session-tab-close' +import { OrcaRuntimeWithCloseStructuredAgentSessionTab } from '../chat/structured-session-tab-close' import type { AgentLaunchTabPublished, AgentLaunchTabPublishRequest -} from '../../../shared/agent-launch/contracts/agent-launch-tab-publication' -import type { AgentLaunchPlacementReceipt } from '../../../shared/agent-launch/contracts/agent-launch-intent' -import type { AgentLaunchPaneAddress } from '../../../shared/agent-launch/contracts/agent-launch-pane-verdict' -import { parseExecutionHostId } from '../../../shared/execution-host/execution-host' -import { ORCA_LAYOUT_OWNER_IS_MAIN } from '../../../shared/workspace-layout/layout-owner-switch' -import type { RuntimePtyWorktreeRecord } from '../terminal/records/runtime-terminal-state-records' -import type { TerminalIdentityReadContext } from '../terminal/query/terminal-identity-read-context' +} from '../../../../shared/agent-launch/contracts/agent-launch-tab-publication' +import type { AgentLaunchPlacementReceipt } from '../../../../shared/agent-launch/contracts/agent-launch-intent' +import type { AgentLaunchPaneAddress } from '../../../../shared/agent-launch/contracts/agent-launch-pane-verdict' +import { parseExecutionHostId } from '../../../../shared/execution-host/execution-host' +import { ORCA_LAYOUT_OWNER_IS_MAIN } from '../../../../shared/workspace-layout/layout-owner-switch' +import type { RuntimePtyWorktreeRecord } from '../../terminal/records/runtime-terminal-state-records' +import type { TerminalIdentityReadContext } from '../../terminal/query/terminal-identity-read-context' /** Where the tab landed against where the launch asked for it, as the window reports it. */ function placementFallback( diff --git a/src/main/runtime/session-tabs/main-layout-close-command.ts b/src/main/runtime/session-tabs/layout/main-layout-close-command.ts similarity index 91% rename from src/main/runtime/session-tabs/main-layout-close-command.ts rename to src/main/runtime/session-tabs/layout/main-layout-close-command.ts index 0e79fce2d93..14508ff61b8 100644 --- a/src/main/runtime/session-tabs/main-layout-close-command.ts +++ b/src/main/runtime/session-tabs/layout/main-layout-close-command.ts @@ -1,10 +1,10 @@ // CLI/phone closes share main's closePane or closeTabs command; stop ended terminals here because layout close itself stops none. -import type { LayoutApplyReply } from '../../../shared/workspace-layout/workspace-layout-command-types' -import type { WindowLayoutCommand } from '../terminal/layout/runtime-layout-apply' +import type { LayoutApplyReply } from '../../../../shared/workspace-layout/workspace-layout-command-types' +import type { WindowLayoutCommand } from '../../terminal/layout/runtime-layout-apply' // Type-only: the stops module sits late in the runtime's class chain, and this runs early in it. -import type { ExplicitCloseStop } from './explicit-terminal-close-pty-stops' -import { parseAppSshPtyId } from '../../../shared/remote-runtime/ssh/ssh-pty-id' +import type { ExplicitCloseStop } from '../terminal-retirement/explicit-terminal-close-pty-stops' +import { parseAppSshPtyId } from '../../../../shared/remote-runtime/ssh/ssh-pty-id' const NO_STOP: ExplicitCloseStop = { stopped: false } diff --git a/src/main/runtime/session-tabs/main-layout-renames.ts b/src/main/runtime/session-tabs/layout/main-layout-renames.ts similarity index 91% rename from src/main/runtime/session-tabs/main-layout-renames.ts rename to src/main/runtime/session-tabs/layout/main-layout-renames.ts index 9eb4e4aaf08..d8a375b5fb8 100644 --- a/src/main/runtime/session-tabs/main-layout-renames.ts +++ b/src/main/runtime/session-tabs/layout/main-layout-renames.ts @@ -1,15 +1,15 @@ // Main-owned terminal names/props use layout commands for every view; null/false retains legacy routing for other workspaces. -import type { RuntimeHeadlessTerminalTabTitles as PersistHeadlessTerminalTitleMethods } from './headless-terminal-tab-titles' +import type { RuntimeHeadlessTerminalTabTitles as PersistHeadlessTerminalTitleMethods } from '../publication/headless-terminal-tab-titles' import { OrcaRuntimeWithMainLayoutAgentLaunchTabs } from './main-layout-agent-launch-tabs' import type { RuntimeTerminalRename, RuntimeTerminalSetPaneTitle -} from '../../../shared/terminal/runtime/runtime-terminal-contracts' -import type { TerminalPaneLayoutNode } from '../../../shared/workspace-layout/terminal-tab-types' -import type { WindowLayoutCommand } from '../terminal/layout/runtime-layout-apply' -import type { RuntimePtyWorktreeRecord } from '../terminal/records/runtime-terminal-state-records' -import { startedMainTerminalSurfaces } from '../terminal/surface/main-terminal-surfaces' -import { paneTitlesForDesktopWindow } from './desktop-pane-title-forwarding' +} from '../../../../shared/terminal/runtime/runtime-terminal-contracts' +import type { TerminalPaneLayoutNode } from '../../../../shared/workspace-layout/terminal-tab-types' +import type { WindowLayoutCommand } from '../../terminal/layout/runtime-layout-apply' +import type { RuntimePtyWorktreeRecord } from '../../terminal/records/runtime-terminal-state-records' +import { startedMainTerminalSurfaces } from '../../terminal/surface/main-terminal-surfaces' +import { paneTitlesForDesktopWindow } from '../publication/desktop-pane-title-forwarding' type MainOwnedPane = { worktreeId: string diff --git a/src/main/runtime/session-tabs/main-layout-session-tab-move.ts b/src/main/runtime/session-tabs/layout/main-layout-session-tab-move.ts similarity index 82% rename from src/main/runtime/session-tabs/main-layout-session-tab-move.ts rename to src/main/runtime/session-tabs/layout/main-layout-session-tab-move.ts index 799f9500b98..70b4e898fec 100644 --- a/src/main/runtime/session-tabs/main-layout-session-tab-move.ts +++ b/src/main/runtime/session-tabs/layout/main-layout-session-tab-move.ts @@ -1,19 +1,19 @@ // Move main-owned tabs through layout commands so every view follows main without a window relay. -import type { OrcaRuntimeWithPruneMobileSessionTabGroupLayout } from '../session-lifecycle/projection/prune-mobile-session-tab-group-layout' -import { ORCA_LAYOUT_OWNER_IS_MAIN } from '../../../shared/workspace-layout/layout-owner-switch' +import type { OrcaRuntimeWithPruneMobileSessionTabGroupLayout } from '../../session-lifecycle/projection/prune-mobile-session-tab-group-layout' +import { ORCA_LAYOUT_OWNER_IS_MAIN } from '../../../../shared/workspace-layout/layout-owner-switch' import type { RuntimeMobileSessionTabMove, RuntimeMobileSessionTabMoveResult, RuntimeMobileSessionTabsSnapshot -} from '../../../shared/remote-runtime/session-graph/runtime-session-contracts' -import { translateSessionTabMove } from '../../../shared/workspace-layout/old-client/old-client-method-translation' -import { resolveSessionTabRow } from '../../../shared/workspace-layout/old-client/old-client-session-tab-rows' -import { startedMainTerminalSurfaces } from '../terminal/surface/main-terminal-surfaces' +} from '../../../../shared/remote-runtime/session-graph/runtime-session-contracts' +import { translateSessionTabMove } from '../../../../shared/workspace-layout/old-client/old-client-method-translation' +import { resolveSessionTabRow } from '../../../../shared/workspace-layout/old-client/old-client-session-tab-rows' +import { startedMainTerminalSurfaces } from '../../terminal/surface/main-terminal-surfaces' import { OrcaRuntimeWithMainLayoutRenames } from './main-layout-renames' -import { liveTerminalsOfTab } from '../session-lifecycle/close/closed-tab-terminal' -import type { WorkspaceLayout } from '../../../shared/workspace-layout/workspace-layout-model' -import type { CommandOf } from '../../../shared/workspace-layout/workspace-layout-command-types' -import { isPaneColumnSplitDropNoOp } from '../../../shared/workspace-layout/tab-groups/pane-column-split-drop-no-op' +import { liveTerminalsOfTab } from '../../session-lifecycle/close/closed-tab-terminal' +import type { WorkspaceLayout } from '../../../../shared/workspace-layout/workspace-layout-model' +import type { CommandOf } from '../../../../shared/workspace-layout/workspace-layout-command-types' +import { isPaneColumnSplitDropNoOp } from '../../../../shared/workspace-layout/tab-groups/pane-column-split-drop-no-op' import { selectMobileSessionTab } from './mobile-session-tab-selection' export abstract class OrcaRuntimeWithMainLayoutTabMoves extends OrcaRuntimeWithMainLayoutRenames { diff --git a/src/main/runtime/session-tabs/main-session-tab-group-placement.ts b/src/main/runtime/session-tabs/layout/main-session-tab-group-placement.ts similarity index 89% rename from src/main/runtime/session-tabs/main-session-tab-group-placement.ts rename to src/main/runtime/session-tabs/layout/main-session-tab-group-placement.ts index 07fa5f8d7a8..6d74d7ac5ea 100644 --- a/src/main/runtime/session-tabs/main-session-tab-group-placement.ts +++ b/src/main/runtime/session-tabs/layout/main-session-tab-group-placement.ts @@ -1,7 +1,7 @@ // Place side-only rows consistently in main groups for both row-writer reorder and projection merge. -import type { RuntimeMobileSessionSnapshotTab } from '../../../shared/remote-runtime/session-graph/runtime-mobile-session-tab-contracts' -import type { RuntimeMobileSessionTabGroup } from '../../../shared/remote-runtime/session-graph/runtime-session-contracts' +import type { RuntimeMobileSessionSnapshotTab } from '../../../../shared/remote-runtime/session-graph/runtime-mobile-session-tab-contracts' +import type { RuntimeMobileSessionTabGroup } from '../../../../shared/remote-runtime/session-graph/runtime-session-contracts' type Group = RuntimeMobileSessionTabGroup diff --git a/src/main/runtime/session-tabs/main-session-tab-order.ts b/src/main/runtime/session-tabs/layout/main-session-tab-order.ts similarity index 94% rename from src/main/runtime/session-tabs/main-session-tab-order.ts rename to src/main/runtime/session-tabs/layout/main-session-tab-order.ts index b1095c7db27..cfc83e0cbbd 100644 --- a/src/main/runtime/session-tabs/main-session-tab-order.ts +++ b/src/main/runtime/session-tabs/layout/main-session-tab-order.ts @@ -1,7 +1,7 @@ // Take only order/groups from main; preserve written rows and terminal/exit facts that may be newer than layout bindings. -import type { RuntimeMobileSessionTabsSnapshot } from '../../../shared/remote-runtime/session-graph/runtime-session-contracts' -import type { RuntimeMobileSessionSnapshotTab } from '../../../shared/remote-runtime/session-graph/runtime-mobile-session-tab-contracts' +import type { RuntimeMobileSessionTabsSnapshot } from '../../../../shared/remote-runtime/session-graph/runtime-session-contracts' +import type { RuntimeMobileSessionSnapshotTab } from '../../../../shared/remote-runtime/session-graph/runtime-mobile-session-tab-contracts' import type { MainSessionTabRows } from './main-session-tab-rows' import { orderIdOf, placeInMainGroups, withStrayIn } from './main-session-tab-group-placement' import { diff --git a/src/main/runtime/session-tabs/main-session-tab-rows.ts b/src/main/runtime/session-tabs/layout/main-session-tab-rows.ts similarity index 97% rename from src/main/runtime/session-tabs/main-session-tab-rows.ts rename to src/main/runtime/session-tabs/layout/main-session-tab-rows.ts index 19ae32dda79..d4d7135d069 100644 --- a/src/main/runtime/session-tabs/main-session-tab-rows.ts +++ b/src/main/runtime/session-tabs/layout/main-session-tab-rows.ts @@ -4,12 +4,12 @@ import { } from './mobile-session-tab-selection' // Use main's rows/order/groups, augmented by window-only rows and live view facts (selection, dirty state, titles, theme/status and editor drafts). -import type { RuntimeMobileSessionSnapshotTab } from '../../../shared/remote-runtime/session-graph/runtime-mobile-session-tab-contracts' +import type { RuntimeMobileSessionSnapshotTab } from '../../../../shared/remote-runtime/session-graph/runtime-mobile-session-tab-contracts' import { orderIdOf, placeInMainGroups, withStrayIn } from './main-session-tab-group-placement' import type { RuntimeMobileSessionTabGroup, RuntimeMobileSessionTabsSnapshot -} from '../../../shared/remote-runtime/session-graph/runtime-session-contracts' +} from '../../../../shared/remote-runtime/session-graph/runtime-session-contracts' /** Main's projection of the rows (projectSessionTabs): the snapshot minus the runtime's stamps. */ export type MainSessionTabRows = Omit< diff --git a/src/main/runtime/session-tabs/mobile-session-tab-order.ts b/src/main/runtime/session-tabs/layout/mobile-session-tab-order.ts similarity index 91% rename from src/main/runtime/session-tabs/mobile-session-tab-order.ts rename to src/main/runtime/session-tabs/layout/mobile-session-tab-order.ts index 6007b444560..dd09c81ee5b 100644 --- a/src/main/runtime/session-tabs/mobile-session-tab-order.ts +++ b/src/main/runtime/session-tabs/layout/mobile-session-tab-order.ts @@ -1,10 +1,10 @@ -import type { OrcaRuntimeWithStoredMobileSnapshotHasStalePreservedTab as BrowserOwnership } from './mobile-session-publication-preservation' -import type { BrowserTabInfo } from '../../../shared/browser/runtime/runtime-browser-contracts' +import type { OrcaRuntimeWithStoredMobileSnapshotHasStalePreservedTab as BrowserOwnership } from '../restoration/mobile-session-publication-preservation' +import type { BrowserTabInfo } from '../../../../shared/browser/runtime/runtime-browser-contracts' import type { RuntimeMobileSessionTabGroup, RuntimeMobileSessionTabsSnapshot -} from '../../../shared/remote-runtime/session-graph/runtime-session-contracts' -import { RuntimeHeadlessTerminalTabTitles } from './headless-terminal-tab-titles' +} from '../../../../shared/remote-runtime/session-graph/runtime-session-contracts' +import { RuntimeHeadlessTerminalTabTitles } from '../publication/headless-terminal-tab-titles' export abstract class RuntimeMobileSessionTabOrder extends RuntimeHeadlessTerminalTabTitles { protected abstract isRendererOwnedMobileBrowserTab( ...args: Parameters diff --git a/src/main/runtime/session-tabs/mobile-session-tab-selection.ts b/src/main/runtime/session-tabs/layout/mobile-session-tab-selection.ts similarity index 95% rename from src/main/runtime/session-tabs/mobile-session-tab-selection.ts rename to src/main/runtime/session-tabs/layout/mobile-session-tab-selection.ts index baaa7f7fb4d..10f81bb8087 100644 --- a/src/main/runtime/session-tabs/mobile-session-tab-selection.ts +++ b/src/main/runtime/session-tabs/layout/mobile-session-tab-selection.ts @@ -1,9 +1,9 @@ -import { getHeadlessMobileSessionGroupId } from '../terminal/surface/mobile-session-layout-projection' -import type { RuntimeMobileSessionSnapshotTab } from '../../../shared/remote-runtime/session-graph/runtime-mobile-session-tab-contracts' +import { getHeadlessMobileSessionGroupId } from '../../terminal/surface/mobile-session-layout-projection' +import type { RuntimeMobileSessionSnapshotTab } from '../../../../shared/remote-runtime/session-graph/runtime-mobile-session-tab-contracts' import type { RuntimeMobileSessionTabsSnapshot, RuntimeMobileSessionTabGroup -} from '../../../shared/remote-runtime/session-graph/runtime-session-contracts' +} from '../../../../shared/remote-runtime/session-graph/runtime-session-contracts' type Selection = { activeGroupId: string | null diff --git a/src/main/runtime/session-tabs/mobile-session-inventory-base.test.ts b/src/main/runtime/session-tabs/mobile-session-inventory-base.test.ts deleted file mode 100644 index 417a1dad8fb..00000000000 --- a/src/main/runtime/session-tabs/mobile-session-inventory-base.test.ts +++ /dev/null @@ -1,240 +0,0 @@ -import { afterEach, describe, expect, it, vi } from 'vitest' -import type { BrowserPageInventoryEntry } from '../../../shared/browser/runtime/browser-page-inventory' -import { browserPageInventorySchema } from '../../../shared/browser/runtime/browser-page-inventory' -import type { RuntimeMobileSessionTabsPublication } from '../../../shared/remote-runtime/session-graph/runtime-session-contracts' -import type { WorktreeMeta } from '../../../shared/worktree/meta-types' -import type { RuntimeStore } from '../construction/runtime-store-contract' -import { AgentBrowserBridge } from '../../browser/agent-browser/agent-browser-bridge' -import '../orca-runtime-tests/orca-runtime-test-lifecycle.spec' -import { - store, - makeWorktreeMeta, - TEST_WORKTREE_ID -} from '../orca-runtime-tests/orca-runtime-test-fixtures.spec' -import { OrcaRuntimeService } from '../orca-runtime' - -const WT = TEST_WORKTREE_ID -const EPOCH = 'renderer:inventory-epoch' - -function entry(id: string): BrowserPageInventoryEntry { - return { - browserPageId: id, - browserWorkspaceId: 'browser-1', - title: `Page ${id}`, - url: `https://${id}.example/`, - profileId: 'default', - loadError: null, - certificateFailure: null - } -} - -function frame( - version: number, - extra: Partial = {} -): RuntimeMobileSessionTabsPublication { - return { - worktree: WT, - worktreeInstanceId: 'occupant-1', - publicationEpoch: EPOCH, - snapshotVersion: version, - activeGroupId: null, - activeTabId: 'tab-1::leaf-1', - activeTabType: 'terminal', - tabs: [ - { - type: 'terminal', - id: 'tab-1::leaf-1', - parentTabId: 'tab-1', - leafId: 'leaf-1', - title: `Terminal v${version}`, - isActive: true - } - ], - ...extra - } -} - -function createRuntime() { - let meta: WorktreeMeta | undefined = makeWorktreeMeta({ instanceId: 'occupant-1' }) - const runtimeStore: RuntimeStore = { - ...store, - getWorktreeMeta: () => meta, - getAllWorktreeMeta: (): Record => (meta ? { [WT]: meta } : {}), - setWorktreeMeta: (_target, updates) => { - meta = { ...makeWorktreeMeta(), ...meta, ...updates } - return meta - }, - removeWorktreeMeta: () => { - meta = undefined - } - } - const runtime = new OrcaRuntimeService(runtimeStore) - runtime.attachWindow(1) - const bridge = vi.mockObject(AgentBrowserBridge.prototype) - bridge.getRegisteredTabs.mockReturnValue(new Map()) - bridge.tabList.mockReturnValue({ tabs: [] }) - runtime.setAgentBrowserBridge(bridge) - const sync = (...frames: RuntimeMobileSessionTabsPublication[]) => - runtime.syncWindowGraph(1, { tabs: [], leaves: [], mobileSessionTabs: frames }) - return { - runtime, - sync, - list: () => runtime.browserTabList({ worktree: `id:${WT}` }), - mobile: () => runtime.listMobileSessionTabs(`id:${WT}`), - recreate: (instanceId: string) => { - meta = makeWorktreeMeta({ instanceId }) - }, - remove: () => runtime.removeWorktreeMetadataAndHistory(runtimeStore, WT) - } -} - -afterEach(() => { - vi.restoreAllMocks() -}) - -describe('acknowledged browser page inventory base', () => { - it.each([ - [10, 'saved-9', 'Page saved-9'], - [100, 'saved-99', 'Page saved-99'] - ] as const)( - 'avoids rescanning %i saved pages across repeated acknowledged syncs', - async (count, lastPageId, lastTitle) => { - const { runtime, sync, list, mobile } = createRuntime() - let pageReads = 0 - const inventory = Array.from({ length: count }, (_, index) => ({ - ...entry(`saved-${index}`), - get browserPageId() { - pageReads++ - return `saved-${index}` - } - })) - await sync(frame(1, { browserPageInventory: inventory })) - runtime.storeMobileSessionSnapshot(WT, frame(100, { browserPageInventory: inventory })) - const validate = vi.spyOn(browserPageInventorySchema, 'safeParse') - pageReads = 0 - - for (let version = 2; version <= 11; version++) { - expect( - (await sync(frame(version, { browserPageInventoryBaseVersion: version - 1 }))) - .mobileSessionResyncWorktrees - ).toBeUndefined() - } - - // N/10N contract: terminal-only publications must not revalidate the saved-page array. - expect(validate).not.toHaveBeenCalled() - expect(pageReads).toBe(0) - const pages = (await list()).tabs - expect(pages).toHaveLength(count) - expect(pages[0]).toMatchObject({ browserPageId: 'saved-0', title: 'Page saved-0' }) - expect(pages.at(-1)).toMatchObject({ browserPageId: lastPageId, title: lastTitle }) - expect((await mobile()).tabs[0]).toMatchObject({ title: 'Terminal v11' }) - expect((await mobile()).snapshotVersion).toBeGreaterThan(100) - } - ) - - it('reuses an authoritative empty inventory after replacing saved pages', async () => { - const { sync, list, mobile } = createRuntime() - await sync(frame(1, { browserPageInventory: [entry('a'), entry('b')] })) - await sync(frame(2, { browserPageInventory: [] })) - expect( - (await sync(frame(3, { browserPageInventoryBaseVersion: 2 }))).mobileSessionResyncWorktrees - ).toBeUndefined() - expect((await list()).tabs).toEqual([]) - expect((await mobile()).tabs[0]).toMatchObject({ title: 'Terminal v3' }) - }) - - it.each([ - ['a wrong base', frame(3, { browserPageInventoryBaseVersion: 1 })], - [ - 'another publication epoch', - frame(3, { publicationEpoch: 'renderer:reloaded', browserPageInventoryBaseVersion: 2 }) - ], - [ - 'another occupant', - frame(3, { worktreeInstanceId: 'occupant-2', browserPageInventoryBaseVersion: 2 }) - ] - ])( - 'requests a full resend for %s without losing the accepted catalog', - async (_label, mismatched) => { - const { sync, list, mobile } = createRuntime() - await sync(frame(1, { browserPageInventory: [entry('old')] })) - await sync(frame(2, { browserPageInventory: [entry('a'), entry('b')] })) - - expect((await sync(mismatched)).mobileSessionResyncWorktrees).toEqual([WT]) - expect((await list()).tabs.map((page) => page.browserPageId)).toEqual(['a', 'b']) - expect((await mobile()).tabs[0]).toMatchObject({ title: 'Terminal v2' }) - - const { browserPageInventoryBaseVersion: _base, ...full } = mismatched - expect( - (await sync({ ...full, browserPageInventory: [entry('z')] })).mobileSessionResyncWorktrees - ).toBeUndefined() - expect((await list()).tabs.map((page) => page.browserPageId)).toEqual(['z']) - expect( - ( - await sync({ - ...full, - snapshotVersion: 4, - browserPageInventoryBaseVersion: 3 - }) - ).mobileSessionResyncWorktrees - ).toBeUndefined() - } - ) - - it('requests inventory when the acknowledged renderer publication carried none', async () => { - const { sync, mobile } = createRuntime() - await sync(frame(1)) - expect((await sync(frame(2))).mobileSessionResyncWorktrees).toBeUndefined() - expect( - (await sync(frame(3, { browserPageInventoryBaseVersion: 2 }))).mobileSessionResyncWorktrees - ).toEqual([WT]) - expect((await mobile()).tabs[0]).toMatchObject({ title: 'Terminal v2' }) - }) - - it('accepts the next base after a duplicate frame loses its acknowledgement', async () => { - const { sync, list, mobile } = createRuntime() - await sync(frame(1, { browserPageInventory: [entry('a')] })) - await sync(frame(2, { browserPageInventoryBaseVersion: 1 })) - expect( - (await sync(frame(2, { browserPageInventoryBaseVersion: 1 }))).mobileSessionResyncWorktrees - ).toBeUndefined() - expect( - (await sync(frame(3, { browserPageInventoryBaseVersion: 2 }))).mobileSessionResyncWorktrees - ).toBeUndefined() - expect((await mobile()).tabs[0]).toMatchObject({ title: 'Terminal v3' }) - expect((await list()).tabs.map((page) => page.browserPageId)).toEqual(['a']) - }) - - it('fences a removed occupant and makes its successor resend in full', async () => { - const { sync, list, recreate, remove } = createRuntime() - await sync(frame(1, { browserPageInventory: [entry('a')] })) - await remove() - recreate('occupant-2') - expect( - (await sync(frame(2, { browserPageInventoryBaseVersion: 1 }))).mobileSessionResyncWorktrees - ).toBeUndefined() - expect((await list()).tabs).toEqual([]) - - const successor = { worktreeInstanceId: 'occupant-2' } - expect( - (await sync(frame(3, { ...successor, browserPageInventoryBaseVersion: 1 }))) - .mobileSessionResyncWorktrees - ).toEqual([WT]) - expect((await list()).tabs).toEqual([]) - await sync(frame(3, { ...successor, browserPageInventory: [entry('b')] })) - expect((await list()).tabs.map((page) => page.browserPageId)).toEqual(['b']) - }) - - it.each([ - [ - 'an inventory beside a base', - { browserPageInventory: [entry('a')], browserPageInventoryBaseVersion: 1 } - ], - ['a fractional base', { browserPageInventoryBaseVersion: 1.5 }] - ])('rejects %s without replacing the accepted catalog', async (_label, malformed) => { - const { sync, list } = createRuntime() - await sync(frame(1, { browserPageInventory: [entry('a')] })) - await expect(sync(frame(2, malformed))).rejects.toThrow('invalid_browser_page_inventory') - expect((await list()).tabs.map((page) => page.browserPageId)).toEqual(['a']) - }) -}) diff --git a/src/main/runtime/session-tabs/paired-host-terminal-close.test.ts b/src/main/runtime/session-tabs/paired-host-terminal-close.test.ts deleted file mode 100644 index e6bc12d19e4..00000000000 --- a/src/main/runtime/session-tabs/paired-host-terminal-close.test.ts +++ /dev/null @@ -1,196 +0,0 @@ -// CLI close must route to the paired runtime that owns the process, not claim a local stop of its remote id (STA-7826). -import { describe, expect, it, vi } from 'vitest' - -import { toRemoteRuntimePtyId } from '../../../shared/remote-runtime/remote-runtime-pty-id' - -import '../orchestration/orchestration-error' - -import { getDefaultWorkspaceSession } from '../../../shared/orca-profiles/constants' - -await import('../orca-runtime-tests/runtime-test-module-registration.spec') -const { OrcaRuntimeService } = await import('../orca-runtime') -await import('../orca-runtime-tests/orca-runtime-test-lifecycle.spec') -const { store, makeRuntimeStoreWithWorkspaceSession } = - await import('../orca-runtime-tests/orca-runtime-test-fixtures.spec') - -const WORKTREE_ID = 'repo-1::/tmp/worktree-a' - -type HostCall = (environmentId: string, method: string, params: unknown) => Promise - -async function pairedHostLeafRuntime(hostCall: HostCall, runtimeStore: typeof store = store) { - const runtime = new OrcaRuntimeService(runtimeStore) - const localStops: string[] = [] - runtime.setPtyController({ - write: () => true, - kill: (ptyId) => { - localStops.push(ptyId) - return false - }, - stopAndWait: async (ptyId) => { - localStops.push(ptyId) - return false - }, - getForegroundProcess: async () => null, - listProcesses: async () => [] - }) - const closeTerminalTab = vi.fn(async () => {}) - runtime.setNotifier({ - worktreesChanged: vi.fn(), - reposChanged: vi.fn(), - activateWorktree: vi.fn(), - createTerminal: vi.fn(), - splitTerminal: vi.fn(), - renameTerminal: vi.fn(), - focusTerminal: vi.fn(), - closeTerminal: vi.fn(), - closeTerminalTab, - terminalFitOverrideChanged: vi.fn(), - terminalDriverChanged: vi.fn() - }) - const call = vi.spyOn(runtime, 'callOrchestrationWorkerServer').mockImplementation(hostCall) - runtime.attachWindow(1) - await runtime.syncWindowGraph(1, { - tabs: [ - { - tabId: 'tab-1', - worktreeId: WORKTREE_ID, - title: 'Shell', - activeLeafId: 'pane:1', - layout: null - } - ], - leaves: [ - { - tabId: 'tab-1', - worktreeId: WORKTREE_ID, - leafId: 'pane:1', - paneRuntimeId: 1, - ptyId: toRemoteRuntimePtyId('term_on_host', 'env-1') - } - ] - }) - return { runtime, call, closeTerminalTab, localStops } -} - -async function listedHandle(runtime: InstanceType): Promise { - const [terminal] = (await runtime.listTerminals()).terminals - expect(terminal?.executionHostId).toBe('runtime:env-1') - return terminal!.handle -} - -describe('closing a terminal that a paired runtime runs', () => { - it("returns the owning host's stop receipt and retires the local mirror", async () => { - const { runtime, call, closeTerminalTab, localStops } = await pairedHostLeafRuntime( - async () => ({ - close: { handle: 'term_on_host', tabId: 'host-tab', ptyKilled: true } - }) - ) - const handle = await listedHandle(runtime) - - await expect(runtime.closeTerminal(handle)).resolves.toEqual({ - handle, - tabId: 'tab-1', - ptyKilled: true - }) - - expect(call).toHaveBeenCalledWith( - 'env-1', - 'terminal.close', - { terminal: 'term_on_host' }, - expect.any(Number) - ) - expect(closeTerminalTab).toHaveBeenCalledWith('tab-1', { - localPtyTeardownOwnedExternally: true - }) - expect(localStops).toEqual([]) - }) - - it('leaves the terminal in place when the owning host cannot be reached', async () => { - const { runtime, closeTerminalTab, localStops } = await pairedHostLeafRuntime(async () => { - throw new Error('connect ETIMEDOUT') - }) - const handle = await listedHandle(runtime) - - await expect(runtime.closeTerminal(handle)).rejects.toThrow('connect ETIMEDOUT') - - expect(closeTerminalTab).not.toHaveBeenCalled() - expect(localStops).toEqual([]) - expect((await runtime.listTerminals()).terminals.map((terminal) => terminal.handle)).toEqual([ - handle - ]) - }) - - it.each(['local', 'runtime:env-1'] as const)( - 'refuses a pinned tab saved in the %s partition before the owning host stops anything', - async (partition) => { - const { runtimeStore } = makeRuntimeStoreWithWorkspaceSession( - { - ...getDefaultWorkspaceSession(), - tabsByWorktree: { - [WORKTREE_ID]: [ - { - id: 'tab-1', - ptyId: toRemoteRuntimePtyId('term_on_host', 'env-1'), - worktreeId: WORKTREE_ID, - title: 'Shell', - customTitle: null, - color: null, - sortOrder: 0, - createdAt: 0, - isPinned: true - } - ] - } - }, - partition - ) - const { runtime, call } = await pairedHostLeafRuntime( - async () => ({ close: { handle: 'term_on_host', tabId: 'host-tab', ptyKilled: true } }), - runtimeStore - ) - const handle = await listedHandle(runtime) - - await expect(runtime.closeTerminal(handle)).rejects.toThrow('terminal_tab_pinned') - await expect(runtime.closeTerminalTab(handle)).rejects.toThrow('terminal_tab_pinned') - expect(call).not.toHaveBeenCalled() - } - ) - - it('leaves a pane rebound during the host call to its new occupant', async () => { - let answerHost: ((value: unknown) => void) | null = null - const { runtime, closeTerminalTab } = await pairedHostLeafRuntime( - () => - new Promise((resolve) => { - answerHost = resolve - }) - ) - const handle = await listedHandle(runtime) - - const closing = runtime.closeTerminal(handle) - await vi.waitFor(() => expect(answerHost).not.toBeNull()) - await runtime.syncWindowGraph(1, { - tabs: [ - { - tabId: 'tab-1', - worktreeId: WORKTREE_ID, - title: 'Shell', - activeLeafId: 'pane:1', - layout: null - } - ], - leaves: [ - { - tabId: 'tab-1', - worktreeId: WORKTREE_ID, - leafId: 'pane:1', - paneRuntimeId: 1, - ptyId: toRemoteRuntimePtyId('term_replacement', 'env-1') - } - ] - }) - answerHost!({ close: { handle: 'term_on_host', tabId: 'host-tab', ptyKilled: true } }) - - await expect(closing).resolves.toEqual({ handle, tabId: 'tab-1', ptyKilled: true }) - expect(closeTerminalTab).not.toHaveBeenCalled() - }) -}) diff --git a/src/main/runtime/session-tabs/desktop-pane-title-forwarding.ts b/src/main/runtime/session-tabs/publication/desktop-pane-title-forwarding.ts similarity index 82% rename from src/main/runtime/session-tabs/desktop-pane-title-forwarding.ts rename to src/main/runtime/session-tabs/publication/desktop-pane-title-forwarding.ts index 1cd4e579fbc..6625cf26ded 100644 --- a/src/main/runtime/session-tabs/desktop-pane-title-forwarding.ts +++ b/src/main/runtime/session-tabs/publication/desktop-pane-title-forwarding.ts @@ -1,9 +1,9 @@ -import { isTerminalLeafId } from '../../../shared/workspace-layout/stable-pane-id' +import { isTerminalLeafId } from '../../../../shared/workspace-layout/stable-pane-id' import type { TerminalPaneLayoutNode, TerminalTab -} from '../../../shared/workspace-layout/terminal-tab-types' -import { sanitizeTerminalLayoutPaneTitles } from '../../../shared/workspace-layout/terminal-topology/terminal-pane-title-sanitization' +} from '../../../../shared/workspace-layout/terminal-tab-types' +import { sanitizeTerminalLayoutPaneTitles } from '../../../../shared/workspace-layout/terminal-topology/terminal-pane-title-sanitization' function collectLeafIds(node: TerminalPaneLayoutNode | null): string[] { if (!node) { diff --git a/src/main/runtime/session-tabs/headless-terminal-tab-titles.ts b/src/main/runtime/session-tabs/publication/headless-terminal-tab-titles.ts similarity index 86% rename from src/main/runtime/session-tabs/headless-terminal-tab-titles.ts rename to src/main/runtime/session-tabs/publication/headless-terminal-tab-titles.ts index 64d03bdd7ec..7ba33c55bbd 100644 --- a/src/main/runtime/session-tabs/headless-terminal-tab-titles.ts +++ b/src/main/runtime/session-tabs/publication/headless-terminal-tab-titles.ts @@ -1,5 +1,5 @@ -import { RuntimeHeadlessTabGroups } from './headless-tab-group-moves' -import type { WorkspaceSessionState } from '../../../shared/workspace-session/workspace-session-state-types' +import { RuntimeHeadlessTabGroups } from '../layout/headless-tab-group-moves' +import type { WorkspaceSessionState } from '../../../../shared/workspace-session/workspace-session-state-types' export abstract class RuntimeHeadlessTerminalTabTitles extends RuntimeHeadlessTabGroups { // Persist a manual terminal rename so a headless rebuild keeps the title // instead of reverting to the generated/default one. diff --git a/src/main/runtime/session-tabs/mobile-session-snapshot-equality.ts b/src/main/runtime/session-tabs/publication/mobile-session-snapshot-equality.ts similarity index 98% rename from src/main/runtime/session-tabs/mobile-session-snapshot-equality.ts rename to src/main/runtime/session-tabs/publication/mobile-session-snapshot-equality.ts index 5f9e0cfe61c..d02699de2f3 100644 --- a/src/main/runtime/session-tabs/mobile-session-snapshot-equality.ts +++ b/src/main/runtime/session-tabs/publication/mobile-session-snapshot-equality.ts @@ -1,4 +1,4 @@ -import type { RuntimeMobileSessionTabsSnapshot } from '../../../shared/remote-runtime/session-graph/runtime-session-contracts' +import type { RuntimeMobileSessionTabsSnapshot } from '../../../../shared/remote-runtime/session-graph/runtime-session-contracts' // Compare rebuilt snapshots by value, excluding newly minted publicationEpoch/snapshotVersion. export function headlessMobileSnapshotContentUnchanged( diff --git a/src/main/runtime/session-tabs/mobile-session-snapshot-version.ts b/src/main/runtime/session-tabs/publication/mobile-session-snapshot-version.ts similarity index 93% rename from src/main/runtime/session-tabs/mobile-session-snapshot-version.ts rename to src/main/runtime/session-tabs/publication/mobile-session-snapshot-version.ts index ea777ffbc2a..52105cf0546 100644 --- a/src/main/runtime/session-tabs/mobile-session-snapshot-version.ts +++ b/src/main/runtime/session-tabs/publication/mobile-session-snapshot-version.ts @@ -1,4 +1,4 @@ -import type { RuntimeMobileSessionTabsSnapshot } from '../../../shared/remote-runtime/session-graph/runtime-session-contracts' +import type { RuntimeMobileSessionTabsSnapshot } from '../../../../shared/remote-runtime/session-graph/runtime-session-contracts' import { mobileSnapshotInventoryOnlyChanged } from './mobile-session-snapshot-equality' /** The snapshot as stored: its version moves past the stored one so readers always see a newer stamp. */ diff --git a/src/main/runtime/session-tabs/mobile-session-tab-subscriptions.ts b/src/main/runtime/session-tabs/publication/mobile-session-tab-subscriptions.ts similarity index 91% rename from src/main/runtime/session-tabs/mobile-session-tab-subscriptions.ts rename to src/main/runtime/session-tabs/publication/mobile-session-tab-subscriptions.ts index a4a97af2695..873564ac673 100644 --- a/src/main/runtime/session-tabs/mobile-session-tab-subscriptions.ts +++ b/src/main/runtime/session-tabs/publication/mobile-session-tab-subscriptions.ts @@ -1,10 +1,10 @@ -import { rendererStatusReplica } from '../session-graph/renderer-status-replica' +import { rendererStatusReplica } from '../../session-graph/renderer-status-replica' import type { ClientHostedPageObservation, MobileSessionTabSubscription -} from '../construction/runtime-identity-state' -import type { RuntimeMobileSessionTabsResult } from '../../../shared/remote-runtime/session-graph/runtime-session-contracts' -import { RuntimeWorkspaceFileTargets } from '../workspaces/workspace-file-session-targets' +} from '../../construction/runtime-identity-state' +import type { RuntimeMobileSessionTabsResult } from '../../../../shared/remote-runtime/session-graph/runtime-session-contracts' +import { RuntimeWorkspaceFileTargets } from '../../workspaces/workspace-file-session-targets' export abstract class RuntimeMobileSessionTabSubscriptions extends RuntimeWorkspaceFileTargets { onMobileSessionTabsChanged( listener: MobileSessionTabSubscription['listener'], diff --git a/src/main/runtime/session-tabs/mobile-session-tabs-delivery.ts b/src/main/runtime/session-tabs/publication/mobile-session-tabs-delivery.ts similarity index 92% rename from src/main/runtime/session-tabs/mobile-session-tabs-delivery.ts rename to src/main/runtime/session-tabs/publication/mobile-session-tabs-delivery.ts index e75f2dd72b7..30eb3f6ee7f 100644 --- a/src/main/runtime/session-tabs/mobile-session-tabs-delivery.ts +++ b/src/main/runtime/session-tabs/publication/mobile-session-tabs-delivery.ts @@ -1,6 +1,6 @@ -import type { RuntimeAgentSenderAssociations } from '../agent-senders/runtime-agent-sender-associations' -import type { MobileSessionTabSubscription } from '../construction/runtime-identity-state' -import type { RuntimeMobileSessionTabsResult } from '../../../shared/remote-runtime/session-graph/runtime-session-contracts' +import type { RuntimeAgentSenderAssociations } from '../../agent-senders/runtime-agent-sender-associations' +import type { MobileSessionTabSubscription } from '../../construction/runtime-identity-state' +import type { RuntimeMobileSessionTabsResult } from '../../../../shared/remote-runtime/session-graph/runtime-session-contracts' type DeliveryArgs = [ result: RuntimeMobileSessionTabsResult, diff --git a/src/main/runtime/session-tabs/orca-runtime-session-tabs-path-alias.test.ts b/src/main/runtime/session-tabs/publication/orca-runtime-session-tabs-path-alias.test.ts similarity index 54% rename from src/main/runtime/session-tabs/orca-runtime-session-tabs-path-alias.test.ts rename to src/main/runtime/session-tabs/publication/orca-runtime-session-tabs-path-alias.test.ts index 3b0ba96ff18..aaba19d730f 100644 --- a/src/main/runtime/session-tabs/orca-runtime-session-tabs-path-alias.test.ts +++ b/src/main/runtime/session-tabs/publication/orca-runtime-session-tabs-path-alias.test.ts @@ -1,10 +1,10 @@ import { describe, expect, it, vi } from 'vitest' -import type { RuntimeMobileSessionTabsSnapshot } from '../../../shared/remote-runtime/session-graph/runtime-session-contracts' +import type { RuntimeMobileSessionTabsSnapshot } from '../../../../shared/remote-runtime/session-graph/runtime-session-contracts' -import { OrcaRuntimeService } from '../orca-runtime' -import { RpcDispatcher } from '../rpc/dispatcher' -import { SESSION_TAB_METHODS } from '../rpc/methods/session-tabs/session-tabs' +import { OrcaRuntimeService } from '../../orca-runtime' +import { RpcDispatcher } from '../../rpc/dispatcher' +import { SESSION_TAB_METHODS } from '../../rpc/methods/session-tabs/session-tabs' vi.mock('electron', () => ({ BrowserWindow: { fromId: vi.fn(() => null) }, @@ -85,12 +85,6 @@ async function publishGraph( }) } -// Desktop frames prepare sender identity first; wait for the scheduled pass to deliver. -async function senderFramesDelivered(runtime: OrcaRuntimeService): Promise { - await new Promise((resolve) => queueMicrotask(resolve)) - await runtime['agentProjections'].senders.withPreparedPublication(() => undefined, false) -} - describe('session tab workspace path aliases', () => { it('delivers a later canonical publication to an early alias subscriber without a false empty frame', async () => { const runtime = new OrcaRuntimeService() @@ -135,66 +129,4 @@ describe('session tab workspace path aliases', () => { }) // Stream frames must use one workspace spelling or clients split tabs across alias keys. - it('names an early alias subscriber stream by one spelling for its whole life', async () => { - const runtime = new OrcaRuntimeService() - runtime.attachWindow(1) - const dispatcher = new RpcDispatcher({ runtime, methods: SESSION_TAB_METHODS }) - const frames: { type?: string; worktree?: string; tabs?: unknown[] }[] = [] - await dispatcher.dispatchStreaming( - { - id: 'sub-early', - authToken: 'token', - method: 'session.tabs.subscribe', - params: { worktree: `id:${ALIAS}` } - }, - (message) => { - const result = JSON.parse(message).result - if (result?.type === 'snapshot' || result?.type === 'updated') { - frames.push(result) - } - }, - { connectionId: 'alias-connection' } - ) - - await publishGraph(runtime) - - await vi.waitFor(() => expect(frames.some((frame) => frame.type === 'updated')).toBe(true)) - expect(frames.map((frame) => frame.worktree)).toEqual(frames.map(() => ALIAS)) - expect(frames.at(-1)?.tabs).toContainEqual(expect.objectContaining({ id: TAB })) - runtime.cleanupSubscriptionsForConnection('alias-connection') - }) -}) - -it('rejects ambiguous later aliases while retaining an exact host spelling', async () => { - const runtime = new OrcaRuntimeService() - runtime.attachWindow(1) - const rpc = new RpcDispatcher({ runtime, methods: SESSION_TAB_METHODS }) - const frames: { type?: string; worktree?: string }[] = [] - try { - await rpc.dispatchStreaming( - { - id: 'ambiguous-alias', - authToken: 'test', - method: 'session.tabs.subscribe', - params: { worktree: `id:${ALIAS}` } - }, - (reply) => frames.push(JSON.parse(reply).result), - { connectionId: 'ambiguous-alias' } - ) - await publishGraph(runtime, WORKTREE, [snapshot('repo::g:/git/example', 'pty-other')]) - runtime.onMobileSessionTabsChanged(() => {}, undefined, 'mobile')() - await senderFramesDelivered(runtime) - expect(frames.filter((frame) => frame.type === 'updated')).toEqual([]) - await publishGraph(runtime, ALIAS, [ - snapshot(WORKTREE), - snapshot('repo::g:/git/example', 'pty-other') - ]) - runtime.onMobileSessionTabsChanged(() => {}, undefined, 'mobile')() - await senderFramesDelivered(runtime) - expect( - frames.filter((frame) => frame.type === 'updated').map((frame) => frame.worktree) - ).toEqual([ALIAS]) - } finally { - runtime.cleanupSubscriptionsForConnection('ambiguous-alias') - } }) diff --git a/src/main/runtime/session-tabs/pty-backed-session-publication.ts b/src/main/runtime/session-tabs/publication/pty-backed-session-publication.ts similarity index 90% rename from src/main/runtime/session-tabs/pty-backed-session-publication.ts rename to src/main/runtime/session-tabs/publication/pty-backed-session-publication.ts index 210421b6995..b484ef725ca 100644 --- a/src/main/runtime/session-tabs/pty-backed-session-publication.ts +++ b/src/main/runtime/session-tabs/publication/pty-backed-session-publication.ts @@ -1,21 +1,21 @@ -import { normalizeMobileSessionTabSelection } from './mobile-session-tab-selection' -import type { OrcaRuntimeWithTouchMobileSessionTabsForWorktree as TouchMobileSessionTabsForWorktreeMethods } from './mobile-session-membership' -import { OrcaRuntimeWithHasLiveOrPersistedServeOrSshOwnedPtyBinding } from '../session-lifecycle/close/has-live-or-persisted-serve-or-ssh-owned-pty-binding' -import type { RuntimePtyWorktreeRecord } from '../terminal/records/runtime-terminal-state-records' -import { normalizeCompatibleAgentTitleForOwner } from '../../../shared/agent-status/title/agent-title-owner' -import { getLatestPtyTitle } from '../workspaces/process-listing/runtime-worktree-status-projection' -import type { OrcaRuntimeWithBuildPtyTerminalSummary as PtyTerminalSummaryMethods } from '../terminal/query/pty-terminal-summary' -import type { RuntimeMobileSessionTabsSnapshot } from '../../../shared/remote-runtime/session-graph/runtime-session-contracts' -import type { RuntimeMobileSessionTerminalTab } from '../../../shared/remote-runtime/session-graph/runtime-mobile-session-tab-contracts' +import { normalizeMobileSessionTabSelection } from '../layout/mobile-session-tab-selection' +import type { OrcaRuntimeWithTouchMobileSessionTabsForWorktree as TouchMobileSessionTabsForWorktreeMethods } from '../restoration/mobile-session-membership' +import { OrcaRuntimeWithHasLiveOrPersistedServeOrSshOwnedPtyBinding } from '../../session-lifecycle/close/has-live-or-persisted-serve-or-ssh-owned-pty-binding' +import type { RuntimePtyWorktreeRecord } from '../../terminal/records/runtime-terminal-state-records' +import { normalizeCompatibleAgentTitleForOwner } from '../../../../shared/agent-status/title/agent-title-owner' +import { getLatestPtyTitle } from '../../workspaces/process-listing/runtime-worktree-status-projection' +import type { OrcaRuntimeWithBuildPtyTerminalSummary as PtyTerminalSummaryMethods } from '../../terminal/query/pty-terminal-summary' +import type { RuntimeMobileSessionTabsSnapshot } from '../../../../shared/remote-runtime/session-graph/runtime-session-contracts' +import type { RuntimeMobileSessionTerminalTab } from '../../../../shared/remote-runtime/session-graph/runtime-mobile-session-tab-contracts' import { buildMaterializedHeadlessParentLayout, getHeadlessMobileSessionGroupId -} from '../terminal/surface/mobile-session-layout-projection' +} from '../../terminal/surface/mobile-session-layout-projection' import { appendChatTabOrder, mergeMobileSessionSnapshotTabs, mergeMobileSessionTabGroups -} from '../session-lifecycle/projection/mobile-session-tab-merge' +} from '../../session-lifecycle/projection/mobile-session-tab-merge' export abstract class OrcaRuntimeWithPublishPtyBackedMobileSessionTerminal extends OrcaRuntimeWithHasLiveOrPersistedServeOrSshOwnedPtyBinding { protected abstract markPaneLiveTitlesDirty(): void diff --git a/src/main/runtime/session-tabs/session-tabs-change-publication.ts b/src/main/runtime/session-tabs/publication/session-tabs-change-publication.ts similarity index 92% rename from src/main/runtime/session-tabs/session-tabs-change-publication.ts rename to src/main/runtime/session-tabs/publication/session-tabs-change-publication.ts index 9756d1b9e9c..299aadf5cca 100644 --- a/src/main/runtime/session-tabs/session-tabs-change-publication.ts +++ b/src/main/runtime/session-tabs/publication/session-tabs-change-publication.ts @@ -1,21 +1,21 @@ import { createMobileSessionTabsDelivery } from './mobile-session-tabs-delivery' -import { OrcaRuntimeWithStoredMobileSnapshotHasStalePreservedTab } from './mobile-session-publication-preservation' -import type { BrowserTabInfo } from '../../../shared/browser/runtime/runtime-browser-contracts' +import { OrcaRuntimeWithStoredMobileSnapshotHasStalePreservedTab } from '../restoration/mobile-session-publication-preservation' +import type { BrowserTabInfo } from '../../../../shared/browser/runtime/runtime-browser-contracts' import type { RuntimeMobileSessionClientTab, RuntimeMobileSessionMarkdownTab -} from '../../../shared/remote-runtime/session-graph/runtime-mobile-session-tab-contracts' +} from '../../../../shared/remote-runtime/session-graph/runtime-mobile-session-tab-contracts' import type { RuntimeMobileSessionTabGroup, RuntimeMobileSessionTabsResult, RuntimeMobileSessionTabsSnapshot -} from '../../../shared/remote-runtime/session-graph/runtime-session-contracts' -import { UNPUBLISHED_WORKTREE_PUBLICATION_EPOCH } from '../../../shared/remote-runtime/session-graph/runtime-session-contracts' -import { getRuntimeBrowserPageRegistry } from '../browser/client-pages/runtime-browser-page-registry' -import { getMobileSessionTabOrderIds } from '../session-lifecycle/projection/mobile-session-tab-merge' -import { readCreatedWorkspaceLaunch } from '../../agent-launch/agent-launch-created-workspace' -import type { AgentSenderRevision } from '../../../shared/orchestration/mailbox/agent-sender-associations' -import { worktreeIdsEqual } from '../../../shared/worktree/id' +} from '../../../../shared/remote-runtime/session-graph/runtime-session-contracts' +import { UNPUBLISHED_WORKTREE_PUBLICATION_EPOCH } from '../../../../shared/remote-runtime/session-graph/runtime-session-contracts' +import { getRuntimeBrowserPageRegistry } from '../../browser/client-pages/runtime-browser-page-registry' +import { getMobileSessionTabOrderIds } from '../../session-lifecycle/projection/mobile-session-tab-merge' +import { readCreatedWorkspaceLaunch } from '../../../agent-launch/agent-launch-created-workspace' +import type { AgentSenderRevision } from '../../../../shared/orchestration/mailbox/agent-sender-associations' +import { worktreeIdsEqual } from '../../../../shared/worktree/id' export abstract class OrcaRuntimeWithScheduleMobileSessionTabsChanged extends OrcaRuntimeWithStoredMobileSnapshotHasStalePreservedTab { protected scheduleMobileSessionTabsChanged(worktreeId: string): void { diff --git a/src/main/runtime/session-tabs/session-title-publisher.ts b/src/main/runtime/session-tabs/publication/session-title-publisher.ts similarity index 91% rename from src/main/runtime/session-tabs/session-title-publisher.ts rename to src/main/runtime/session-tabs/publication/session-title-publisher.ts index 181d394ea0f..915bee84217 100644 --- a/src/main/runtime/session-tabs/session-title-publisher.ts +++ b/src/main/runtime/session-tabs/publication/session-title-publisher.ts @@ -1,5 +1,5 @@ -import { OrcaRuntimeWithStopTerminalsForProject } from '../terminal/stop/project-terminal-stop' -import { HEADLESS_RUNTIME_WINDOW_ID } from '../../../shared/remote-runtime/session-graph/runtime-session-contracts' +import { OrcaRuntimeWithStopTerminalsForProject } from '../../terminal/stop/project-terminal-stop' +import { HEADLESS_RUNTIME_WINDOW_ID } from '../../../../shared/remote-runtime/session-graph/runtime-session-contracts' export type SessionTitlePublisher = { windowId: number diff --git a/src/main/runtime/session-tabs/renderer-owned-tab-properties.test.ts b/src/main/runtime/session-tabs/renderer-owned-tab-properties.test.ts deleted file mode 100644 index 37639ec0209..00000000000 --- a/src/main/runtime/session-tabs/renderer-owned-tab-properties.test.ts +++ /dev/null @@ -1,192 +0,0 @@ -import '../orca-runtime-tests/orca-runtime-test-lifecycle.spec' -import { expect, it, vi } from 'vitest' - -import { mkdtemp, rm } from 'node:fs/promises' - -import { tmpdir } from 'node:os' - -import { join } from 'node:path' - -import { - agentSessionLeaseFixture, - agentSessionRecordFixture -} from '../../../shared/agent-session/lifecycle/records/agent-session-record.test-fixture' - -import { closeTestJournalHostDatabases } from '../../native-chat/agent-session-journal/store-lifecycle/journal-host-database-test-support' - -import { createStructuredChatNamingHandler } from '../../native-chat/structured-chat-naming' - -import { recordingStructuredAgentSessionLogger } from '../../native-chat/agent-session-wire/host/testing/structured-agent-session-logger.test-fixture' - -import { ensureTestStructuredAgentSessionHost as ensureStructuredAgentSessionHost } from '../agent-session/records/agent-session-record-store-test-harness' -import { - readPersistedTestAgentSessionStore, - seedTestAgentSessionRecordStore -} from '../agent-session/records/agent-session-record-store-persistence.test-fixture' - -import { stopStructuredAgentSessionRuntime } from '../agent-session/structured-agent-session-runtime' - -import type { AgentSessionRecordStore } from '../agent-session/records/agent-session-record-store' - -import '../orca-runtime-tests/runtime-test-module-registration.spec' -import { OrcaRuntimeService } from '../orca-runtime' - -import { electronMocks } from '../orca-runtime-test-mocks/setup.spec' - -import { - TEST_WORKTREE_ID, - makeRuntimeStoreWithWorkspaceSession, - makeWorkspaceSessionWithHeadlessTerminal -} from '../orca-runtime-tests/orca-runtime-test-fixtures.spec' - -import type { RuntimeNotifier } from '../client/events/runtime-notifier-contract' - -import { RpcDispatcher } from '../rpc/dispatcher' - -import { SESSION_TAB_MUTATION_METHODS } from '../rpc/methods/session-tabs/session-tab-mutation-methods' - -async function fixture(session = makeWorkspaceSessionWithHeadlessTerminal()) { - const { runtimeStore, getSession } = makeRuntimeStoreWithWorkspaceSession(session) - const runtime = new OrcaRuntimeService(runtimeStore) - const notifier = { - worktreesChanged: vi.fn(), - reposChanged: vi.fn(), - activateWorktree: vi.fn(), - createTerminal: vi.fn(), - splitTerminal: vi.fn(), - renameTerminal: vi.fn(), - focusTerminal: vi.fn(), - closeTerminal: vi.fn(), - terminalFitOverrideChanged: vi.fn(), - terminalDriverChanged: vi.fn() - } satisfies RuntimeNotifier - runtime.attachWindow(1) - await runtime.syncWindowGraph(1, { tabs: [], leaves: [] }) - electronMocks.BrowserWindow.fromId.mockReturnValue({ isDestroyed: () => false }) - runtime.setNotifier(notifier) - const dispatcher = new RpcDispatcher({ runtime, methods: SESSION_TAB_MUTATION_METHODS }) - return { runtime, runtimeStore, getSession, session, notifier, dispatcher } -} - -it('refuses a combined native chat edit before saving its name, while accepting a title alone', async () => { - const directory = await mkdtemp(join(tmpdir(), 'orca-native-tab-props-')) - const record = { - ...agentSessionRecordFixture( - agentSessionLeaseFixture({ - ownerProcess: null, - reservedSpawnToken: null, - claimStatus: 'released' - }) - ), - conversationName: 'Existing saved name' - } - const sessionId = record.sessionId - const tabId = `agent-session:${sessionId}` - const alias = 'Existing tab alias' - const { runtime, dispatcher, getSession, notifier } = await fixture( - makeWorkspaceSessionWithHeadlessTerminal({ - unifiedTabs: { - [TEST_WORKTREE_ID]: [ - { - id: `structured-agent-session-${sessionId}`, - entityId: sessionId, - groupId: 'group', - worktreeId: TEST_WORKTREE_ID, - contentType: 'agent-session', - agentSessionAgent: 'claude', - label: 'Claude Chat', - customLabel: alias, - color: null, - sortOrder: 1, - createdAt: 1 - } - ] - } - }) - ) - try { - await seedTestAgentSessionRecordStore(directory, { - records: [record] - }) - let recordStore: AgentSessionRecordStore | null = null - const { logger } = recordingStructuredAgentSessionLogger() - const host = await ensureStructuredAgentSessionHost({ - logger, - stateDirectory: directory, - hostId: 'local', - claimKeyId: 'key-1', - resolveWorkspacePath: async () => directory, - resolveEnvironment: async () => ({}), - resolveLaunchArgs: () => [], - resolveClaudeAuthPolicy: () => ({ account: 'managed' }), - conversationNaming: createStructuredChatNamingHandler({ - getStore: () => recordStore, - getSettings: () => ({}), - workerTaskTitle: () => null, - readFirstPrompt: async () => '', - readJournalFirstPrompt: async () => '', - generate: async () => null, - onNamed: () => {}, - logger - }) - }) - recordStore = host.deps.store - vi.spyOn(runtime, 'ensureStructuredAgentSessionHost').mockResolvedValue(undefined) - runtime['storeMobileSessionSnapshot'](TEST_WORKTREE_ID, { - worktree: TEST_WORKTREE_ID, - publicationEpoch: 'native-tab-props', - snapshotVersion: 1, - activeGroupId: 'group', - activeTabId: tabId, - activeTabType: 'agent-session', - tabs: [ - { - type: 'agent-session', - id: tabId, - sessionId, - agent: 'claude', - title: 'Existing saved name', - isActive: true - } - ] - }) - const before = await readPersistedTestAgentSessionStore(directory) - expect(before.records[sessionId]?.conversationName).toBe('Existing saved name') - const params = { - worktree: `id:${TEST_WORKTREE_ID}`, - tabId, - customTitle: ' Renamed through tab props ' - } - expect( - await dispatcher.dispatch({ - id: 'native-combined', - authToken: 'token', - method: 'session.tabs.setTabProps', - params: { ...params, isPinned: true } - }) - ).toMatchObject({ ok: false, error: { code: 'capability_unsupported' } }) - expect({ - saved: await readPersistedTestAgentSessionStore(directory), - alias: getSession().unifiedTabs?.[TEST_WORKTREE_ID]?.[0]?.customLabel - }).toEqual({ saved: before, alias }) - expect(notifier.renameTerminal).not.toHaveBeenCalled() - - expect( - await dispatcher.dispatch({ - id: 'native-title', - authToken: 'token', - method: 'session.tabs.setTabProps', - params - }) - ).toMatchObject({ ok: true, result: { updated: true } }) - expect( - (await readPersistedTestAgentSessionStore(directory)).records[sessionId]?.conversationName - ).toBe('Renamed through tab props') - expect(getSession().unifiedTabs?.[TEST_WORKTREE_ID]?.[0]?.customLabel).toBe(alias) - expect(notifier.renameTerminal).not.toHaveBeenCalled() - } finally { - await stopStructuredAgentSessionRuntime() - await closeTestJournalHostDatabases() - await rm(directory, { recursive: true, force: true }) - } -}) diff --git a/src/main/runtime/session-tabs/headless-editor-tabs.test.ts b/src/main/runtime/session-tabs/restoration/headless-editor-tabs.test.ts similarity index 92% rename from src/main/runtime/session-tabs/headless-editor-tabs.test.ts rename to src/main/runtime/session-tabs/restoration/headless-editor-tabs.test.ts index e871ea57724..e54595ae6a0 100644 --- a/src/main/runtime/session-tabs/headless-editor-tabs.test.ts +++ b/src/main/runtime/session-tabs/restoration/headless-editor-tabs.test.ts @@ -1,10 +1,10 @@ import { beforeEach, describe, expect, it, vi } from 'vitest' -import { ownedEditorFileId } from '../../../shared/workspace-session/workspace-session-pane-ownership' -import type { WorkspaceSessionState } from '../../../shared/workspace-session/workspace-session-state-types' +import { ownedEditorFileId } from '../../../../shared/workspace-session/workspace-session-pane-ownership' +import type { WorkspaceSessionState } from '../../../../shared/workspace-session/workspace-session-state-types' import { retireHeadlessEditorTab } from './headless-editor-tabs' const mocks = vi.hoisted(() => ({ layoutOwnerIsMain: true })) -vi.mock('../../../shared/workspace-layout/layout-owner-switch', () => ({ +vi.mock('../../../../shared/workspace-layout/layout-owner-switch', () => ({ get ORCA_LAYOUT_OWNER_IS_MAIN() { return mocks.layoutOwnerIsMain } diff --git a/src/main/runtime/session-tabs/headless-editor-tabs.ts b/src/main/runtime/session-tabs/restoration/headless-editor-tabs.ts similarity index 93% rename from src/main/runtime/session-tabs/headless-editor-tabs.ts rename to src/main/runtime/session-tabs/restoration/headless-editor-tabs.ts index eede2dfe288..42811bf4396 100644 --- a/src/main/runtime/session-tabs/headless-editor-tabs.ts +++ b/src/main/runtime/session-tabs/restoration/headless-editor-tabs.ts @@ -1,24 +1,24 @@ import { retireMobileSessionTabSelection, resolveMobileSessionActiveTab -} from './mobile-session-tab-selection' +} from '../layout/mobile-session-tab-selection' /** Headless hosts project/retire persisted editors themselves; paired desktops mirror them without a publishing renderer. */ import type { RuntimeMobileSessionFileTab, RuntimeMobileSessionMarkdownTab -} from '../../../shared/remote-runtime/session-graph/runtime-mobile-session-tab-contracts' -import type { RuntimeMobileSessionTabsSnapshot } from '../../../shared/remote-runtime/session-graph/runtime-session-contracts' -import type { Tab } from '../../../shared/workspace-layout/tab-groups/tab-types' -import { ORCA_LAYOUT_OWNER_IS_MAIN } from '../../../shared/workspace-layout/layout-owner-switch' -import { editorRowHost } from '../../../shared/workspace-session/session-tab-file-host' +} from '../../../../shared/remote-runtime/session-graph/runtime-mobile-session-tab-contracts' +import type { RuntimeMobileSessionTabsSnapshot } from '../../../../shared/remote-runtime/session-graph/runtime-session-contracts' +import type { Tab } from '../../../../shared/workspace-layout/tab-groups/tab-types' +import { ORCA_LAYOUT_OWNER_IS_MAIN } from '../../../../shared/workspace-layout/layout-owner-switch' +import { editorRowHost } from '../../../../shared/workspace-session/session-tab-file-host' import { editorTabNamesFile, sameEditorFile -} from '../../../shared/workspace-layout/editor-tabs/workspace-layout-editor-tab-file' +} from '../../../../shared/workspace-layout/editor-tabs/workspace-layout-editor-tab-file' import type { PersistedOpenFile, WorkspaceSessionState -} from '../../../shared/workspace-session/workspace-session-state-types' +} from '../../../../shared/workspace-session/workspace-session-state-types' export type HeadlessEditorTab = RuntimeMobileSessionMarkdownTab | RuntimeMobileSessionFileTab diff --git a/src/main/runtime/session-tabs/mobile-session-hydration.ts b/src/main/runtime/session-tabs/restoration/mobile-session-hydration.ts similarity index 91% rename from src/main/runtime/session-tabs/mobile-session-hydration.ts rename to src/main/runtime/session-tabs/restoration/mobile-session-hydration.ts index 28ebe11ee02..a94f92cf0c3 100644 --- a/src/main/runtime/session-tabs/mobile-session-hydration.ts +++ b/src/main/runtime/session-tabs/restoration/mobile-session-hydration.ts @@ -1,36 +1,36 @@ import { normalizeMobileSessionTabSelection, restoreLegacyMobileSessionNavigation -} from './mobile-session-tab-selection' -import type { OrcaRuntimeWithBuildHeadlessMobileSessionBrowserTabs as BuildHeadlessMobileSessionBrowserTabsMethods } from '../session-lifecycle/projection/build-headless-mobile-session-browser-tabs' +} from '../layout/mobile-session-tab-selection' +import type { OrcaRuntimeWithBuildHeadlessMobileSessionBrowserTabs as BuildHeadlessMobileSessionBrowserTabsMethods } from '../../session-lifecycle/projection/build-headless-mobile-session-browser-tabs' import type { OrcaRuntimeWithStoredMobileSnapshotHasStalePreservedTab as StoredMobileSnapshotHasStalePreservedTabMethods } from './mobile-session-publication-preservation' -import type { OrcaRuntimeWithReconcileHeadlessMobileSessionBrowserTabs as ReconcileHeadlessMobileSessionBrowserTabsMethods } from '../session-lifecycle/projection/reconcile-headless-mobile-session-browser-tabs' +import type { OrcaRuntimeWithReconcileHeadlessMobileSessionBrowserTabs as ReconcileHeadlessMobileSessionBrowserTabsMethods } from '../../session-lifecycle/projection/reconcile-headless-mobile-session-browser-tabs' import type { BrowserWindow } from 'electron' -import { RuntimeSessionTabsInventoryPublication } from './session-tabs-inventory-publication' -import type { WorkspaceSessionState } from '../../../shared/workspace-session/workspace-session-state-types' -import { getRuntimeBrowserPageRegistry } from '../browser/client-pages/runtime-browser-page-registry' -import { splitWorktreeIdForFilesystem } from '../../../shared/worktree/id' -import { buildHeadlessMobileSessionTerminalTabs } from '../terminal/surface/mobile-session-terminal-projection' +import { RuntimeSessionTabsInventoryPublication } from '../inventory/session-tabs-inventory-publication' +import type { WorkspaceSessionState } from '../../../../shared/workspace-session/workspace-session-state-types' +import { getRuntimeBrowserPageRegistry } from '../../browser/client-pages/runtime-browser-page-registry' +import { splitWorktreeIdForFilesystem } from '../../../../shared/worktree/id' +import { buildHeadlessMobileSessionTerminalTabs } from '../../terminal/surface/mobile-session-terminal-projection' import { buildHeadlessMobileSessionEditorTabs } from './headless-editor-tabs' -import type { RuntimeMobileSessionSnapshotTab } from '../../../shared/remote-runtime/session-graph/runtime-mobile-session-tab-contracts' +import type { RuntimeMobileSessionSnapshotTab } from '../../../../shared/remote-runtime/session-graph/runtime-mobile-session-tab-contracts' import type { RuntimeMobileSessionTabGroup, RuntimeMobileSessionTabsSnapshot -} from '../../../shared/remote-runtime/session-graph/runtime-session-contracts' +} from '../../../../shared/remote-runtime/session-graph/runtime-session-contracts' import { collectHeadlessParentTabOrder, getHeadlessMobileSessionGroupId, pickHeadlessActiveTerminalTab, pickRestoredActiveGroupId -} from '../terminal/surface/mobile-session-layout-projection' +} from '../../terminal/surface/mobile-session-layout-projection' import { appendChatTabOrder, keepSnapshotChatTabs, mergeMobileSessionSnapshotTabs, mergeMobileSessionTabGroups -} from '../session-lifecycle/projection/mobile-session-tab-merge' -import { appendBrowserTabOrder } from '../session-lifecycle/projection/mobile-session-browser-group-projection' -import { headlessMobileSnapshotContentUnchanged } from './mobile-session-snapshot-equality' +} from '../../session-lifecycle/projection/mobile-session-tab-merge' +import { appendBrowserTabOrder } from '../../session-lifecycle/projection/mobile-session-browser-group-projection' +import { headlessMobileSnapshotContentUnchanged } from '../publication/mobile-session-snapshot-equality' export abstract class OrcaRuntimeWithHydrateHeadlessMobileSessionTabsFromWorkspaceSession extends RuntimeSessionTabsInventoryPublication { protected abstract buildHeadlessMobileSessionBrowserTabs( diff --git a/src/main/runtime/session-tabs/mobile-session-membership.ts b/src/main/runtime/session-tabs/restoration/mobile-session-membership.ts similarity index 85% rename from src/main/runtime/session-tabs/mobile-session-membership.ts rename to src/main/runtime/session-tabs/restoration/mobile-session-membership.ts index 16c0cef5ea4..04794107d8d 100644 --- a/src/main/runtime/session-tabs/mobile-session-membership.ts +++ b/src/main/runtime/session-tabs/restoration/mobile-session-membership.ts @@ -1,18 +1,18 @@ -import type { MobileSessionTabSubscription } from '../construction/runtime-identity-state' -import type { OrcaRuntimeWithScheduleMobileSessionTabsChanged as SessionTabsPublication } from './session-tabs-change-publication' -import type { OrcaRuntimeWithPruneMobileSessionTabGroupLayout as SessionTabsProjection } from '../session-lifecycle/projection/prune-mobile-session-tab-group-layout' -import type { OrcaRuntimeWithGetTerminalInteractiveWait as GetTerminalInteractiveWaitMethods } from '../terminal/wait/terminal-interactive-wait' -import { OrcaRuntimeWithPublishPtyBackedMobileSessionTerminal } from './pty-backed-session-publication' -import { getRepoIdFromWorktreeId } from '../../../shared/worktree/id' -import { parsePaneKey } from '../../../shared/workspace-layout/stable-pane-id' -import { hasHostAuthoritativeTerminalMembership } from '../../persistence/terminal-topology/pane-ownership/terminal-topology-membership' +import type { MobileSessionTabSubscription } from '../../construction/runtime-identity-state' +import type { OrcaRuntimeWithScheduleMobileSessionTabsChanged as SessionTabsPublication } from '../publication/session-tabs-change-publication' +import type { OrcaRuntimeWithPruneMobileSessionTabGroupLayout as SessionTabsProjection } from '../../session-lifecycle/projection/prune-mobile-session-tab-group-layout' +import type { OrcaRuntimeWithGetTerminalInteractiveWait as GetTerminalInteractiveWaitMethods } from '../../terminal/wait/terminal-interactive-wait' +import { OrcaRuntimeWithPublishPtyBackedMobileSessionTerminal } from '../publication/pty-backed-session-publication' +import { getRepoIdFromWorktreeId } from '../../../../shared/worktree/id' +import { parsePaneKey } from '../../../../shared/workspace-layout/stable-pane-id' +import { hasHostAuthoritativeTerminalMembership } from '../../../persistence/terminal-topology/pane-ownership/terminal-topology-membership' import type { RuntimeMobileSessionTabsSnapshot, RuntimeSyncedLeaf -} from '../../../shared/remote-runtime/session-graph/runtime-session-contracts' -import { retireTerminalSurfacesFromSnapshot } from '../terminal/surface/mobile-session-terminal-retirement' -import { ORCA_LAYOUT_OWNER_IS_MAIN } from '../../../shared/workspace-layout/layout-owner-switch' -import { startedMainTerminalSurfaces } from '../terminal/surface/main-terminal-surfaces' +} from '../../../../shared/remote-runtime/session-graph/runtime-session-contracts' +import { retireTerminalSurfacesFromSnapshot } from '../../terminal/surface/mobile-session-terminal-retirement' +import { ORCA_LAYOUT_OWNER_IS_MAIN } from '../../../../shared/workspace-layout/layout-owner-switch' +import { startedMainTerminalSurfaces } from '../../terminal/surface/main-terminal-surfaces' export abstract class OrcaRuntimeWithTouchMobileSessionTabsForWorktree extends OrcaRuntimeWithPublishPtyBackedMobileSessionTerminal { protected abstract createMobileSessionTabsDelivery(): ReturnType< diff --git a/src/main/runtime/session-tabs/mobile-session-preservation.ts b/src/main/runtime/session-tabs/restoration/mobile-session-preservation.ts similarity index 91% rename from src/main/runtime/session-tabs/mobile-session-preservation.ts rename to src/main/runtime/session-tabs/restoration/mobile-session-preservation.ts index 810df01e3ac..4781eab645a 100644 --- a/src/main/runtime/session-tabs/mobile-session-preservation.ts +++ b/src/main/runtime/session-tabs/restoration/mobile-session-preservation.ts @@ -1,27 +1,27 @@ -import { isStructuredAgentSessionHostTabId } from '../../../shared/agent-session/view/structured-agent-session-host-tab-id' +import { isStructuredAgentSessionHostTabId } from '../../../../shared/agent-session/view/structured-agent-session-host-tab-id' import { normalizeMobileSessionTabSelection, preserveLegacyPendingNavigation, resolveMobileSessionActiveTab -} from './mobile-session-tab-selection' +} from '../layout/mobile-session-tab-selection' import type { OrcaRuntimeWithStoredMobileSnapshotHasStalePreservedTab as StoredMobileSnapshotHasStalePreservedTabMethods } from './mobile-session-publication-preservation' import { OrcaRuntimeWithSyncMobileSessionTabs } from './mobile-session-reconciliation' -import type { RuntimeMobileSessionTabsSnapshot } from '../../../shared/remote-runtime/session-graph/runtime-session-contracts' -import type { RuntimeMobileSessionTerminalTab } from '../../../shared/remote-runtime/session-graph/runtime-mobile-session-tab-contracts' +import type { RuntimeMobileSessionTabsSnapshot } from '../../../../shared/remote-runtime/session-graph/runtime-session-contracts' +import type { RuntimeMobileSessionTerminalTab } from '../../../../shared/remote-runtime/session-graph/runtime-mobile-session-tab-contracts' import { appendChatTabOrder, getMobileSessionSnapshotTabIdentityKeys, mergeMobileSessionSnapshotTabs, mergeMobileSessionTabGroups -} from '../session-lifecycle/projection/mobile-session-tab-merge' -import { terminalLayoutContainsLeaf } from '../../../shared/workspace-session/workspace-session-pane-ownership' -import { ORCA_LAYOUT_OWNER_IS_MAIN } from '../../../shared/workspace-layout/layout-owner-switch' -import { terminalIsOfTab } from '../session-lifecycle/close/closed-tab-terminal' -import { getHeadlessMobileSessionGroupId } from '../terminal/surface/mobile-session-layout-projection' +} from '../../session-lifecycle/projection/mobile-session-tab-merge' +import { terminalLayoutContainsLeaf } from '../../../../shared/workspace-session/workspace-session-pane-ownership' +import { ORCA_LAYOUT_OWNER_IS_MAIN } from '../../../../shared/workspace-layout/layout-owner-switch' +import { terminalIsOfTab } from '../../session-lifecycle/close/closed-tab-terminal' +import { getHeadlessMobileSessionGroupId } from '../../terminal/surface/mobile-session-layout-projection' import { appendBrowserTabOrder, collectBrowserGroupAssignment -} from '../session-lifecycle/projection/mobile-session-browser-group-projection' +} from '../../session-lifecycle/projection/mobile-session-browser-group-projection' export abstract class OrcaRuntimeWithMergePreservedHeadlessMobileSessionTabs extends OrcaRuntimeWithSyncMobileSessionTabs { protected abstract collectPreservedHeadlessMobileSessionTabs( diff --git a/src/main/runtime/session-tabs/mobile-session-publication-preservation.ts b/src/main/runtime/session-tabs/restoration/mobile-session-publication-preservation.ts similarity index 92% rename from src/main/runtime/session-tabs/mobile-session-publication-preservation.ts rename to src/main/runtime/session-tabs/restoration/mobile-session-publication-preservation.ts index 8691947412d..9656aa5826b 100644 --- a/src/main/runtime/session-tabs/mobile-session-publication-preservation.ts +++ b/src/main/runtime/session-tabs/restoration/mobile-session-publication-preservation.ts @@ -1,18 +1,18 @@ -import type { OrcaRuntimeWithScheduleMobileSessionTabsChanged as ScheduleMobileSessionTabsChangedMethods } from './session-tabs-change-publication' +import type { OrcaRuntimeWithScheduleMobileSessionTabsChanged as ScheduleMobileSessionTabsChangedMethods } from '../publication/session-tabs-change-publication' import { OrcaRuntimeWithMergePreservedHeadlessMobileSessionTabs } from './mobile-session-preservation' import type { RuntimeMobileSessionBrowserTab, RuntimeMobileSessionSnapshotTab -} from '../../../shared/remote-runtime/session-graph/runtime-mobile-session-tab-contracts' +} from '../../../../shared/remote-runtime/session-graph/runtime-mobile-session-tab-contracts' import type { RuntimeMobileSessionTabsRemovedResult, RuntimeMobileSessionTabsSnapshot -} from '../../../shared/remote-runtime/session-graph/runtime-session-contracts' -import { getMobileSessionSnapshotTabIdentityKeys } from '../session-lifecycle/projection/mobile-session-tab-merge' -import { getRuntimeBrowserPageRegistry } from '../browser/client-pages/runtime-browser-page-registry' -import { isHeadlessBuiltPublication } from './mobile-session-snapshot-equality' -import { sameRuntimeBrowserPlacement } from '../../../shared/browser/client-hosting/runtime-browser-placement' -import type { ClientHostedBrowserRowsEvent } from '../../../shared/browser/client-hosting/client-hosted-browser-rows' +} from '../../../../shared/remote-runtime/session-graph/runtime-session-contracts' +import { getMobileSessionSnapshotTabIdentityKeys } from '../../session-lifecycle/projection/mobile-session-tab-merge' +import { getRuntimeBrowserPageRegistry } from '../../browser/client-pages/runtime-browser-page-registry' +import { isHeadlessBuiltPublication } from '../publication/mobile-session-snapshot-equality' +import { sameRuntimeBrowserPlacement } from '../../../../shared/browser/client-hosting/runtime-browser-placement' +import type { ClientHostedBrowserRowsEvent } from '../../../../shared/browser/client-hosting/client-hosted-browser-rows' export abstract class OrcaRuntimeWithStoredMobileSnapshotHasStalePreservedTab extends OrcaRuntimeWithMergePreservedHeadlessMobileSessionTabs { protected abstract getListedBrowserTabsByPageId( diff --git a/src/main/runtime/session-tabs/mobile-session-reconciliation.ts b/src/main/runtime/session-tabs/restoration/mobile-session-reconciliation.ts similarity index 92% rename from src/main/runtime/session-tabs/mobile-session-reconciliation.ts rename to src/main/runtime/session-tabs/restoration/mobile-session-reconciliation.ts index c62fa302123..cb06177a8d8 100644 --- a/src/main/runtime/session-tabs/mobile-session-reconciliation.ts +++ b/src/main/runtime/session-tabs/restoration/mobile-session-reconciliation.ts @@ -1,24 +1,24 @@ -import { reconcileChatTabIdentities } from '../agent-session/agent-session-tab-identity' -import { preserveTerminalRetirementProofs } from '../terminal/surface/mobile-session-terminal-retirement-proof' -import { stampMobileSnapshotVersion } from './mobile-session-snapshot-version' -import { ORCA_LAYOUT_OWNER_IS_MAIN } from '../../../shared/workspace-layout/layout-owner-switch' -import { startedMainTerminalSurfaces } from '../terminal/surface/main-terminal-surfaces' +import { reconcileChatTabIdentities } from '../chat/agent-session-tab-identity' +import { preserveTerminalRetirementProofs } from '../../terminal/surface/mobile-session-terminal-retirement-proof' +import { stampMobileSnapshotVersion } from '../publication/mobile-session-snapshot-version' +import { ORCA_LAYOUT_OWNER_IS_MAIN } from '../../../../shared/workspace-layout/layout-owner-switch' +import { startedMainTerminalSurfaces } from '../../terminal/surface/main-terminal-surfaces' import { headlessMobileSnapshotContentUnchanged, mobileSnapshotIdentityUnchanged, mobileSnapshotInventoryOnlyChanged -} from './mobile-session-snapshot-equality' +} from '../publication/mobile-session-snapshot-equality' import type { OrcaRuntimeWithMergePreservedHeadlessMobileSessionTabs as MergePreservedHeadlessMobileSessionTabsMethods } from './mobile-session-preservation' import type { OrcaRuntimeWithStoredMobileSnapshotHasStalePreservedTab as StoredMobileSnapshotHasStalePreservedTabMethods } from './mobile-session-publication-preservation' -import { OrcaRuntimeWithWriteOrchestrationPointerPty } from '../orchestration/terminal-authority/write-orchestration-pointer-pty' +import { OrcaRuntimeWithWriteOrchestrationPointerPty } from '../../orchestration/terminal-authority/write-orchestration-pointer-pty' import type { RuntimeMobileSessionTabsPublication, RuntimeMobileSessionTabsSnapshot -} from '../../../shared/remote-runtime/session-graph/runtime-session-contracts' -import { withAcceptedBrowserPageInventory } from './mobile-session-inventory-base' -import type { WorkspaceSessionState } from '../../../shared/workspace-session/workspace-session-state-types' -import { getMobileSessionSnapshotTabIdentityKeys } from '../session-lifecycle/projection/mobile-session-tab-merge' -import { HEADLESS_RUNTIME_WINDOW_ID } from '../../../shared/remote-runtime/session-graph/runtime-session-contracts' +} from '../../../../shared/remote-runtime/session-graph/runtime-session-contracts' +import { withAcceptedBrowserPageInventory } from '../inventory/mobile-session-inventory-base' +import type { WorkspaceSessionState } from '../../../../shared/workspace-session/workspace-session-state-types' +import { getMobileSessionSnapshotTabIdentityKeys } from '../../session-lifecycle/projection/mobile-session-tab-merge' +import { HEADLESS_RUNTIME_WINDOW_ID } from '../../../../shared/remote-runtime/session-graph/runtime-session-contracts' export abstract class OrcaRuntimeWithSyncMobileSessionTabs extends OrcaRuntimeWithWriteOrchestrationPointerPty { storeMobileSessionSnapshot( diff --git a/src/main/runtime/session-tabs/renderer-session-terminal-rescue.ts b/src/main/runtime/session-tabs/restoration/renderer-session-terminal-rescue.ts similarity index 92% rename from src/main/runtime/session-tabs/renderer-session-terminal-rescue.ts rename to src/main/runtime/session-tabs/restoration/renderer-session-terminal-rescue.ts index e0ba5863a5e..2079016fdc0 100644 --- a/src/main/runtime/session-tabs/renderer-session-terminal-rescue.ts +++ b/src/main/runtime/session-tabs/restoration/renderer-session-terminal-rescue.ts @@ -1,9 +1,9 @@ -import type { OrcaRuntimeWithWaitForLeafPtyId as WaitForLeafPtyIdMethods } from '../terminal/view/renderer-terminal-snapshot' -import { OrcaRuntimeWithWaitForMobileTerminalSurface } from '../terminal/view/mobile-terminal-surface' -import { parsePaneKey } from '../../../shared/workspace-layout/stable-pane-id' -import type { RuntimePtyWorktreeRecord } from '../terminal/records/runtime-terminal-state-records' -import type { RuntimeMobileSessionCreateTerminalResult } from '../../../shared/remote-runtime/session-graph/runtime-session-contracts' -import { worktreeIdsEqual } from '../../../shared/worktree/id' +import type { OrcaRuntimeWithWaitForLeafPtyId as WaitForLeafPtyIdMethods } from '../../terminal/view/renderer-terminal-snapshot' +import { OrcaRuntimeWithWaitForMobileTerminalSurface } from '../../terminal/view/mobile-terminal-surface' +import { parsePaneKey } from '../../../../shared/workspace-layout/stable-pane-id' +import type { RuntimePtyWorktreeRecord } from '../../terminal/records/runtime-terminal-state-records' +import type { RuntimeMobileSessionCreateTerminalResult } from '../../../../shared/remote-runtime/session-graph/runtime-session-contracts' +import { worktreeIdsEqual } from '../../../../shared/worktree/id' export abstract class OrcaRuntimeWithRestoreLivePairedRendererSessionOwnedMobileTerminals extends OrcaRuntimeWithWaitForMobileTerminalSurface { protected abstract resolveHandleForTab( diff --git a/src/main/runtime/session-tabs/runtime-inventory-publication-authority.test.ts b/src/main/runtime/session-tabs/runtime-inventory-publication-authority.test.ts deleted file mode 100644 index 15487269c56..00000000000 --- a/src/main/runtime/session-tabs/runtime-inventory-publication-authority.test.ts +++ /dev/null @@ -1,202 +0,0 @@ -import { describe, expect, it, vi } from 'vitest' -import { OrcaRuntimeService } from '../orca-runtime' -import { getSessionTabsInventoryPublication } from './session-tabs-inventory-test-fixture' - -function createInventoryRuntime( - runtimeStore: ConstructorParameters[0] = null -): OrcaRuntimeService { - const runtime = new OrcaRuntimeService(runtimeStore) - runtime.setPtyController({ listProcesses: vi.fn(async () => []) } as never) - return runtime -} - -async function waitForInventoryWaiter(runtime: OrcaRuntimeService): Promise { - const publication = getSessionTabsInventoryPublication(runtime) - for (let index = 0; index < 20 && publication.pendingWaiterCount === 0; index += 1) { - await Promise.resolve() - } - expect(publication.pendingWaiterCount).toBe(1) -} - -describe('authoritative session tab inventory publication', () => { - it('primes daemon-backed inventory but withholds headed results until renderer publication', async () => { - const runtime = createInventoryRuntime() - runtime.attachWindow(1) - const collect = vi.spyOn( - runtime as unknown as { collectAllMobileSessionTabs: () => Promise }, - 'collectAllMobileSessionTabs' - ) - let settled = false - - const pending = runtime.listAllMobileSessionTabsInventory().then((result) => { - settled = true - return result - }) - await waitForInventoryWaiter(runtime) - - expect(collect).toHaveBeenCalledTimes(1) - await runtime.syncWindowGraph(1, { tabs: [], leaves: [] }) - await Promise.resolve() - expect(settled).toBe(false) - - await runtime.syncWindowGraph(1, { tabs: [], leaves: [], mobileSessionTabs: [] }) - await expect(pending).resolves.toEqual({ snapshots: [], authoritative: true }) - expect(collect).toHaveBeenCalledTimes(2) - }) - - it('retries once and serves an unlabeled scan when the PTY census is unavailable', async () => { - const runtime = new OrcaRuntimeService() - const collect = vi.spyOn( - runtime as unknown as { collectAllMobileSessionTabs: () => Promise }, - 'collectAllMobileSessionTabs' - ) - runtime.attachWindow(1) - await runtime.syncWindowGraph(1, { tabs: [], leaves: [], mobileSessionTabs: [] }) - - await expect(runtime.listAllMobileSessionTabsInventory()).resolves.toEqual({ snapshots: [] }) - // Why: the retry gives daemon-backed tabs a post-race restore chance. - expect(collect).toHaveBeenCalledTimes(2) - }) - - it('requires the current headed renderer generation to publish', async () => { - const runtime = createInventoryRuntime() - runtime.attachWindow(1) - await runtime.syncWindowGraph(1, { - tabs: [], - leaves: [], - mobileSessionTabs: [] - }) - runtime.markRendererReloading(1) - let settled = false - - const pending = runtime.listAllMobileSessionTabsInventory().then((result) => { - settled = true - return result - }) - await waitForInventoryWaiter(runtime) - await runtime.syncWindowGraph(1, { tabs: [], leaves: [] }) - await Promise.resolve() - expect(settled).toBe(false) - - await runtime.syncWindowGraph(1, { - tabs: [], - leaves: [], - mobileSessionTabs: [ - { - worktree: 'repo::/restored', - publicationEpoch: 'renderer-reloaded', - snapshotVersion: 1, - activeGroupId: null, - activeTabId: null, - activeTabType: null, - tabs: [] - } - ] - }) - await expect(pending).resolves.toMatchObject({ - authoritative: true, - snapshots: [{ worktree: 'repo::/restored', publicationEpoch: 'renderer-reloaded' }] - }) - }) - - it('withholds authority while the renderer owes a requested worktree resync', async () => { - const runtime = createInventoryRuntime() - const worktree = 'repo::/resync' - runtime.attachWindow(1) - await runtime.syncWindowGraph(1, { tabs: [], leaves: [], mobileSessionTabs: [] }) - - const incomplete = await runtime.syncWindowGraph(1, { - tabs: [], - leaves: [], - mobileSessionTabs: [], - unchangedMobileSessionWorktrees: [worktree] - }) - expect(incomplete.mobileSessionResyncWorktrees).toEqual([worktree]) - const pending = runtime.listAllMobileSessionTabsInventory() - await waitForInventoryWaiter(runtime) - - await runtime.syncWindowGraph(1, { - tabs: [], - leaves: [], - mobileSessionTabs: [ - { - worktree, - publicationEpoch: 'renderer-resynced', - snapshotVersion: 1, - activeGroupId: null, - activeTabId: null, - activeTabType: null, - tabs: [] - } - ] - }) - - await expect(pending).resolves.toMatchObject({ - authoritative: true, - snapshots: [{ worktree, publicationEpoch: 'renderer-resynced' }] - }) - }) - - it('restores publication authority when a renderer reload is cancelled', async () => { - const runtime = createInventoryRuntime() - runtime.attachWindow(1) - await runtime.syncWindowGraph(1, { tabs: [], leaves: [], mobileSessionTabs: [] }) - const fence = runtime.markRendererReloading(1) - if (!fence) { - throw new Error('expected renderer reload fence') - } - const pending = runtime.listAllMobileSessionTabsInventory() - await waitForInventoryWaiter(runtime) - - expect(runtime.markRendererReloadCancelled(1, fence)).toBe(true) - - await expect(pending).resolves.toEqual({ snapshots: [], authoritative: true }) - }) - - it('restores authoritative headless publication after a failed desktop promotion', async () => { - const runtime = createInventoryRuntime() - await runtime.syncWindowGraph(0, { tabs: [], leaves: [] }) - runtime.attachWindow(1) - const pending = runtime.listAllMobileSessionTabsInventory() - await waitForInventoryWaiter(runtime) - - runtime.markGraphReloadFailed(1, 'renderer-process-gone') - - await expect(pending).resolves.toEqual({ snapshots: [], authoritative: true }) - }) - - it('removes a publication waiter when the request is cancelled', async () => { - const runtime = createInventoryRuntime() - runtime.attachWindow(1) - const controller = new AbortController() - const pending = runtime.listAllMobileSessionTabsInventory(undefined, controller.signal) - await waitForInventoryWaiter(runtime) - - controller.abort() - - await expect(pending).rejects.toThrow('client_disconnected') - expect(getSessionTabsInventoryPublication(runtime).pendingWaiterCount).toBe(0) - }) - - it('does not let a secondary renderer graph publish inventory authority', async () => { - const runtime = createInventoryRuntime() - runtime.attachWindow(1) - let settled = false - - const pending = runtime.listAllMobileSessionTabsInventory().then((result) => { - settled = true - return result - }) - await waitForInventoryWaiter(runtime) - - await expect( - runtime.syncWindowGraph(2, { tabs: [], leaves: [], mobileSessionTabs: [] }) - ).rejects.toThrow('Runtime graph publisher does not match the authoritative window') - await Promise.resolve() - expect(settled).toBe(false) - expect(getSessionTabsInventoryPublication(runtime).epoch).toBeNull() - - await runtime.syncWindowGraph(1, { tabs: [], leaves: [], mobileSessionTabs: [] }) - await expect(pending).resolves.toEqual({ snapshots: [], authoritative: true }) - }) -}) diff --git a/src/main/runtime/session-tabs/session-tab-close-force.test.ts b/src/main/runtime/session-tabs/session-tab-close-force.test.ts deleted file mode 100644 index 42c787536f4..00000000000 --- a/src/main/runtime/session-tabs/session-tab-close-force.test.ts +++ /dev/null @@ -1,110 +0,0 @@ -// Confirmed pinned-tab closes carry force in both layout builds. -import { afterEach, describe, expect, it, vi } from 'vitest' -import { SESSION_TAB_CLOSE_INTENT_RUNTIME_CAPABILITY } from '../../../shared/remote-runtime/protocol/session-tabs-runtime-capabilities' -import { z } from 'zod' -import { RpcDispatcher } from '../rpc/dispatcher' -import { SESSION_TAB_METHODS } from '../rpc/methods/session-tabs/session-tabs' -import { - ACK_TAB, - ACK_WORKTREE, - createAcknowledgedTabRetirementFixture -} from './acknowledged-terminal-tab-retirement-fixture' - -// Read at each close, so one import serves both builds. -const layoutOwner = vi.hoisted(() => ({ isMain: false })) -vi.mock('../../../shared/workspace-layout/layout-owner-switch', () => ({ - get ORCA_LAYOUT_OWNER_IS_MAIN() { - return layoutOwner.isMain - } -})) - -const Reply = z.object({ ok: z.boolean(), error: z.object({ code: z.string() }).optional() }) - -const disposers: (() => Promise)[] = [] -afterEach(async () => { - for (const dispose of disposers.splice(0)) { - await dispose() - } - vi.restoreAllMocks() - layoutOwner.isMain = false -}) - -async function pinnedServerTab(layoutOwnerIsMain: boolean) { - layoutOwner.isMain = layoutOwnerIsMain - const f = await createAcknowledgedTabRetirementFixture(true) - disposers.push(() => f.dispose()) - const stopped: string[] = [] - f.runtime.setPtyController({ - write: () => true, - kill: (ptyId: string) => { - stopped.push(ptyId) - return true - }, - getForegroundProcess: async () => null - }) - const session = f.store.getWorkspaceSession() - f.store.setWorkspaceSession({ - ...session, - tabsByWorktree: { - ...session.tabsByWorktree, - [ACK_WORKTREE]: session.tabsByWorktree[ACK_WORKTREE].map((tab) => ({ - ...tab, - isPinned: true - })) - } - }) - // Model the window pin guard: pinned tabs require force. - const windowClose = f.closeTerminalTab.getMockImplementation()! - f.acknowledgement.resolve() - f.closeTerminalTab.mockImplementation(async (_tabId?: unknown, options?: unknown) => { - if (!(typeof options === 'object' && options !== null && 'force' in options && options.force)) { - throw new Error('terminal_tab_pinned') - } - await windowClose() - }) - const dispatcher = new RpcDispatcher({ - runtime: f.runtime, - methods: SESSION_TAB_METHODS - }) - const close = async ( - params: Record, - clientCapabilities: string[] = [SESSION_TAB_CLOSE_INTENT_RUNTIME_CAPABILITY] - ): Promise> => { - let reply: z.infer | undefined - await dispatcher.dispatchStreaming( - { - id: 'close-1', - authToken: 'unused', - method: 'session.tabs.close', - params: { worktree: `id:${ACK_WORKTREE}`, tabId: ACK_TAB, reason: 'user', ...params } - }, - (raw) => { - reply = Reply.parse(JSON.parse(raw)) - }, - { - clientKind: 'runtime', - pairedDeviceId: 'paired-desktop', - clientCapabilities - } - ) - return reply! - } - return { f, stopped, close } -} - -describe.each([false, true])('ORCA_LAYOUT_OWNER_IS_MAIN=%s', (layoutOwnerIsMain) => { - it('refuses an unforced close of a pinned tab and keeps it and its terminals', async () => { - const { f, stopped, close } = await pinnedServerTab(layoutOwnerIsMain) - const reply = await close({}) - expect(reply.error?.code).toBe('terminal_tab_pinned') - expect(f.hasTab()).toBe(true) - expect(stopped).toEqual([]) - }) - - it('ignores force on a reasonless legacy close, which never carried a confirmation', async () => { - const { f, close } = await pinnedServerTab(layoutOwnerIsMain) - const reply = await close({ reason: undefined, force: true }, []) - expect(reply.error?.code).toBe('terminal_tab_pinned') - expect(f.hasTab()).toBe(true) - }) -}) diff --git a/src/main/runtime/session-tabs/session-tab-prototype-dispatch.test.ts b/src/main/runtime/session-tabs/session-tab-prototype-dispatch.test.ts deleted file mode 100644 index b05e54cb774..00000000000 --- a/src/main/runtime/session-tabs/session-tab-prototype-dispatch.test.ts +++ /dev/null @@ -1,61 +0,0 @@ -import { describe, expect, it } from 'vitest' - -import { OrcaRuntimeService } from '../orca-runtime' -import '../../native-chat/agent-session-wire/host/structured-agent-session-registry' - -class GraphRuntime extends OrcaRuntimeService { - get graphTabs() { - return this.tabs - } - get graphLeaves() { - return this.leaves - } - get graphLeavesByPtyId() { - return this.leavesByPtyId - } - get graphAvailability() { - return this.graphStatus - } - get graphEpoch() { - return this.rendererGraphEpoch - } - get detachedLeaves() { - return this.detachedPreAllocatedLeaves - } - get syncCallbacks() { - return this.graphSyncCallbacks - } -} - -const graph = { - tabs: [{ tabId: 'tab', worktreeId: 'workspace', activeLeafId: 'leaf', layout: null, title: '' }], - leaves: [ - { - tabId: 'tab', - worktreeId: 'workspace', - leafId: 'leaf', - paneRuntimeId: 1, - ptyId: 'pty', - paneTitle: null - } - ] -} - -describe('runtime graph ownership', () => { - it('shares detached preallocated leaves with terminal identity during renderer reload', async () => { - const runtime = new GraphRuntime() - const handle = runtime.preAllocateHandleForPty('pty') - runtime.attachWindow(1) - await runtime.syncWindowGraph(1, graph) - const leaf = runtime.graphLeaves.get('tab::leaf') - - runtime.markRendererReloading(1) - - expect(runtime.detachedLeaves.get('pty')).toBe(leaf) - await runtime.syncWindowGraph(1, { tabs: [], leaves: [] }) - runtime.onPtyData('pty', 'after omitted leaf\n', 100) - await expect(runtime.readTerminal(handle)).resolves.toMatchObject({ - tail: ['after omitted leaf'] - }) - }) -}) diff --git a/src/main/runtime/session-tabs/session-tabs-headless-main-change.test.ts b/src/main/runtime/session-tabs/session-tabs-headless-main-change.test.ts deleted file mode 100644 index 47e12358749..00000000000 --- a/src/main/runtime/session-tabs/session-tabs-headless-main-change.test.ts +++ /dev/null @@ -1,79 +0,0 @@ -// Main-owned layout changes must reach subscribed phones without a window to republish rows. -import { describe, expect, it, vi } from 'vitest' -import { HEADLESS_RUNTIME_WINDOW_ID } from '../../../shared/remote-runtime/session-graph/runtime-session-contracts' -import type { RuntimeMobileSessionTabsResult } from '../../../shared/remote-runtime/session-graph/runtime-session-contracts' -import { TEST_WORKTREE_ID } from '../orca-runtime-tests/orca-runtime-test-fixtures.spec' -import { - SURFACE_TAB_ID, - surfaceRuntime -} from '../terminal/surface/terminal-surface-replies.test-fixture' -import { - MOVED_STRIP, - SAVED_STRIP, - moveAndSplitTabs, - tabStrip, - threeTabSurfaceRuntime -} from './session-tabs-layout-moves.test-fixture' - -vi.mock('../../../shared/workspace-layout/layout-owner-switch', () => ({ - ORCA_LAYOUT_OWNER_IS_MAIN: true -})) - -describe('session.tabs on a windowless server (switch on)', () => { - it("a tab main renames reaches a subscribed phone's rows", async () => { - vi.useFakeTimers() - try { - const { runtime } = surfaceRuntime() - await runtime.syncWindowGraph(HEADLESS_RUNTIME_WINDOW_ID, { tabs: [], leaves: [] }) - await runtime.listMobileSessionTabs(`id:${TEST_WORKTREE_ID}`) - const seen: RuntimeMobileSessionTabsResult[] = [] - runtime.onMobileSessionTabsChanged((snapshot) => { - seen.push(snapshot) - }) - - await runtime.applyLayoutCommand({ - type: 'renameTab', - workspace: TEST_WORKTREE_ID, - tabId: SURFACE_TAB_ID, - kind: 'custom', - title: 'Build' - }) - await vi.runAllTimersAsync() - - // Pushed by main on its own, before any phone asks again. - expect(seen.at(-1)?.tabs.map((tab) => tab.title)).toEqual(['Build', 'Build']) - const listed = await runtime.listMobileSessionTabs(`id:${TEST_WORKTREE_ID}`) - expect(listed.tabs.map((tab) => tab.title)).toEqual(['Build', 'Build']) - } finally { - vi.useRealTimers() - } - }) - - it("a reorder and a move to a split follow main's layout, listed and pushed", async () => { - vi.useFakeTimers() - try { - const { runtime } = threeTabSurfaceRuntime() - await runtime.syncWindowGraph(HEADLESS_RUNTIME_WINDOW_ID, { tabs: [], leaves: [] }) - expect(tabStrip(await runtime.listMobileSessionTabs(`id:${TEST_WORKTREE_ID}`))).toEqual( - SAVED_STRIP - ) - const seen: RuntimeMobileSessionTabsResult[] = [] - runtime.onMobileSessionTabsChanged((snapshot) => { - seen.push(snapshot) - }) - - await moveAndSplitTabs(runtime) - await vi.runAllTimersAsync() - - // Pushed by main on its own, and listed, with no window to republish. - expect(tabStrip(seen.at(-1))).toEqual(MOVED_STRIP) - const listed = await runtime.listMobileSessionTabs(`id:${TEST_WORKTREE_ID}`) - expect(tabStrip(listed)).toEqual(MOVED_STRIP) - // A second ask changes nothing: the merge is settled. - const again = await runtime.listMobileSessionTabs(`id:${TEST_WORKTREE_ID}`) - expect(again.snapshotVersion).toBe(listed.snapshotVersion) - } finally { - vi.useRealTimers() - } - }) -}) diff --git a/src/main/runtime/session-tabs/session-tabs-inventory-publication.test.ts b/src/main/runtime/session-tabs/session-tabs-inventory-publication.test.ts deleted file mode 100644 index 92f932ffe9b..00000000000 --- a/src/main/runtime/session-tabs/session-tabs-inventory-publication.test.ts +++ /dev/null @@ -1,121 +0,0 @@ -import { describe, expect, it } from 'vitest' -import type { RuntimeGraphStatus } from '../../../shared/remote-runtime/session-graph/runtime-session-contracts' -import { OrcaRuntimeService } from '../orca-runtime' - -class InventoryPublicationRuntime extends OrcaRuntimeService { - setGraph(status: RuntimeGraphStatus, epoch: number): void { - this.graphStatus = status - if (this.rendererGraphEpoch !== epoch) { - this.terminalIdentity.advanceRendererEpoch() - } - expect(this.rendererGraphEpoch).toBe(epoch) - } - - get epoch(): number | null { - return this.sessionTabsInventoryPublicationEpoch - } - - get pendingWaiterCount(): number { - return this.sessionTabsInventoryWaiters.size - } - - reset(): void { - this.sessionTabsInventoryPublicationEpoch = null - } - - addPublicationListener(listener: () => void): void { - this.sessionTabsInventoryWaiters.add(listener) - } - - removePublicationListener(listener: () => void): void { - this.sessionTabsInventoryWaiters.delete(listener) - } - - override waitForSessionTabsInventoryPublication(signal?: AbortSignal): Promise { - return super.waitForSessionTabsInventoryPublication(signal) - } - - override getAuthoritativeSessionTabsInventoryEpoch(): number | null { - return super.getAuthoritativeSessionTabsInventoryEpoch() - } - - override markSessionTabsInventoryPublished(): void { - super.markSessionTabsInventoryPublished() - } -} - -function inventoryPublication() { - const publication = new InventoryPublicationRuntime(null) - publication.setGraph('ready', 1) - return { publication } -} - -describe('session tab inventory publication ownership', () => { - it('keeps publication and waiters isolated between runtime owners', async () => { - const first = inventoryPublication() - const second = inventoryPublication() - const firstWait = first.publication.waitForSessionTabsInventoryPublication() - const secondWait = second.publication.waitForSessionTabsInventoryPublication() - - first.publication.markSessionTabsInventoryPublished() - await firstWait - expect(first.publication.pendingWaiterCount).toBe(0) - expect(second.publication.pendingWaiterCount).toBe(1) - expect(second.publication.epoch).toBeNull() - - second.publication.markSessionTabsInventoryPublished() - await secondWait - }) - - it('uses the live graph status and epoch after the owner was constructed', async () => { - const { publication } = inventoryPublication() - publication.markSessionTabsInventoryPublished() - publication.setGraph('reloading', 2) - expect(publication.getAuthoritativeSessionTabsInventoryEpoch()).toBeNull() - const pending = publication.waitForSessionTabsInventoryPublication() - expect(publication.pendingWaiterCount).toBe(1) - - publication.setGraph('ready', 2) - publication.markSessionTabsInventoryPublished() - await pending - expect(publication.getAuthoritativeSessionTabsInventoryEpoch()).toBe(2) - }) - - it('removes a newly-aborted waiter without cancelling another caller', async () => { - const { publication } = inventoryPublication() - const controller = new AbortController() - const cancelled = publication.waitForSessionTabsInventoryPublication(controller.signal) - const surviving = publication.waitForSessionTabsInventoryPublication() - controller.abort() - - await expect(cancelled).rejects.toThrow('client_disconnected') - expect(publication.pendingWaiterCount).toBe(1) - publication.markSessionTabsInventoryPublished() - await surviving - }) - - it('notifies a captured listener set once per epoch', () => { - const { publication } = inventoryPublication() - const calls: string[] = [] - const addedDuringPublication = (): void => { - calls.push('added') - publication.removePublicationListener(addedDuringPublication) - } - const first = (): void => { - calls.push('first') - publication.removePublicationListener(first) - publication.addPublicationListener(addedDuringPublication) - } - publication.addPublicationListener(first) - - publication.markSessionTabsInventoryPublished() - publication.markSessionTabsInventoryPublished() - expect(calls).toEqual(['first']) - expect(publication.pendingWaiterCount).toBe(1) - - publication.setGraph('ready', 2) - publication.markSessionTabsInventoryPublished() - expect(calls).toEqual(['first', 'added']) - expect(publication.pendingWaiterCount).toBe(0) - }) -}) diff --git a/src/main/runtime/session-tabs/session-tabs-inventory-test-fixture.ts b/src/main/runtime/session-tabs/session-tabs-inventory-test-fixture.ts deleted file mode 100644 index c8ec2ed97ad..00000000000 --- a/src/main/runtime/session-tabs/session-tabs-inventory-test-fixture.ts +++ /dev/null @@ -1,26 +0,0 @@ -import type { OrcaRuntimeService } from '../orca-runtime' - -export function getSessionTabsInventoryPublication(runtime: OrcaRuntimeService) { - return { - get epoch(): number | null { - const epoch: unknown = Object.getOwnPropertyDescriptor( - runtime, - 'sessionTabsInventoryPublicationEpoch' - )?.value - if (epoch === null || typeof epoch === 'number') { - return epoch - } - throw new Error('Runtime does not own a session tab inventory publication epoch') - }, - get pendingWaiterCount(): number { - const waiters: unknown = Object.getOwnPropertyDescriptor( - runtime, - 'sessionTabsInventoryWaiters' - )?.value - if (!(waiters instanceof Set)) { - throw new Error('Runtime does not own session tab inventory waiters') - } - return waiters.size - } - } -} diff --git a/src/main/runtime/session-tabs/session-tabs-layout-moves.test-fixture.ts b/src/main/runtime/session-tabs/session-tabs-layout-moves.test-fixture.ts deleted file mode 100644 index 422c10757f1..00000000000 --- a/src/main/runtime/session-tabs/session-tabs-layout-moves.test-fixture.ts +++ /dev/null @@ -1,85 +0,0 @@ -// Model desktop reorder/split layout commands; session.tabs must list the resulting main-owned groups/order. -import type { RuntimeMobileSessionTabsResult } from '../../../shared/remote-runtime/session-graph/runtime-session-contracts' -import { TEST_WORKTREE_ID } from '../orca-runtime-tests/orca-runtime-test-fixtures.spec' -import { - SURFACE_TAB_ID, - surfaceRuntime -} from '../terminal/surface/terminal-surface-replies.test-fixture' - -export const SECOND_TAB_ID = '55555555-5555-4555-8555-555555555555' -export const THIRD_TAB_ID = '66666666-6666-4666-8666-666666666666' -const ADDED_TABS = [ - { id: SECOND_TAB_ID, leafId: '77777777-7777-4777-8777-777777777777' }, - { id: THIRD_TAB_ID, leafId: '88888888-8888-4888-8888-888888888888' } -] -export const SAVED_GROUP_ID = 'group-a' - -/** Each group's tab order, as saved: one group. */ -export const SAVED_STRIP = [[SURFACE_TAB_ID, SECOND_TAB_ID, THIRD_TAB_ID]] -/** After moveAndSplitTabs: the third tab first, the second in a split of its own. */ -export const MOVED_STRIP = [[THIRD_TAB_ID, SURFACE_TAB_ID], [SECOND_TAB_ID]] - -export const tabStrip = (listed: RuntimeMobileSessionTabsResult | undefined): string[][] => - (listed?.tabGroups ?? []).map((group) => group.tabOrder) - -/** The fixture's split tab plus two single-pane tabs, all in one saved group. */ -export function threeTabSurfaceRuntime(): ReturnType { - const harness = surfaceRuntime() - const session = harness.store.getSession() - const [first] = session.tabsByWorktree[TEST_WORKTREE_ID] ?? [] - if (!first) { - throw new Error('surfaceRuntime saves one tab') - } - const extra = ADDED_TABS.map(({ id }, index) => ({ - ...first, - id, - ptyId: null, - sortOrder: index + 1, - createdAt: index + 2 - })) - harness.setSession({ - ...session, - tabsByWorktree: { [TEST_WORKTREE_ID]: [first, ...extra] }, - terminalLayoutsByTabId: { - ...session.terminalLayoutsByTabId, - ...Object.fromEntries( - ADDED_TABS.map(({ id, leafId }) => [ - id, - { root: { type: 'leaf' as const, leafId }, activeLeafId: leafId, expandedLeafId: null } - ]) - ) - }, - tabGroups: { - [TEST_WORKTREE_ID]: [ - { - id: SAVED_GROUP_ID, - worktreeId: TEST_WORKTREE_ID, - activeTabId: SURFACE_TAB_ID, - tabOrder: SAVED_STRIP[0]! - } - ] - }, - activeGroupIdByWorktree: { [TEST_WORKTREE_ID]: SAVED_GROUP_ID } - }) - return harness -} - -/** A desktop's drag of the third tab to the front, then Move Tab to Split (right) on the second. */ -export async function moveAndSplitTabs( - runtime: ReturnType['runtime'] -): Promise { - await runtime.applyLayoutCommand({ - type: 'moveTab', - workspace: TEST_WORKTREE_ID, - tabId: THIRD_TAB_ID, - toGroupId: SAVED_GROUP_ID, - index: 0 - }) - await runtime.applyLayoutCommand({ - type: 'splitGroup', - workspace: TEST_WORKTREE_ID, - tabId: SECOND_TAB_ID, - besideGroupId: SAVED_GROUP_ID, - direction: 'right' - }) -} diff --git a/src/main/runtime/session-tabs/session-tabs-main-rows-parity.test.ts b/src/main/runtime/session-tabs/session-tabs-main-rows-parity.test.ts deleted file mode 100644 index 26c398513a4..00000000000 --- a/src/main/runtime/session-tabs/session-tabs-main-rows-parity.test.ts +++ /dev/null @@ -1,107 +0,0 @@ -// Phones/paired desktops must project main layout after create/close/rename despite stale window rows; rows arrive with the window's next publication. -import { describe, expect, it, vi } from 'vitest' -import type { RuntimeMobileSessionTabsSnapshot } from '../../../shared/remote-runtime/session-graph/runtime-session-contracts' - -import { - HEADLESS_LEAF_ID, - HEADLESS_SECOND_LEAF_ID, - TEST_WORKTREE_ID -} from '../orca-runtime-tests/orca-runtime-test-fixtures.spec' -import { - SURFACE_TAB_ID, - surfaceRuntime -} from '../terminal/surface/terminal-surface-replies.test-fixture' -import { - MOVED_STRIP, - SAVED_GROUP_ID, - SAVED_STRIP, - moveAndSplitTabs, - tabStrip, - threeTabSurfaceRuntime -} from './session-tabs-layout-moves.test-fixture' - -vi.mock('../../../shared/workspace-layout/layout-owner-switch', () => ({ - ORCA_LAYOUT_OWNER_IS_MAIN: true -})) - -const row = (leafId: string) => `${SURFACE_TAB_ID}::${leafId}` - -/** The window's publication as it was before main's change: both panes, the old title. */ -function stalePublication( - version: number, - activeLeafId: string = HEADLESS_LEAF_ID -): RuntimeMobileSessionTabsSnapshot { - const tabs = [HEADLESS_LEAF_ID, HEADLESS_SECOND_LEAF_ID].map((leafId) => ({ - type: 'terminal' as const, - id: row(leafId), - title: 'Persisted Terminal', - parentTabId: SURFACE_TAB_ID, - leafId, - isActive: leafId === activeLeafId - })) - return { - worktree: TEST_WORKTREE_ID, - publicationEpoch: 'renderer', - snapshotVersion: version, - activeGroupId: null, - activeTabId: row(activeLeafId), - activeTabType: 'terminal', - tabs - } -} - -async function phoneRows(runtime: ReturnType['runtime']) { - const listed = await runtime.listMobileSessionTabs(`id:${TEST_WORKTREE_ID}`) - return listed.tabs.map((tab) => ({ - id: tab.id, - title: tab.title, - customTitle: tab.type === 'terminal' ? tab.customTitle : undefined - })) -} - -describe('session.tabs rows follow main’s layout (switch on)', () => { - it('a tab main renamed before the window republished', async () => { - const { runtime } = surfaceRuntime() - runtime.attachWindow(1) - await runtime.syncWindowGraph(1, { - tabs: [], - leaves: [], - mobileSessionTabs: [stalePublication(1)] - }) - await runtime.applyLayoutCommand({ - type: 'renameTab', - workspace: TEST_WORKTREE_ID, - tabId: SURFACE_TAB_ID, - kind: 'custom', - title: 'Build' - }) - await runtime.syncWindowGraph(1, { - tabs: [], - leaves: [], - mobileSessionTabs: [stalePublication(2)] - }) - - const rows = await phoneRows(runtime) - expect(rows.map((entry) => [entry.title, entry.customTitle])).toEqual([ - ['Build', 'Build'], - ['Build', 'Build'] - ]) - }) - - it("a reorder and a move to a split main made, before the window's groups caught up", async () => { - const { runtime } = threeTabSurfaceRuntime() - runtime.attachWindow(1) - const publication = (version: number): RuntimeMobileSessionTabsSnapshot => ({ - ...stalePublication(version), - activeGroupId: SAVED_GROUP_ID, - tabGroups: [{ id: SAVED_GROUP_ID, activeTabId: SURFACE_TAB_ID, tabOrder: SAVED_STRIP[0]! }] - }) - await runtime.syncWindowGraph(1, { tabs: [], leaves: [], mobileSessionTabs: [publication(1)] }) - await moveAndSplitTabs(runtime) - await runtime.syncWindowGraph(1, { tabs: [], leaves: [], mobileSessionTabs: [publication(2)] }) - - expect(tabStrip(await runtime.listMobileSessionTabs(`id:${TEST_WORKTREE_ID}`))).toEqual( - MOVED_STRIP - ) - }) -}) diff --git a/src/main/runtime/session-tabs/session-tabs-phone-layout-moves.test.ts b/src/main/runtime/session-tabs/session-tabs-phone-layout-moves.test.ts deleted file mode 100644 index 89930b5c9a8..00000000000 --- a/src/main/runtime/session-tabs/session-tabs-phone-layout-moves.test.ts +++ /dev/null @@ -1,107 +0,0 @@ -// Windowless phone split moves and subsequent creates must retain main-owned groups/order. -import { describe, expect, it, vi } from 'vitest' -import { HEADLESS_RUNTIME_WINDOW_ID } from '../../../shared/remote-runtime/session-graph/runtime-session-contracts' - -vi.mock('../../../shared/workspace-layout/layout-owner-switch', () => ({ - ORCA_LAYOUT_OWNER_IS_MAIN: true -})) - -// Fragments stay side-effect ordered: mocks, then lifecycle, then fixtures. -await import('../orca-runtime-tests/runtime-test-module-registration.spec') -await import('../orca-runtime-tests/orca-runtime-test-lifecycle.spec') -const { TEST_WORKTREE_ID, TEST_WORKTREE_PATH } = - await import('../orca-runtime-tests/orca-runtime-test-fixtures.spec') -const { SURFACE_TAB_ID } = await import('../terminal/surface/terminal-surface-replies.test-fixture') -const { SAVED_GROUP_ID, SECOND_TAB_ID, THIRD_TAB_ID, tabStrip, threeTabSurfaceRuntime } = - await import('./session-tabs-layout-moves.test-fixture') - -const WORKTREE = `id:${TEST_WORKTREE_ID}` -const CHAT = 'agent-session:s1' - -/** The three saved tabs on a server with no window, whose spawns bind their pane as the host's do. */ -async function headlessRuntime() { - const harness = threeTabSurfaceRuntime() - const { runtime, bindPane } = harness - await runtime.syncWindowGraph(HEADLESS_RUNTIME_WINDOW_ID, { tabs: [], leaves: [] }) - runtime.setPtyController({ - spawn: vi.fn(async (args: { worktreeId?: string; tabId?: string; leafId?: string }) => { - await bindPane({ - worktreeId: args.worktreeId!, - tabId: args.tabId!, - leafId: args.leafId!, - ptyId: 'pty-new' - }) - return { id: 'pty-new' } - }), - write: () => true, - kill: () => true, - stopAndWait: async () => true, - getForegroundProcess: async () => null, - listProcesses: async () => - ['pty-a', 'pty-b', 'pty-new'].map((id) => ({ id, cwd: TEST_WORKTREE_PATH, title: 'sh' })) - }) - await runtime.listMobileSessionTabs(WORKTREE) - return harness -} - -const orderOf = (rows: readonly { type: string; id: string; parentTabId?: string }[]) => [ - ...new Set(rows.map((row) => (row.type === 'terminal' ? row.parentTabId! : row.id))) -] - -describe("a phone's layout change on a windowless server (switch on)", () => { - it.each([ - { - client: 'a phone with split-group placement', - supportsSplitGroupPlacement: true, - order: (created: string) => [SURFACE_TAB_ID, created, SECOND_TAB_ID, THIRD_TAB_ID] - }, - { - client: 'an older phone, at the end as today', - supportsSplitGroupPlacement: false, - order: (created: string) => [SURFACE_TAB_ID, SECOND_TAB_ID, THIRD_TAB_ID, created] - } - ])('places a terminal $client creates after a split tab', async (testCase) => { - const { runtime } = await headlessRuntime() - const splitRow = (await runtime.listMobileSessionTabs(WORKTREE)).tabs.find( - (row) => row.type === 'terminal' && row.parentTabId === SURFACE_TAB_ID - ) - - const created = await runtime.createMobileSessionTerminal(WORKTREE, { - afterTabId: splitRow?.id, - clientNavigationId: 'phone', - supportsSplitGroupPlacement: testCase.supportsSplitGroupPlacement - }) - - const listed = await runtime.listMobileSessionTabs(WORKTREE) - const order = testCase.order(created.tab.parentTabId) - expect(tabStrip(listed)).toEqual([order]) - expect(orderOf(listed.tabs)).toEqual(order) - }) - - it("places a terminal created after a chat main holds in the chat's group, after it", async () => { - const { runtime } = await headlessRuntime() - await runtime.publishStructuredAgentSessionTab({ - workspaceId: TEST_WORKTREE_ID, - sessionId: 's1', - agent: 'claude', - activate: true - }) - await runtime.moveMobileSessionTab(WORKTREE, { - kind: 'split', - tabId: CHAT, - targetGroupId: SAVED_GROUP_ID, - splitDirection: 'right' - }) - - const created = await runtime.createMobileSessionTerminal(WORKTREE, { - afterTabId: CHAT, - clientNavigationId: 'phone', - supportsSplitGroupPlacement: true - }) - - expect(tabStrip(await runtime.listMobileSessionTabs(WORKTREE))).toEqual([ - [SURFACE_TAB_ID, SECOND_TAB_ID, THIRD_TAB_ID], - [CHAT, created.tab.parentTabId] - ]) - }) -}) diff --git a/src/main/runtime/session-tabs/session-tabs-windowed-main-change.test.ts b/src/main/runtime/session-tabs/session-tabs-windowed-main-change.test.ts deleted file mode 100644 index 50e01825b8f..00000000000 --- a/src/main/runtime/session-tabs/session-tabs-windowed-main-change.test.ts +++ /dev/null @@ -1,137 +0,0 @@ -// Main layout changes must reach subscribed phones even without another attached-window publication. -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import type { - RuntimeMobileSessionTabsResult, - RuntimeMobileSessionTabsSnapshot -} from '../../../shared/remote-runtime/session-graph/runtime-session-contracts' -import { - HEADLESS_LEAF_ID, - HEADLESS_SECOND_LEAF_ID, - TEST_WORKTREE_ID -} from '../orca-runtime-tests/orca-runtime-test-fixtures.spec' -import { - SURFACE_TAB_ID, - surfaceRuntime -} from '../terminal/surface/terminal-surface-replies.test-fixture' -import { - MOVED_STRIP, - SECOND_TAB_ID, - moveAndSplitTabs, - tabStrip, - threeTabSurfaceRuntime -} from './session-tabs-layout-moves.test-fixture' - -vi.mock('../../../shared/workspace-layout/layout-owner-switch', () => ({ - ORCA_LAYOUT_OWNER_IS_MAIN: true -})) - -type Runtime = ReturnType['runtime'] - -const rowOf = (leafId: string): string => `${SURFACE_TAB_ID}::${leafId}` - -/** A workspace on an SSH host whose layout main has not loaded: the window's rows stand. */ -const UNLOADED_SSH_ROWS: RuntimeMobileSessionTabsSnapshot = { - worktree: 'repo-ssh::/srv/remote', - publicationEpoch: 'renderer', - snapshotVersion: 1, - activeGroupId: 'ssh-group', - activeTabId: 'ssh-tab::ssh-leaf', - activeTabType: 'terminal', - tabGroups: [{ id: 'ssh-group', activeTabId: 'ssh-tab', tabOrder: ['ssh-tab'] }], - tabs: [ - { - type: 'terminal', - id: 'ssh-tab::ssh-leaf', - title: 'remote shell', - parentTabId: 'ssh-tab', - leafId: 'ssh-leaf', - isActive: true - } - ] -} - -/** The window's one publication: both panes of the saved split, under their saved title. */ -function windowPublication(): RuntimeMobileSessionTabsSnapshot { - return { - worktree: TEST_WORKTREE_ID, - publicationEpoch: 'renderer', - snapshotVersion: 1, - activeGroupId: null, - activeTabId: rowOf(HEADLESS_LEAF_ID), - activeTabType: 'terminal', - tabs: [HEADLESS_LEAF_ID, HEADLESS_SECOND_LEAF_ID].map((leafId) => ({ - type: 'terminal' as const, - id: rowOf(leafId), - title: 'Persisted Terminal', - parentTabId: SURFACE_TAB_ID, - leafId, - isActive: leafId === HEADLESS_LEAF_ID - })) - } -} - -/** Attaches a window that publishes once, then records every push a phone gets. */ -async function windowedPhone(runtime: Runtime): Promise { - runtime.attachWindow(1) - await runtime.syncWindowGraph(1, { - tabs: [], - leaves: [], - mobileSessionTabs: [windowPublication(), UNLOADED_SSH_ROWS] - }) - await vi.runAllTimersAsync() - const seen: RuntimeMobileSessionTabsResult[] = [] - runtime.onMobileSessionTabsChanged((snapshot) => { - seen.push(snapshot) - }) - return seen -} - -const listed = (runtime: Runtime) => runtime.listMobileSessionTabs(`id:${TEST_WORKTREE_ID}`) -const parentTabsOf = ( - rows: Pick | undefined -): string[] => [ - ...new Set((rows?.tabs ?? []).map((tab) => (tab.type === 'terminal' ? tab.parentTabId : tab.id))) -] - -/** The terminal tabs main's layout holds for the workspace, in saved order. */ -function layoutTabIds(store: ReturnType['store']): string[] { - return (store.getSession().tabsByWorktree[TEST_WORKTREE_ID] ?? []).map((tab) => tab.id) -} - -describe('session.tabs on a windowed server follow main without a window publish (switch on)', () => { - beforeEach(() => { - vi.useFakeTimers() - }) - afterEach(() => { - vi.useRealTimers() - }) - - it('a CLI create reaches the pushed and listed rows', async () => { - const { runtime, store } = surfaceRuntime() - const seen = await windowedPhone(runtime) - - await runtime.applyLayoutCommand({ - type: 'createTerminalTab', - workspace: TEST_WORKTREE_ID, - tabId: SECOND_TAB_ID - }) - await vi.runAllTimersAsync() - - expect(layoutTabIds(store)).toEqual([SURFACE_TAB_ID, SECOND_TAB_ID]) - expect(parentTabsOf(seen.at(-1))).toEqual([SURFACE_TAB_ID, SECOND_TAB_ID]) - expect(parentTabsOf(await listed(runtime))).toEqual([SURFACE_TAB_ID, SECOND_TAB_ID]) - }) - - it("after the window closes, main's later moves reach the phone, as no-window rows", async () => { - const { runtime } = threeTabSurfaceRuntime() - const seen = await windowedPhone(runtime) - runtime.markGraphUnavailable(1) - await vi.runAllTimersAsync() - - await moveAndSplitTabs(runtime) - await vi.runAllTimersAsync() - - expect(tabStrip(seen.at(-1))).toEqual(MOVED_STRIP) - expect(tabStrip(await listed(runtime))).toEqual(MOVED_STRIP) - }) -}) diff --git a/src/main/runtime/session-tabs/session-title-publisher.test.ts b/src/main/runtime/session-tabs/session-title-publisher.test.ts deleted file mode 100644 index aeecd4af804..00000000000 --- a/src/main/runtime/session-tabs/session-title-publisher.test.ts +++ /dev/null @@ -1,118 +0,0 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import type { RuntimeMobileSessionTabsResult } from '../../../shared/remote-runtime/session-graph/runtime-session-contracts' -import type { RuntimeMobileSessionTerminalTab } from '../../../shared/remote-runtime/session-graph/runtime-mobile-session-tab-contracts' - -const layoutOwner = vi.hoisted(() => ({ isMain: false })) -vi.mock('../../../shared/workspace-layout/layout-owner-switch', () => ({ - get ORCA_LAYOUT_OWNER_IS_MAIN() { - return layoutOwner.isMain - } -})) - -// Preserve side-effect order: mocks, lifecycle, fixtures. -await import('../orca-runtime-tests/runtime-test-module-registration.spec') -const { electronMocks } = await import('../orca-runtime-test-mocks/setup.spec') -const { OrcaRuntimeService } = await import('../orca-runtime') -await import('../orca-runtime-tests/orca-runtime-test-lifecycle.spec') -const { - HEADLESS_LEAF_ID, - TEST_WORKTREE_ID, - makeHeadlessTerminalLayout, - makeRuntimeStoreWithWorkspaceSession, - makeWorkspaceSessionWithHeadlessTerminal -} = await import('../orca-runtime-tests/orca-runtime-test-fixtures.spec') - -const name = { agent: 'codex' as const, sessionId: 'session-1', title: 'Saved task' } -const surface: RuntimeMobileSessionTerminalTab = { - type: 'terminal', - id: `host-tab::${HEADLESS_LEAF_ID}`, - parentTabId: 'host-tab', - leafId: HEADLESS_LEAF_ID, - ptyId: 'serve-retained-pty', - title: 'Codex', - aiVaultTitle: name, - resolvesSessionTitle: true, - isActive: true -} - -describe.each([false, true])('session title publisher, main layout=%s', (isMain) => { - beforeEach(() => { - layoutOwner.isMain = isMain - vi.useFakeTimers() - electronMocks.BrowserWindow.fromId.mockReturnValue({ isDestroyed: () => false }) - }) - afterEach(() => vi.useRealTimers()) - - async function host() { - const session = makeWorkspaceSessionWithHeadlessTerminal() - const saved = session.tabsByWorktree[TEST_WORKTREE_ID][0] - saved.ptyId = surface.ptyId! - saved.aiVaultTitle = name - session.terminalLayoutsByTabId['host-tab'] = makeHeadlessTerminalLayout({ - [HEADLESS_LEAF_ID]: surface.ptyId! - }) - const { runtimeStore } = makeRuntimeStoreWithWorkspaceSession(session) - const runtime = new OrcaRuntimeService(runtimeStore) - await runtime.syncWindowGraph(0, { tabs: [], leaves: [] }) - runtime.registerPty(surface.ptyId!, TEST_WORKTREE_ID, null, { - tabId: surface.parentTabId, - leafId: surface.leafId - }) - runtime.attachWindow(1) - const events: RuntimeMobileSessionTabsResult[] = [] - const unsubscribe = runtime.onMobileSessionTabsChanged((frame) => events.push(frame)) - async function publish( - windowId: number, - version: number, - rows: RuntimeMobileSessionTerminalTab[] = [surface], - includeWorktree = true, - generation = `renderer-${windowId}` - ) { - await runtime.syncWindowGraph(windowId, { - rendererGeneration: generation, - tabs: [], - leaves: [], - mobileSessionTabs: includeWorktree - ? [ - { - worktree: TEST_WORKTREE_ID, - publicationEpoch: generation, - snapshotVersion: version, - activeGroupId: null, - activeTabId: rows[0]?.id ?? null, - activeTabType: rows.length ? 'terminal' : null, - tabs: rows - } - ] - : [] - }) - } - async function latest() { - await vi.advanceTimersByTimeAsync(100) - const frame = events.findLast((event) => event.worktree === TEST_WORKTREE_ID)! - expect(frame).toBeDefined() - expect(frame.tabs).toEqual([expect.objectContaining({ id: surface.id })]) - return frame - } - return { runtime, events, unsubscribe, publish, latest } - } - - it('revokes authoritative null and publishes a newer terminal-only frame when its window closes', async () => { - const h = await host() - try { - await h.publish(1, 1, [{ ...surface, aiVaultTitle: null }]) - const before = await h.latest() - expect(before.tabs[0]).toMatchObject({ resolvesSessionTitle: true, aiVaultTitle: null }) - h.events.length = 0 - // Window destruction precedes main's close callback. - electronMocks.BrowserWindow.fromId.mockReturnValue(null) - h.runtime.markGraphUnavailable(1) - const after = await h.latest() - expect(after.snapshotVersion).toBeGreaterThan(before.snapshotVersion) - expect(after.tabs[0]).not.toHaveProperty('resolvesSessionTitle') - expect(after.tabs[0]).not.toHaveProperty('aiVaultTitle', null) - } finally { - h.unsubscribe() - } - }) -}) diff --git a/src/main/runtime/session-tabs/terminal-close-observed-exit-test-fixture.ts b/src/main/runtime/session-tabs/terminal-close-observed-exit-test-fixture.ts deleted file mode 100644 index 44f97593342..00000000000 --- a/src/main/runtime/session-tabs/terminal-close-observed-exit-test-fixture.ts +++ /dev/null @@ -1,157 +0,0 @@ -import { rmSync } from 'node:fs' -import { DaemonPtyRouter } from '../../daemon/providers/routing/daemon-pty-router' -import { - createMockSubprocess, - startDaemonAdapterHarness -} from '../../daemon/providers/adapter/testing/daemon-pty-adapter-test-harness' -import { startLateExitHarness } from '../../ipc/pty/daemon-late-exit-test-fixture' -import { bindProviderListeners } from '../../ipc/pty/provider/bind-listeners' -import { finishPtyShutdown } from '../../ipc/pty/provider/liveness' -import { setLocalPtyProvider } from '../../ipc/pty/provider/registry' -import { shutdownProviderAndDetectExit } from '../../ipc/pty/provider/shutdown-detect' -import type { PtyRuntimeControllerDeps } from '../../ipc/pty/runtime/controller-deps' -import { - killPtyFromRuntimeController, - stopAndWaitPtyFromRuntimeController -} from '../../ipc/pty/runtime/kill' -import { OrcaRuntimeService } from '../orca-runtime' - -export type ObservedExitSocketScenario = - | 'healthy' - | 'unrelated-endpoint-gone' - | 'physical-exit-observed' - -export async function runObservedExitSocketScenario(scenario: ObservedExitSocketScenario) { - const harness = await startLateExitHarness() - const legacy = await startDaemonAdapterHarness(() => createMockSubprocess()) - const router = new DaemonPtyRouter({ current: harness.adapter, legacy: [legacy.adapter] }) - let fallbackKills = 0 - try { - await router.discoverLegacySessions() - setLocalPtyProvider(router) - bindProviderListeners(harness.session) - const ports = { - runtime: harness.runtime, - getLocalPtyProviderStartupPromise: () => undefined, - shutdownProviderAndDetectExit, - rememberSyntheticKillExit: harness.session.rememberSyntheticKillExit, - sendPtyExitToRenderer: harness.session.sendPtyExitToRenderer, - finishPtyShutdown, - retiredRejectedPtyIds: new Map() - } - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: stop/kill read only these controller ports and optional store; spawn ports are unused. - const deps = ports as unknown as PtyRuntimeControllerDeps - harness.runtime.setPtyController({ - write: () => true, - getForegroundProcess: async () => null, - kill: (id) => { - fallbackKills++ - return killPtyFromRuntimeController(deps, id) - }, - stopAndWait: (id) => - stopAndWaitPtyFromRuntimeController(deps, id, { deadlineMs: Date.now() + 1_500 }) - }) - const list = await harness.runtime.listTerminals() - const terminal = list.terminals.find((entry) => entry.ptyId === harness.id) - if (!terminal) { - throw new Error('Fixture terminal missing') - } - if (scenario !== 'healthy') { - await legacy.server.shutdown() - } - if (scenario !== 'physical-exit-observed') { - harness.pauseStream() - } - const close = await harness.runtime.closeTerminal(terminal.handle) - const targetInventory = await harness.adapter.listProcesses() - const targetProbe = await harness.adapter.probePtyLiveness(harness.id) - const routerProbe = await router.probePtyLiveness(harness.id) - const beforeStreamResume = await harness.capture() - harness.resumeStream() - await harness.waitForExit() - const settled = await harness.capture() - return { - scenario, - close: { - ptyKilled: close.ptyKilled, - ptyStopVerdict: close.ptyStopVerdict ?? null - }, - fallbackKills, - targetInventoryCount: targetInventory.length, - targetProbe, - routerProbe, - beforeStreamResume, - settled - } - } finally { - router.disposeRouterOnly() - await harness.dispose() - legacy.adapter.dispose() - await legacy.server.shutdown() - rmSync(legacy.dir, { recursive: true, force: true }) - } -} - -const CONTROL_PTY_ID = 'repo::/tmp/observed-exit-control@@pty' -const WORKTREE_ID = 'repo::/tmp/observed-exit-control' -const FIRST_INCARNATION = '10000000-0000-4000-8000-000000000001' -const NEXT_INCARNATION = '10000000-0000-4000-8000-000000000002' -const BINDING = { - tabId: 'control-tab', - leafId: '10000000-0000-4000-8000-000000000004' -} - -class ObservedExitRuntime extends OrcaRuntimeService { - async closeControl(): Promise { - return (await this.stopExplicitlyClosedTabPtys([CONTROL_PTY_ID], CONTROL_PTY_ID)).stopped - } -} - -export type ObservedExitControl = - | 'same-incarnation' - | 'replacement' - | 'unverified' - | 'legacy-unstamped' - | 'throw-after-exit' - -export async function runObservedExitControl(control: ObservedExitControl) { - const runtime = new ObservedExitRuntime() - const original = control === 'legacy-unstamped' ? undefined : FIRST_INCARNATION - let fallbackKills = 0 - runtime.registerPty(CONTROL_PTY_ID, WORKTREE_ID, null, { - ...BINDING, - ...(original ? { incarnationId: original } : {}) - }) - runtime.setPtyController({ - write: () => true, - kill: () => { - fallbackKills++ - return true - }, - getForegroundProcess: async () => null, - stopAndWait: async () => { - runtime.onPtyExit(CONTROL_PTY_ID, control === 'unverified' ? -1 : 0, original) - if (control === 'replacement') { - runtime.registerPty(CONTROL_PTY_ID, WORKTREE_ID, null, { - ...BINDING, - incarnationId: NEXT_INCARNATION - }) - } - if (control === 'throw-after-exit') { - throw new Error('unverified transport failure') - } - return false - } - }) - try { - const stopped = await runtime.closeControl() - return { - scenario: control, - stopped, - fallbackKills, - verdict: runtime.getPtyLivenessVerdict(CONTROL_PTY_ID) - } - } finally { - runtime.onPtyExit(CONTROL_PTY_ID, 0, control === 'replacement' ? NEXT_INCARNATION : original) - } -} diff --git a/src/main/runtime/session-tabs/terminal-close-observed-exit.test.ts b/src/main/runtime/session-tabs/terminal-close-observed-exit.test.ts deleted file mode 100644 index 364493c095e..00000000000 --- a/src/main/runtime/session-tabs/terminal-close-observed-exit.test.ts +++ /dev/null @@ -1,44 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { - runObservedExitControl, - runObservedExitSocketScenario -} from './terminal-close-observed-exit-test-fixture' - -describe('closing a terminal after observing its physical exit', () => { - it('preserves the physical cause when an unrelated daemon prevents aggregate verification', async () => { - const result = await runObservedExitSocketScenario('physical-exit-observed') - expect(result.close).toEqual({ ptyKilled: true, ptyStopVerdict: null }) - expect(result.fallbackKills).toBe(0) - expect(result.targetInventoryCount).toBe(0) - expect(result.targetProbe).toBe(false) - expect(result.routerProbe).toBeNull() - expect(result.settled).toMatchObject({ - connected: false, - exitCause: { kind: 'operator_close' }, - headlessModelRetained: false, - titleTrackerRetained: false, - liveness: 'exited', - rendererExitCount: 1, - providerExitCount: 1, - exitListenerCalls: 1 - }) - }) - - it('does not treat target absence as an earned exit before the stream delivers it', async () => { - const result = await runObservedExitSocketScenario('unrelated-endpoint-gone') - expect(result.close).toEqual({ ptyKilled: false, ptyStopVerdict: 'unverifiable' }) - expect(result.fallbackKills).toBe(1) - expect(result.targetProbe).toBe(false) - expect(result.routerProbe).toBeNull() - expect(result.beforeStreamResume.providerExitCount).toBe(0) - }) - - it.each(['replacement', 'unverified', 'legacy-unstamped', 'throw-after-exit'] as const)( - 'does not reuse an exit for %s', - async (control) => { - const result = await runObservedExitControl(control) - expect(result.stopped).toBe(false) - expect(result.fallbackKills).toBe(1) - } - ) -}) diff --git a/src/main/runtime/session-tabs/acknowledged-terminal-tab-retirement-fixture.ts b/src/main/runtime/session-tabs/terminal-retirement/acknowledged-terminal-tab-retirement-fixture.ts similarity index 85% rename from src/main/runtime/session-tabs/acknowledged-terminal-tab-retirement-fixture.ts rename to src/main/runtime/session-tabs/terminal-retirement/acknowledged-terminal-tab-retirement-fixture.ts index 9de92f142d3..8a2ea5cfe76 100644 --- a/src/main/runtime/session-tabs/acknowledged-terminal-tab-retirement-fixture.ts +++ b/src/main/runtime/session-tabs/terminal-retirement/acknowledged-terminal-tab-retirement-fixture.ts @@ -2,17 +2,17 @@ import { mkdtempSync, rmSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' import { vi } from 'vitest' -import { getDefaultWorkspaceSession } from '../../../shared/orca-profiles/constants' -import type { PersistedState } from '../../../shared/orca-profiles/persisted-state-types' -import type { RuntimeSyncWindowGraph } from '../../../shared/remote-runtime/session-graph/runtime-session-contracts' -import { closeTerminalTabInWorkspaceSession } from '../../../shared/workspace-session/workspace-session-terminal-tab-close' -import { ProfileStateSqliteAuthority } from '../../persistence/profile-state/profile-state-sqlite-authority' -import { DelayedAuthority } from '../../persistence/loading-store/profile-writing/profile-state-delayed-authority-fixture' -import { Store } from '../../persistence/loading-store/store' -import { OrcaRuntimeService } from '../orca-runtime' -import { buildHeadlessMobileSessionTerminalTabs } from '../terminal/surface/mobile-session-terminal-projection' -import { setRuntimeDesktopSurface } from '../construction/runtime-desktop-surface' -import { advanceTerminalTopologyRevision } from '../../persistence/terminal-topology/pane-ownership/terminal-topology-membership' +import { getDefaultWorkspaceSession } from '../../../../shared/orca-profiles/constants' +import type { PersistedState } from '../../../../shared/orca-profiles/persisted-state-types' +import type { RuntimeSyncWindowGraph } from '../../../../shared/remote-runtime/session-graph/runtime-session-contracts' +import { closeTerminalTabInWorkspaceSession } from '../../../../shared/workspace-session/workspace-session-terminal-tab-close' +import { ProfileStateSqliteAuthority } from '../../../persistence/profile-state/profile-state-sqlite-authority' +import { DelayedAuthority } from '../../../persistence/loading-store/profile-writing/profile-state-delayed-authority-fixture' +import { Store } from '../../../persistence/loading-store/store' +import { OrcaRuntimeService } from '../../orca-runtime' +import { buildHeadlessMobileSessionTerminalTabs } from '../../terminal/surface/mobile-session-terminal-projection' +import { setRuntimeDesktopSurface } from '../../construction/runtime-desktop-surface' +import { advanceTerminalTopologyRevision } from '../../../persistence/terminal-topology/pane-ownership/terminal-topology-membership' export const ACK_WORKTREE = 'repo1::/tmp/worktree' export const ACK_TAB = '11111111-1111-4111-8111-111111111111' diff --git a/src/main/runtime/session-tabs/acknowledged-terminal-tab-retirement.test.ts b/src/main/runtime/session-tabs/terminal-retirement/acknowledged-terminal-tab-retirement.test.ts similarity index 92% rename from src/main/runtime/session-tabs/acknowledged-terminal-tab-retirement.test.ts rename to src/main/runtime/session-tabs/terminal-retirement/acknowledged-terminal-tab-retirement.test.ts index 2e6b89e3cc7..5827313048a 100644 --- a/src/main/runtime/session-tabs/acknowledged-terminal-tab-retirement.test.ts +++ b/src/main/runtime/session-tabs/terminal-retirement/acknowledged-terminal-tab-retirement.test.ts @@ -5,8 +5,8 @@ import { ACK_WORKTREE, createAcknowledgedTabRetirementFixture } from './acknowledged-terminal-tab-retirement-fixture' -import { advanceTerminalTopologyRevision } from '../../persistence/terminal-topology/pane-ownership/terminal-topology-membership' -import { ORCA_LAYOUT_OWNER_IS_MAIN } from '../../../shared/workspace-layout/layout-owner-switch' +import { advanceTerminalTopologyRevision } from '../../../persistence/terminal-topology/pane-ownership/terminal-topology-membership' +import { ORCA_LAYOUT_OWNER_IS_MAIN } from '../../../../shared/workspace-layout/layout-owner-switch' // Main-owned closes have no window ack; their counterparts live in acknowledged-terminal-tab-retirement-main-close.test.ts. const itSwitchOff = it.skipIf(ORCA_LAYOUT_OWNER_IS_MAIN) diff --git a/src/main/runtime/session-tabs/explicit-terminal-close-pty-stops.ts b/src/main/runtime/session-tabs/terminal-retirement/explicit-terminal-close-pty-stops.ts similarity index 86% rename from src/main/runtime/session-tabs/explicit-terminal-close-pty-stops.ts rename to src/main/runtime/session-tabs/terminal-retirement/explicit-terminal-close-pty-stops.ts index 53eb22738e0..6803122ab3a 100644 --- a/src/main/runtime/session-tabs/explicit-terminal-close-pty-stops.ts +++ b/src/main/runtime/session-tabs/terminal-retirement/explicit-terminal-close-pty-stops.ts @@ -1,8 +1,8 @@ -import { IMMEDIATE_KILL_REPLY_BUDGET_MS } from '../../daemon/sessions/immediate-kill-reply-budget' -import { OrcaRuntimeWithFocusTerminal } from '../terminal/focus/focus-terminal' +import { IMMEDIATE_KILL_REPLY_BUDGET_MS } from '../../../daemon/sessions/immediate-kill-reply-budget' +import { OrcaRuntimeWithFocusTerminal } from '../../terminal/focus/focus-terminal' -import { SSH_PROVIDER_UNREGISTERED_REASON } from '../../../shared/terminal/pty/lifecycle/pty-liveness-verdict' -import { errorMessage } from '../../../shared/errors/error-message' +import { SSH_PROVIDER_UNREGISTERED_REASON } from '../../../../shared/terminal/pty/lifecycle/pty-liveness-verdict' +import { errorMessage } from '../../../../shared/errors/error-message' // Include immediate-kill and follow-up inventory budgets; agent exit hooks can delay verification. const EXPLICIT_TERMINAL_CLOSE_STOP_TIMEOUT_MS = IMMEDIATE_KILL_REPLY_BUDGET_MS + 2_000 diff --git a/src/main/runtime/session-tabs/explicit-terminal-close-stops.ts b/src/main/runtime/session-tabs/terminal-retirement/explicit-terminal-close-stops.ts similarity index 93% rename from src/main/runtime/session-tabs/explicit-terminal-close-stops.ts rename to src/main/runtime/session-tabs/terminal-retirement/explicit-terminal-close-stops.ts index cbd640d64ef..3f29a519e0a 100644 --- a/src/main/runtime/session-tabs/explicit-terminal-close-stops.ts +++ b/src/main/runtime/session-tabs/terminal-retirement/explicit-terminal-close-stops.ts @@ -1,12 +1,12 @@ -import type { WorktreePtyHostFence } from '../workspaces/removal/worktree-pty-host-fence' -import type { RuntimeTerminalClose } from '../../../shared/terminal/runtime/runtime-terminal-contracts' -import type { RuntimePtyTabCloseAuthority } from '../terminal/records/runtime-terminal-state-records' -import { parsePaneKey } from '../../../shared/workspace-layout/stable-pane-id' -import type { ResolvedWorktree } from '../workspaces/catalog/runtime-worktree-path-identity' -import { ORCA_LAYOUT_OWNER_IS_MAIN } from '../../../shared/workspace-layout/layout-owner-switch' -import type { LayoutApplyReply } from '../../../shared/workspace-layout/workspace-layout-command-types' -import type { WindowLayoutCommand } from '../terminal/layout/runtime-layout-apply' -import { closeMainOwnedPaneByHandle } from './main-handle-close' +import type { WorktreePtyHostFence } from '../../workspaces/removal/worktree-pty-host-fence' +import type { RuntimeTerminalClose } from '../../../../shared/terminal/runtime/runtime-terminal-contracts' +import type { RuntimePtyTabCloseAuthority } from '../../terminal/records/runtime-terminal-state-records' +import { parsePaneKey } from '../../../../shared/workspace-layout/stable-pane-id' +import type { ResolvedWorktree } from '../../workspaces/catalog/runtime-worktree-path-identity' +import { ORCA_LAYOUT_OWNER_IS_MAIN } from '../../../../shared/workspace-layout/layout-owner-switch' +import type { LayoutApplyReply } from '../../../../shared/workspace-layout/workspace-layout-command-types' +import type { WindowLayoutCommand } from '../../terminal/layout/runtime-layout-apply' +import { closeMainOwnedPaneByHandle } from '../layout/main-handle-close' import { NO_STOP, OrcaRuntimeWithExplicitCloseTabPtyStops, diff --git a/src/main/runtime/session-tabs/headless-terminal-tab-close.ts b/src/main/runtime/session-tabs/terminal-retirement/headless-terminal-tab-close.ts similarity index 88% rename from src/main/runtime/session-tabs/headless-terminal-tab-close.ts rename to src/main/runtime/session-tabs/terminal-retirement/headless-terminal-tab-close.ts index 2f8f341d432..b6c3d628836 100644 --- a/src/main/runtime/session-tabs/headless-terminal-tab-close.ts +++ b/src/main/runtime/session-tabs/terminal-retirement/headless-terminal-tab-close.ts @@ -1,22 +1,22 @@ -import type { RuntimeHeadlessTabProperties as HeadlessTabPropertiesMethods } from './headless-tab-properties' -import type { RuntimeHeadlessTabGroups as HeadlessTabGroupsMethods } from './headless-tab-group-moves' -import type { RuntimeHeadlessTerminalTabTitles as PersistHeadlessTerminalTitleMethods } from './headless-terminal-tab-titles' -import { OrcaRuntimeWithMainLayoutTabMoves } from './main-layout-session-tab-move' -import { ORCA_LAYOUT_OWNER_IS_MAIN } from '../../../shared/workspace-layout/layout-owner-switch' +import type { RuntimeHeadlessTabProperties as HeadlessTabPropertiesMethods } from '../layout/headless-tab-properties' +import type { RuntimeHeadlessTabGroups as HeadlessTabGroupsMethods } from '../layout/headless-tab-group-moves' +import type { RuntimeHeadlessTerminalTabTitles as PersistHeadlessTerminalTitleMethods } from '../publication/headless-terminal-tab-titles' +import { OrcaRuntimeWithMainLayoutTabMoves } from '../layout/main-layout-session-tab-move' +import { ORCA_LAYOUT_OWNER_IS_MAIN } from '../../../../shared/workspace-layout/layout-owner-switch' import type { RuntimeMobileSessionTabMove, RuntimeMobileSessionTabMoveResult, RuntimeMobileSessionTabsSnapshot, RuntimeSessionTabCloseReason -} from '../../../shared/remote-runtime/session-graph/runtime-session-contracts' -import type { RuntimeMobileSessionTerminalTab } from '../../../shared/remote-runtime/session-graph/runtime-mobile-session-tab-contracts' -import { parseAppSshPtyId } from '../../../shared/remote-runtime/ssh/ssh-pty-id' -import { retireMobileSessionTabSelection } from './mobile-session-tab-selection' -import { paneTitlesForDesktopWindow } from './desktop-pane-title-forwarding' -import { appendRetiredTerminalSurfaceProofs } from '../../../shared/workspace-layout/terminal-surfaces/terminal-retirement-proof-ledger' -import type { RuntimePtyWorktreeRecord } from '../terminal/records/runtime-terminal-state-records' -import type { TerminalPaneLayoutNode } from '../../../shared/workspace-layout/terminal-tab-types' -import type { RuntimeTerminalRename } from '../../../shared/terminal/runtime/runtime-terminal-contracts' +} from '../../../../shared/remote-runtime/session-graph/runtime-session-contracts' +import type { RuntimeMobileSessionTerminalTab } from '../../../../shared/remote-runtime/session-graph/runtime-mobile-session-tab-contracts' +import { parseAppSshPtyId } from '../../../../shared/remote-runtime/ssh/ssh-pty-id' +import { retireMobileSessionTabSelection } from '../layout/mobile-session-tab-selection' +import { paneTitlesForDesktopWindow } from '../publication/desktop-pane-title-forwarding' +import { appendRetiredTerminalSurfaceProofs } from '../../../../shared/workspace-layout/terminal-surfaces/terminal-retirement-proof-ledger' +import type { RuntimePtyWorktreeRecord } from '../../terminal/records/runtime-terminal-state-records' +import type { TerminalPaneLayoutNode } from '../../../../shared/workspace-layout/terminal-tab-types' +import type { RuntimeTerminalRename } from '../../../../shared/terminal/runtime/runtime-terminal-contracts' export abstract class OrcaRuntimeWithCloseHeadlessMobileTerminalTab extends OrcaRuntimeWithMainLayoutTabMoves { protected abstract applyHeadlessTerminalPaneLayoutToSnapshot( diff --git a/src/main/runtime/session-tabs/paired-host-terminal-close.ts b/src/main/runtime/session-tabs/terminal-retirement/paired-host-terminal-close.ts similarity index 91% rename from src/main/runtime/session-tabs/paired-host-terminal-close.ts rename to src/main/runtime/session-tabs/terminal-retirement/paired-host-terminal-close.ts index cd18a06ec23..a0949e8613a 100644 --- a/src/main/runtime/session-tabs/paired-host-terminal-close.ts +++ b/src/main/runtime/session-tabs/terminal-retirement/paired-host-terminal-close.ts @@ -1,7 +1,7 @@ -import { parseRemoteRuntimePtyId } from '../../../shared/remote-runtime/remote-runtime-pty-id' -import type { RuntimeTerminalClose } from '../../../shared/terminal/runtime/runtime-terminal-contracts' -import type { WorkspaceSessionState } from '../../../shared/workspace-session/workspace-session-state-types' -import { findUnifiedTerminalTabs } from '../../../shared/workspace-session/workspace-session-terminal-tab-close' +import { parseRemoteRuntimePtyId } from '../../../../shared/remote-runtime/remote-runtime-pty-id' +import type { RuntimeTerminalClose } from '../../../../shared/terminal/runtime/runtime-terminal-contracts' +import type { WorkspaceSessionState } from '../../../../shared/workspace-session/workspace-session-state-types' +import { findUnifiedTerminalTabs } from '../../../../shared/workspace-session/workspace-session-terminal-tab-close' const PAIRED_HOST_TERMINAL_CLOSE_TIMEOUT_MS = 15_000 diff --git a/src/main/runtime/session-tabs/terminal-retirement-async-durability.test.ts b/src/main/runtime/session-tabs/terminal-retirement/terminal-retirement-async-durability.test.ts similarity index 51% rename from src/main/runtime/session-tabs/terminal-retirement-async-durability.test.ts rename to src/main/runtime/session-tabs/terminal-retirement/terminal-retirement-async-durability.test.ts index 7e0b9d27ce7..ab50bbc03e6 100644 --- a/src/main/runtime/session-tabs/terminal-retirement-async-durability.test.ts +++ b/src/main/runtime/session-tabs/terminal-retirement/terminal-retirement-async-durability.test.ts @@ -1,11 +1,6 @@ -import { afterEach, expect, it, vi } from 'vitest' -import { - ACK_INCARNATION, - ACK_LEAF, - ACK_TAB, - createAcknowledgedTabRetirementFixture -} from './acknowledged-terminal-tab-retirement-fixture' -import { ORCA_LAYOUT_OWNER_IS_MAIN } from '../../../shared/workspace-layout/layout-owner-switch' +import { afterEach, expect, it } from 'vitest' +import { createAcknowledgedTabRetirementFixture } from './acknowledged-terminal-tab-retirement-fixture' +import { ORCA_LAYOUT_OWNER_IS_MAIN } from '../../../../shared/workspace-layout/layout-owner-switch' // The window's acknowledged close; a layout-owner build closes in main without one, and the twin // of that case is in acknowledged-terminal-tab-retirement-main-close.test.ts. @@ -39,22 +34,3 @@ itSwitchOff('withholds the acknowledged close until its host retirement is durab await expect(closing).resolves.toEqual({ closed: true, retirementConfirmed: true }) expect(f.hasTab()).toBe(false) }) - -it('publishes physical-exit retirement before its durable write completes', async () => { - const f = await fixture() - await f.store.flushPendingOrThrowAsync() - const published = vi.fn() - const unsubscribe = f.runtime.onMobileSessionTabsChanged(published) - const gate = f.authority.pause() - const exiting = f.runtime.onPtyExit('pty-a', 0, ACK_INCARNATION, { providerExitObserved: true }) - await gate.started.promise - // Why: a client re-activating the exited pane in this window must already find it retired. - expect(published).toHaveBeenCalled() - gate.finish.resolve() - await exiting - expect(published).toHaveBeenCalled() - expect( - f.store.getWorkspaceSession().terminalLayoutsByTabId[ACK_TAB].ptyIdsByLeafId?.[ACK_LEAF] - ).toBeUndefined() - unsubscribe() -}) diff --git a/src/main/runtime/session-tabs/terminal-surface-retirements.ts b/src/main/runtime/session-tabs/terminal-retirement/terminal-surface-retirements.ts similarity index 87% rename from src/main/runtime/session-tabs/terminal-surface-retirements.ts rename to src/main/runtime/session-tabs/terminal-retirement/terminal-surface-retirements.ts index 74e130e2117..30adc7389c6 100644 --- a/src/main/runtime/session-tabs/terminal-surface-retirements.ts +++ b/src/main/runtime/session-tabs/terminal-retirement/terminal-surface-retirements.ts @@ -1,22 +1,22 @@ -import type { OrcaRuntimeWithBindPtyIncarnationHandle as BindPtyIncarnationHandleMethods } from '../terminal/identity/terminal-handle-bindings' -import { OrcaRuntimeWithTouchMobileSessionTabsForWorktree } from './mobile-session-membership' -import type { RetiredTerminalSurface } from '../terminal/surface/mobile-session-terminal-retirement' -import type { RuntimeMobileSessionRetiredTerminalSurface } from '../../../shared/remote-runtime/session-graph/runtime-session-contracts' +import type { OrcaRuntimeWithBindPtyIncarnationHandle as BindPtyIncarnationHandleMethods } from '../../terminal/identity/terminal-handle-bindings' +import { OrcaRuntimeWithTouchMobileSessionTabsForWorktree } from '../restoration/mobile-session-membership' +import type { RetiredTerminalSurface } from '../../terminal/surface/mobile-session-terminal-retirement' +import type { RuntimeMobileSessionRetiredTerminalSurface } from '../../../../shared/remote-runtime/session-graph/runtime-session-contracts' import { LOCAL_EXECUTION_HOST_ID, parseExecutionHostId -} from '../../../shared/execution-host/execution-host' -import { ORCA_LAYOUT_OWNER_IS_MAIN } from '../../../shared/workspace-layout/layout-owner-switch' -import { keepsExitedPane } from '../terminal/lifecycle/exited-split-pane-layout-close' -import type { ExitedSplitPaneFacts } from '../terminal/lifecycle/exited-split-pane-rule' +} from '../../../../shared/execution-host/execution-host' +import { ORCA_LAYOUT_OWNER_IS_MAIN } from '../../../../shared/workspace-layout/layout-owner-switch' +import { keepsExitedPane } from '../../terminal/lifecycle/exited-split-pane-layout-close' +import type { ExitedSplitPaneFacts } from '../../terminal/lifecycle/exited-split-pane-rule' import { forgetClosedPaneOfExit, type ClosedPaneOfExit -} from '../terminal/lifecycle/closed-pane-of-exited-pty' -import { retireTerminalSurfaceFromPersistence } from '../terminal/surface/mobile-session-terminal-persistence-retirement' -import { retireTerminalSurfacesFromSnapshot } from '../terminal/surface/mobile-session-terminal-retirement' -import { attachRetirementProofsToSnapshot } from '../terminal/surface/mobile-session-terminal-retirement-proof' -import { getRepoIdFromWorktreeId } from '../../../shared/worktree/id' +} from '../../terminal/lifecycle/closed-pane-of-exited-pty' +import { retireTerminalSurfaceFromPersistence } from '../../terminal/surface/mobile-session-terminal-persistence-retirement' +import { retireTerminalSurfacesFromSnapshot } from '../../terminal/surface/mobile-session-terminal-retirement' +import { attachRetirementProofsToSnapshot } from '../../terminal/surface/mobile-session-terminal-retirement-proof' +import { getRepoIdFromWorktreeId } from '../../../../shared/worktree/id' export abstract class OrcaRuntimeWithPersistTerminalSurfaceRetirements extends OrcaRuntimeWithTouchMobileSessionTabsForWorktree { protected abstract findHandleForPtyRecord( diff --git a/src/main/runtime/terminal/driver/terminal-driver-resources.ts b/src/main/runtime/terminal/driver/terminal-driver-resources.ts index c9522bc0313..cb8019ded2f 100644 --- a/src/main/runtime/terminal/driver/terminal-driver-resources.ts +++ b/src/main/runtime/terminal/driver/terminal-driver-resources.ts @@ -1,5 +1,5 @@ import type { RuntimeServiceCommandSurface } from '../../construction/runtime-service-command-surface' -import type { OrcaRuntimeWithCloseStructuredAgentSessionTab as ChatPresentation } from '../../session-tabs/structured-session-tab-close' +import type { OrcaRuntimeWithCloseStructuredAgentSessionTab as ChatPresentation } from '../../session-tabs/chat/structured-session-tab-close' import { remoteCliBrowserScopeWorkspaceId, resolveRemoteCliBrowserScopeSelector diff --git a/src/main/runtime/terminal/identity/preallocated-terminal-handles.ts b/src/main/runtime/terminal/identity/preallocated-terminal-handles.ts index 7bc82b5a38e..c9042887543 100644 --- a/src/main/runtime/terminal/identity/preallocated-terminal-handles.ts +++ b/src/main/runtime/terminal/identity/preallocated-terminal-handles.ts @@ -3,7 +3,7 @@ import type { OrcaRuntimeWithInvalidateAllHandlesForPty } from '../lifecycle/pty import { randomUUID } from 'node:crypto' import type { PtyIncarnationId } from '../../../../shared/terminal/pty/lifecycle/pty-incarnation' import { forgetPtySurface } from '../surface/pty-recorded-surface-topology' -import { RuntimeMobileSessionTabSubscriptions } from '../../session-tabs/mobile-session-tab-subscriptions' +import { RuntimeMobileSessionTabSubscriptions } from '../../session-tabs/publication/mobile-session-tab-subscriptions' export abstract class RuntimePreallocatedTerminalHandles extends RuntimeMobileSessionTabSubscriptions { protected abstract deliverPendingMessagesForPty(ptyId: string): void diff --git a/src/main/runtime/terminal/launch/mobile-terminal-create.ts b/src/main/runtime/terminal/launch/mobile-terminal-create.ts index abd026f63e2..e58af9509d3 100644 --- a/src/main/runtime/terminal/launch/mobile-terminal-create.ts +++ b/src/main/runtime/terminal/launch/mobile-terminal-create.ts @@ -1,4 +1,4 @@ -import type { OrcaRuntimeWithScheduleMobileSessionTabsChanged as SessionTabsPublication } from '../../session-tabs/session-tabs-change-publication' +import type { OrcaRuntimeWithScheduleMobileSessionTabsChanged as SessionTabsPublication } from '../../session-tabs/publication/session-tabs-change-publication' import { OrcaRuntimeWithFailedStartPanes } from './failed-start-pane' import type { WorktreeStartupLaunch } from '../../../../shared/worktree/creation/launch-types' import type { TuiAgent } from '../../../../shared/agent-launch/catalog/tui-agent' diff --git a/src/main/runtime/terminal/launch/mobile-terminal-owned-create.ts b/src/main/runtime/terminal/launch/mobile-terminal-owned-create.ts index 425da863f50..540a9956640 100644 --- a/src/main/runtime/terminal/launch/mobile-terminal-owned-create.ts +++ b/src/main/runtime/terminal/launch/mobile-terminal-owned-create.ts @@ -1,4 +1,4 @@ -import type { OrcaRuntimeWithScheduleMobileSessionTabsChanged as SessionTabsPublication } from '../../session-tabs/session-tabs-change-publication' +import type { OrcaRuntimeWithScheduleMobileSessionTabsChanged as SessionTabsPublication } from '../../session-tabs/publication/session-tabs-change-publication' import { OrcaRuntimeWithResolveMobileSessionTerminalCommand } from './mobile-terminal-startup' import type { TuiAgent } from '../../../../shared/agent-launch/catalog/tui-agent' import type { SleepingAgentLaunchConfig } from '../../../../shared/agent-session/lifecycle/agent-session-resume' diff --git a/src/main/runtime/terminal/launch/terminal-split.ts b/src/main/runtime/terminal/launch/terminal-split.ts index e2d8db3fbb9..7dd91ef96d9 100644 --- a/src/main/runtime/terminal/launch/terminal-split.ts +++ b/src/main/runtime/terminal/launch/terminal-split.ts @@ -1,7 +1,7 @@ import type { TerminalSplitOptions } from './terminal-split-surface' import type { SplitPaneInMainOptions, SplitPaneSource } from './terminal-split-in-main' import type { RuntimePtyWorktreeRecord } from '../records/runtime-terminal-state-records' -import { OrcaRuntimeWithStopExplicitlyClosedTabPtys } from '../../session-tabs/explicit-terminal-close-stops' +import { OrcaRuntimeWithStopExplicitlyClosedTabPtys } from '../../session-tabs/terminal-retirement/explicit-terminal-close-stops' import type { TerminalPaneSplitSource } from '../../../../shared/feature-education/feature-education-telemetry' import type { RuntimeTerminalSplit } from '../../../../shared/terminal/runtime/runtime-terminal-contracts' import { randomUUID } from 'node:crypto' diff --git a/src/main/runtime/terminal/surface/main-terminal-surfaces.ts b/src/main/runtime/terminal/surface/main-terminal-surfaces.ts index c88cc7c2e98..546836e3591 100644 --- a/src/main/runtime/terminal/surface/main-terminal-surfaces.ts +++ b/src/main/runtime/terminal/surface/main-terminal-surfaces.ts @@ -9,9 +9,9 @@ import type { RuntimeSyncWindowGraph, RuntimeMobileSessionTabsSnapshot } from '../../../../shared/remote-runtime/session-graph/runtime-session-contracts' -import { withMainSessionTabRows } from '../../session-tabs/main-session-tab-rows' -import { withMainTabOrder } from '../../session-tabs/main-session-tab-order' -import { headlessMobileSnapshotContentUnchanged } from '../../session-tabs/mobile-session-snapshot-equality' +import { withMainSessionTabRows } from '../../session-tabs/layout/main-session-tab-rows' +import { withMainTabOrder } from '../../session-tabs/layout/main-session-tab-order' +import { headlessMobileSnapshotContentUnchanged } from '../../session-tabs/publication/mobile-session-snapshot-equality' import { composeMainTerminalSurfaces, TerminalSurfaceIndex, diff --git a/src/main/runtime/terminal/surface/terminal-surface-index.ts b/src/main/runtime/terminal/surface/terminal-surface-index.ts index 25311713fbc..e437935feae 100644 --- a/src/main/runtime/terminal/surface/terminal-surface-index.ts +++ b/src/main/runtime/terminal/surface/terminal-surface-index.ts @@ -27,7 +27,7 @@ import { import { projectRuntimeSurfaces } from '../records/runtime-leaf-record-projection' import type { WorkspaceLayoutReads } from './workspace-layout-stream' import type { WorkspaceSessionState } from '../../../../shared/workspace-session/workspace-session-state-types' -import { loadChatTabLayout } from '../../agent-session/agent-session-tab-layout' +import { loadChatTabLayout } from '../../session-tabs/chat/agent-session-tab-layout' type LoadedPartition = Pick diff --git a/src/main/runtime/terminal/surface/wsl-distro-loss-exit-retention.test.ts b/src/main/runtime/terminal/surface/wsl-distro-loss-exit-retention.test.ts index 794b9b0d95b..85bdbafbf48 100644 --- a/src/main/runtime/terminal/surface/wsl-distro-loss-exit-retention.test.ts +++ b/src/main/runtime/terminal/surface/wsl-distro-loss-exit-retention.test.ts @@ -5,7 +5,7 @@ import { ACK_SECOND_LEAF, ACK_TAB, createAcknowledgedTabRetirementFixture -} from '../../session-tabs/acknowledged-terminal-tab-retirement-fixture' +} from '../../session-tabs/terminal-retirement/acknowledged-terminal-tab-retirement-fixture' const fixtures: Awaited>[] = [] afterEach(async () => { diff --git a/src/main/runtime/terminal/view/renderer-terminal-snapshot.ts b/src/main/runtime/terminal/view/renderer-terminal-snapshot.ts index f1ebe320f22..17e01563047 100644 --- a/src/main/runtime/terminal/view/renderer-terminal-snapshot.ts +++ b/src/main/runtime/terminal/view/renderer-terminal-snapshot.ts @@ -1,4 +1,4 @@ -import { OrcaRuntimeWithRestoreLivePairedRendererSessionOwnedMobileTerminals } from '../../session-tabs/renderer-session-terminal-rescue' +import { OrcaRuntimeWithRestoreLivePairedRendererSessionOwnedMobileTerminals } from '../../session-tabs/restoration/renderer-session-terminal-rescue' import type { TerminalOscLinkRange } from '../../../../shared/terminal/links/terminal-osc-link-ranges' import type { RuntimeLeafRecord } from '../records/runtime-terminal-state-records' diff --git a/src/main/runtime/terminal/wait/terminal-interactive-wait.ts b/src/main/runtime/terminal/wait/terminal-interactive-wait.ts index 20e681313d4..7f2c4a77088 100644 --- a/src/main/runtime/terminal/wait/terminal-interactive-wait.ts +++ b/src/main/runtime/terminal/wait/terminal-interactive-wait.ts @@ -13,7 +13,7 @@ import type { TerminalWaitPermissionInputs, TerminalWaitStatusEvidence } from './terminal-wait-permission' -import type { AgentLaunchScope } from '../../session-tabs/structured-session-tab-restoration' +import type { AgentLaunchScope } from '../../session-tabs/chat/structured-session-tab-restoration' import { withTimeout } from '../../../../shared/concurrency/promise-timeout-fallback' import { TERMINAL_INTERACTIVE_WAIT_PROBE_TIMEOUT_MS } from './terminal-interactive-probe-budget' import { parsePaneKey } from '../../../../shared/workspace-layout/stable-pane-id' 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 93e20b83dac..e33dfbae38f 100644 --- a/src/main/runtime/workspaces/process-listing/workspace-process-listing.ts +++ b/src/main/runtime/workspaces/process-listing/workspace-process-listing.ts @@ -23,11 +23,11 @@ import { attachRuntimeWorktreeAgentRowWaits } from './runtime-worktree-agent-row import { compareWorktreePs } from './runtime-worktree-status-projection' import type { Repo } from '../../../../shared/repository/repo-types' import { enrichMissingRepoGitRemoteIdentities } from '../../../workspaces/catalog/repo-git-remote-identity-enrichment' -import { ensureStructuredAgentSessionHost as installStructuredAgentSessionHost } from '../../agent-session/structured-agent-session-runtime' +import { ensureStructuredAgentSessionHost as installStructuredAgentSessionHost } from '../../agent-session/installation/structured-agent-session-runtime' import { createStructuredAttentionMobileDelivery, readStructuredAttentionWorkspaceLabels -} from '../../agent-session/structured-agent-session-mobile-attention' +} from '../../agent-session/lifecycle/structured-agent-session-mobile-attention' import { createStructuredAgentSessionLogger, neverThrowingStructuredAgentSessionLogger @@ -59,8 +59,8 @@ import { import { isWorkspaceNotificationMuted } from '../../push/notifications/workspace-notification-mute' import { WorkerAutoReleaseActivity } from '../../orchestration/terminal-authority/release/worker-auto-release-activity' import { nativeChatIdleStopMs } from '../../../../shared/native-chat/settings/native-chat-idle-stop' -import { prWatchWorkspaceSources } from '../../agent-session/pr-watch-workspace-sources' -import { startPRWatchRuntime } from '../../agent-session/pr-watch-runtime' +import { prWatchWorkspaceSources } from '../../agent-session/lifecycle/pr-watch-workspace-sources' +import { startPRWatchRuntime } from '../../agent-session/lifecycle/pr-watch-runtime' const DEFAULT_WORKTREE_PS_LIMIT = 200 export abstract class OrcaRuntimeWithGetWorktreePs extends RuntimeChatWorkerEvents { diff --git a/src/main/runtime/workspaces/removal/structured-session-worktree-teardown.ts b/src/main/runtime/workspaces/removal/structured-session-worktree-teardown.ts index a4b88945b72..c370ada0d7f 100644 --- a/src/main/runtime/workspaces/removal/structured-session-worktree-teardown.ts +++ b/src/main/runtime/workspaces/removal/structured-session-worktree-teardown.ts @@ -18,7 +18,7 @@ import { captureStructuredSessionSurface, retireCapturedStructuredSessionSurface, type StructuredSessionSurfaceRuntime -} from '../../agent-session/structured-agent-session-close' +} from '../../agent-session/lifecycle/structured-agent-session-close' import type { WorktreePtyHostFence } from './worktree-pty-host-fence' import { getRepoIdFromWorktreeId } from '../../../../shared/worktree/id' import type { StructuredAgentId } from '../../../../shared/agent-session/lifecycle/provider-handles/agent-session-provider-handle' diff --git a/src/main/runtime/workspaces/sleep/runtime-workspace-sleep-operations.ts b/src/main/runtime/workspaces/sleep/runtime-workspace-sleep-operations.ts index ca145979c8a..68a2172cc3d 100644 --- a/src/main/runtime/workspaces/sleep/runtime-workspace-sleep-operations.ts +++ b/src/main/runtime/workspaces/sleep/runtime-workspace-sleep-operations.ts @@ -1,4 +1,4 @@ -import { OrcaRuntimeWithRestoreStructuredAgentSessionTabsOnce } from '../../session-tabs/structured-session-tab-restoration' +import { OrcaRuntimeWithRestoreStructuredAgentSessionTabsOnce } from '../../session-tabs/chat/structured-session-tab-restoration' import type { RuntimeWorktreeTerminalSleepResult } from '../../../../shared/terminal/runtime/runtime-terminal-contracts' import type { WorkspaceSleepNotice, diff --git a/src/main/runtime/workspaces/workspace-host-notifications.ts b/src/main/runtime/workspaces/workspace-host-notifications.ts index 1ba04d49e77..78a62b530ad 100644 --- a/src/main/runtime/workspaces/workspace-host-notifications.ts +++ b/src/main/runtime/workspaces/workspace-host-notifications.ts @@ -1,7 +1,7 @@ import { getRepoRoutingConnectionId } from '../../../shared/execution-host/execution-host' -import type { OrcaRuntimeWithHydrateHeadlessMobileSessionTabsFromWorkspaceSession } from '../session-tabs/mobile-session-hydration' +import type { OrcaRuntimeWithHydrateHeadlessMobileSessionTabsFromWorkspaceSession } from '../session-tabs/restoration/mobile-session-hydration' import type { OrcaRuntimeWithBuildHeadlessMobileSessionBrowserTabs } from '../session-lifecycle/projection/build-headless-mobile-session-browser-tabs' -import type { OrcaRuntimeWithScheduleMobileSessionTabsChanged } from '../session-tabs/session-tabs-change-publication' +import type { OrcaRuntimeWithScheduleMobileSessionTabsChanged } from '../session-tabs/publication/session-tabs-change-publication' import type { RuntimeWorkspaceRepoScanRefresh } from './catalog/workspace-repo-scan-refresh' import type { SshConnectionState } from '../../../shared/remote-runtime/ssh/ssh-types' import { getPublicSshState } from '../hosts/platform-probe/public-ssh-state' diff --git a/src/main/startup/quit/main-process-quit-pending-writer.test.ts b/src/main/startup/quit/main-process-quit-pending-writer.test.ts deleted file mode 100644 index e65be0ca83e..00000000000 --- a/src/main/startup/quit/main-process-quit-pending-writer.test.ts +++ /dev/null @@ -1,212 +0,0 @@ -import { EventEmitter } from 'node:events' -import { mkdtemp, rm } from 'node:fs/promises' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { afterEach, expect, it, vi } from 'vitest' -import { - closeTestStores, - createSqliteTestStore, - readPersistedStateJson -} from '../../persistence/persistence-test-harness' -import { WILL_QUIT_TEARDOWN_DEADLINE_MS } from '../../../shared/app-lifecycle/shutdown/quit-teardown-deadline' - -const settled = () => vi.fn(async () => {}) -const idle = () => vi.fn() -const stopAgentHookServer = idle() -const stopStructuredAgentSessionRuntime = settled() -const beginSshShutdown = settled() -const killAllPty = idle() -const disconnectDaemon = settled() -const closeAllWatchers = settled() - -// Every teardown member settles except the profile store, so only the writer can hold quit. -const dependencies: Record> = { - '../../ipc/filesystem/watchers/filesystem-watcher-shutdown': { closeAllWatchers }, - '../../ipc/worktrees/creation/worktree-base-directory-watcher': { - disposeWorktreeBaseDirectoryWatchers: settled() - }, - '../../ipc/folder-repo-git-upgrade': { stopFolderRepoGitUpgradeWatch: idle() }, - '../../ipc/pty/kill-all': { killAllPty }, - '../../daemon/providers/lifecycle/daemon-provider-state': { - disconnectDaemon, - shutdownDaemon: settled() - }, - '../../ipc/ssh/ssh-shutdown-drain': { beginSshShutdown }, - '../cloud-startup/main-process-connector-startup': { desktopConnectorCloud: () => null }, - '../../agent-hooks/server/agent-hook-server': { agentHookServer: { stop: stopAgentHookServer } }, - '../../agent-hooks/wsl-relay/wsl-hook-relay-manager': { - wslHookRelayManager: { disposeAll: idle() } - }, - '../../agent-hooks/installation/managed-agent-hook-controls': { - removeManagedAgentHooksAsync: vi.fn(async () => []) - }, - '../../runtime/agent-session/structured-agent-session-runtime': { - stopStructuredAgentSessionRuntime - }, - '../../runtime/agent-session/structured-agent-session-runtime-teardown': { - setStructuredAgentSessionTeardownTrigger: idle() - }, - '../../runtime/files/watch/file-watcher-leases': { - awaitRuntimeFileWatcherUnsubscribes: settled() - }, - '../../runtime/rpc/server/runtime-metadata': { clearRuntimeMetadataIfOwned: idle() }, - '../../browser/client-hosts/lifecycle/paired-runtime-browser-client-host-runtime': { - shutdownPairedRuntimeBrowserClientHosts: settled() - }, - '../../ipc/browser/desktop-browser-bridge-wiring': { disposeDesktopBrowserBridge: idle() }, - '../../orca-profiles/cloud-session/profile-cloud-session-owner': { - flushUnsavedCloudSessions: idle() - }, - '../../browser/guest-lifecycle/manager/browser-manager': { - browserManager: { setBrowserGuestStateChangedListener: idle(), setOffscreenTabOpener: idle() } - }, - '../../browser/sessions/profiles/browser-session-registry': { browserSessionRegistry: {} }, - '../../browser/routing/local-host-partitions/local-ssh-browser-route': { - closeAllLocalSshBrowserRoutes: settled() - }, - '../../codex/history/index/codex-state-db-backfill-recovery': { - stopCodexStateDbBackfillRecoveries: settled() - }, - '../../codex/history/shared-store/codex-account-history-index': { - stopCodexAccountHistoryWork: idle() - }, - '../../git/refs/maintenance/local-repo-ref-maintenance': { - awaitPackedRefsLockRelease: settled() - }, - '../../dock/unread-badge': { setUnreadDockBadgeCount: idle() }, - '../../tray/system-tray': { destroySystemTray: idle() }, - '../../telemetry/client': { shutdownTelemetry: settled() }, - '../../observability/index': { shutdownObservability: settled() }, - '../../updater/updater-service': { isQuittingForUpdate: vi.fn(() => false) }, - '../../updater/updater-lifecycle-diagnostics': { recordUpdaterLifecycle: idle() }, - '../../macos-permissions/macos-tcc-prompt-notice': { stopTccPromptNotice: idle() }, - '../../pty/history/terminal-history-gc': { cancelHistoryGc: idle() }, - './window-all-closed-quit-policy': { shouldQuitWhenAllWindowsClosed: vi.fn(() => false) }, - '../configure-process': { isDevParentShutdownRequested: vi.fn(() => false) }, - '../../persistence/loading-store/user-data-path': { - getCanonicalUserDataPath: vi.fn(() => '/unused') - } -} - -afterEach(() => { - vi.doUnmock('electron') - vi.doUnmock('../main-process-state') - for (const moduleName of Object.keys(dependencies)) { - vi.doUnmock(moduleName) - } - vi.restoreAllMocks() - vi.useRealTimers() - vi.resetModules() -}) - -async function startQuit( - flushFinalOrThrowAsync: () => Promise, - services: Record = {}, - beforeQuit?: () => Promise -) { - disconnectDaemon.mockClear() - closeAllWatchers.mockClear() - beginSshShutdown.mockClear() - killAllPty.mockClear() - vi.resetModules() - vi.useFakeTimers() - const app = Object.assign(new EventEmitter(), { quit: vi.fn() }) - const admission = { release: vi.fn() } - const store = { - flushPendingOrThrowAsync: settled(), - flushFinalOrThrowAsync: vi.fn(flushFinalOrThrowAsync), - freezeWritesAsync: settled() - } - const profileStateAdmission: typeof admission | undefined = admission - const state = { - isQuitting: false, - watcherShutdownDone: true, - store, - profileStateAdmission, - ...services - } - vi.doMock('electron', () => ({ app })) - vi.doMock('../main-process-state', () => ({ mainProcessState: state })) - for (const [moduleName, exports] of Object.entries(dependencies)) { - vi.doMock(moduleName, () => exports) - } - vi.spyOn(console, 'warn').mockImplementation(() => {}) - const { installMainProcessQuitHandlers } = await import('./main-process-quit') - const { quitTeardownStartGate } = await import('./quit-teardown-start-gate') - quitTeardownStartGate.resetForTests() - installMainProcessQuitHandlers() - await beforeQuit?.() - app.emit('before-quit', { defaultPrevented: false }) - app.emit('will-quit', { preventDefault: vi.fn() }) - return { app, admission, store, state } -} - -it('checkpoints pane state during a held synchronous deletion, then saves later metadata before releasing ownership', async () => { - const directory = await mkdtemp(join(tmpdir(), 'orca-quit-checkpoint-')) - const { Store } = await import('../../persistence/loading-store/store') - const dataFile = join(directory, 'orca-data.json') - const profile = createSqliteTestStore(Store, { dataFile }) - const savedTab = () => JSON.parse(readPersistedStateJson(dataFile)).workspaceSession.activeTabId - await profile.flushPendingOrThrowAsync({ fullCheckpoint: true }) - const checkpointSaved = Promise.withResolvers() - const savePending = profile.flushPendingOrThrowAsync.bind(profile) - vi.spyOn(profile, 'flushPendingOrThrowAsync').mockImplementation(async (...args) => { - try { - await savePending(...args) - checkpointSaved.resolve() - } catch (error) { - checkpointSaved.reject(error) - throw error - } - }) - const final = vi.spyOn(profile, 'flushFinalOrThrowAsync') - const freeze = vi.spyOn(profile, 'freezeWritesAsync') - let release!: () => void - let captureGrid!: () => void - const grid = new Promise((resolve) => { - captureGrid = () => { - profile.getWorkspaceSession().activeTabId = 'pane-grid-before-stop' - resolve() - } - }) - const runtime = { - flushPaneGrids: () => grid, - getOffscreenBrowserBackend: () => null, - getAgentBrowserBridge: () => null, - getEmulatorBridge: () => null, - disposeSkillUploadSessions: async () => {}, - getRuntimeId: () => undefined, - closeNotificationDismissals: async () => {} - } - try { - const { admission, app } = await startQuit( - async () => {}, - { store: profile, runtime, watcherShutdownDone: false }, - async () => { - const { worktreeRemovalLifetime } = - await import('../../workspaces/removal/worktree-removal-lifetime') - release = worktreeRemovalLifetime.acquirePreparation() - } - ) - captureGrid() - await grid - await checkpointSaved.promise - expect(savedTab()).toBe('pane-grid-before-stop') - await vi.advanceTimersByTimeAsync(WILL_QUIT_TEARDOWN_DEADLINE_MS) - expect(app.quit).toHaveBeenCalledOnce() - expect(final).not.toHaveBeenCalled() - expect(freeze).not.toHaveBeenCalled() - expect(admission.release).not.toHaveBeenCalled() - expect(closeAllWatchers).not.toHaveBeenCalled() - expect(disconnectDaemon).not.toHaveBeenCalled() - profile.getWorkspaceSession().activeTabId = 'metadata-after-delete' - release() - await vi.waitFor(() => expect(admission.release).toHaveBeenCalledOnce()) - expect(savedTab()).toBe('metadata-after-delete') - expect(freeze).toHaveBeenCalledOnce() - } finally { - release?.() - await closeTestStores() - await rm(directory, { recursive: true, force: true }) - } -}) diff --git a/src/main/startup/quit/main-process-quit-update-veto.test.ts b/src/main/startup/quit/main-process-quit-update-veto.test.ts deleted file mode 100644 index e14c803a1ee..00000000000 --- a/src/main/startup/quit/main-process-quit-update-veto.test.ts +++ /dev/null @@ -1,118 +0,0 @@ -import { EventEmitter } from 'node:events' -import { afterEach, expect, it, vi } from 'vitest' - -const dependencyExports: [string, string[]][] = [ - ['../../ipc/filesystem/watchers/filesystem-watcher-shutdown', ['closeAllWatchers']], - [ - '../../ipc/worktrees/creation/worktree-base-directory-watcher', - ['disposeWorktreeBaseDirectoryWatchers'] - ], - ['../../ipc/folder-repo-git-upgrade', ['stopFolderRepoGitUpgradeWatch']], - ['../../ipc/pty/kill-all', ['killAllPty']], - [ - '../../daemon/providers/lifecycle/daemon-provider-state', - ['disconnectDaemon', 'shutdownDaemon'] - ], - ['../../ipc/ssh/ssh-shutdown-drain', ['beginSshShutdown']], - ['../../agent-hooks/server/agent-hook-server', ['agentHookServer']], - ['../../agent-hooks/wsl-relay/wsl-hook-relay-manager', ['wslHookRelayManager']], - ['../../agent-hooks/installation/managed-agent-hook-controls', ['removeManagedAgentHooksAsync']], - [ - '../../runtime/agent-session/structured-agent-session-runtime', - ['stopStructuredAgentSessionRuntime'] - ], - [ - '../../runtime/agent-session/structured-agent-session-runtime-teardown', - ['setStructuredAgentSessionTeardownTrigger'] - ], - ['../../runtime/files/watch/file-watcher-leases', ['awaitRuntimeFileWatcherUnsubscribes']], - ['../../runtime/rpc/server/runtime-metadata', ['clearRuntimeMetadataIfOwned']], - [ - '../../browser/client-hosts/lifecycle/paired-runtime-browser-client-host-runtime', - ['shutdownPairedRuntimeBrowserClientHosts'] - ], - ['../../ipc/browser/desktop-browser-bridge-wiring', ['disposeDesktopBrowserBridge']], - ['../../orca-profiles/cloud-session/profile-cloud-session-owner', ['flushUnsavedCloudSessions']], - ['../../browser/guest-lifecycle/manager/browser-manager', ['browserManager']], - ['../../browser/sessions/profiles/browser-session-registry', ['browserSessionRegistry']], - [ - '../../codex/history/index/codex-state-db-backfill-recovery', - ['stopCodexStateDbBackfillRecoveries'] - ], - ['../../codex/history/shared-store/codex-account-history-index', ['stopCodexAccountHistoryWork']], - ['../../git/refs/maintenance/local-repo-ref-maintenance', ['awaitPackedRefsLockRelease']], - ['../../workspaces/removal/worktree-background-removal', ['stopBackgroundWorktreeRemovals']], - ['./quit-teardown-deadline', ['settleTeardownWithinDeadline', 'settleWithinMs']], - ['./quit-teardown-start-gate', ['quitTeardownStartGate']], - ['../../dock/unread-badge', ['setUnreadDockBadgeCount']], - ['../../tray/system-tray', ['destroySystemTray']], - ['../../telemetry/client', ['shutdownTelemetry']], - ['../../observability/index', ['shutdownObservability']], - ['../../updater/updater-service', ['isQuittingForUpdate']], - ['../../updater/updater-lifecycle-diagnostics', ['recordUpdaterLifecycle']], - ['../../macos-permissions/macos-tcc-prompt-notice', ['stopTccPromptNotice']], - ['../../pty/history/terminal-history-gc', ['cancelHistoryGc']], - ['./window-all-closed-quit-policy', ['shouldQuitWhenAllWindowsClosed']], - ['../configure-process', ['isDevParentShutdownRequested']], - ['../../persistence/loading-store/user-data-path', ['getCanonicalUserDataPath']] -] - -it('keeps startup services live when the updater has vetoed before-quit', async () => { - vi.resetModules() - const app = new EventEmitter() - const fenceAndCloseNow = vi.fn() - const setMobileRelayPairingProvider = vi.fn() - const unsubscribeAgentAwakeStatusChanges = vi.fn() - const dispose = vi.fn() - const stop = vi.fn() - const state = { - isQuitting: false, - desktopRelayService: { fenceAndCloseNow }, - runtimeRpc: { setMobileRelayPairingProvider }, - unsubscribeAgentAwakeStatusChanges, - agentAwakeService: { dispose }, - rateLimits: { stop } - } - vi.doMock('electron', () => ({ app })) - vi.doMock('../main-process-state', () => ({ mainProcessState: state })) - for (const [moduleName, exports] of dependencyExports) { - vi.doMock(moduleName, () => Object.fromEntries(exports.map((name) => [name, vi.fn()]))) - } - const exitListenersBefore = process.listeners('exit') - const { installMainProcessQuitHandlers } = await import('./main-process-quit') - installMainProcessQuitHandlers() - - app.emit('before-quit', { defaultPrevented: true }) - - expect(state.isQuitting).toBe(false) - expect(fenceAndCloseNow).not.toHaveBeenCalled() - expect(setMobileRelayPairingProvider).not.toHaveBeenCalled() - expect(unsubscribeAgentAwakeStatusChanges).not.toHaveBeenCalled() - expect(dispose).not.toHaveBeenCalled() - expect(stop).not.toHaveBeenCalled() - expect(state.agentAwakeService).toEqual({ dispose }) - expect(state.unsubscribeAgentAwakeStatusChanges).toBe(unsubscribeAgentAwakeStatusChanges) - - app.emit('before-quit', { defaultPrevented: false }) - - expect(state.isQuitting).toBe(true) - expect(fenceAndCloseNow).toHaveBeenCalledOnce() - expect(setMobileRelayPairingProvider).toHaveBeenCalledWith(null) - expect(unsubscribeAgentAwakeStatusChanges).toHaveBeenCalledOnce() - expect(dispose).toHaveBeenCalledOnce() - expect(stop).toHaveBeenCalledOnce() - for (const listener of process.listeners('exit')) { - if (!exitListenersBefore.includes(listener)) { - process.removeListener('exit', listener) - } - } -}) - -afterEach(() => { - vi.doUnmock('electron') - vi.doUnmock('../main-process-state') - for (const [moduleName] of dependencyExports) { - vi.doUnmock(moduleName) - } - vi.resetModules() -}) diff --git a/src/main/startup/quit/main-process-quit.ts b/src/main/startup/quit/main-process-quit.ts index 63812a5ab6f..177340b251e 100644 --- a/src/main/startup/quit/main-process-quit.ts +++ b/src/main/startup/quit/main-process-quit.ts @@ -9,8 +9,8 @@ import { beginSshShutdown } from '../../ipc/ssh/ssh-shutdown-drain' import { agentHookServer } from '../../agent-hooks/server/agent-hook-server' import { wslHookRelayManager } from '../../agent-hooks/wsl-relay/wsl-hook-relay-manager' import { removeManagedAgentHooksAsync } from '../../agent-hooks/installation/managed-agent-hook-controls' -import { stopStructuredAgentSessionRuntime } from '../../runtime/agent-session/structured-agent-session-runtime' -import { setStructuredAgentSessionTeardownTrigger } from '../../runtime/agent-session/structured-agent-session-runtime-teardown' +import { stopStructuredAgentSessionRuntime } from '../../runtime/agent-session/installation/structured-agent-session-runtime' +import { setStructuredAgentSessionTeardownTrigger } from '../../runtime/agent-session/installation/structured-agent-session-runtime-teardown' import { awaitRuntimeFileWatcherUnsubscribes } from '../../runtime/files/watch/file-watcher-leases' import { clearRuntimeMetadataIfOwned } from '../../runtime/rpc/server/runtime-metadata' import { shutdownPairedRuntimeBrowserClientHosts } from '../../browser/client-hosts/lifecycle/paired-runtime-browser-client-host-runtime' diff --git a/src/main/window/attach-main-window-services.ts b/src/main/window/attach-main-window-services.ts index 79a10149f1a..fe022bcadb4 100644 --- a/src/main/window/attach-main-window-services.ts +++ b/src/main/window/attach-main-window-services.ts @@ -46,7 +46,7 @@ import { import { startFolderRepoGitUpgradeWatch } from '../ipc/folder-repo-git-upgrade' import { scheduleMainWindowAutoUpdaterSetup } from '../updater/lifecycle/main-window-updater' import { registerRuntimeWindowLifecycle } from './runtime-window-lifecycle' -import { ensureStructuredAgentSessionHostUnlessRefused } from '../runtime/agent-session/structured-agent-session-host-refusal' +import { ensureStructuredAgentSessionHostUnlessRefused } from '../runtime/agent-session/installation/structured-agent-session-host-refusal' import { getAgentSessionAttachmentStore } from '../native-chat/agent-session-attachments/agent-session-attachment-store-registry' import { registerDroppedPathPreparation } from './file-drop/dropped-path-preparation-ipc' import { isPluginFramePermissionRequest } from './security/host-frame-permission-policy' diff --git a/src/main/wsl/orcad/__tests__/wsl-orcad-midturn-stop-lane.ts b/src/main/wsl/orcad/__tests__/wsl-orcad-midturn-stop-lane.ts index 3f6bf9bd702..490889dcc4d 100644 --- a/src/main/wsl/orcad/__tests__/wsl-orcad-midturn-stop-lane.ts +++ b/src/main/wsl/orcad/__tests__/wsl-orcad-midturn-stop-lane.ts @@ -17,7 +17,7 @@ import { subscribeRemoteRuntimeTransport } from '../../../../shared/remote-runti import { latestNativeChatOrcaStopCut } from '../../../../shared/native-chat/transcript/continuation/native-chat-orca-stop-cut' import { quotePosixShell } from '../../../../shared/shell/launch/shell-argument-quoting' import type { WslHostStatus } from '../../../../shared/remote-runtime/wsl-hosts/wsl-host-types' -import { claudeSessionIdForOrcaSession } from '../../../claude/structured/claude-structured-session-id' +import { claudeSessionIdForOrcaSession } from '../../../claude/structured/lifecycle/claude-structured-session-id' import '../../../orcad/artifact-slots/orcad-artifact-materializer' import { packagedClaudeChatScenario } from '../../../orcad/testing/structured-chat/orcad-structured-chat-scenario' import { wslDistroHolderKey } from '../../discovery/wsl-distro-holder-record' diff --git a/src/main/wsl/orcad/__tests__/wsl-orcad-structured-chat-contract.ts b/src/main/wsl/orcad/__tests__/wsl-orcad-structured-chat-contract.ts index eaa78f09971..3655977b146 100644 --- a/src/main/wsl/orcad/__tests__/wsl-orcad-structured-chat-contract.ts +++ b/src/main/wsl/orcad/__tests__/wsl-orcad-structured-chat-contract.ts @@ -12,7 +12,7 @@ import { ELECTRON_REMOTE_RUNTIME_CLIENT_CAPABILITIES } from '../../../../shared/ import '../../../../shared/remote-runtime/requests/remote-runtime-request-socket' import { subscribeRemoteRuntimeTransport } from '../../../../shared/remote-runtime/requests/remote-runtime-subscription-transport' import type { RemoteRuntimeTransportSubscription } from '../../../../shared/remote-runtime/requests/remote-runtime-subscription-contract' -import { claudeSessionIdForOrcaSession } from '../../../claude/structured/claude-structured-session-id' +import { claudeSessionIdForOrcaSession } from '../../../claude/structured/lifecycle/claude-structured-session-id' import { packagedClaudeChatScenario } from '../../../orcad/testing/structured-chat/orcad-structured-chat-scenario' import { quotePosixShell } from '../../../../shared/shell/launch/shell-argument-quoting' import { wslClaudeChatScenario } from './wsl-orcad-chat-scenario' diff --git a/tests/e2e/cross-version-wire/structured-agent-session-surface-execution.ts b/tests/e2e/cross-version-wire/structured-agent-session-surface-execution.ts index 68cac7a2066..4326f2c1c96 100644 --- a/tests/e2e/cross-version-wire/structured-agent-session-surface-execution.ts +++ b/tests/e2e/cross-version-wire/structured-agent-session-surface-execution.ts @@ -1,9 +1,9 @@ -import { availableRevealWorkspace } from '../../../src/main/runtime/session-tabs/structured-workspace-authority.test-fixture' +import { availableRevealWorkspace } from '../../../src/main/runtime/session-tabs/chat/structured-workspace-authority.test-fixture' import { expect, vi } from 'vitest' import type { structuredHostStub } from './structured-agent-session-host-fixture' import { AGENT_SESSION_ITEM_DETAIL_RUNTIME_CAPABILITY } from '../../../src/shared/agent-session/capabilities/agent-session-runtime-capabilities' import type { OrcaRuntimeService } from '../../../src/main/runtime/orca-runtime' -import type { StructuredSessionSurfaceRuntime } from '../../../src/main/runtime/agent-session/structured-agent-session-close' +import type { StructuredSessionSurfaceRuntime } from '../../../src/main/runtime/agent-session/lifecycle/structured-agent-session-close' import { RuntimeSubscriptionRegistry } from '../../../src/main/runtime/client/runtime-subscription-registry' import { resetStructuredAgentSessionClosesBeforeCreateForTests } from '../../../src/main/runtime/rpc/methods/structured-sessions/creation/structured-agent-session-close-before-create' import { AGENT_SESSION_CREATE_MESSAGE_RUNTIME_CAPABILITY } from '../../../src/shared/agent-session/lifecycle/operations/agent-session-create-capabilities' diff --git a/tests/e2e/native-chat-startup-option-pickers.unit.test.ts b/tests/e2e/native-chat-startup-option-pickers.unit.test.ts deleted file mode 100644 index 582b7141b23..00000000000 --- a/tests/e2e/native-chat-startup-option-pickers.unit.test.ts +++ /dev/null @@ -1,180 +0,0 @@ -import { readTestHostJournal } from '../../src/main/native-chat/agent-session-journal/journal-observation.test-support' -// @vitest-environment happy-dom - -import { cleanup, fireEvent, render, screen } from '@testing-library/react' -import { createElement } from 'react' -import { afterEach, expect, it, vi } from 'vitest' -import { computeAgentSessionPayloadFingerprint } from '../../src/shared/agent-session/lifecycle/operations/agent-session-mutation-envelope' -import { claudeSessionIdForOrcaSession } from '../../src/main/claude/structured/claude-structured-session-id' -import { hostTestMessage } from '../../src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-host-test-data.test-fixture' -import { StructuredAgentSessionStartupAttempts } from '../../src/main/native-chat/agent-session-wire/startup/structured-agent-session-startup-attempt' -import { createScriptedClaudeRuntime } from '../../src/main/runtime/agent-session/installation/structured-claude-scripted-runtime-test-support' -import { TooltipProvider } from '../../src/renderer/src/components/ui/tooltip' -import { NativeChatSessionOptionPickers } from '../../src/renderer/src/components/native-chat/session/options/controls/NativeChatSessionOptionPickers' -import { structuredAgentSessionSeedCatalog } from '../../src/shared/agent-session/options/model-catalog/structured-agent-session-seed-catalog' -import { - applyStructuredAgentSessionOptions, - createStructuredAgentSessionOptionState -} from '../../src/shared/agent-session/options/structured-agent-session-options' -import { structuredAgentSessionOptionSnapshot } from '../../src/shared/agent-session/options/view/structured-agent-session-option-snapshot' - -vi.mock('@/i18n/i18n', () => ({ - translate: (_key: string, fallback: string, values?: Record) => - Object.entries(values ?? {}).reduce( - (text, [key, value]) => text.replaceAll(`{{${key}}}`, String(value)), - fallback - ) -})) -afterEach(() => cleanup()) - -it('picks model then effort through the menus during startup and uses both in the first reply', async () => { - const SESSION = 'picker-startup-pair' - const CALLER = { callerKey: 'picker-client' } - const claude = createScriptedClaudeRuntime([SESSION]) - const picked: Promise[] = [] - let operation = 0 - claude.behave(SESSION, { initHangs: true, sendsNoStartFrame: true }) - try { - const host = await claude.install() - await host.attach(CALLER, claude.attachParams(SESSION, null, { options: { model: 'opus' } })) - await vi.waitFor(() => expect(claude.child(SESSION).initializing).toBe(true)) - const child = claude.child(SESSION) - let replyModel = 'opus' - let replyEffort = 'high' - let firstReply: { model: string; effort: string } | undefined - child.connection.supportedModels = async () => - ['sonnet', 'opus'].map((value) => ({ - value, - displayName: value, - supportsEffort: true, - supportedEffortLevels: ['low', 'high'] - })) - child.connection.setModel = async (value) => { - replyModel = value ?? 'opus' - } - child.connection.applyFlagSettings = async (settings) => { - if (typeof settings.effortLevel === 'string') { - replyEffort = settings.effortLevel - } - } - child.connection.getSettings = async () => ({ effective: { effortLevel: replyEffort } }) - child.connection.send = async (_message, beforeDispatch) => { - await beforeDispatch?.() - child.calls.push('send') - firstReply = { model: replyModel, effort: replyEffort } - child.handlers.onMessage?.({ - type: 'assistant', - session_id: claudeSessionIdForOrcaSession(SESSION), - uuid: 'first-reply', - message: { - role: 'assistant', - model: replyModel, - content: [{ type: 'text', text: firstReply.effort }] - } - }) - } - // Let delivery wake before the callers waiting on the same ready child resume. - const readiness = StructuredAgentSessionStartupAttempts.prototype.readiness - const delayed = vi - .spyOn(StructuredAgentSessionStartupAttempts.prototype, 'readiness') - .mockImplementation(function ( - this: StructuredAgentSessionStartupAttempts, - sessionId, - identity - ) { - const selected = readiness.call(this, sessionId, identity) - return selected - ? { - wait: async (budget) => { - const outcome = await selected.wait(budget) - await new Promise((resolve) => setTimeout(resolve, 0)) - return outcome - } - } - : null - }) - const envelope = (method: string, fields: Record) => ({ - sessionId: SESSION, - clientOperationId: `${Date.now()}-${(++operation).toString(16).padStart(32, '0')}`, - expectedRuntimeFence: host.deps.store.getRecord(SESSION)?.lease.runtimeFence ?? 0, - payloadFingerprint: computeAgentSessionPayloadFingerprint({ - method, - sessionId: SESSION, - fields - }) - }) - const setOption = (key: string, value: string | boolean) => { - if (typeof value !== 'string') { - throw new Error('This flow picks select options.') - } - const write = host - .setOption(CALLER, { - envelope: envelope('agentSession.setOption', { key, value }), - key, - value - }) - .then((result) => { - expect(result).toMatchObject({ ok: true }) - return { snapshot: [] } - }) - picked.push(write) - return write - } - const seed = structuredAgentSessionSeedCatalog('claude') - if (!seed) { - throw new Error('Claude options are not registered.') - } - const snapshot = structuredAgentSessionOptionSnapshot( - applyStructuredAgentSessionOptions(createStructuredAgentSessionOptionState('claude'), seed, { - models: ['opus', 'sonnet'].map((id) => ({ - id, - label: id, - isDefault: id === 'opus', - efforts: [ - { value: 'low', label: 'Low' }, - { value: 'high', label: 'High' } - ] - })), - current: { model: 'opus', effort: 'high' } - }) - ) - render( - createElement( - TooltipProvider, - null, - createElement(NativeChatSessionOptionPickers, { - surface: { - getSnapshot: () => snapshot, - setOption, - invokeAction: async () => ({ snapshot }), - subscribe: () => () => {} - }, - snapshot, - isWorking: false - }) - ) - ) - fireEvent.click(screen.getByRole('button', { name: /^Model opus\b/ })) - fireEvent.click(await screen.findByRole('option', { name: 'sonnet' })) - fireEvent.click(await screen.findByRole('radio', { name: 'Low' })) - const body = hostTestMessage('reply using these choices') - await expect( - host.send(CALLER, { envelope: envelope('agentSession.send', { body }), body }) - ).resolves.toMatchObject({ ok: true }) - child.answerInit() - await Promise.all(picked) - await vi.waitFor(async () => { - const reply = (await readTestHostJournal(host, SESSION)).items.find( - (item) => item.body.kind === 'message' && item.body.role === 'assistant' - ) - expect(reply?.body).toMatchObject({ - blocks: [{ type: 'text', text: 'low' }] - }) - }) - expect(firstReply).toEqual({ model: 'sonnet', effort: 'low' }) - delayed.mockRestore() - } finally { - await claude.dispose() - await Promise.allSettled(picked) - } -}) diff --git a/tests/e2e/session-tabs/mobile-session-active-publication.unit.test.ts b/tests/e2e/session-tabs/mobile-session-active-publication.unit.test.ts deleted file mode 100644 index e69918212db..00000000000 --- a/tests/e2e/session-tabs/mobile-session-active-publication.unit.test.ts +++ /dev/null @@ -1,128 +0,0 @@ -import '../../../src/main/runtime/orca-runtime-tests/runtime-test-module-registration.spec' - -import { afterEach, describe, expect, it, vi } from 'vitest' -import type { OrcaRuntimeService } from '../../../src/main/runtime/orca-runtime' -import { TEST_WORKTREE_ID as WT } from '../../../src/main/runtime/orca-runtime-tests/orca-runtime-test-fixtures.spec' -import { createRuntimeFixture } from './active-tab-publication.test-fixture' -import type { - RuntimeMobileSessionTabsResult, - RuntimeMobileSessionTabsSnapshot -} from '../../../src/shared/remote-runtime/session-graph/runtime-session-contracts' -import { buildMobileSessionTabSnapshots } from '../../../src/renderer/src/runtime/sync-runtime-graph/mobile-session-snapshots' -import { makeState } from '../../../src/renderer/src/runtime/sync-runtime-graph/testing/sync-runtime-graph-test-harness' - -import '../../../src/main/runtime/session-tabs/main-session-tab-rows' - -const A = 'agent-session:chat-a' -const B = 'agent-session:chat-b' -const C = 'agent-session:chat-c' - -afterEach(() => { - vi.useRealTimers() -}) - -function createRuntime() { - return createRuntimeFixture().runtime -} - -async function publish(runtime: OrcaRuntimeService, id: string, activate = true) { - await runtime.publishStructuredAgentSessionTab({ - workspaceId: WT, - sessionId: id.slice('agent-session:'.length), - agent: id === A ? 'claude' : 'codex', - activate - }) -} - -function rendererFrame( - selected: string, - version: number, - simulatorOnlyGroup = false -): RuntimeMobileSessionTabsSnapshot { - const chats = [A, B, C].map((id, index) => ({ - id: `window-${index}`, - entityId: id.slice('agent-session:'.length), - contentType: 'agent-session' as const, - groupId: 'g', - worktreeId: WT, - label: id, - customLabel: null, - color: null, - sortOrder: index, - createdAt: 1 - })) - const unified = [ - ...chats, - { - ...chats[0]!, - id: 'sim-tab', - entityId: 'simulator', - contentType: 'simulator' as const, - groupId: simulatorOnlyGroup ? 'sim-only' : 'g' - } - ] - const snapshot = buildMobileSessionTabSnapshots( - makeState({ - unifiedTabsByWorktree: { [WT]: unified }, - groupsByWorktree: { - [WT]: [ - { - id: 'g', - worktreeId: WT, - activeTabId: unified.find((tab) => - tab.contentType === 'agent-session' - ? `agent-session:${tab.entityId}` === (simulatorOnlyGroup ? A : selected) - : !simulatorOnlyGroup && tab.id === selected - )!.id, - tabOrder: unified.filter((tab) => tab.groupId === 'g').map((tab) => tab.id), - recentTabIds: [] - }, - ...(simulatorOnlyGroup - ? [ - { - id: 'sim-only', - worktreeId: WT, - activeTabId: 'sim-tab', - tabOrder: ['sim-tab'], - recentTabIds: [] - } - ] - : []) - ] - }, - activeGroupIdByWorktree: { [WT]: simulatorOnlyGroup ? 'sim-only' : 'g' } - }), - false - )[0]! - return { ...snapshot, publicationEpoch: 'renderer:active-publication', snapshotVersion: version } -} - -function accept(runtime: OrcaRuntimeService, frame: RuntimeMobileSessionTabsSnapshot) { - return runtime.syncWindowGraph(1, { tabs: [], leaves: [], mobileSessionTabs: [frame] }) -} - -const list = (runtime: OrcaRuntimeService) => runtime.listMobileSessionTabs(`id:${WT}`) -function expectSelection( - snapshot: RuntimeMobileSessionTabsResult | RuntimeMobileSessionTabsSnapshot | undefined, - id: string | null -) { - expect(snapshot?.activeTabId).toBe(id) - expect(snapshot?.activeTabType).toBe(id ? 'agent-session' : null) - expect(snapshot?.tabs.filter((tab) => tab.isActive).map((tab) => tab.id)).toEqual(id ? [id] : []) -} - -describe('host active-tab publication', () => { - it('keeps main-created inventory while current renderer navigation wins, and fences older renderer revisions', async () => { - const runtime = createRuntime() - await publish(runtime, A) - await accept(runtime, rendererFrame(A, 10)) - const beforeCreate = rendererFrame(A, 11) - await publish(runtime, C) - await accept(runtime, beforeCreate) - expectSelection(await list(runtime), A) - expect((await list(runtime)).tabs.map((tab) => tab.id)).toContain(C) - await accept(runtime, rendererFrame(C, 12)) - await accept(runtime, beforeCreate) - expectSelection(await list(runtime), C) - }) -}) diff --git a/tests/e2e/structured-attention-headless-delivery.unit.test.ts b/tests/e2e/structured-attention-headless-delivery.unit.test.ts deleted file mode 100644 index d512e74c993..00000000000 --- a/tests/e2e/structured-attention-headless-delivery.unit.test.ts +++ /dev/null @@ -1,69 +0,0 @@ -import { build } from 'esbuild' -import { mkdtempSync, rmSync } from 'node:fs' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { expect, it } from 'vitest' -import { runProcess } from '@orca/process-host' - -it('loads and delivers actual host notifications in plain Node without Electron installed', async () => { - const directory = mkdtempSync(join(tmpdir(), 'orca-headless-attention-')) - const bundle = join(directory, 'notification-host.cjs') - try { - await build({ - stdin: { - resolveDir: process.cwd(), - sourcefile: 'structured-attention-headless-notification.ts', - contents: ` - import {createStructuredAttentionMobileDelivery} from './src/main/runtime/agent-session/structured-agent-session-mobile-attention' - import {RuntimeMobileNotificationController} from './src/main/runtime/push/notifications/runtime-mobile-notification-controller' - import {getDefaultNotificationSettings} from './src/shared/notifications/notification-settings-defaults' - const controller = new RuntimeMobileNotificationController() - controller.configureDismissalStore(${JSON.stringify(join(directory, 'state'))}) - const events = [] - controller.onDispatched(event => events.push(event)) - const delivery = createStructuredAttentionMobileDelivery({ - readNotificationSettings: getDefaultNotificationSettings, - readWorkspaceLabels: () => ({worktreeLabel:'Notes'}), - isWorkspaceMuted: () => false, - readOrchestration: () => undefined, - dispatch: event => controller.dispatch(event), - reconcile: state => controller.reconcileStructuredPromptAttention(state), - now: () => 60_000 - }) - const scope = {executionHostId:'local',wslDistro:null,workspaceId:'folder-a',workspaceKind:'folder'} - const summary = {sessionId:'session-a',workspaceId:'folder-a',agent:'claude',status:'attention',updatedAt:1} - delivery.deliver({ - type:'prompt', - prompt:{scope,sessionId:'session-a',promptId:'approval-a',raisedAt:1,journalCursor:{epoch:'journal-a',sequence:1}} - },summary) - for (const outcome of ['failure','success']) { - delivery.deliver({type:'completion',completion:{scope,sessionId:'session-a',turnId:outcome,outcome,completedAt:2}},summary) - } - console.log(JSON.stringify(events.map(({title,body,agentState}) => ({title,body,agentState})))) - ` - }, - bundle: true, - platform: 'node', - target: 'node18', - format: 'cjs', - external: ['electron'], - outfile: bundle, - logLevel: 'silent' - }) - const result = await runProcess({ - program: process.execPath, - args: [bundle], - cwd: directory - }) - - expect(result.stderr).toBe('') - expect(result.code).toBe(0) - expect(JSON.parse(result.stdout)).toEqual([ - { title: 'Notes - Claude needs input', body: 'Claude needs input.', agentState: 'blocked' }, - { title: 'Notes - Claude failed', body: 'Claude failed.', agentState: 'done' }, - { title: 'Notes - Claude finished', body: 'Claude finished.', agentState: 'done' } - ]) - } finally { - rmSync(directory, { recursive: true, force: true }) - } -}) diff --git a/tests/e2e/structured-attention-read-retirement.test-fixture.tsx b/tests/e2e/structured-attention-read-retirement.test-fixture.tsx index 54637537f68..f682d252e61 100644 --- a/tests/e2e/structured-attention-read-retirement.test-fixture.tsx +++ b/tests/e2e/structured-attention-read-retirement.test-fixture.tsx @@ -22,7 +22,7 @@ import { RuntimeMobileNotificationController, type MobileNotificationEvent } from '../../src/main/runtime/push/notifications/runtime-mobile-notification-controller' -import { createStructuredAttentionMobileDelivery } from '../../src/main/runtime/agent-session/structured-agent-session-mobile-attention' +import { createStructuredAttentionMobileDelivery } from '../../src/main/runtime/agent-session/lifecycle/structured-agent-session-mobile-attention' import { call, installStructuredHostStub, diff --git a/tests/e2e/structured-chat-tabs-open-close.spec.ts b/tests/e2e/structured-chat-tabs-open-close.spec.ts deleted file mode 100644 index 87406018b82..00000000000 --- a/tests/e2e/structured-chat-tabs-open-close.spec.ts +++ /dev/null @@ -1,187 +0,0 @@ -import { existsSync, readFileSync } from 'node:fs' -import type { Page } from '@stablyai/playwright-test' -import { expect } from './helpers/orca-app' -import { waitForActiveWorktree, waitForSessionReady } from './helpers/store' -import { buildFakeAgentCommandOverride } from './helpers/fake-agent-command-override' -import { SUPPORTED, createChatOnHost, test } from './helpers/structured-claude-stub' -import { resolveCliCommand } from '../../src/shared/shell/command-resolution/node-cli-command-resolution' -import { claudeSessionIdForOrcaSession } from '../../src/main/claude/structured/claude-structured-session-id' -import { buildClaudeModelListArgs } from '../../src/shared/agent-session/options/model-catalog/claude-model-list-probe' - -type ChatTab = { id: string; entityId: string } - -function readChatTabs(page: Page, worktreeId: string): Promise { - return page.evaluate( - (wt) => - (window.__store?.getState().unifiedTabsByWorktree[wt] ?? []) - .filter((tab) => tab.contentType === 'agent-session') - .map((tab) => ({ id: tab.id, entityId: tab.entityId })), - worktreeId - ) -} - -async function waitForChatTab(page: Page, worktreeId: string, sessionId: string): Promise { - let tabId: string | undefined - await expect - .poll( - async () => { - tabId = (await readChatTabs(page, worktreeId)).find((tab) => tab.entityId === sessionId)?.id - return tabId - }, - { timeout: 30_000 } - ) - .toBeTruthy() - return tabId! -} - -function tabInStrip(page: Page, tabId: string) { - return page.locator(`[data-testid="sortable-tab"][data-tab-id="${tabId}"]`) -} - -/** Every Claude process Orca started, as the stub recorded it. */ -function readStubLaunches(launchLog: string): { pid: number; args: string[] }[] { - if (!existsSync(launchLog)) { - return [] - } - return readFileSync(launchLog, 'utf8') - .split('\n') - .filter(Boolean) - .map((line) => { - const entry: unknown = JSON.parse(line) - if ( - typeof entry !== 'object' || - entry === null || - !('pid' in entry) || - typeof entry.pid !== 'number' || - !('args' in entry) || - !Array.isArray(entry.args) - ) { - throw new Error(`unreadable stub launch: ${line}`) - } - return { pid: entry.pid, args: entry.args.map(String) } - }) -} - -function readStubRequests(launchLog: string, pid: number) { - const file = `${launchLog}.requests.jsonl` - if (!existsSync(file)) { - return [] - } - return readFileSync(file, 'utf8') - .split('\n') - .filter(Boolean) - .flatMap((line) => { - const entry: unknown = JSON.parse(line) - if ( - typeof entry !== 'object' || - entry === null || - !('pid' in entry) || - !('type' in entry) || - !('subtype' in entry) - ) { - throw new Error(`unreadable stub request: ${line}`) - } - return entry.pid === pid ? [{ type: entry.type, subtype: entry.subtype }] : [] - }) -} - -test.describe('structured chat tabs', () => { - test.skip(!SUPPORTED, 'the Claude stub wrapper is POSIX-only') - - test('open from the host and the New tab menu, show in the tab bar, and close', async ({ - orcaPage: page, - electronApp, - claudeStub - }) => { - test.setTimeout(120_000) - await waitForSessionReady(page) - const worktreeId = await waitForActiveWorktree(page) - // An absolute Command setting is used as-is or refuses the start; it never falls back. - await page.evaluate(async (command) => { - await window.__store?.getState().updateSettings({ - nativeChatProviders: { claude: true, codex: true }, - defaultTuiAgent: 'claude', - agentCmdOverrides: { claude: command } - }) - }, buildFakeAgentCommandOverride(claudeStub.command)) - - const first = await createChatOnHost(page, worktreeId) - const firstTab = await waitForChatTab(page, worktreeId, first) - await expect(tabInStrip(page, firstTab)).toBeVisible() - const second = await createChatOnHost(page, worktreeId) - const secondTab = await waitForChatTab(page, worktreeId, second) - await expect(tabInStrip(page, secondTab)).toBeVisible() - await expect(tabInStrip(page, firstTab)).toBeVisible() - - // The window closes one chat from its tab; the host closes the other. - await tabInStrip(page, firstTab).locator('[data-tab-close-button="true"]').click() - await expect(tabInStrip(page, firstTab)).toHaveCount(0) - await expect(tabInStrip(page, secondTab)).toBeVisible() - const closed = await page.evaluate( - ({ wt, tabId }) => - window.api.runtime.call({ - method: 'session.tabs.close', - params: { worktree: `id:${wt}`, tabId, reason: 'user' } - }), - { wt: worktreeId, tabId: `agent-session:${second}` } - ) - expect(closed, JSON.stringify(closed)).toMatchObject({ ok: true }) - await expect(tabInStrip(page, secondTab)).toHaveCount(0) - - // A chat the window opens from the New tab menu. - await page.getByRole('button', { name: 'New tab' }).click({ force: true }) - const claudeOption = page.getByRole('menuitem', { - name: 'Claude Configure Claude', - exact: true - }) - await expect(claudeOption).toBeVisible({ timeout: 15_000 }) - await claudeOption.click({ force: true }) - let opened: ChatTab | undefined - await expect - .poll( - async () => { - opened = (await readChatTabs(page, worktreeId))[0] - return opened?.entityId - }, - { timeout: 30_000 } - ) - .toBeTruthy() - await expect(tabInStrip(page, opened!.id)).toBeVisible() - - // Orca's own lookup, on its shell-hydrated PATH and isolated HOME, lands on the stub. - const mainEnv = await electronApp.evaluate(() => ({ - pathEnv: process.env.PATH ?? null, - homePath: process.env.HOME - })) - expect(resolveCliCommand('claude', mainEnv)).toBe(claudeStub.command) - // Only this stub's version/catalog probes or one of these exact conversations may start. - const providerIds = [first, second, opened!.entityId].map((id) => - claudeSessionIdForOrcaSession(id) - ) - await expect.poll(() => readStubLaunches(claudeStub.launchLog).length).toBeGreaterThan(0) - for (const { pid, args } of readStubLaunches(claudeStub.launchLog)) { - if (providerIds.some((id) => args.includes(id))) { - continue - } - if (args[0] === '--version') { - expect(args).toEqual(['--version']) - continue - } - expect(args).toEqual([ - ...buildClaudeModelListArgs(), - '--setting-sources', - 'user,project,local' - ]) - await expect - .poll(() => readStubRequests(claudeStub.launchLog, pid)) - .toEqual([ - { type: 'control_request', subtype: 'list_models' }, - { type: 'control_request', subtype: 'get_settings' }, - { type: 'control_request', subtype: 'initialize' } - ]) - } - - await tabInStrip(page, opened!.id).locator('[data-tab-close-button="true"]').click() - await expect(tabInStrip(page, opened!.id)).toHaveCount(0) - }) -})