diff --git a/.github/workflows/pr.yml b/.github/workflows/pr.yml index 13bed76ed0c..8826fd393ed 100644 --- a/.github/workflows/pr.yml +++ b/.github/workflows/pr.yml @@ -512,6 +512,10 @@ jobs: if: needs.code_paths.outputs.static_analysis == 'true' run: bun config/scripts/localization/source-extraction/audit-localization-coverage.mjs --check + - name: Verify startup and worktree localization coverage + if: needs.code_paths.outputs.static_analysis == 'true' + run: bun run verify:startup-worktree-localization-coverage + - name: Verify mobile localization if: needs.code_paths.outputs.static_analysis == 'true' run: bun config/scripts/localization/catalog-validation/verify-mobile-localization.mjs diff --git a/.gitignore b/.gitignore index e9ca3822d36..b585bdd9e91 100644 --- a/.gitignore +++ b/.gitignore @@ -121,6 +121,9 @@ validation-screenshots/ test-results/ playwright-report/ +# Claude Code settings are machine-local. +**/.claude/settings.local.json + # Agent skills are installed per machine. /.claude/skills/ /.agents/skills/ diff --git a/README.md b/README.md index 79d002770f7..bc1defaa9c6 100644 --- a/README.md +++ b/README.md @@ -292,11 +292,9 @@ Pair with your desktop app to monitor and steer your agents from your phone. - **Discord:** Join the community on **[Discord](https://discord.gg/fzjDKHxv8Q)**. - **Twitter / X:** Follow **[@orca_build](https://x.com/orca_build)** for updates and announcements. -- **WeChat:** Scan to join an Orca community WeChat group. If one group is full, join another. +- **WeChat:** Scan to join an Orca community WeChat group. - WeChat QR code for the Orca community - WeChat QR code for the Orca community - WeChat QR code for the Orca community + WeChat QR code for the Orca community - **Feedback & Ideas:** We ship fast. Missing something? [Request a new feature](https://github.com/stablyai/orca/issues). - **Privacy:** See the [privacy & telemetry docs](https://www.onorca.dev/docs/telemetry) for what anonymous usage data Orca collects and how to opt out. diff --git a/cloud/apps/relay-edge/spike/run-all-lifecycle.ts b/cloud/apps/relay-edge/spike/run-all-lifecycle.ts index 04de1249906..a4e00c9fc29 100644 --- a/cloud/apps/relay-edge/spike/run-all-lifecycle.ts +++ b/cloud/apps/relay-edge/spike/run-all-lifecycle.ts @@ -1,5 +1,5 @@ // Later run-all.ts checks against the same host: rebind, orphan grace, silence, -// forced resets and pre-upgrade refusals. +// forced resets. import WebSocket from 'ws' import { GRACE_MS, ORIGIN, PING_MS, PORT, SILENCE_MS, makeControl, openPhone, record, sleep, waitFor, type Ctx, type Control } from './run-all-harness' @@ -89,12 +89,4 @@ export async function runLifecycleChecks(ctx: Ctx, main: Control, mainAck: Ack): back.client.closeNow() } - // Bad JWT -> 401 before upgrade; malformed host id -> 429. - { - const bad = new WebSocket(`ws://127.0.0.1:${PORT}/v1/host/control`, { headers: { authorization: 'Bearer nope' } }) - const status = await new Promise((res) => bad.on('unexpected-response', (_q, r) => res(r.statusCode ?? 0))) - const badHost = new WebSocket(`ws://127.0.0.1:${PORT}/v1/connect/short`) - const s2 = await new Promise((res) => badHost.on('unexpected-response', (_q, r) => res(r.statusCode ?? 0))) - record('R11/R5 ES256 JWKS rejects bad token (401); malformed host id 429', status === 401 && s2 === 429, `${status},${s2}`) - } } diff --git a/cloud/apps/relay-edge/spike/run-all.ts b/cloud/apps/relay-edge/spike/run-all.ts index ce1d8a6ee09..49627e7cf86 100644 --- a/cloud/apps/relay-edge/spike/run-all.ts +++ b/cloud/apps/relay-edge/spike/run-all.ts @@ -100,11 +100,6 @@ async function runTests(ctx: Ctx): Promise { const mainAck = await main.client.connect() const transport = main.bindTransport(mainAck.generation) - // Alarm-driven app ping, answered by the shipped client's pong handler. - await sleep(PING_MS * 3 + 300) - record('R2/R5 alarm-driven JSON ping parsed by shipped client, pong keeps control alive', - main.events.pings >= 2 && main.client.isLive(), `pings=${main.events.pings} live=${main.client.isLive()}`) - // Phone connect -> conn-open (strict, shipped parser) -> host data -> relay-hello (shipped parser). const phone = openPhone(ctx) const helloOk = await waitFor(() => phone.hello !== null, 5000) diff --git a/config/build-plugins/react-compiler-uncompiled-files.mjs b/config/build-plugins/react-compiler-uncompiled-files.mjs new file mode 100644 index 00000000000..9c7826c0f19 --- /dev/null +++ b/config/build-plugins/react-compiler-uncompiled-files.mjs @@ -0,0 +1,36 @@ +import { readFileSync } from 'node:fs' +import { resolve } from 'node:path' +import { fileURLToPath } from 'node:url' + +// Why: import.meta.url, not dirname — electron-vite's config bundle rewrites only the former. +const REPO_ROOT = fileURLToPath(new URL('../..', import.meta.url)) + +export const UNCOMPILED_LIST = 'config/react-compiler-uncompiled-files.txt' +// Hand-kept list plus every file still in a hazard ratchet; compiled, these would run differently. +export const UNCOMPILED_FILE_LISTS = [ + UNCOMPILED_LIST, + 'config/render-path-translate-baseline.txt', + 'config/react-compiler-hazard-baseline.txt' +] + +/** Repo-relative paths from a list or count baseline: `[count ]path[#detail][ # note]`. */ +export function parseListedFiles(text) { + return text + .split('\n') + .map((line) => line.trim()) + .filter((line) => line && !line.startsWith('#')) + .map((line) => + line + .replace(/^\d+\s+/, '') + .split('#')[0] + .trim() + ) +} + +export function readListedFiles(list, root = REPO_ROOT) { + return parseListedFiles(readFileSync(resolve(root, list), 'utf8')) +} + +export function reactCompilerExcludedFiles(root = REPO_ROOT) { + return [...new Set(UNCOMPILED_FILE_LISTS.flatMap((list) => readListedFiles(list, root)))] +} diff --git a/config/build-plugins/react-compiler.ts b/config/build-plugins/react-compiler.ts index fcdb314daa8..33ec76cc24b 100644 --- a/config/build-plugins/react-compiler.ts +++ b/config/build-plugins/react-compiler.ts @@ -1,25 +1,5 @@ -import { readFileSync } from 'node:fs' -import { resolve } from 'node:path' import type { Options } from '@vitejs/plugin-react' - -// Hand-kept list plus every file still in a hazard ratchet; compiled, these would run differently. -const UNCOMPILED_FILE_LISTS = [ - 'config/react-compiler-uncompiled-files.txt', - 'config/render-path-translate-baseline.txt', - 'config/react-compiler-hazard-baseline.txt' -] - -function listedFiles(list: string): string[] { - return readFileSync(resolve(list), 'utf8') - .split('\n') - .map((line) => line.trim()) - .filter((line) => line && !line.startsWith('#')) - .map((line) => line.replace(/^\d+\s+/, '').split('#')[0]) -} - -export function reactCompilerExcludedFiles(): string[] { - return [...new Set(UNCOMPILED_FILE_LISTS.flatMap(listedFiles))] -} +import { reactCompilerExcludedFiles } from './react-compiler-uncompiled-files.mjs' export function isReactCompilerEnabled(): boolean { return process.env.ORCA_REACT_COMPILER !== '0' diff --git a/config/focus-setting-read-baseline.txt b/config/focus-setting-read-baseline.txt index 4b3f4c25346..bbb5f649286 100644 --- a/config/focus-setting-read-baseline.txt +++ b/config/focus-setting-read-baseline.txt @@ -12,17 +12,17 @@ 3 src/renderer/src/components/LinearIssueTextEditor.tsx 3 src/renderer/src/components/LinearIssueWorkspace.tsx 5 src/renderer/src/components/LinearItemDrawer.tsx -1 src/renderer/src/components/NativeChatResumeOnRestartGroups.tsx +1 src/renderer/src/components/native-chat-recovery/tree/NativeChatResumeOnRestartGroups.tsx 1 src/renderer/src/components/activity/ActivityPrototypePage.tsx 1 src/renderer/src/components/activity/activity-scope-filter-controls.tsx 2 src/renderer/src/components/activity/activity-thread-actions.ts 1 src/renderer/src/components/activity/use-agent-pane-thread-store-data.ts 1 src/renderer/src/components/activity/use-agent-pane-threads.ts 4 src/renderer/src/components/agent/AgentSettingsDialog.tsx -1 src/renderer/src/components/automations/automation-host-client.ts +1 src/renderer/src/components/automations/hosts/automation-host-client.ts 1 src/renderer/src/components/automations/automations-page-fixtures.ts 1 src/renderer/src/components/automations/use-automations-page-controller.ts -1 src/renderer/src/components/automations/use-automations-page-destination-form.ts +1 src/renderer/src/components/automations/authoring/use-automations-page-destination-form.ts 1 src/renderer/src/components/browser-pane/ReopenBrowserPageOnServerButton.tsx 1 src/renderer/src/components/browser-pane/browser-reopen-on-server.ts 1 src/renderer/src/components/browser-pane/stream-remote/use-remote-browser-page-stream.ts @@ -204,11 +204,11 @@ 1 src/renderer/src/hooks/ipc-events/runtime-environment-subscription-selection.ts 1 src/renderer/src/hooks/ipc-events/settings-sidebar-ipc-bridge.ts 1 src/renderer/src/hooks/ipc-events/terminal-request-ipc-bridge.ts -1 src/renderer/src/hooks/use-active-skill-discovery-runtime-target.ts +1 src/renderer/src/hooks/skills/discovery/use-active-skill-discovery-runtime-target.ts 2 src/renderer/src/hooks/use-integration-provider-status-refresh.ts -1 src/renderer/src/hooks/useActiveProjectSkillRuntime.ts +1 src/renderer/src/hooks/skills/runtime/useActiveProjectSkillRuntime.ts 1 src/renderer/src/hooks/useEditorExternalWatch.ts -1 src/renderer/src/hooks/useInstalledAgentSkills.ts +1 src/renderer/src/hooks/skills/discovery/useInstalledAgentSkills.ts 1 src/renderer/src/hooks/useIpcEvents.ts 4 src/renderer/src/hooks/useIssueMetadata.ts 2 src/renderer/src/hooks/useLinearIssuePublication.ts @@ -230,7 +230,7 @@ 1 src/renderer/src/lib/workspace/ownership/runtime-session-mirror-owners.ts 1 src/renderer/src/lib/runtime-session-mirror-targets.ts 1 src/renderer/src/lib/workspace/ownership/single-runtime-legacy-owner.ts -1 src/renderer/src/lib/skill-runtime-command.ts +1 src/renderer/src/lib/skills/runtime/skill-runtime-command.ts 1 src/renderer/src/lib/terminal-close-route.ts 4 src/renderer/src/lib/terminal-worktree-route.ts # resolveTerminalPtyOwner: teardown, close and PTY identity read spawn's attribution (round 3 F8), which retired the deprecated resolver's readers 3 src/renderer/src/lib/unread-badge-count-selector.ts diff --git a/config/host-list-render-baseline.txt b/config/host-list-render-baseline.txt index 09d3a029300..8cceee047a8 100644 --- a/config/host-list-render-baseline.txt +++ b/config/host-list-render-baseline.txt @@ -1,7 +1,7 @@ # JSX mapped straight over a host collection, per file, outside components/host-picker. # This is a RATCHET: counts may only go DOWN. Draw host lists with HostCombobox or # useBoundedHostRows. Prune after a fix: pnpm check:host-list-render-ratchet --prune -1 src/renderer/src/components/automations/AutomationRunsDashboard.tsx +1 src/renderer/src/components/automations/runs/AutomationRunsDashboard.tsx 1 src/renderer/src/components/right-sidebar/ai-vault/panel/AiVaultPanelControls.tsx 1 src/renderer/src/components/right-sidebar/source-control/ai/SourceControlAgentActionDialogForm.tsx 1 src/renderer/src/components/settings/browser/profiles/BrowserSessionCookiesSection.tsx diff --git a/config/react-compiler-bailout-baseline.txt b/config/react-compiler-bailout-baseline.txt index d1bc3f33bea..68511863f1e 100644 --- a/config/react-compiler-bailout-baseline.txt +++ b/config/react-compiler-bailout-baseline.txt @@ -28,27 +28,27 @@ 1 src/renderer/src/components/artifacts/ArtifactPublishButton.tsx 2 src/renderer/src/components/artifacts/ArtifactsPage.tsx 2 src/renderer/src/components/artifacts/useArtifactPagination.ts -2 src/renderer/src/components/automations/AutomationEditorPromptEditor.tsx -1 src/renderer/src/components/automations/AutomationHostFilterNotice.tsx -1 src/renderer/src/components/automations/AutomationProjectCombobox.tsx -1 src/renderer/src/components/automations/AutomationRunHistory.tsx -1 src/renderer/src/components/automations/AutomationRunsDashboard.tsx -1 src/renderer/src/components/automations/AutomationRunsTable.tsx +2 src/renderer/src/components/automations/authoring/AutomationEditorPromptEditor.tsx +1 src/renderer/src/components/automations/hosts/AutomationHostFilterNotice.tsx +1 src/renderer/src/components/automations/authoring/AutomationProjectCombobox.tsx +1 src/renderer/src/components/automations/runs/AutomationRunHistory.tsx +1 src/renderer/src/components/automations/runs/AutomationRunsDashboard.tsx +1 src/renderer/src/components/automations/runs/AutomationRunsTable.tsx 1 src/renderer/src/components/automations/AutomationsPageSurface.tsx -1 src/renderer/src/components/automations/use-automation-agent-picker-entries.ts -2 src/renderer/src/components/automations/use-automation-create-destination.ts -4 src/renderer/src/components/automations/use-automation-host-catalog.ts -4 src/renderer/src/components/automations/use-automation-list-search.ts -2 src/renderer/src/components/automations/use-automation-migrate-action.ts -1 src/renderer/src/components/automations/use-automation-runs-dashboard.ts -1 src/renderer/src/components/automations/use-automations-page-list-state.ts +1 src/renderer/src/components/automations/authoring/use-automation-agent-picker-entries.ts +2 src/renderer/src/components/automations/authoring/use-automation-create-destination.ts +4 src/renderer/src/components/automations/hosts/use-automation-host-catalog.ts +4 src/renderer/src/components/automations/listing/use-automation-list-search.ts +2 src/renderer/src/components/automations/authoring/use-automation-migrate-action.ts +1 src/renderer/src/components/automations/runs/use-automation-runs-dashboard.ts +1 src/renderer/src/components/automations/listing/use-automations-page-list-state.ts 1 src/renderer/src/components/automations/use-automations-page-local-state.ts 1 src/renderer/src/components/automations/use-automations-page-refresh.ts -1 src/renderer/src/components/automations/use-automations-page-setup-state.ts +1 src/renderer/src/components/automations/authoring/use-automations-page-setup-state.ts 1 src/renderer/src/components/automations/use-automations-page-store-state.ts -1 src/renderer/src/components/automations/use-external-automation-scope-retention.ts -2 src/renderer/src/components/automations/use-scoped-external-automations.ts -16 src/renderer/src/components/automations/use-selected-automation-run-history.ts +1 src/renderer/src/components/automations/external/use-external-automation-scope-retention.ts +2 src/renderer/src/components/automations/external/use-scoped-external-automations.ts +16 src/renderer/src/components/automations/runs/use-selected-automation-run-history.ts 7 src/renderer/src/components/browser-extension-install-dialog.tsx 1 src/renderer/src/components/browser-pane/ClientHostedBrowserPagePane.tsx 2 src/renderer/src/components/browser-pane/annotate/MarkupOverlay.tsx @@ -206,7 +206,7 @@ 1 src/renderer/src/components/mobile/WindowsFirewallNotice.tsx 2 src/renderer/src/components/mobile/use-mobile-page-paired-devices.ts 1 src/renderer/src/components/mobile/use-mobile-pairing-generation.ts -1 src/renderer/src/components/native-chat-restart-runtimes.ts +1 src/renderer/src/components/native-chat-recovery/offers/native-chat-restart-runtimes.ts 1 src/renderer/src/components/native-chat/NativeChatStructuredSession.tsx 8 src/renderer/src/components/native-chat/attachments/chips/use-native-chat-composer-attachments.ts 2 src/renderer/src/components/native-chat/attachments/intake/use-native-chat-resolved-path-attachments.ts @@ -542,16 +542,16 @@ 4 src/renderer/src/components/sidebar/worktree-list/viewport/use-row-measurement.ts 1 src/renderer/src/components/sidebar/worktree-list/viewport/use-scroll-to-top.ts 1 src/renderer/src/components/sidebar/worktree-list/viewport/use-virtualizer.ts -1 src/renderer/src/components/skills/SkillBundleInstallFlow.tsx -2 src/renderer/src/components/skills/SkillInstallDialog.tsx -4 src/renderer/src/components/skills/SkillInstallManagementDialog.tsx -1 src/renderer/src/components/skills/SkillShareDialog.tsx -1 src/renderer/src/components/skills/SkillSharedLinkRow.tsx +1 src/renderer/src/components/skills/installation/SkillBundleInstallFlow.tsx +2 src/renderer/src/components/skills/installation/SkillInstallDialog.tsx +4 src/renderer/src/components/skills/installation/SkillInstallManagementDialog.tsx +1 src/renderer/src/components/skills/sharing/SkillShareDialog.tsx +1 src/renderer/src/components/skills/sharing/SkillSharedLinkRow.tsx 1 src/renderer/src/components/skills/SkillsPage.tsx 1 src/renderer/src/components/skills/setup/WslAgentSkillSetupPanel.tsx -2 src/renderer/src/components/skills/use-owned-skill-shares.ts -1 src/renderer/src/components/skills/use-reviewed-skill-plan.ts -1 src/renderer/src/components/skills/use-skill-delete-flow.ts +2 src/renderer/src/components/skills/sharing/use-owned-skill-shares.ts +1 src/renderer/src/components/skills/freshness/use-reviewed-skill-plan.ts +1 src/renderer/src/components/skills/deletion/use-skill-delete-flow.ts 1 src/renderer/src/components/sparse/SparseCheckoutPresetSelect.tsx 1 src/renderer/src/components/ssh-host-recovery/SshHostMoveAnywayAction.tsx 2 src/renderer/src/components/star-nag/StarNagAgentValueMomentObserver.tsx @@ -693,16 +693,16 @@ 1 src/renderer/src/hooks/composer-state/workspace-identity-state.ts 3 src/renderer/src/hooks/linear-issue-committed-state.ts 1 src/renderer/src/hooks/use-audio-capture.ts -1 src/renderer/src/hooks/use-bundled-skill-install.ts +1 src/renderer/src/hooks/skills/installation/use-bundled-skill-install.ts 2 src/renderer/src/hooks/useDetectedAgents.ts 2 src/renderer/src/hooks/useGitHubTaskItems.ts 2 src/renderer/src/hooks/useImmediateMutation.ts -6 src/renderer/src/hooks/useInstalledAgentSkills.ts +6 src/renderer/src/hooks/skills/discovery/useInstalledAgentSkills.ts 1 src/renderer/src/hooks/useIssueMetadata.ts 3 src/renderer/src/hooks/useLinearIssuePublication.ts 1 src/renderer/src/hooks/useMacTccAttributionSeveredNotice.ts 1 src/renderer/src/hooks/useSettingsNavigationMetadata.ts -4 src/renderer/src/hooks/useSkillFreshness.ts +4 src/renderer/src/hooks/skills/freshness/useSkillFreshness.ts 1 src/renderer/src/hooks/useTaskPageGitHubWorkItemMutation.ts 6 src/renderer/src/hooks/useVirtualizedScrollAnchor.ts 1 src/renderer/src/lib/host-chat-program-acquisition.ts diff --git a/config/react-compiler-hazard-baseline.txt b/config/react-compiler-hazard-baseline.txt index 27196222a7d..3f359d3ae77 100644 --- a/config/react-compiler-hazard-baseline.txt +++ b/config/react-compiler-hazard-baseline.txt @@ -1,5 +1,5 @@ # Grandfathered code React Compiler would run differently (#:). # Generated; never hand-edit. Lower after a fix: pnpm check:react-compiler-compat-ratchet --prune 1 src/renderer/src/components/agent/agent-launch-picker-drafts.ts#useAgentPickerSetup:discarded-subscription -1 src/renderer/src/components/native-chat-restart-runtimes.ts#useNativeChatRestartRuntimes:discarded-subscription +1 src/renderer/src/components/native-chat-recovery/offers/native-chat-restart-runtimes.ts#useNativeChatRestartRuntimes:discarded-subscription 1 src/renderer/src/components/right-sidebar/source-control/ai/use-source-control-action-agent-choice.ts#useSourceControlActionAgentChoice:store-read-in-memo-block diff --git a/config/reliability-gates.jsonc b/config/reliability-gates.jsonc index ba5ff1a6f61..3615e183b7f 100644 --- a/config/reliability-gates.jsonc +++ b/config/reliability-gates.jsonc @@ -460,10 +460,10 @@ "oracle": "Audit2251 narrows agent-paste-draft.test.ts from 25 authored cases (26 literal cases) to four. Retained cases cover buffered readiness on PTY binding, separate spawn/composer lifetimes, real per-PTY paste/Enter serialization against a competing paste, and frame closure/no Enter after a rejected content chunk. Intentionally lost alarms include agent marker and fallback examples, direct-write failure/rejection, missing-PTY and Codex process-only timeout paths, exact nonprimary-PTY routing, full large-body chunk reconstruction, escaping/CRLF samples, internal laziness/yield work assertions, oversized preflight refusal, and exact configured delay/budget counts. No equivalent replacement, new execution, real PTY/provider delivery, rendered/native UI, deployment, measured performance or cross-platform result is claimed. Historical prior account (preserved verbatim): Mobile owner-layout policy retires whole tests and mixed registrations without equivalent replacement coverage. Retained callbacks and reduced selectors need fresh execution at their stated scope; prior measurements do not validate them. Historical oracle: Audit2003: Remove agent-prompt absence routing, throwing/live/missing-probe and cached-probe-count examples from the stale-leaf source. Controller-proven absence, unknown-liveness admission, obsolete-absence clearing and same-ID respawn fences remain at a supplied provider/row seam. Preserve the independent wire-codec receipt only in its original scope. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, physical provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1991: Remove partial-runtime terminal-send guard/status/floor/query projection and argument-inventory samples. Retained RPC viewport admission, authenticated-client spoof refusal, text admission and stale-binding fences remain bounded mock-boundary behavior. The unchanged wire-codec receipt remains valid only for its original command; it does not validate this reduced RPC selector. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, physical provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1908 removes the complete prompt-presentation hook and literal interactive-protocol mapping suites and narrows the interactive card and prompt-card input suites. Lost alarms include replacement approval A settling after answered B; collapse/expand composer ownership and partial-answer presentation; identical new waits after an unmounted view; collapsed transcript re-reads; answered/dismissed status-backed persistence and retirement; and literal answer-to-PTY byte arrays. The retained stale-PTY acknowledgment, cancellation/answer retry, and answered-approval remount/rebind assertions remain meaningful but are not equivalent replacement coverage. No fresh reduced-selector result, physical provider, rendered/native-focus, mixed-version deployment, soak, or measured-budget validation is claimed. The unchanged wire-codec receipt remains valid only for its exact command. Historical prior account (preserved verbatim): Retained exact unchanged-source receipts remain the only current execution evidence. Reduced selectors have no fresh execution result. Historical pre-audit oracle account for changed sources: Existing exact unchanged-selector receipts remain the only current execution evidence. Changed source selectors have no fresh execution result. Historical prior-source oracle account: Existing exact unchanged-selector receipts remain the only current execution evidence. Changed source selectors have no fresh execution result. Historical prior-source oracle account: Retained unchanged-selector receipts are the only current execution evidence. Reduced-source assertions await validation. Historical prior oracle: The retained unchanged-source receipts are the only current execution evidence; reduced-source assertions await validation. Historical oracle account (not a current claim for changed sources): The retained unchanged-source receipts are the only current execution evidence; reduced-source assertions await validation. Historical oracle account (not a current claim for changed sources): After acknowledged phone replies with stale host status, the exact card disappears and Send is enabled; unknown, refused or unverifiable-settlement replies retain enabled choices, while an older host's accepted reply dismisses like an acknowledged one; a same-occurrence view toggle retains pending acknowledgment and real replacements discard it. A slow 32 KiB SSH answer completes all chunks before Enter; cancellation preserves issued bytes but omits remaining groups. Paired settlement invokes the actual provider and lost callbacks remain unknown; older hosts deliver ordinary messages, launch and selector groups once and their accepted answers dismiss as before. An answered card stays hidden across a view remount; a collapsed card is a strip that frees the composer and expands back; an identical question in a new wait shows again; a composer send caught by a new card keeps its bubble without submitting or clearing the line under it. Audit2450 removes the MobileNativeChatView failure-banner callback-only example whose old banner is supplied unchanged by its props. Retain fatal-read gating and the ordering test that preserves a new delivery notice. The removed false-send/old-banner combination has no equivalent replacement; prior raw receipts and budgets retain their original source scope. No new soak, platform, performance or red/green claim.", "commands": [ "ORCA_BACKGROUND_LAUNCH=1 pnpm test src/renderer/src/components/native-chat/prompts/NativeChatInteractiveCard.test.tsx src/renderer/src/components/native-chat/prompts/NativeChatResolvedView.prompt-card-input.test.tsx src/renderer/src/components/native-chat/surfaces/integration/NativeChatResolvedView.prompt-card-composer.test.tsx src/renderer/src/components/native-chat/conversation/turns/NativeChatResolvedView.turn-status.test.tsx src/renderer/src/runtime/hosted-terminals/inspection/runtime-terminal-inspection.test.ts src/renderer/src/lib/agent-session/messaging/paste/agent-paste-draft.test.ts src/renderer/src/lib/agent-session/messaging/paste/agent-paste-draft-submit-retry.test.ts src/main/ipc/pty/ipc/write-input-user-input.test.ts src/main/ipc/pty/pty-write-ipc-validation.test.ts src/main/runtime/terminal/input/runtime-terminal-writer.test.ts src/main/runtime/rpc/terminal-send.test.ts src/main/runtime/terminal/input/terminal-send-stale-leaf-liveness.test.ts --maxWorkers=2", - "ORCA_BACKGROUND_LAUNCH=1 mobile/node_modules/.bin/vitest run --config mobile/vitest.config.ts mobile/src/session/native-chat/MobileNativeChatView.prompt-presentation.test.ts mobile/src/session/native-chat/MobileNativeChatView.failure-banner.test.ts mobile/src/session/mobile-prompt-controller.test.ts --maxWorkers=2", + "ORCA_BACKGROUND_LAUNCH=1 mobile/node_modules/.bin/vitest run --config mobile/vitest.config.ts mobile/src/session/native-chat/MobileNativeChatView.failure-banner.test.ts mobile/src/session/native-chat/input/mobile-prompt-controller.test.ts --maxWorkers=2", "ORCA_BACKGROUND_LAUNCH=1 pnpm test tests/e2e/cross-version-wire/cross-version-terminal-wire.unit.test.ts --maxWorkers=1", "ORCA_BACKGROUND_LAUNCH=1 pnpm test src/renderer/src/components/native-chat/prompts/NativeChatInteractiveCard.test.tsx src/renderer/src/components/native-chat/prompts/NativeChatResolvedView.prompt-card-input.test.tsx src/renderer/src/components/native-chat/conversation/turns/NativeChatResolvedView.turn-status.test.tsx src/renderer/src/runtime/hosted-terminals/inspection/runtime-terminal-inspection.test.ts src/renderer/src/lib/agent-session/messaging/paste/agent-paste-draft.test.ts src/renderer/src/lib/agent-session/messaging/paste/agent-paste-draft-submit-retry.test.ts src/main/ipc/pty/ipc/write-input-user-input.test.ts src/main/ipc/pty/pty-write-ipc-validation.test.ts --maxWorkers=2", - "ORCA_BACKGROUND_LAUNCH=1 mobile/node_modules/.bin/vitest run --config mobile/vitest.config.ts mobile/src/session/native-chat/MobileNativeChatView.prompt-presentation.test.ts mobile/src/session/native-chat/MobileNativeChatView.failure-banner.test.ts --maxWorkers=2" + "ORCA_BACKGROUND_LAUNCH=1 mobile/node_modules/.bin/vitest run --config mobile/vitest.config.ts mobile/src/session/native-chat/MobileNativeChatView.failure-banner.test.ts --maxWorkers=2" ], "testFiles": [ "src/renderer/src/components/native-chat/prompts/NativeChatInteractiveCard.test.tsx", @@ -478,9 +478,9 @@ "src/main/runtime/terminal/input/runtime-terminal-writer.test.ts", "src/main/runtime/rpc/terminal-send.test.ts", "src/main/runtime/terminal/input/terminal-send-stale-leaf-liveness.test.ts", - "mobile/src/session/native-chat/MobileNativeChatView.prompt-presentation.test.ts", + "mobile/src/session/native-chat/MobileNativeChatView.failure-banner.test.ts", - "mobile/src/session/mobile-prompt-controller.test.ts", + "mobile/src/session/native-chat/input/mobile-prompt-controller.test.ts", "tests/e2e/cross-version-wire/cross-version-terminal-wire.unit.test.ts" ], "assertionRefs": [ @@ -491,18 +491,12 @@ "sends only one cancellation, can cancel an answer, and permits retry after unknown" ] }, + { - "file": "mobile/src/session/native-chat/MobileNativeChatView.prompt-presentation.test.ts", - "assertions": [ - "a late answer cannot reshow an answered replacement occurrence", - "a late answer cannot dismiss a replacement session" - ] - }, - { - "file": "mobile/src/session/mobile-prompt-controller.test.ts", + "file": "mobile/src/session/native-chat/input/mobile-prompt-controller.test.ts", "assertions": [ "retains permission choices on %s", - "shows a collapsed prompt again as a new wait", + "keeps an acknowledged Deny hidden after the chat screen remounts on a lingering status", "settles the terminal answer for Q1 after Q2 arrives without hiding Q2", "keeps structured answer controls after a thrown send" @@ -1796,7 +1790,7 @@ "Complete CI soak with zero unexplained flakes and preserve the observable oracle." ], "demotionRule": "Keep experimental until CI soak; investigate failures without relaxing fidelity or resource-count assertions.", - "coverageNotes": "Audit2365 further reduces the supporting renderer agent-status suites. It removes the title-batch publication bound and generated-title sample, ordered acceptance/publication and nested/reentrant scheduling ledgers, Jcode manually assembled session-start sample, freshness-tick epoch example, repeated quit-capture identity and batched-clear examples, and sequential/batch retained-cap examples. Those alarms are no longer present; the following historical account must not be read as current coverage for them. No equivalent replacement or fresh execution evidence is claimed. Audit1400 intentionally deletes or reduces the listed sources. No fresh execution result validates their reduced selectors. Historical coverage account: Actual title-sync subscriber and Zustand publications are covered on macOS. Existing fixtures include SSH/runtime owner invalidation and folder workspaces; no live remote transport was launched. The guard has no platform branches, remote execution, liveness verdict or wire change. The test-value audit retires sequential/batch same-reducer replay, isolated capture-field examples, provider permutations and mock scheduling ledgers from the supporting renderer suites. The title batch publication bound remains, as do checkpoint precedence and real shutdown capture checks. This supplies no replacement evidence for the retired alarms; historical executed commands, counts and results remain historical. The test-value audit also retires isolated freshness-epoch, timestamp/attribution-copy, suppressor/reference and retained below-cap/overwrite examples from agent-status.test.ts. The original title-sync assertion references remain; retained stale-snapshot, cleanup and hard-bound checks are not equivalent replacements for these lost alarms. Historical commands, counts and results remain historical. Audit1400: src/renderer/src/lib/ai-vault-tab-title-sync-inputs.test.ts reduced. Loses one scan/count registration; retains owner invalidation and actual stale-reference release. No equivalent replacement coverage is claimed.", + "coverageNotes": "Audit2365 further reduces the supporting renderer agent-status suites. It removes the title-batch publication bound and generated-title sample, ordered acceptance/publication and nested/reentrant scheduling ledgers, Jcode manually assembled session-start sample, freshness-tick epoch example, repeated quit-capture identity and batched-clear examples, and sequential/batch retained-cap examples. Those alarms are no longer present; the following historical account must not be read as current coverage for them. No equivalent replacement or fresh execution evidence is claimed. Audit1400 intentionally deletes or reduces the listed sources. No fresh execution result validates their reduced selectors. Historical coverage account: Actual title-sync subscriber and Zustand publications are covered on macOS. Existing fixtures include SSH/runtime owner invalidation and folder workspaces; no live remote transport was launched. The guard has no platform branches, remote execution, liveness verdict or wire change. The test-value audit retires sequential/batch same-reducer replay, isolated capture-field examples, provider permutations and mock scheduling ledgers from the supporting renderer suites. The title batch publication bound remains, as do checkpoint precedence and real shutdown capture checks. This supplies no replacement evidence for the retired alarms; historical executed commands, counts and results remain historical. The test-value audit also retires isolated freshness-epoch, timestamp/attribution-copy, suppressor/reference and retained below-cap/overwrite examples from agent-status.test.ts. The original title-sync assertion references remain; retained stale-snapshot, cleanup and hard-bound checks are not equivalent replacements for these lost alarms. Historical commands, counts and results remain historical. Audit1400: src/renderer/src/lib/ai-vault-tab-title-sync-inputs.test.ts reduced. Loses one scan/count registration; retains owner invalidation and actual stale-reference release. No equivalent replacement coverage is claimed. Audit3146 incorporates source3132: seven authored/nine expanded provider-session lifecycle and shutdown examples are deliberately retired without replacement, including completed-session remote/manual-shutdown promotion and quit/done precedence over heartbeat. Captured-record conditional replacement and clockless Codex owner/root turn-fact isolation remain; they do not replace these alarms or establish actual shutdown/resume coverage.", "invariant": "Title-sync publications must not enumerate unchanged session collections, while title identity, provider availability, active pane, stored title and effective execution-host changes retain their previous invalidation decisions.", "oracle": "No current automated execution oracle is claimed for this gate after Audit1400 retired changed-source receipts. Historical oracle account: Fifty live heartbeat publications with 500 retained and 500 sleeping records cause zero unchanged-map enumerations and no extra scheduled reconciliations. Provider identity, additions/removals, agent/pane ownership, effective host, active pane and stored title changes still invalidate.", "commands": [], @@ -4230,10 +4224,10 @@ "providers": ["remote-runtime"], "coveredPlatforms": ["macos"], "coveredProviders": ["remote-runtime"], - "coverageNotes": "Audit3096 source-only reduction (3087/3088): retire 69 authored/76 expanded cases, including complete recovery-portals and reconnect-banner suites. Intentionally lose dead/default TUI replay, generated alternate-frame style composition, reset/mode/dimension and legacy missing-mode-boundary alarms, UI notice/action/reveal policies, and isolated recovery lifecycle variants, without equivalent replacement. Retained registrations and callbacks are unchanged; headless cells are not pixels, and no fresh runtime, host, SSH, WSL, rendered-app or performance result is claimed. Audit3086 source-only reduction (3079/3080/3081): intentionally retire 93 authored/100 expanded mock-boundary cases, including the complete spawn-errors and SSH reconnect overlay suites, without replacement. Retired alarms include spawn classification/ownership, reply ceilings and renderer-write failure recovery, disconnect/detach fencing branches, authority facts, and overlay retry/visibility wiring. Retained callbacks are unchanged; no fresh execution, real PTY/SSH, rendered UI, or performance result is claimed. Audit2432: The broad unit command loses the isolated BranchPicker open-change notification sample. Its unique true/false callback alarm is intentionally retired; reopening/status-refresh behavior was not exercised. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2425: The broad unit command loses the workspace-copy-status supplied readError forwarding sample. It did not exercise the branch-switch blocking promised by its title. This alarm is intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2417: The broad unit command loses two ordinary clean Git cherry-pick/revert success samples and two terminal startup foreground-read work-budget samples. These unique alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2412: The broad unit command loses the whole six-case fake-React-hook scroll-anchor suite, two generic draft-retention samples, a simple new-agent order sample, a real history-publication batching-count sample, an unmounted handoff abort/timer sample and three basic WSL preview/error samples. These alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2404: The broad unit command loses the standalone share-name lookup 503 propagation suite, initial deletion placement-kind sample, direct changed-mtime stale sample, first-pass rollback existence example and abandoned-preparation directory sample. These exact alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2397 review amendment: The broad unit command loses three standalone suites, two partial-case definitions and two URL table rows across package/download/placement tests. Keep initial wrong-port authorization, modified independent-copy digest refusal and abort-after-begin cancellation dispatch. The remaining alarms are deliberately retired; no equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2393 current-parent refresh2401: Remove the basic skill-install service alias sample and original public managed-remove receiptless refusal case. Preserve the upstream request ownership suite and transaction interruption coverage. No equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2389: The broad unit command loses the missing-preview suite, plain-global destination sample and prepublished-receipt recovery example. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2385: The broad unit command loses four authored walker/staging/protocol examples (six expanded cases); no equivalent replacement or fresh validation is claimed for the reduced suite. Audit2383: The unscoped Vitest command no longer includes the removed Antigravity catalogue suite; its exact provider-root/owner example has no equivalent replacement or fresh validation claim. Audit2377/2381: The unscoped Vitest command includes the reduced bundled-skill and native-discovery suites; the eight removed backup/legacy/catalogue/symlink/SSH-builder examples have no replacement-equivalence or fresh validation claim here. Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit1640 removes low-value IPC, SSH, workspace and transcript-watcher tests without equivalent replacement coverage. Per-source reviews record retained public refusal, cancellation, execution-host and real-filesystem outcomes with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Deterministic main-IPC contract tests cover disconnect-driven close delivery, exactly-once close, per-subscription teardown isolation against a failing socket close and a throwing liveness probe, containment of a throwing renderer send on the unguarded host-close path, and continued suppression of stale payloads from a retired transport. A headed paired-server journey (real Orca host plus a separate paired Orca desktop client) covers hidden-but-mounted reveal, cold-parked reveal, and cold-parked reveal across a disconnect/reconnect. Live Linux and Windows paired-server evidence and real sleep/wake transport loss remain uncollected.", + "coverageNotes": "Audit3209 composes approved sources3202/3206: deliberately retires seven authored/expanded cases in four whole suites without equivalent replacement. Work-item queries lose real GitHub/GitLab oversized ASCII secret-prefix empty-query and whitespace-before-trim refusal alarms; inputs share the imported size bound and exercise only its fast length branch, with no multibyte or actual provider/exposure guarantee. Skill sharing loses complete/partial managed-bundle and destination-ambiguity association checks plus three negative origin/path/scheme admission examples; these do not establish uploaded contents, arbitrary-URL fetching, authorization or execution. Retain exact originless-project direct-link fallback, cloud-delete confirmation, bundled-target repair/owner isolation and explicit Windows-host preference over stale WSL suites. Rejected3201 runtime-preference removal is excluded. No real cloud/network/host/disk, mobile or mixed-version execution validation is claimed. Audit3200 composes approved source3194: deliberately retires thirteen authored registrations/twenty-seven expanded cases in six whole automation host/list policy suites without equivalent replacement. Real RPC category/retryability and wrapped-timeout recognition, unscoped-failure/scoped-success health evidence precedence, exact-ID create selectors and per-run workspace omission, paired-web local/SSH/absent host catalog routing, incompatible/removed/unhydrated/offline execution health, runtime-before-nested-SSH recovery dispatch, and no-owned-focus/successor/foreign-list focus policy alarms are consciously lost. Retain exact20line orphan allow/refuse/precondition and exact90line cross-host same-ID search suites. No retry-timer/fence lifecycle, actual reconnect/network/write delivery, native focus, mobile/mixed-version runtime or disk persistence coverage is claimed. Audit3191 combines approved source3182/3187/3188: deliberately retires thirteen authored Vitest registrations and fifteen expanded cases, including five whole suites, without equivalent replacement. Attachment intake loses real portal/native-capture terminal interception and unowned-container refusal, immediate child-only committed availability/claim-ref negotiation and delivery, and direct-target over stable focused/background composer routing through disable/re-enable/remount and independent question focus. Exact destination/cache/draft and final-stat owner/workspace/File-release suites remain; they do not replace Surface recipient routing. Automation authoring loses destination runtime catalog membership, local/direct-SSH exclusion of paired-runtime repos, unknown-runtime empty catalog, logical project/host/setup/repo/path context payload, and missing/nonready setup refusal; these were genuine direct helper alarms, while exact schedule transformation, legacy schedule and setup-decision suites remain. Agent picker loses setup-chat/terminal/missing-installer/unsupported-or-unknown-host row projection samples and the ordinary unsearched menu variant; the entire original26-line resume recipe suite remains, including reported bypass versus default/absent permission modes, as does the exact search-result menu callback with its fixtures, model/effort commits and staged Arguments reopen outcome. Rejected predecessor3180 full recipe deletion is excluded. No actual native drag/cursor/focus/IME, upload bytes or disk/restart persistence, full automation save/scheduler/runtime transport, real resume-process flags/environment delivery, or native menu/rendered layout validation is claimed. Audit3178 combines source3169/3170/3175: deliberately retires eight authored units (six Vitest cases and two imperative custom relay scenarios), including two whole suites, without equivalent replacement. Voice Section loses per-model pending-delete isolation across interleaved A/B completion and the two-success refresh-call alarm; exact VoicePane delayed key-clear/newer enabled-toggle merge remains and does not replace row deletion coverage. Speech loses dedicated rating-scale/inclusive-ceiling, unsupported-versus-unmeasured, explicit/system-language precedence/locale alias, accuracy versus fast named/default/best-measured selection, and unmeasured/no-match examples; exact offered-user-pick versus retired-selection case and its fixture remain. Relay loses legacy ping-delivery count/liveness sampled before the silence deadline and grouped malformed Bearer/host-ID 401/429 routing checks; twelve real Worker/DurableObject/shipped-client scenarios remain, not equivalent replacement for those narrow alarms. Six prior speech cases are not all deleted: approved successor3175 keeps the original user-choice case. No actual credential/file persistence, native/GPU/engine/download delivery, production assignment policy or deployed-runtime validation is claimed by this reduction. Audit3165 combines source3160/3162: deliberately retires six authored/expanded cases across three whole suites without equivalent replacement. Launch/status losses: observed React-render pending/resuming coordination across settings and deferred offer read; stale-offer reread suppressing dialog reopen; held-local-chat recovery visibility with new-chat preferences off; disabled-local admission avoiding offer RPC despite an injected but unconsumed paired-tab fixture; and run-only lost-reply uncertainty reachability until direct viewed-run retirement. Launch probe does not prove arbitrary synchronous-store atomicity, the paired fixture is not remote runtime enrollment, and the status case directly marks viewed state rather than rendering the summary. Crew-hook losses: old-host method_not_found cache persists across party changes but is released by independently supplied connection generation/verified pairing status or pairing revision, with actual frame publication and teardown. These are real narrow coordination, admission, uncertainty and mixed-version cache alarms consciously lost. Exact web verified-runtime writer handoff guard remains; it does not replace those alarms or prove live host/native/mobile delivery. Audit3156 combines3147/3150/3152/3153/3154: deliberately retires39authored/40expanded native-chat recovery cases, eight whole suites and two orphan test-support files without equivalent replacement. Lost alarms: lost-reply unconfirmed reconciliation, skipped rows/counts and missed-frame repair, unknown/pending outcome and omitted-failure-list compatibility, uncertain history after dismissal, retry/refusal/dismiss lifecycle, hidden/consumed picker ownership, result-tree keyboard focus/disclosure and all-skipped retirement; unconfirmed-over-conflict guidance and failed-chat changes despite older host timestamps; nearest-listed ancestor/cyclic forest shape, descendant membership, host ordering/missing-host local fallback; skipped/readiness/admission counts, provisional skip/progress monotonicity, early per-chat verdicts with batch pending protection, older-host waiting, start-slot/delivery distinction, retry-over-failure and unknown-after-withdrawal attention; remote snooze/reconnect/reoffer, unseen mixed summary through open/close, watched completion retirement, new success beside old failure, failed-reread mixed-result preservation, filter/collapse completion resets, retry summary replacement and current-offer/history selection; cross-host workspace identity, rendered cyclic reachability, nested tri-state/toggle propagation, project eligibility isolation and collapse preserving selection. Exact fallback-list completion barrier, batched verdict/cleanup retention, stale-read versus dismissal publication race, and requested-but-never-rendered finished-run retirement remain; they do not replace retired alarms. Audit3146 combines source reviews3132/3133/3135/3138/3143: intentionally retire20authored/31expanded cases without equivalent replacement. Provider-session losses: structured-native terminal-resume exclusion, metadata-less completed identity, new-turn completion clearing, Pi provider-only/periodic/manual promotion, changed-transcript launch-config isolation, Pi/omp/prime-agent completed-session remote/manual-shutdown promotion, and quit/done precedence over heartbeat. Side-thread/question losses: finished-pane acquisition, hidden title/recap states, local/relay/relay-done conversation takeover with prompt/session/child resets, plain-message abandonment, compaction/session replacement and completion resets. Codex startup losses: incoming-owner cached child replacement, old-relay foreign live-session correction, completed foreign-root turn-fact permutations. Transcript losses: real temporary-JSONL partial sibling/final-child completion, unlabelled child attribution, compact cached replay preservation and100/1000completed-child roster retention/release. Compiler-ratchet losses: valid-line uncompiled-list parser grammar examples and injected-existence stale-path filtering; these did not exercise actual filesystem canonicalization or build exclusion. These are real lifecycle, ownership, replay, liveness and retention alarms, including recent#40246 regressions, deliberately lost. Retained conditional record replacement, clockless root/SSH owner isolation, persisted main-thread fork rejection, partial/final question-answer lifetime, cached-roster/missing-ID/live HTTP/durable startup boundaries and restarted-relay refusal/acceptance do not replace those losses. No native/SSH/WSL execution or equivalent coverage is claimed. Audit3128 scoped coverage reduction: Audit3121 removes VoiceDictationLanguageSetting.test.tsx (Spanish-to-es callback and unsupported-model Korean option presence) and voice-speech-model-rows.test.ts (provider/language-order/retired-on-disk list policy); these real narrow alarms are deliberately retired without replacement. VoiceSpeechModelSection per-model concurrent deletion remains unchanged. Audit3122 removes the direct absolute/parent-segment sparse-directory exception-type sample and the five-row IPC sparse-preset error-code/non-save table (two authored/six expanded cases). Those real typed-validation and IPC refusal/error-code alarms are deliberately retired. Keep both real symlink/junction floating-directory trust cases and the minimal RPC structured validation-reason serialization case. The RPC case does not replace IPC save/refusal behavior, typed normalization for both path inputs, actual Git sparse checkout or rendered localization. No equivalent replacement or fresh test/runtime/platform/remote/performance validation is claimed. Audit3124 removes ExperimentalPane.test.tsx (ordinary Pet switch callback), WorkspaceDirectorySetting.test.tsx (padded absolute saved-path normalization/no-write blur), and repository-search.perf.test.ts (navigation/selected-pane builder-call policy, fixture cardinality/nonempty entries and renamed project keyword inclusion). These real narrow alarms are retired without replacement; RepositoryPane.search.test.tsx search-to-sparse-editor request remains unchanged. Audit3129: resolver Windows case-insensitive and POSIX case-sensitive configured-env composition plus mocked-base launch-preflight Windows composition are intentionally no longer checked by the two deleted suites. No equivalent coverage claimed. Keep runtime-structured-agent-host-env.test.ts unchanged: configured Windows Claude-home account identity and host-account precedence remain checked. Audit3114 incorporates source3101: retire three structured Claude child-environment wrapper cases covering inherited stamp isolation/default and explicit entrypoint, Windows SDK-key canonicalization/default/duplicate-key order, and configured lookup/final environment/config-dir conjunction. Keep direct auth/session sanitation and Windows-versus-Linux overlay checks, actual executable lookup from supplied inherited PATH, native Windows child environment delivery, and stale option-mutation fencing. These are not equivalent replacements for the retired wrapper alarms. No fresh test/runtime, real login-shell probe, Claude SDK startup, remote/mixed-version, UI or performance result is claimed. Audit3114 incorporates source3105: retire 17 authored/20 expanded daemon launch-note cases, including the entire two-case SessionLaunchNote suite. Deliberately lose split-marker carry across same-token re-arm, stale-token retirement refusal, foreground tri-state and serial settlement, omitted-note/no-incarnation mixed-version policy, sticky retirement, first-incarnation/replacement launch preservation and held-launch precedence. Keep only the unchanged unresolved foreground-read race against a later finished attach. Supplied notes/foreground and runtime calls do not establish actual daemon/main restart, SSH, native Windows observation, mobile UI, equivalent replacement or fresh runtime/performance validation. Audit3114 incorporates source3109: retire six authored/35 expanded pricing cases: 21 accepted model-name examples, 10 unsupported/future-model fail-closed examples, malformed TTL clamp, unknown-model estimate refusal, flat-model long-context disregard and oversized long-context clamp. Keep mixed five-minute/one-hour write allocation and short/all-long/mixed long-context allocation with original fixed oracles. Real parser/refusal/bounds alarms are knowingly lost without equivalent replacement; retained tests do not validate provider rates, actual billing or request threshold classification. Preserve the archived usage-scan-append source-freeze receipt without transferring historical execution/performance credit. No fresh runtime result is claimed. Audit3108 source-only reduction (3094/3095/3100): retire 27 authored/30 expanded cases, including complete markdown view-state, file-preview link-open and CLI agent-server-route suites, without replacement. Deliberate losses include preview visibility/reference lifetime and same-path owners; SSH stat, directory/missing-target, explicit-null owner, nonmarkdown line/column, local URI routing, remote-to-client guard and same-file reuse; document-preview source-owner/folder/reuse routing, stable grant location and outside-workspace POSIX/Windows request projection; and verified remote CLI send/check refusal, suggested --on argv/copy, shell no-probe bypass, unverified-launch admission and older-peer refusal. Retain two markdown source-runtime/qualified-reveal alarms, one stale grant-rejection fence and two remote read/mutation evidence policies, with original callbacks. Final last-wins reveal did not prove transient cancellation; CLI prerequisite did not prove no real send, and envelope tests do not execute server refusal. No fresh runtime, rendered UI, actual file/SSH/paired transport, authorization, mixed-version or performance result is claimed. Audit3096 source-only reduction (3087/3088): retire 69 authored/76 expanded cases, including complete recovery-portals and reconnect-banner suites. Intentionally lose dead/default TUI replay, generated alternate-frame style composition, reset/mode/dimension and legacy missing-mode-boundary alarms, UI notice/action/reveal policies, and isolated recovery lifecycle variants, without equivalent replacement. Retained registrations and callbacks are unchanged; headless cells are not pixels, and no fresh runtime, host, SSH, WSL, rendered-app or performance result is claimed. Audit3086 source-only reduction (3079/3080/3081): intentionally retire 93 authored/100 expanded mock-boundary cases, including the complete spawn-errors and SSH reconnect overlay suites, without replacement. Retired alarms include spawn classification/ownership, reply ceilings and renderer-write failure recovery, disconnect/detach fencing branches, authority facts, and overlay retry/visibility wiring. Retained callbacks are unchanged; no fresh execution, real PTY/SSH, rendered UI, or performance result is claimed. Audit2432: The broad unit command loses the isolated BranchPicker open-change notification sample. Its unique true/false callback alarm is intentionally retired; reopening/status-refresh behavior was not exercised. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2425: The broad unit command loses the workspace-copy-status supplied readError forwarding sample. It did not exercise the branch-switch blocking promised by its title. This alarm is intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2417: The broad unit command loses two ordinary clean Git cherry-pick/revert success samples and two terminal startup foreground-read work-budget samples. These unique alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2412: The broad unit command loses the whole six-case fake-React-hook scroll-anchor suite, two generic draft-retention samples, a simple new-agent order sample, a real history-publication batching-count sample, an unmounted handoff abort/timer sample and three basic WSL preview/error samples. These alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2404: The broad unit command loses the standalone share-name lookup 503 propagation suite, initial deletion placement-kind sample, direct changed-mtime stale sample, first-pass rollback existence example and abandoned-preparation directory sample. These exact alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2397 review amendment: The broad unit command loses three standalone suites, two partial-case definitions and two URL table rows across package/download/placement tests. Keep initial wrong-port authorization, modified independent-copy digest refusal and abort-after-begin cancellation dispatch. The remaining alarms are deliberately retired; no equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2393 current-parent refresh2401: Remove the basic skill-install service alias sample and original public managed-remove receiptless refusal case. Preserve the upstream request ownership suite and transaction interruption coverage. No equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2389: The broad unit command loses the missing-preview suite, plain-global destination sample and prepublished-receipt recovery example. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2385: The broad unit command loses four authored walker/staging/protocol examples (six expanded cases); no equivalent replacement or fresh validation is claimed for the reduced suite. Audit2383: The unscoped Vitest command no longer includes the removed Antigravity catalogue suite; its exact provider-root/owner example has no equivalent replacement or fresh validation claim. Audit2377/2381: The unscoped Vitest command includes the reduced bundled-skill and native-discovery suites; the eight removed backup/legacy/catalogue/symlink/SSH-builder examples have no replacement-equivalence or fresh validation claim here. Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit1640 removes low-value IPC, SSH, workspace and transcript-watcher tests without equivalent replacement coverage. Per-source reviews record retained public refusal, cancellation, execution-host and real-filesystem outcomes with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Deterministic main-IPC contract tests cover disconnect-driven close delivery, exactly-once close, per-subscription teardown isolation against a failing socket close and a throwing liveness probe, containment of a throwing renderer send on the unguarded host-close path, and continued suppression of stale payloads from a retired transport. A headed paired-server journey (real Orca host plus a separate paired Orca desktop client) covers hidden-but-mounted reveal, cold-parked reveal, and cold-parked reveal across a disconnect/reconnect. Live Linux and Windows paired-server evidence and real sleep/wake transport loss remain uncollected.", "motivatingLinks": ["tests/e2e/paired-remote-terminal-parked-reveal-interactivity.spec.ts"], "invariant": "Every renderer-held runtime subscription receives exactly one terminal close event when its transport is retired, including when the retirement advanced the transport generation first, and a single failing teardown never abandons that environment's remaining subscriptions nor escapes into the transport that reported the close. Payload frames from a retired transport stay suppressed. A revealed remote terminal therefore reattaches over a live multiplex connection: its buffer restores, typed input reaches the host PTY, the echo paints without a tab flip, and the PTY converges on the revealed pane grid.", - "oracle": "Audit3096 source-only reduction (3087/3088): retire 69 authored/76 expanded cases, including complete recovery-portals and reconnect-banner suites. Intentionally lose dead/default TUI replay, generated alternate-frame style composition, reset/mode/dimension and legacy missing-mode-boundary alarms, UI notice/action/reveal policies, and isolated recovery lifecycle variants, without equivalent replacement. Retained registrations and callbacks are unchanged; headless cells are not pixels, and no fresh runtime, host, SSH, WSL, rendered-app or performance result is claimed. Audit3086 source-only reduction (3079/3080/3081): intentionally retire 93 authored/100 expanded mock-boundary cases, including the complete spawn-errors and SSH reconnect overlay suites, without replacement. Retired alarms include spawn classification/ownership, reply ceilings and renderer-write failure recovery, disconnect/detach fencing branches, authority facts, and overlay retry/visibility wiring. Retained callbacks are unchanged; no fresh execution, real PTY/SSH, rendered UI, or performance result is claimed. Audit2432: The broad unit command loses the isolated BranchPicker open-change notification sample. Its unique true/false callback alarm is intentionally retired; reopening/status-refresh behavior was not exercised. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2425: The broad unit command loses the workspace-copy-status supplied readError forwarding sample. It did not exercise the branch-switch blocking promised by its title. This alarm is intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2417: The broad unit command loses two ordinary clean Git cherry-pick/revert success samples and two terminal startup foreground-read work-budget samples. These unique alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2412: The broad unit command loses the whole six-case fake-React-hook scroll-anchor suite, two generic draft-retention samples, a simple new-agent order sample, a real history-publication batching-count sample, an unmounted handoff abort/timer sample and three basic WSL preview/error samples. These alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2404: The broad unit command loses the standalone share-name lookup 503 propagation suite, initial deletion placement-kind sample, direct changed-mtime stale sample, first-pass rollback existence example and abandoned-preparation directory sample. These exact alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2397 review amendment: The broad unit command loses three standalone suites, two partial-case definitions and two URL table rows across package/download/placement tests. Keep initial wrong-port authorization, modified independent-copy digest refusal and abort-after-begin cancellation dispatch. The remaining alarms are deliberately retired; no equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2393 current-parent refresh2401: Remove the basic skill-install service alias sample and original public managed-remove receiptless refusal case. Preserve the upstream request ownership suite and transaction interruption coverage. No equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2389: The broad unit command loses the missing-preview suite, plain-global destination sample and prepublished-receipt recovery example. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2385: The broad unit command loses four authored walker/staging/protocol examples (six expanded cases); no equivalent replacement or fresh validation is claimed for the reduced suite. Audit2383: The unscoped Vitest command no longer includes the removed Antigravity catalogue suite; its exact provider-root/owner example has no equivalent replacement or fresh validation claim. Audit2377/2381: The unscoped Vitest command includes the reduced bundled-skill and native-discovery suites; the eight removed backup/legacy/catalogue/symlink/SSH-builder examples have no replacement-equivalence or fresh validation claim here. Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): The main IPC contract test subscribes terminal.multiplex through the real handler, disconnects the environment, and asserts the renderer received exactly one {type: close} subscription event. Two isolation tests subscribe a second stream to the same environment and make the first one fail -- in its socket close, and in the liveness probe inside notifyClosed -- then assert the disconnect does not throw, both transports closed, and every close the renderer could still receive was delivered. A third drives a host-initiated close through the transport callback, which is the one notifyClosed call site with no surrounding guard, with a renderer send that throws, and asserts it cannot escape into the WebSocket close handler. A fourth test asserts that after retirement a late response frame is not forwarded and a late transport close does not re-send. The paired-server journey runs three reveal scenarios against one real host and one real paired desktop client, and for each records buffer restore, host-side receipt of the typed marker through an out-of-band host sink file, live paint without a tab flip, and PTY-versus-pane grid convergence.", + "oracle": "Audit3209 composes approved sources3202/3206: deliberately retires seven authored/expanded cases in four whole suites without equivalent replacement. Work-item queries lose real GitHub/GitLab oversized ASCII secret-prefix empty-query and whitespace-before-trim refusal alarms; inputs share the imported size bound and exercise only its fast length branch, with no multibyte or actual provider/exposure guarantee. Skill sharing loses complete/partial managed-bundle and destination-ambiguity association checks plus three negative origin/path/scheme admission examples; these do not establish uploaded contents, arbitrary-URL fetching, authorization or execution. Retain exact originless-project direct-link fallback, cloud-delete confirmation, bundled-target repair/owner isolation and explicit Windows-host preference over stale WSL suites. Rejected3201 runtime-preference removal is excluded. No real cloud/network/host/disk, mobile or mixed-version execution validation is claimed. Audit3200 composes approved source3194: deliberately retires thirteen authored registrations/twenty-seven expanded cases in six whole automation host/list policy suites without equivalent replacement. Real RPC category/retryability and wrapped-timeout recognition, unscoped-failure/scoped-success health evidence precedence, exact-ID create selectors and per-run workspace omission, paired-web local/SSH/absent host catalog routing, incompatible/removed/unhydrated/offline execution health, runtime-before-nested-SSH recovery dispatch, and no-owned-focus/successor/foreign-list focus policy alarms are consciously lost. Retain exact20line orphan allow/refuse/precondition and exact90line cross-host same-ID search suites. No retry-timer/fence lifecycle, actual reconnect/network/write delivery, native focus, mobile/mixed-version runtime or disk persistence coverage is claimed. Audit3191 combines approved source3182/3187/3188: deliberately retires thirteen authored Vitest registrations and fifteen expanded cases, including five whole suites, without equivalent replacement. Attachment intake loses real portal/native-capture terminal interception and unowned-container refusal, immediate child-only committed availability/claim-ref negotiation and delivery, and direct-target over stable focused/background composer routing through disable/re-enable/remount and independent question focus. Exact destination/cache/draft and final-stat owner/workspace/File-release suites remain; they do not replace Surface recipient routing. Automation authoring loses destination runtime catalog membership, local/direct-SSH exclusion of paired-runtime repos, unknown-runtime empty catalog, logical project/host/setup/repo/path context payload, and missing/nonready setup refusal; these were genuine direct helper alarms, while exact schedule transformation, legacy schedule and setup-decision suites remain. Agent picker loses setup-chat/terminal/missing-installer/unsupported-or-unknown-host row projection samples and the ordinary unsearched menu variant; the entire original26-line resume recipe suite remains, including reported bypass versus default/absent permission modes, as does the exact search-result menu callback with its fixtures, model/effort commits and staged Arguments reopen outcome. Rejected predecessor3180 full recipe deletion is excluded. No actual native drag/cursor/focus/IME, upload bytes or disk/restart persistence, full automation save/scheduler/runtime transport, real resume-process flags/environment delivery, or native menu/rendered layout validation is claimed. Audit3178 combines source3169/3170/3175: deliberately retires eight authored units (six Vitest cases and two imperative custom relay scenarios), including two whole suites, without equivalent replacement. Voice Section loses per-model pending-delete isolation across interleaved A/B completion and the two-success refresh-call alarm; exact VoicePane delayed key-clear/newer enabled-toggle merge remains and does not replace row deletion coverage. Speech loses dedicated rating-scale/inclusive-ceiling, unsupported-versus-unmeasured, explicit/system-language precedence/locale alias, accuracy versus fast named/default/best-measured selection, and unmeasured/no-match examples; exact offered-user-pick versus retired-selection case and its fixture remain. Relay loses legacy ping-delivery count/liveness sampled before the silence deadline and grouped malformed Bearer/host-ID 401/429 routing checks; twelve real Worker/DurableObject/shipped-client scenarios remain, not equivalent replacement for those narrow alarms. Six prior speech cases are not all deleted: approved successor3175 keeps the original user-choice case. No actual credential/file persistence, native/GPU/engine/download delivery, production assignment policy or deployed-runtime validation is claimed by this reduction. Audit3165 combines source3160/3162: deliberately retires six authored/expanded cases across three whole suites without equivalent replacement. Launch/status losses: observed React-render pending/resuming coordination across settings and deferred offer read; stale-offer reread suppressing dialog reopen; held-local-chat recovery visibility with new-chat preferences off; disabled-local admission avoiding offer RPC despite an injected but unconsumed paired-tab fixture; and run-only lost-reply uncertainty reachability until direct viewed-run retirement. Launch probe does not prove arbitrary synchronous-store atomicity, the paired fixture is not remote runtime enrollment, and the status case directly marks viewed state rather than rendering the summary. Crew-hook losses: old-host method_not_found cache persists across party changes but is released by independently supplied connection generation/verified pairing status or pairing revision, with actual frame publication and teardown. These are real narrow coordination, admission, uncertainty and mixed-version cache alarms consciously lost. Exact web verified-runtime writer handoff guard remains; it does not replace those alarms or prove live host/native/mobile delivery. Audit3156 combines3147/3150/3152/3153/3154: deliberately retires39authored/40expanded native-chat recovery cases, eight whole suites and two orphan test-support files without equivalent replacement. Lost alarms: lost-reply unconfirmed reconciliation, skipped rows/counts and missed-frame repair, unknown/pending outcome and omitted-failure-list compatibility, uncertain history after dismissal, retry/refusal/dismiss lifecycle, hidden/consumed picker ownership, result-tree keyboard focus/disclosure and all-skipped retirement; unconfirmed-over-conflict guidance and failed-chat changes despite older host timestamps; nearest-listed ancestor/cyclic forest shape, descendant membership, host ordering/missing-host local fallback; skipped/readiness/admission counts, provisional skip/progress monotonicity, early per-chat verdicts with batch pending protection, older-host waiting, start-slot/delivery distinction, retry-over-failure and unknown-after-withdrawal attention; remote snooze/reconnect/reoffer, unseen mixed summary through open/close, watched completion retirement, new success beside old failure, failed-reread mixed-result preservation, filter/collapse completion resets, retry summary replacement and current-offer/history selection; cross-host workspace identity, rendered cyclic reachability, nested tri-state/toggle propagation, project eligibility isolation and collapse preserving selection. Exact fallback-list completion barrier, batched verdict/cleanup retention, stale-read versus dismissal publication race, and requested-but-never-rendered finished-run retirement remain; they do not replace retired alarms. Audit3146 combines source reviews3132/3133/3135/3138/3143: intentionally retire20authored/31expanded cases without equivalent replacement. Provider-session losses: structured-native terminal-resume exclusion, metadata-less completed identity, new-turn completion clearing, Pi provider-only/periodic/manual promotion, changed-transcript launch-config isolation, Pi/omp/prime-agent completed-session remote/manual-shutdown promotion, and quit/done precedence over heartbeat. Side-thread/question losses: finished-pane acquisition, hidden title/recap states, local/relay/relay-done conversation takeover with prompt/session/child resets, plain-message abandonment, compaction/session replacement and completion resets. Codex startup losses: incoming-owner cached child replacement, old-relay foreign live-session correction, completed foreign-root turn-fact permutations. Transcript losses: real temporary-JSONL partial sibling/final-child completion, unlabelled child attribution, compact cached replay preservation and100/1000completed-child roster retention/release. Compiler-ratchet losses: valid-line uncompiled-list parser grammar examples and injected-existence stale-path filtering; these did not exercise actual filesystem canonicalization or build exclusion. These are real lifecycle, ownership, replay, liveness and retention alarms, including recent#40246 regressions, deliberately lost. Retained conditional record replacement, clockless root/SSH owner isolation, persisted main-thread fork rejection, partial/final question-answer lifetime, cached-roster/missing-ID/live HTTP/durable startup boundaries and restarted-relay refusal/acceptance do not replace those losses. No native/SSH/WSL execution or equivalent coverage is claimed. Audit3128 scoped coverage reduction: Audit3121 removes VoiceDictationLanguageSetting.test.tsx (Spanish-to-es callback and unsupported-model Korean option presence) and voice-speech-model-rows.test.ts (provider/language-order/retired-on-disk list policy); these real narrow alarms are deliberately retired without replacement. VoiceSpeechModelSection per-model concurrent deletion remains unchanged. Audit3122 removes the direct absolute/parent-segment sparse-directory exception-type sample and the five-row IPC sparse-preset error-code/non-save table (two authored/six expanded cases). Those real typed-validation and IPC refusal/error-code alarms are deliberately retired. Keep both real symlink/junction floating-directory trust cases and the minimal RPC structured validation-reason serialization case. The RPC case does not replace IPC save/refusal behavior, typed normalization for both path inputs, actual Git sparse checkout or rendered localization. No equivalent replacement or fresh test/runtime/platform/remote/performance validation is claimed. Audit3124 removes ExperimentalPane.test.tsx (ordinary Pet switch callback), WorkspaceDirectorySetting.test.tsx (padded absolute saved-path normalization/no-write blur), and repository-search.perf.test.ts (navigation/selected-pane builder-call policy, fixture cardinality/nonempty entries and renamed project keyword inclusion). These real narrow alarms are retired without replacement; RepositoryPane.search.test.tsx search-to-sparse-editor request remains unchanged. Audit3129: resolver Windows case-insensitive and POSIX case-sensitive configured-env composition plus mocked-base launch-preflight Windows composition are intentionally no longer checked by the two deleted suites. No equivalent coverage claimed. Keep runtime-structured-agent-host-env.test.ts unchanged: configured Windows Claude-home account identity and host-account precedence remain checked. Audit3114 incorporates source3101: retire three structured Claude child-environment wrapper cases covering inherited stamp isolation/default and explicit entrypoint, Windows SDK-key canonicalization/default/duplicate-key order, and configured lookup/final environment/config-dir conjunction. Keep direct auth/session sanitation and Windows-versus-Linux overlay checks, actual executable lookup from supplied inherited PATH, native Windows child environment delivery, and stale option-mutation fencing. These are not equivalent replacements for the retired wrapper alarms. No fresh test/runtime, real login-shell probe, Claude SDK startup, remote/mixed-version, UI or performance result is claimed. Audit3114 incorporates source3105: retire 17 authored/20 expanded daemon launch-note cases, including the entire two-case SessionLaunchNote suite. Deliberately lose split-marker carry across same-token re-arm, stale-token retirement refusal, foreground tri-state and serial settlement, omitted-note/no-incarnation mixed-version policy, sticky retirement, first-incarnation/replacement launch preservation and held-launch precedence. Keep only the unchanged unresolved foreground-read race against a later finished attach. Supplied notes/foreground and runtime calls do not establish actual daemon/main restart, SSH, native Windows observation, mobile UI, equivalent replacement or fresh runtime/performance validation. Audit3114 incorporates source3109: retire six authored/35 expanded pricing cases: 21 accepted model-name examples, 10 unsupported/future-model fail-closed examples, malformed TTL clamp, unknown-model estimate refusal, flat-model long-context disregard and oversized long-context clamp. Keep mixed five-minute/one-hour write allocation and short/all-long/mixed long-context allocation with original fixed oracles. Real parser/refusal/bounds alarms are knowingly lost without equivalent replacement; retained tests do not validate provider rates, actual billing or request threshold classification. Preserve the archived usage-scan-append source-freeze receipt without transferring historical execution/performance credit. No fresh runtime result is claimed. Audit3108 source-only reduction (3094/3095/3100): retire 27 authored/30 expanded cases, including complete markdown view-state, file-preview link-open and CLI agent-server-route suites, without replacement. Deliberate losses include preview visibility/reference lifetime and same-path owners; SSH stat, directory/missing-target, explicit-null owner, nonmarkdown line/column, local URI routing, remote-to-client guard and same-file reuse; document-preview source-owner/folder/reuse routing, stable grant location and outside-workspace POSIX/Windows request projection; and verified remote CLI send/check refusal, suggested --on argv/copy, shell no-probe bypass, unverified-launch admission and older-peer refusal. Retain two markdown source-runtime/qualified-reveal alarms, one stale grant-rejection fence and two remote read/mutation evidence policies, with original callbacks. Final last-wins reveal did not prove transient cancellation; CLI prerequisite did not prove no real send, and envelope tests do not execute server refusal. No fresh runtime, rendered UI, actual file/SSH/paired transport, authorization, mixed-version or performance result is claimed. Audit3096 source-only reduction (3087/3088): retire 69 authored/76 expanded cases, including complete recovery-portals and reconnect-banner suites. Intentionally lose dead/default TUI replay, generated alternate-frame style composition, reset/mode/dimension and legacy missing-mode-boundary alarms, UI notice/action/reveal policies, and isolated recovery lifecycle variants, without equivalent replacement. Retained registrations and callbacks are unchanged; headless cells are not pixels, and no fresh runtime, host, SSH, WSL, rendered-app or performance result is claimed. Audit3086 source-only reduction (3079/3080/3081): intentionally retire 93 authored/100 expanded mock-boundary cases, including the complete spawn-errors and SSH reconnect overlay suites, without replacement. Retired alarms include spawn classification/ownership, reply ceilings and renderer-write failure recovery, disconnect/detach fencing branches, authority facts, and overlay retry/visibility wiring. Retained callbacks are unchanged; no fresh execution, real PTY/SSH, rendered UI, or performance result is claimed. Audit2432: The broad unit command loses the isolated BranchPicker open-change notification sample. Its unique true/false callback alarm is intentionally retired; reopening/status-refresh behavior was not exercised. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2425: The broad unit command loses the workspace-copy-status supplied readError forwarding sample. It did not exercise the branch-switch blocking promised by its title. This alarm is intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2417: The broad unit command loses two ordinary clean Git cherry-pick/revert success samples and two terminal startup foreground-read work-budget samples. These unique alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2412: The broad unit command loses the whole six-case fake-React-hook scroll-anchor suite, two generic draft-retention samples, a simple new-agent order sample, a real history-publication batching-count sample, an unmounted handoff abort/timer sample and three basic WSL preview/error samples. These alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2404: The broad unit command loses the standalone share-name lookup 503 propagation suite, initial deletion placement-kind sample, direct changed-mtime stale sample, first-pass rollback existence example and abandoned-preparation directory sample. These exact alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2397 review amendment: The broad unit command loses three standalone suites, two partial-case definitions and two URL table rows across package/download/placement tests. Keep initial wrong-port authorization, modified independent-copy digest refusal and abort-after-begin cancellation dispatch. The remaining alarms are deliberately retired; no equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2393 current-parent refresh2401: Remove the basic skill-install service alias sample and original public managed-remove receiptless refusal case. Preserve the upstream request ownership suite and transaction interruption coverage. No equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2389: The broad unit command loses the missing-preview suite, plain-global destination sample and prepublished-receipt recovery example. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2385: The broad unit command loses four authored walker/staging/protocol examples (six expanded cases); no equivalent replacement or fresh validation is claimed for the reduced suite. Audit2383: The unscoped Vitest command no longer includes the removed Antigravity catalogue suite; its exact provider-root/owner example has no equivalent replacement or fresh validation claim. Audit2377/2381: The unscoped Vitest command includes the reduced bundled-skill and native-discovery suites; the eight removed backup/legacy/catalogue/symlink/SSH-builder examples have no replacement-equivalence or fresh validation claim here. Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): The main IPC contract test subscribes terminal.multiplex through the real handler, disconnects the environment, and asserts the renderer received exactly one {type: close} subscription event. Two isolation tests subscribe a second stream to the same environment and make the first one fail -- in its socket close, and in the liveness probe inside notifyClosed -- then assert the disconnect does not throw, both transports closed, and every close the renderer could still receive was delivered. A third drives a host-initiated close through the transport callback, which is the one notifyClosed call site with no surrounding guard, with a renderer send that throws, and asserts it cannot escape into the WebSocket close handler. A fourth test asserts that after retirement a late response frame is not forwarded and a late transport close does not re-send. The paired-server journey runs three reveal scenarios against one real host and one real paired desktop client, and for each records buffer restore, host-side receipt of the typed marker through an out-of-band host sink file, live paint without a tab flip, and PTY-versus-pane grid convergence.", "commands": [ "pnpm exec vitest run --config config/vitest.config.ts", "pnpm exec playwright test tests/e2e/paired-remote-terminal-parked-reveal-interactivity.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1" @@ -4319,7 +4313,19 @@ "Audit2425 removes use-workspace-copy-status original5, which returns a fixture-supplied readError string through statusReadError. No consumer blocker or attempted branch switch established refusal; the unique error-forwarding sample is intentionally retired. Other copy ownership and stale-refresh cases are not equivalent error-path coverage. No equivalent replacement or fresh validation is claimed.", "Audit2432 removes BranchPicker.test.tsx original3, which only asserted onOpenChange(true/false) with an always-mounted mocked Popover. It never reopened the picker or consumed the callback in the parent status-refresh owner, despite its title. Lose that unique open/close notification alarm. Retained blocker/collision recovery and asynchronous post-unmount outcome cases are not equivalent replacement coverage. No fresh validation of the reduced selector is claimed.", "Audit3086 source-only reduction (3079/3080/3081): intentionally retire 93 authored/100 expanded mock-boundary cases, including the complete spawn-errors and SSH reconnect overlay suites, without replacement. Retired alarms include spawn classification/ownership, reply ceilings and renderer-write failure recovery, disconnect/detach fencing branches, authority facts, and overlay retry/visibility wiring. Retained callbacks are unchanged; no fresh execution, real PTY/SSH, rendered UI, or performance result is claimed.", - "Audit3096 source-only reduction (3087/3088): retire 69 authored/76 expanded cases, including complete recovery-portals and reconnect-banner suites. Intentionally lose dead/default TUI replay, generated alternate-frame style composition, reset/mode/dimension and legacy missing-mode-boundary alarms, UI notice/action/reveal policies, and isolated recovery lifecycle variants, without equivalent replacement. Retained registrations and callbacks are unchanged; headless cells are not pixels, and no fresh runtime, host, SSH, WSL, rendered-app or performance result is claimed." + "Audit3096 source-only reduction (3087/3088): retire 69 authored/76 expanded cases, including complete recovery-portals and reconnect-banner suites. Intentionally lose dead/default TUI replay, generated alternate-frame style composition, reset/mode/dimension and legacy missing-mode-boundary alarms, UI notice/action/reveal policies, and isolated recovery lifecycle variants, without equivalent replacement. Retained registrations and callbacks are unchanged; headless cells are not pixels, and no fresh runtime, host, SSH, WSL, rendered-app or performance result is claimed.", + "Audit3108 source-only reduction (3094/3095/3100): retire 27 authored/30 expanded cases, including complete markdown view-state, file-preview link-open and CLI agent-server-route suites, without replacement. Deliberate losses include preview visibility/reference lifetime and same-path owners; SSH stat, directory/missing-target, explicit-null owner, nonmarkdown line/column, local URI routing, remote-to-client guard and same-file reuse; document-preview source-owner/folder/reuse routing, stable grant location and outside-workspace POSIX/Windows request projection; and verified remote CLI send/check refusal, suggested --on argv/copy, shell no-probe bypass, unverified-launch admission and older-peer refusal. Retain two markdown source-runtime/qualified-reveal alarms, one stale grant-rejection fence and two remote read/mutation evidence policies, with original callbacks. Final last-wins reveal did not prove transient cancellation; CLI prerequisite did not prove no real send, and envelope tests do not execute server refusal. No fresh runtime, rendered UI, actual file/SSH/paired transport, authorization, mixed-version or performance result is claimed.", + "Audit3114 incorporates source3101: retire three structured Claude child-environment wrapper cases covering inherited stamp isolation/default and explicit entrypoint, Windows SDK-key canonicalization/default/duplicate-key order, and configured lookup/final environment/config-dir conjunction. Keep direct auth/session sanitation and Windows-versus-Linux overlay checks, actual executable lookup from supplied inherited PATH, native Windows child environment delivery, and stale option-mutation fencing. These are not equivalent replacements for the retired wrapper alarms. No fresh test/runtime, real login-shell probe, Claude SDK startup, remote/mixed-version, UI or performance result is claimed.", + "Audit3114 incorporates source3105: retire 17 authored/20 expanded daemon launch-note cases, including the entire two-case SessionLaunchNote suite. Deliberately lose split-marker carry across same-token re-arm, stale-token retirement refusal, foreground tri-state and serial settlement, omitted-note/no-incarnation mixed-version policy, sticky retirement, first-incarnation/replacement launch preservation and held-launch precedence. Keep only the unchanged unresolved foreground-read race against a later finished attach. Supplied notes/foreground and runtime calls do not establish actual daemon/main restart, SSH, native Windows observation, mobile UI, equivalent replacement or fresh runtime/performance validation.", + "Audit3114 incorporates source3109: retire six authored/35 expanded pricing cases: 21 accepted model-name examples, 10 unsupported/future-model fail-closed examples, malformed TTL clamp, unknown-model estimate refusal, flat-model long-context disregard and oversized long-context clamp. Keep mixed five-minute/one-hour write allocation and short/all-long/mixed long-context allocation with original fixed oracles. Real parser/refusal/bounds alarms are knowingly lost without equivalent replacement; retained tests do not validate provider rates, actual billing or request threshold classification. Preserve the archived usage-scan-append source-freeze receipt without transferring historical execution/performance credit. No fresh runtime result is claimed.", + "Audit3128 scoped coverage reduction: Audit3121 removes VoiceDictationLanguageSetting.test.tsx (Spanish-to-es callback and unsupported-model Korean option presence) and voice-speech-model-rows.test.ts (provider/language-order/retired-on-disk list policy); these real narrow alarms are deliberately retired without replacement. VoiceSpeechModelSection per-model concurrent deletion remains unchanged. Audit3122 removes the direct absolute/parent-segment sparse-directory exception-type sample and the five-row IPC sparse-preset error-code/non-save table (two authored/six expanded cases). Those real typed-validation and IPC refusal/error-code alarms are deliberately retired. Keep both real symlink/junction floating-directory trust cases and the minimal RPC structured validation-reason serialization case. The RPC case does not replace IPC save/refusal behavior, typed normalization for both path inputs, actual Git sparse checkout or rendered localization. No equivalent replacement or fresh test/runtime/platform/remote/performance validation is claimed. Audit3124 removes ExperimentalPane.test.tsx (ordinary Pet switch callback), WorkspaceDirectorySetting.test.tsx (padded absolute saved-path normalization/no-write blur), and repository-search.perf.test.ts (navigation/selected-pane builder-call policy, fixture cardinality/nonempty entries and renamed project keyword inclusion). These real narrow alarms are retired without replacement; RepositoryPane.search.test.tsx search-to-sparse-editor request remains unchanged. Audit3129: resolver Windows case-insensitive and POSIX case-sensitive configured-env composition plus mocked-base launch-preflight Windows composition are intentionally no longer checked by the two deleted suites. No equivalent coverage claimed. Keep runtime-structured-agent-host-env.test.ts unchanged: configured Windows Claude-home account identity and host-account precedence remain checked.", + "Audit3146 combines source reviews3132/3133/3135/3138/3143: intentionally retire20authored/31expanded cases without equivalent replacement. Provider-session losses: structured-native terminal-resume exclusion, metadata-less completed identity, new-turn completion clearing, Pi provider-only/periodic/manual promotion, changed-transcript launch-config isolation, Pi/omp/prime-agent completed-session remote/manual-shutdown promotion, and quit/done precedence over heartbeat. Side-thread/question losses: finished-pane acquisition, hidden title/recap states, local/relay/relay-done conversation takeover with prompt/session/child resets, plain-message abandonment, compaction/session replacement and completion resets. Codex startup losses: incoming-owner cached child replacement, old-relay foreign live-session correction, completed foreign-root turn-fact permutations. Transcript losses: real temporary-JSONL partial sibling/final-child completion, unlabelled child attribution, compact cached replay preservation and100/1000completed-child roster retention/release. Compiler-ratchet losses: valid-line uncompiled-list parser grammar examples and injected-existence stale-path filtering; these did not exercise actual filesystem canonicalization or build exclusion. These are real lifecycle, ownership, replay, liveness and retention alarms, including recent#40246 regressions, deliberately lost. Retained conditional record replacement, clockless root/SSH owner isolation, persisted main-thread fork rejection, partial/final question-answer lifetime, cached-roster/missing-ID/live HTTP/durable startup boundaries and restarted-relay refusal/acceptance do not replace those losses. No native/SSH/WSL execution or equivalent coverage is claimed.", + "Audit3156 combines3147/3150/3152/3153/3154: deliberately retires39authored/40expanded native-chat recovery cases, eight whole suites and two orphan test-support files without equivalent replacement. Lost alarms: lost-reply unconfirmed reconciliation, skipped rows/counts and missed-frame repair, unknown/pending outcome and omitted-failure-list compatibility, uncertain history after dismissal, retry/refusal/dismiss lifecycle, hidden/consumed picker ownership, result-tree keyboard focus/disclosure and all-skipped retirement; unconfirmed-over-conflict guidance and failed-chat changes despite older host timestamps; nearest-listed ancestor/cyclic forest shape, descendant membership, host ordering/missing-host local fallback; skipped/readiness/admission counts, provisional skip/progress monotonicity, early per-chat verdicts with batch pending protection, older-host waiting, start-slot/delivery distinction, retry-over-failure and unknown-after-withdrawal attention; remote snooze/reconnect/reoffer, unseen mixed summary through open/close, watched completion retirement, new success beside old failure, failed-reread mixed-result preservation, filter/collapse completion resets, retry summary replacement and current-offer/history selection; cross-host workspace identity, rendered cyclic reachability, nested tri-state/toggle propagation, project eligibility isolation and collapse preserving selection. Exact fallback-list completion barrier, batched verdict/cleanup retention, stale-read versus dismissal publication race, and requested-but-never-rendered finished-run retirement remain; they do not replace retired alarms.", + "Audit3165 combines source3160/3162: deliberately retires six authored/expanded cases across three whole suites without equivalent replacement. Launch/status losses: observed React-render pending/resuming coordination across settings and deferred offer read; stale-offer reread suppressing dialog reopen; held-local-chat recovery visibility with new-chat preferences off; disabled-local admission avoiding offer RPC despite an injected but unconsumed paired-tab fixture; and run-only lost-reply uncertainty reachability until direct viewed-run retirement. Launch probe does not prove arbitrary synchronous-store atomicity, the paired fixture is not remote runtime enrollment, and the status case directly marks viewed state rather than rendering the summary. Crew-hook losses: old-host method_not_found cache persists across party changes but is released by independently supplied connection generation/verified pairing status or pairing revision, with actual frame publication and teardown. These are real narrow coordination, admission, uncertainty and mixed-version cache alarms consciously lost. Exact web verified-runtime writer handoff guard remains; it does not replace those alarms or prove live host/native/mobile delivery.", + "Audit3178 combines source3169/3170/3175: deliberately retires eight authored units (six Vitest cases and two imperative custom relay scenarios), including two whole suites, without equivalent replacement. Voice Section loses per-model pending-delete isolation across interleaved A/B completion and the two-success refresh-call alarm; exact VoicePane delayed key-clear/newer enabled-toggle merge remains and does not replace row deletion coverage. Speech loses dedicated rating-scale/inclusive-ceiling, unsupported-versus-unmeasured, explicit/system-language precedence/locale alias, accuracy versus fast named/default/best-measured selection, and unmeasured/no-match examples; exact offered-user-pick versus retired-selection case and its fixture remain. Relay loses legacy ping-delivery count/liveness sampled before the silence deadline and grouped malformed Bearer/host-ID 401/429 routing checks; twelve real Worker/DurableObject/shipped-client scenarios remain, not equivalent replacement for those narrow alarms. Six prior speech cases are not all deleted: approved successor3175 keeps the original user-choice case. No actual credential/file persistence, native/GPU/engine/download delivery, production assignment policy or deployed-runtime validation is claimed by this reduction.", + "Audit3191 combines approved source3182/3187/3188: deliberately retires thirteen authored Vitest registrations and fifteen expanded cases, including five whole suites, without equivalent replacement. Attachment intake loses real portal/native-capture terminal interception and unowned-container refusal, immediate child-only committed availability/claim-ref negotiation and delivery, and direct-target over stable focused/background composer routing through disable/re-enable/remount and independent question focus. Exact destination/cache/draft and final-stat owner/workspace/File-release suites remain; they do not replace Surface recipient routing. Automation authoring loses destination runtime catalog membership, local/direct-SSH exclusion of paired-runtime repos, unknown-runtime empty catalog, logical project/host/setup/repo/path context payload, and missing/nonready setup refusal; these were genuine direct helper alarms, while exact schedule transformation, legacy schedule and setup-decision suites remain. Agent picker loses setup-chat/terminal/missing-installer/unsupported-or-unknown-host row projection samples and the ordinary unsearched menu variant; the entire original26-line resume recipe suite remains, including reported bypass versus default/absent permission modes, as does the exact search-result menu callback with its fixtures, model/effort commits and staged Arguments reopen outcome. Rejected predecessor3180 full recipe deletion is excluded. No actual native drag/cursor/focus/IME, upload bytes or disk/restart persistence, full automation save/scheduler/runtime transport, real resume-process flags/environment delivery, or native menu/rendered layout validation is claimed.", + "Audit3200 composes approved source3194: deliberately retires thirteen authored registrations/twenty-seven expanded cases in six whole automation host/list policy suites without equivalent replacement. Real RPC category/retryability and wrapped-timeout recognition, unscoped-failure/scoped-success health evidence precedence, exact-ID create selectors and per-run workspace omission, paired-web local/SSH/absent host catalog routing, incompatible/removed/unhydrated/offline execution health, runtime-before-nested-SSH recovery dispatch, and no-owned-focus/successor/foreign-list focus policy alarms are consciously lost. Retain exact20line orphan allow/refuse/precondition and exact90line cross-host same-ID search suites. No retry-timer/fence lifecycle, actual reconnect/network/write delivery, native focus, mobile/mixed-version runtime or disk persistence coverage is claimed.", + "Audit3209 composes approved sources3202/3206: deliberately retires seven authored/expanded cases in four whole suites without equivalent replacement. Work-item queries lose real GitHub/GitLab oversized ASCII secret-prefix empty-query and whitespace-before-trim refusal alarms; inputs share the imported size bound and exercise only its fast length branch, with no multibyte or actual provider/exposure guarantee. Skill sharing loses complete/partial managed-bundle and destination-ambiguity association checks plus three negative origin/path/scheme admission examples; these do not establish uploaded contents, arbitrary-URL fetching, authorization or execution. Retain exact originless-project direct-link fallback, cloud-delete confirmation, bundled-target repair/owner isolation and explicit Windows-host preference over stale WSL suites. Rejected3201 runtime-preference removal is excluded. No real cloud/network/host/disk, mobile or mixed-version execution validation is claimed." ], "demotionRule": "Demote if a retired runtime transport can leave a renderer subscription without a close event, if a close is delivered more than once, if one failing teardown strands its sibling subscriptions, if payload frames from a retired transport reach the renderer, or if a revealed remote terminal can stay blank or reject input after a reconnect." }, @@ -4437,7 +4443,7 @@ "providers": ["remote-runtime"], "coveredPlatforms": ["macos"], "coveredProviders": [], - "coverageNotes": "Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2090 (sources2088/2089): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2086 (sources2082/2083): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2076 (sources2073/2074): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime-tests/terminal-handles-part-02.spec.ts: recovers a moved SSH pane through the tab it now sits in, not the one its lease froze; reports a plain expired orphan; does not report a pane whose only recent lease was superseded; does not report a pane whose only recent lease had its relay id recycled; picks the eligible orphan over a superseded predecessor that matches first; collects the same tabs the per-tab reader reports, in one sweep of the leases; reports no candidate when no lease names any of the worktree tabs. src/main/runtime/orca-runtime-tests/runtime-availability.spec.ts: starts unavailable with no authoritative window; reports the configured Windows terminal shell on status; reports floating workspace availability from settings on status; polls floating tabs with targeted PTY liveness and no repo/provider inventory; hydrates persisted tabs when the store cannot report repos; advertises browser screencast only when a renderer window is available; routes mobile Codex reset consumption through the account mutation coordinator; maps a definite pre-provider rejection into an authoritative current snapshot. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Frozen current literal-import graph reaches these changed test bytes; unresolved local and computed edges remain debt, and current reachability is not historical execution or equivalent replacement evidence. Historical prior account (preserved verbatim): Audit2043: Remove the registration-wait, webview-security, preview-authorization, guest-lifecycle and grant-IPC unit suites and the sibling-directory assertion reference. Runtime and browser capability consumers also lose removed imported examples. Remaining document-policy, file-reader and grant-registry assertions do not replace those alarms. Preserve the 27 independent dated receipts at their original unchanged selectors; reduced prospective unit selectors have no fresh result or equivalent replacement claim. Historical prior account (preserved verbatim): Audit1973: Delete the browser RPC forwarding/schema/scalar suite and its prospective selector. Preserve all27 unrelated dated receipts; no actual browser operation alarm is replaced. Whole original changed dated receipts are retired, never narrowed or transferred. This metadata review claims no fresh execution, equivalent replacement, provider/PTY, live remote/mobile, rendered, cross-platform, soak or measured-budget result. Historical prior account (preserved verbatim): Audit1925 (sources1922/1923): The complete terminal-file-link-actions suite is removed. Lose supplied local/remote menu-row inventories, browser label/order/download/reveal callback forwarding, platform-copy and source-group pinning examples. No OS reveal/download, real remote preview or browser navigation was exercised; the other real document-preview sources are not equivalent replacements. Preserve meaningful remaining selectors/assertions and unchanged dated receipts within their original scope. Reduced selectors have no fresh gate execution evidence in this metadata packet. No equivalent replacement, physical watcher/PTY/provider, live SSH/remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): Audit1899 replays sealed Audit1895: workspace-doc-history.test.ts is entirely removed from its current command and testFiles. Supplied recency/dedupe/cap/title/identity examples and the10000-row getter-read budget alarm are intentionally lost. No current assertionRef or active receipt selects that file. Unrelated active receipts and all prior gap literals remain verbatim; no replacement history/index-work coverage or new browser/paired-preview gate execution is claimed. Historical coverage account before Audit1899: Audit1853 reduces LinkActionPopover.test.tsx and archives its complete 2026-09-06 mixed-selector receipt. The lost copy/open-state and Settings callback-order/omission alarms are accepted without equivalent replacement coverage. No fresh execution of this gate is credited. Audit1709 removes low-value test definitions and retires affected assertion or execution-receipt claims without equivalent replacement coverage. Per-source reviews bound retained behavior and injected/native/remote limits. Unchanged assertions and receipts keep their original scope; gates lacking current active evidence are downgraded. Historical scope before this audit: Audit1687 removes low-value test projections, mock wiring, private-state assertions, inventories and duplicate examples without equivalent replacement coverage. Per-source reviews record retained public behavior and refusal boundaries with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1630 removes low-value Git, GitHub/GitLab and IPC projections, argument inventories and duplicate examples without equivalent replacement coverage. Per-source reviews record retained cancellation, ownership, authorization, filesystem and SQLite boundaries with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1571 removes mock forwarding, capability/schema inventories, private predicates, supplied error/result replays, and filesystem-mocked persistence checks without equivalent replacement claims. Retained changed tests also exercise real local permission-file reread, registry proxy rollback/credential retirement, site display recovery, and pending sender/credential/document admission with injected Electron/UI producers. Retained network tests exercise owned stream credit/cleanup, generation and retirement fences, real loopback proxy/SOCKS bytes and file-backed binding state. SSH/WSL/paired runtime, native sessions, authority producers and storage clears remain injected; simulated relaunch uses filesystem mocks. The unchanged profile-retirement suite was statically reviewed and not rerun. No actual SSH/WSL runtime, native Chromium jar deletion, durable process restart, remote DNS or external site proof. Receipts selecting changed tests are retired and unaffected receipts remain unchanged. Historical scope before this audit: Audit1568 removes API inventories, supplied mock-value/forwarding assertions, implementation-shape tables and negative/setup cases that do not reach their intended boundary, without equivalent replacement claims. Retained changed definitions exercise owned manager lifetime/queue/refcount/clamp and real synthetic process/files/staging boundaries. Seventeen unchanged native Electron definitions across this combined audit are statically reviewed and not rerun. Changed native suites exercise local popup wire/cookie/session and clean/native process-identity behavior; known popup-admission flaws remain unfixed. Unit native/event/session/registry inputs remain injected. No actual OS focus, registry/host execution, CRX verification or durable restart proof. Receipts selecting changed tests are retired and unaffected receipts remain unchanged. Historical scope before this audit: Audit1564 retires copied cookie key recipes, mock bridge/preview forwarding and flag tables, source-spelling/script inventories and setup-only alarms without equivalent replacement coverage. Retained changed cases exercise actual scoped SQLite merge/rollback/schema refusal, owned cancellation and grant authority/canonical containment, ranged response consistency, replacement guest ownership and executed guest-script promise/DOM cleanup behavior. Session, host response, geometry/observer and transport producers remain injected where documented. One unchanged native extension definition is not rerun locally; no actual remote filesystem, native layout/focus or authentication claim. Receipts selecting modified tests are retired; unaffected exact-selector receipts remain unchanged. Historical scope before this audit: Audit1412 changes referenced sources. Retained unchanged-source receipts apply only to their unchanged commands; the reduced selectors have no new execution result. Historical coverage account (not a current claim for changed sources): Audit1386 changes referenced sources; no new execution result validates reduced selectors. Retained unchanged receipts apply only to unchanged commands. Historical coverage: Audit1308 changes referenced sources. Retained unchanged-source receipts apply only to their unchanged commands; the reduced selectors have no new execution result. Historical coverage account (not a current claim for changed sources): A macOS desktop host and a separate paired Electron client exercise the Explorer preview action end to end: the document renders inside the client-local orca-preview guest, the client gains exactly one browser workspace and it is the document one, the host's own page registry and tab snapshot gain nothing, the split does not take focus from the source editor, an explicit click activates the preview, and closing it with its X leaves the editor and terminal intact. Both host oracles are read in a run where an ordinary URL browser tab from the same client does arrive in them, because a host that cannot project browser pages at all would otherwise answer the absence question the same way. A second journey quits that client with a document tab open and relaunches it on the same profile, which is the restore the user's original report turned on: the same workspace row comes back blank and named by the document, renders again, and does so over a grant URL that differs from the one that was quit. The same journey pins the guest URL to the orca-preview scheme, so a regression back to file:// or to a host browser page is visible. The rewritten journey caught a live gap the old one could not see: since previews became browser pages they had no chrome to hand focus to their guest, so main refused every reported link click as coming from an unfocused guest and the one route out of a preview was dead. Main's own log answered it — registered true, grant live, focused false — after the embedder reported the anchor really taking six real presses. The pane now hands focus over when it is the reader's surface, and the journey routes. The preview's own components moved out of the editor folder into browser-pane/workspace-doc/ with this change, since a preview is a browser pane and no longer an editor one; their i18n keys keep the historical auto.components.editor.HtmlDocPreview prefix rather than dropping thirty translated strings across four locales for a tidier key path. Seven gate commands named those files by their old paths and were re-issued at the new ones, and the nine dated runs behind them were retired rather than left naming files that are no longer there, on the same principle this gate already applied twice: vitest treats a missing named file as a filter and exits 0, so such a command reports green while silently running only the half that still exists. Each retired record's finding is carried into the replacement run recorded below it, including the red half of the entry/subresource pair, which was re-measured by re-applying its mutant at the new path rather than being dropped. The fence over the page-management channels was decided channel by channel before it was built, and that decision record is: of the 23 channels that can name a page, 6 are allowed for a workspace-document page — the tool channels the reader drives, which reach it through the one authority that reads both halves of the registry — 9 refuse (download accept and cancel, devtools, certificate proceed, client page metadata publish, viewport override, WebAuthn account response, registration probe, registration repair), 3 cannot name a page at all because they take a profile or a worktree instead, and the rest are the registration and activation doors, refused on membership. What shipped is not the per-channel guard that classification implies: eleven call sites read the browsing map directly, so a guard per channel is exactly the caller-flag seam that has to be remembered at every future call site. The registry was split in two instead, which makes the classification structural — a document guest is absent from the browsing map, so every refusing channel refuses by absence rather than by a guard, and a channel added later inherits the refusal without being classified at all. Unit contracts cover grant scoping and path containment, per-owner read routing, refusal of a truncated or over-cap read, the old-server binary degradation, scheme admission on will-attach-webview, the guest navigation policy, the plan layer's local/SSH/paired/out-of-worktree routing, and the distinct sentence the reader sees for each failure reason. The paired browser-creation surfaces this gate still owns — capability rejection cleanup, canonical page identity, reconciliation rollback, close convergence — keep their existing headed and headless journeys. Linux and Windows live journeys remain gaps. A refused subresource is a notice on a rendered document rather than a failure panel, since only the entry document's failure leaves the reader with nothing; the entry document is served as text by every owner and cannot be refused for its format at all. Grants die with the renderer document that minted them, at window creation and on every reload, because the renderer holds the only record of which preview owns which grant. The mint and revoke channels answer only the trusted renderer, and a preview tab is never republished to mobile clients, which have no grant to read it with. External URLs leave the preview only via a trusted user click on an anchor while the preview is focused; script-driven navigation and popups reach nothing. The guest's navigation sinks are deny-only and route no URL at all, and the guest carries a preview-only preload, pinned by will-attach-webview and denied to every other attach path, whose capture-phase click handler reports an anchor's URL to main; main answers only a report from a preview guest with a live bound grant that is the focused contents, and only for http(s). Two earlier reader-facing records from 2026-08-26, which measured a shape where a subresource failure was filtered out and the panel still carried an unsupported-asset sentence, were retired with that shape rather than left contradicting the 10/10 runs of the command they share. Two more were retired on the same principle when the external-link design changed: a record showing that removing a recent-input gate let the unattended document open two browser tabs, and a record showing that dropping the webview's allowpopups attribute left a target=_blank press with nothing to route. Both measured machinery that no longer exists — the input gate could not tell a script's navigation from the click it followed, which is the case now recorded below, and the preload intercepts the press before Chromium considers a popup at all, so allowpopups was removed. WebRTC is fenced by the guest's IP-handling policy alone: this Chromium answers a webrtc content-security-policy directive as unrecognized and gathers candidates anyway, so the directive is deliberately absent from the served policy and a unit assertion keeps it out. A standalone Electron probe on the same version gathered 7 candidates including a STUN reflexive one without the policy and 0 with it. Two command paths this gate used to carry no longer exist, and their structured evidence was retired with them rather than left naming files that are no longer there: vitest treats a missing named file as a filter and exits 0, so such a command reports green while silently running only the half that still exists. The first is src/renderer/src/lib/file-preview-capability-cleanup.test.ts, deleted in STA-5557 when HTML previews stopped creating paired browser tabs: on 2026-08-12 its five-assertion STA-4063 oracle ran red 5/5 on scan e4c278eb52 and on main bc2e30000b, partially green 2/5 on pre-fix PR #14100, and green 5/5 on candidate 14b5877a75; the surviving half of that oracle is web-runtime-browser-capability-cleanup.test.ts, still commanded above. The second is tests/e2e/paired-remote-html-browser-focus.spec.ts, renamed in STA-5557 to paired-remote-html-preview-local-render.spec.ts because the journey no longer proves anything about browser focus: its 2026-08-12 runs established the owning-runtime routing and no-focus-steal behavior of the then-current browser-tab preview (red on main 346e59c879 and a90a18d43d, green on candidates d05217c40d and b7de9c0961, red again with only the side-preview focus or routing seam disabled), and its 2026-08-26 runs are recorded below under the current path. An adversarial pass after the journey landed found four coverage gaps rather than shipping defects, and all four are pinned here. The page url had a third door: the navigation commit wrote whatever url was reported, unfenced, and while nothing reaches it for a document page today it sat one report away from giving a document page a URL that persistence, the publish boundary and the address bar all read. The group projection was the load-bearing half of the mobile publish boundary that no test had: removing it alone left the whole suite green, because no test in it had tab groups, while the phone payload gained a group whose order and active tab named a document tab it was never sent. The focus handoff was covered only in the narrowing direction, so widening it — dropping the page-activity check, or either half of the reader-surface check — survived both suites. And the handoff itself was offered once and never again, so another app taking the front left the preview's one route out shut until the pane remounted, which is a desktop gap rather than a test-only one. The standalone capability-cleanup and browser-placement ledger suites were removed, including their mixed-version rejection, cleanup transfer, capacity and partition alarms. web-runtime-session.test.ts no longer supplies browser creation, rollback or recovery assertions. The grouped workspace-document exclusion remains; the separate no-group publication example was removed. Existing live/browser-store evidence does not establish equivalent replacement alarms. Earlier descriptions of the removed fixtures and their run results are historical. The client-owned-placement and layout-groups suites are removed. The broad mirror fixture no longer supplies preview placement/reservation/move assertions. Browser rows retain pre-response replay and real local-workspace reuse; focus intent retains response ordering and exact-leaf sibling ordering. Supplied browser-layout and placement/focus projection alarms are lost; retained evidence is narrower and not equivalent. The test-value audit retires renderer grant-release mock ledgers, direct creation/title/session-field copies, notification/onboarding calls and several placement/per-page projections. Canonical-ID rejection, document reopen/restore and preview URL fences remain; they do not prove close-to-registry revocation or replace every lost alarm. Historical execution evidence is unchanged. The test-value audit removed the direct legacy editor-preview hydration example from tabs-hydration.test.ts. Dropping legacy preview chrome while preserving the same-document ordinary editor no longer has that alarm. The surviving corrupt-id deduplication case does not cover that migration, and retained preview journeys are not equivalent replacement coverage. Historical run counts and migration mutation findings describe the earlier suite. Audit1308: src/renderer/src/components/editor/EditorPanelShell.header.test.tsx removed. Header visibility and mocked editor-surface inventory alarms disappear. No equivalent replacement coverage is claimed. Audit1312 removes low-value imported specs from aggregate test drivers; old whole-driver execution receipts are archived. Retained registrations are unchanged. No equivalent replacement coverage is claimed. Audit1383: src/main/runtime/orca-runtime-tests/worktree-native-chat-setup.spec.ts reduced. Lose command-list/receipt/default/background activation matrices whose provider spawn returns canned IDs. Retained test proves actual tab allocation separation, not terminal startup. No equivalent replacement coverage is claimed. Existing exact unaffected receipts and their platform/provider/budget claims remain scoped to unchanged selectors. Changed optional selectors have no new execution result. Audit1386: src/renderer/src/lib/doc-preview-grants.test.ts reduced. Repeated-mount mint count, ordinary release/remint and failed-mint cache retry standalone alarms removed; no actual grant server/access test. No equivalent replacement coverage is claimed. Audit1401: src/main/runtime/orca-runtime-tests/mobile-session-tabs-duplicate-pty-repair.spec.ts removed. Loses listing-on-already-repaired-data alarm; it never established runtime repair invocation. src/main/runtime/orca-runtime-tests/mobile-session-tabs-split-agent-tab.spec.ts removed. Loses actual mobile split sibling shell versus recorded-agent resume command alarms; no equivalent coverage asserted. src/main/runtime/orca-runtime-tests/worktree-native-chat-setup.spec.ts removed. Loses separate setup/startup tab result in that manually assembled path. src/main/runtime/orca-runtime.test.ts reduced. Driver registration/import of a whole-deleted selected spec is removed; directly authored cases remain unchanged. No extra authored removal credit. No equivalent replacement coverage is claimed. The existing primary-selector receipt and its claims remain scoped to their unchanged sources; the broad optional command has no new execution result. Audit1412: src/main/browser/guest-lifecycle/manager/browser-manager-guest-policy-profile.test.ts removed. Loses workspace-document in-grant navigation/popup refusal, cleanup/re-attach, cross-registry guest authorization and browsing-map separation alarms. No equivalent browser policy coverage is claimed. No equivalent replacement coverage is claimed. Audit1421 removes browser-address-bar-suggestions.test.ts. Document suggestion title/path matching, recency merging and path-prefix ranking alarms are lost. No equivalent replacement coverage is claimed. Historical receipts remain scoped to unchanged selectors; the reduced command has no new execution result. Audit2452 removes the whole fake-effect browser-close routing suite. Active selectors and assertion references no longer select it. Its requested-worktree default close, sibling-page close and explicit missing-page typed reply alarms are intentionally retired without equivalent replacement. Prior dated receipts remain unchanged and scoped to their original sources; no fresh execution of the reduced gate, rendered browser, live remote, mobile or cross-platform validation is claimed.", + "coverageNotes": "Audit3108: doc-preview-grants.test.ts now retains only the stale grant-rejection race: a late rejected grant request must not evict a newer grant registry entry, witnessed by later revocation of grant-2. Retire stable minted-location and outside-workspace POSIX/Windows request-projection alarms without replacement. The direct nonempty grant selector remains unchanged; no real grant-server/file authorization, SSH/HTML delivery or native-focus result is claimed. Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2090 (sources2088/2089): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2086 (sources2082/2083): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2076 (sources2073/2074): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime-tests/terminal-handles-part-02.spec.ts: recovers a moved SSH pane through the tab it now sits in, not the one its lease froze; reports a plain expired orphan; does not report a pane whose only recent lease was superseded; does not report a pane whose only recent lease had its relay id recycled; picks the eligible orphan over a superseded predecessor that matches first; collects the same tabs the per-tab reader reports, in one sweep of the leases; reports no candidate when no lease names any of the worktree tabs. src/main/runtime/orca-runtime-tests/runtime-availability.spec.ts: starts unavailable with no authoritative window; reports the configured Windows terminal shell on status; reports floating workspace availability from settings on status; polls floating tabs with targeted PTY liveness and no repo/provider inventory; hydrates persisted tabs when the store cannot report repos; advertises browser screencast only when a renderer window is available; routes mobile Codex reset consumption through the account mutation coordinator; maps a definite pre-provider rejection into an authoritative current snapshot. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Frozen current literal-import graph reaches these changed test bytes; unresolved local and computed edges remain debt, and current reachability is not historical execution or equivalent replacement evidence. Historical prior account (preserved verbatim): Audit2043: Remove the registration-wait, webview-security, preview-authorization, guest-lifecycle and grant-IPC unit suites and the sibling-directory assertion reference. Runtime and browser capability consumers also lose removed imported examples. Remaining document-policy, file-reader and grant-registry assertions do not replace those alarms. Preserve the 27 independent dated receipts at their original unchanged selectors; reduced prospective unit selectors have no fresh result or equivalent replacement claim. Historical prior account (preserved verbatim): Audit1973: Delete the browser RPC forwarding/schema/scalar suite and its prospective selector. Preserve all27 unrelated dated receipts; no actual browser operation alarm is replaced. Whole original changed dated receipts are retired, never narrowed or transferred. This metadata review claims no fresh execution, equivalent replacement, provider/PTY, live remote/mobile, rendered, cross-platform, soak or measured-budget result. Historical prior account (preserved verbatim): Audit1925 (sources1922/1923): The complete terminal-file-link-actions suite is removed. Lose supplied local/remote menu-row inventories, browser label/order/download/reveal callback forwarding, platform-copy and source-group pinning examples. No OS reveal/download, real remote preview or browser navigation was exercised; the other real document-preview sources are not equivalent replacements. Preserve meaningful remaining selectors/assertions and unchanged dated receipts within their original scope. Reduced selectors have no fresh gate execution evidence in this metadata packet. No equivalent replacement, physical watcher/PTY/provider, live SSH/remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): Audit1899 replays sealed Audit1895: workspace-doc-history.test.ts is entirely removed from its current command and testFiles. Supplied recency/dedupe/cap/title/identity examples and the10000-row getter-read budget alarm are intentionally lost. No current assertionRef or active receipt selects that file. Unrelated active receipts and all prior gap literals remain verbatim; no replacement history/index-work coverage or new browser/paired-preview gate execution is claimed. Historical coverage account before Audit1899: Audit1853 reduces LinkActionPopover.test.tsx and archives its complete 2026-09-06 mixed-selector receipt. The lost copy/open-state and Settings callback-order/omission alarms are accepted without equivalent replacement coverage. No fresh execution of this gate is credited. Audit1709 removes low-value test definitions and retires affected assertion or execution-receipt claims without equivalent replacement coverage. Per-source reviews bound retained behavior and injected/native/remote limits. Unchanged assertions and receipts keep their original scope; gates lacking current active evidence are downgraded. Historical scope before this audit: Audit1687 removes low-value test projections, mock wiring, private-state assertions, inventories and duplicate examples without equivalent replacement coverage. Per-source reviews record retained public behavior and refusal boundaries with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1630 removes low-value Git, GitHub/GitLab and IPC projections, argument inventories and duplicate examples without equivalent replacement coverage. Per-source reviews record retained cancellation, ownership, authorization, filesystem and SQLite boundaries with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1571 removes mock forwarding, capability/schema inventories, private predicates, supplied error/result replays, and filesystem-mocked persistence checks without equivalent replacement claims. Retained changed tests also exercise real local permission-file reread, registry proxy rollback/credential retirement, site display recovery, and pending sender/credential/document admission with injected Electron/UI producers. Retained network tests exercise owned stream credit/cleanup, generation and retirement fences, real loopback proxy/SOCKS bytes and file-backed binding state. SSH/WSL/paired runtime, native sessions, authority producers and storage clears remain injected; simulated relaunch uses filesystem mocks. The unchanged profile-retirement suite was statically reviewed and not rerun. No actual SSH/WSL runtime, native Chromium jar deletion, durable process restart, remote DNS or external site proof. Receipts selecting changed tests are retired and unaffected receipts remain unchanged. Historical scope before this audit: Audit1568 removes API inventories, supplied mock-value/forwarding assertions, implementation-shape tables and negative/setup cases that do not reach their intended boundary, without equivalent replacement claims. Retained changed definitions exercise owned manager lifetime/queue/refcount/clamp and real synthetic process/files/staging boundaries. Seventeen unchanged native Electron definitions across this combined audit are statically reviewed and not rerun. Changed native suites exercise local popup wire/cookie/session and clean/native process-identity behavior; known popup-admission flaws remain unfixed. Unit native/event/session/registry inputs remain injected. No actual OS focus, registry/host execution, CRX verification or durable restart proof. Receipts selecting changed tests are retired and unaffected receipts remain unchanged. Historical scope before this audit: Audit1564 retires copied cookie key recipes, mock bridge/preview forwarding and flag tables, source-spelling/script inventories and setup-only alarms without equivalent replacement coverage. Retained changed cases exercise actual scoped SQLite merge/rollback/schema refusal, owned cancellation and grant authority/canonical containment, ranged response consistency, replacement guest ownership and executed guest-script promise/DOM cleanup behavior. Session, host response, geometry/observer and transport producers remain injected where documented. One unchanged native extension definition is not rerun locally; no actual remote filesystem, native layout/focus or authentication claim. Receipts selecting modified tests are retired; unaffected exact-selector receipts remain unchanged. Historical scope before this audit: Audit1412 changes referenced sources. Retained unchanged-source receipts apply only to their unchanged commands; the reduced selectors have no new execution result. Historical coverage account (not a current claim for changed sources): Audit1386 changes referenced sources; no new execution result validates reduced selectors. Retained unchanged receipts apply only to unchanged commands. Historical coverage: Audit1308 changes referenced sources. Retained unchanged-source receipts apply only to their unchanged commands; the reduced selectors have no new execution result. Historical coverage account (not a current claim for changed sources): A macOS desktop host and a separate paired Electron client exercise the Explorer preview action end to end: the document renders inside the client-local orca-preview guest, the client gains exactly one browser workspace and it is the document one, the host's own page registry and tab snapshot gain nothing, the split does not take focus from the source editor, an explicit click activates the preview, and closing it with its X leaves the editor and terminal intact. Both host oracles are read in a run where an ordinary URL browser tab from the same client does arrive in them, because a host that cannot project browser pages at all would otherwise answer the absence question the same way. A second journey quits that client with a document tab open and relaunches it on the same profile, which is the restore the user's original report turned on: the same workspace row comes back blank and named by the document, renders again, and does so over a grant URL that differs from the one that was quit. The same journey pins the guest URL to the orca-preview scheme, so a regression back to file:// or to a host browser page is visible. The rewritten journey caught a live gap the old one could not see: since previews became browser pages they had no chrome to hand focus to their guest, so main refused every reported link click as coming from an unfocused guest and the one route out of a preview was dead. Main's own log answered it — registered true, grant live, focused false — after the embedder reported the anchor really taking six real presses. The pane now hands focus over when it is the reader's surface, and the journey routes. The preview's own components moved out of the editor folder into browser-pane/workspace-doc/ with this change, since a preview is a browser pane and no longer an editor one; their i18n keys keep the historical auto.components.editor.HtmlDocPreview prefix rather than dropping thirty translated strings across four locales for a tidier key path. Seven gate commands named those files by their old paths and were re-issued at the new ones, and the nine dated runs behind them were retired rather than left naming files that are no longer there, on the same principle this gate already applied twice: vitest treats a missing named file as a filter and exits 0, so such a command reports green while silently running only the half that still exists. Each retired record's finding is carried into the replacement run recorded below it, including the red half of the entry/subresource pair, which was re-measured by re-applying its mutant at the new path rather than being dropped. The fence over the page-management channels was decided channel by channel before it was built, and that decision record is: of the 23 channels that can name a page, 6 are allowed for a workspace-document page — the tool channels the reader drives, which reach it through the one authority that reads both halves of the registry — 9 refuse (download accept and cancel, devtools, certificate proceed, client page metadata publish, viewport override, WebAuthn account response, registration probe, registration repair), 3 cannot name a page at all because they take a profile or a worktree instead, and the rest are the registration and activation doors, refused on membership. What shipped is not the per-channel guard that classification implies: eleven call sites read the browsing map directly, so a guard per channel is exactly the caller-flag seam that has to be remembered at every future call site. The registry was split in two instead, which makes the classification structural — a document guest is absent from the browsing map, so every refusing channel refuses by absence rather than by a guard, and a channel added later inherits the refusal without being classified at all. Unit contracts cover grant scoping and path containment, per-owner read routing, refusal of a truncated or over-cap read, the old-server binary degradation, scheme admission on will-attach-webview, the guest navigation policy, the plan layer's local/SSH/paired/out-of-worktree routing, and the distinct sentence the reader sees for each failure reason. The paired browser-creation surfaces this gate still owns — capability rejection cleanup, canonical page identity, reconciliation rollback, close convergence — keep their existing headed and headless journeys. Linux and Windows live journeys remain gaps. A refused subresource is a notice on a rendered document rather than a failure panel, since only the entry document's failure leaves the reader with nothing; the entry document is served as text by every owner and cannot be refused for its format at all. Grants die with the renderer document that minted them, at window creation and on every reload, because the renderer holds the only record of which preview owns which grant. The mint and revoke channels answer only the trusted renderer, and a preview tab is never republished to mobile clients, which have no grant to read it with. External URLs leave the preview only via a trusted user click on an anchor while the preview is focused; script-driven navigation and popups reach nothing. The guest's navigation sinks are deny-only and route no URL at all, and the guest carries a preview-only preload, pinned by will-attach-webview and denied to every other attach path, whose capture-phase click handler reports an anchor's URL to main; main answers only a report from a preview guest with a live bound grant that is the focused contents, and only for http(s). Two earlier reader-facing records from 2026-08-26, which measured a shape where a subresource failure was filtered out and the panel still carried an unsupported-asset sentence, were retired with that shape rather than left contradicting the 10/10 runs of the command they share. Two more were retired on the same principle when the external-link design changed: a record showing that removing a recent-input gate let the unattended document open two browser tabs, and a record showing that dropping the webview's allowpopups attribute left a target=_blank press with nothing to route. Both measured machinery that no longer exists — the input gate could not tell a script's navigation from the click it followed, which is the case now recorded below, and the preload intercepts the press before Chromium considers a popup at all, so allowpopups was removed. WebRTC is fenced by the guest's IP-handling policy alone: this Chromium answers a webrtc content-security-policy directive as unrecognized and gathers candidates anyway, so the directive is deliberately absent from the served policy and a unit assertion keeps it out. A standalone Electron probe on the same version gathered 7 candidates including a STUN reflexive one without the policy and 0 with it. Two command paths this gate used to carry no longer exist, and their structured evidence was retired with them rather than left naming files that are no longer there: vitest treats a missing named file as a filter and exits 0, so such a command reports green while silently running only the half that still exists. The first is src/renderer/src/lib/file-preview-capability-cleanup.test.ts, deleted in STA-5557 when HTML previews stopped creating paired browser tabs: on 2026-08-12 its five-assertion STA-4063 oracle ran red 5/5 on scan e4c278eb52 and on main bc2e30000b, partially green 2/5 on pre-fix PR #14100, and green 5/5 on candidate 14b5877a75; the surviving half of that oracle is web-runtime-browser-capability-cleanup.test.ts, still commanded above. The second is tests/e2e/paired-remote-html-browser-focus.spec.ts, renamed in STA-5557 to paired-remote-html-preview-local-render.spec.ts because the journey no longer proves anything about browser focus: its 2026-08-12 runs established the owning-runtime routing and no-focus-steal behavior of the then-current browser-tab preview (red on main 346e59c879 and a90a18d43d, green on candidates d05217c40d and b7de9c0961, red again with only the side-preview focus or routing seam disabled), and its 2026-08-26 runs are recorded below under the current path. An adversarial pass after the journey landed found four coverage gaps rather than shipping defects, and all four are pinned here. The page url had a third door: the navigation commit wrote whatever url was reported, unfenced, and while nothing reaches it for a document page today it sat one report away from giving a document page a URL that persistence, the publish boundary and the address bar all read. The group projection was the load-bearing half of the mobile publish boundary that no test had: removing it alone left the whole suite green, because no test in it had tab groups, while the phone payload gained a group whose order and active tab named a document tab it was never sent. The focus handoff was covered only in the narrowing direction, so widening it — dropping the page-activity check, or either half of the reader-surface check — survived both suites. And the handoff itself was offered once and never again, so another app taking the front left the preview's one route out shut until the pane remounted, which is a desktop gap rather than a test-only one. The standalone capability-cleanup and browser-placement ledger suites were removed, including their mixed-version rejection, cleanup transfer, capacity and partition alarms. web-runtime-session.test.ts no longer supplies browser creation, rollback or recovery assertions. The grouped workspace-document exclusion remains; the separate no-group publication example was removed. Existing live/browser-store evidence does not establish equivalent replacement alarms. Earlier descriptions of the removed fixtures and their run results are historical. The client-owned-placement and layout-groups suites are removed. The broad mirror fixture no longer supplies preview placement/reservation/move assertions. Browser rows retain pre-response replay and real local-workspace reuse; focus intent retains response ordering and exact-leaf sibling ordering. Supplied browser-layout and placement/focus projection alarms are lost; retained evidence is narrower and not equivalent. The test-value audit retires renderer grant-release mock ledgers, direct creation/title/session-field copies, notification/onboarding calls and several placement/per-page projections. Canonical-ID rejection, document reopen/restore and preview URL fences remain; they do not prove close-to-registry revocation or replace every lost alarm. Historical execution evidence is unchanged. The test-value audit removed the direct legacy editor-preview hydration example from tabs-hydration.test.ts. Dropping legacy preview chrome while preserving the same-document ordinary editor no longer has that alarm. The surviving corrupt-id deduplication case does not cover that migration, and retained preview journeys are not equivalent replacement coverage. Historical run counts and migration mutation findings describe the earlier suite. Audit1308: src/renderer/src/components/editor/EditorPanelShell.header.test.tsx removed. Header visibility and mocked editor-surface inventory alarms disappear. No equivalent replacement coverage is claimed. Audit1312 removes low-value imported specs from aggregate test drivers; old whole-driver execution receipts are archived. Retained registrations are unchanged. No equivalent replacement coverage is claimed. Audit1383: src/main/runtime/orca-runtime-tests/worktree-native-chat-setup.spec.ts reduced. Lose command-list/receipt/default/background activation matrices whose provider spawn returns canned IDs. Retained test proves actual tab allocation separation, not terminal startup. No equivalent replacement coverage is claimed. Existing exact unaffected receipts and their platform/provider/budget claims remain scoped to unchanged selectors. Changed optional selectors have no new execution result. Audit1386: src/renderer/src/lib/doc-preview-grants.test.ts reduced. Repeated-mount mint count, ordinary release/remint and failed-mint cache retry standalone alarms removed; no actual grant server/access test. No equivalent replacement coverage is claimed. Audit1401: src/main/runtime/orca-runtime-tests/mobile-session-tabs-duplicate-pty-repair.spec.ts removed. Loses listing-on-already-repaired-data alarm; it never established runtime repair invocation. src/main/runtime/orca-runtime-tests/mobile-session-tabs-split-agent-tab.spec.ts removed. Loses actual mobile split sibling shell versus recorded-agent resume command alarms; no equivalent coverage asserted. src/main/runtime/orca-runtime-tests/worktree-native-chat-setup.spec.ts removed. Loses separate setup/startup tab result in that manually assembled path. src/main/runtime/orca-runtime.test.ts reduced. Driver registration/import of a whole-deleted selected spec is removed; directly authored cases remain unchanged. No extra authored removal credit. No equivalent replacement coverage is claimed. The existing primary-selector receipt and its claims remain scoped to their unchanged sources; the broad optional command has no new execution result. Audit1412: src/main/browser/guest-lifecycle/manager/browser-manager-guest-policy-profile.test.ts removed. Loses workspace-document in-grant navigation/popup refusal, cleanup/re-attach, cross-registry guest authorization and browsing-map separation alarms. No equivalent browser policy coverage is claimed. No equivalent replacement coverage is claimed. Audit1421 removes browser-address-bar-suggestions.test.ts. Document suggestion title/path matching, recency merging and path-prefix ranking alarms are lost. No equivalent replacement coverage is claimed. Historical receipts remain scoped to unchanged selectors; the reduced command has no new execution result. Audit2452 removes the whole fake-effect browser-close routing suite. Active selectors and assertion references no longer select it. Its requested-worktree default close, sibling-page close and explicit missing-page typed reply alarms are intentionally retired without equivalent replacement. Prior dated receipts remain unchanged and scoped to their original sources; no fresh execution of the reduced gate, rendered browser, live remote, mobile or cross-platform validation is claimed.", "motivatingLinks": [ "https://linear.app/stably/issue/STA-5557/remote-html-preview-render-workspace-files-locally-over-the-file", "https://linear.app/stably/issue/STA-3872/unable-to-open-html-files-in-remote-server", @@ -4448,7 +4454,7 @@ "https://github.com/stablyai/orca/pull/13876" ], "invariant": "Opening one HTML preview from a paired client renders the workspace document in exactly one client-local browser tab, located by that document and served over the orca-preview scheme. The client gains exactly that one browser workspace and it is the document one — blank where a URL page carries a URL, named by the document, with the chip naming the file — while the host gains no browser page at all, neither in its own page registry nor in the tab snapshot its clients publish into. The preview occupies its own split without taking focus from the source editor; an explicit click activates it, and closing it removes only the preview. Following a document from a file link is the other half of that switch and does move the reader to it, tab group included, whether the preview is new or already open, because opening a file is a request to look at it. A document tab quit with the client comes back as the same row on a grant the relaunched client mints afresh. A preview is named by the browser page it is open in, not by a namespace of its own, and the page registry has two halves: a workspace-document guest is registered in its own map and is absent from the browsing one entirely. That absence is the fence. Page, session and profile management, agent tab enumeration and command targeting, download routing and certificate attribution all read the browsing map directly, in more places than a per-channel guard could be remembered in, so none of them can name a document page and none of them carries a guard. Browser tools the reader drives (element grab, hover describe, selection capture, the annotation viewport bridge) are the one operation that legitimately spans the halves, and they go through the single authority that reads both, keyed by the page and its hosting renderer. The halves are disjoint in both directions: browsing registration refuses a page the document half already holds, and minting a grant refuses a page the browsing half already holds, so one id can never name a surface in both. The headless backend acts on that refusal by destroying the window it had already opened rather than leaving a policy-less page behind an id nothing can drive, keeping nothing under that id for its own shutdown to hand back. Registration refuses on the same terms when the guest it was asked about is already gone. The exit door is guarded in both its halves: a preview withdraws by revoking its grant and never through the unregister channel, so a page the document half holds arriving there is refused before either the registration teardown or the grab-state disposal beside it, which would otherwise drop the intent an in-flight preview grab compares by identity and leave that grab answering ok without ever arming its guest. A bridge request whose guest does not resolve is refused without tearing down the page it named, so a misaddressed request cannot cancel a healthy page's in-flight downloads and grabs. The annotation viewport bridge resolves its guest when its serialized op actually runs rather than when the request arrived, so a cross-process navigation while it waited cannot leave the bridge installed in a retired guest while the reader looks at a new one. State main keys by a preview's page is disposed when that page's grant is revoked, which is the only signal a preview's surface is gone. A tool asking for a page whose guest has not attached yet waits for that registration and arms when it arrives, rather than answering not-ready at the reader; that wait resolves only the request already naming this page, never the worktree-wide or any-tab waits the CLI and agents use to ask for a browser tab to drive. Handing the previewed document to the reader's own machine routes on the owners its grant was minted against — the file's own connection owner and the worktree's own runtime owner, neither read from the tab's stored fields. Only a document proven to live on this machine reaches the client OS; one with a resolved remote owner is downloaded first; and one whose owner cannot be resolved at all, workspace root included, is refused with a message naming that, because the download route would otherwise read the same absolute path on the client and hand back a same-named local file under the remote document's name. A runtime-owned path that falls outside its worktree root is refused by that route itself and surfaces as a failure toast rather than a download. Nothing the document does writes a file to this machine either: the preview partition denies downloads outright instead of routing them through the browser download flow, which has no page to attribute a preview's bytes to and would otherwise reserve a name in this desktop's Downloads folder and write them there unprompted. That refusal is visible to the reader and invisible to the document: the preview's shell carries a fixed sentence saying downloads are off, published at most once per preview per interval so a document asking in a loop cannot fill Orca's chrome, while the page itself gets back exactly what it got before, which is nothing. The sentence names no file, because the document chooses the name it offers; and a refusal never takes the document away the way an entry document's own failure does, whatever it names. A preview is a browser tab, not an editor tab in a preview mode: it is named the way a browser tab is named — by the document it shows when that document declares a title, and by the file it shows when it does not — while the chip goes on naming the file and the host whatever the document calls itself. A title is refused on the same terms the url is: a document that declares none has Chromium report the grant URL as its title, and that title is stored, mirrored onto the tab and written to disk, so anything carrying the scheme falls back to the file instead. It is created by the preview action as a page located by its document, it carries the workspace-relative path copy the editor's path header owned, and closing it revokes the grant that made the document readable while a URL tab closing beside it revokes nothing. Chrome persisted by builds that made previews editor tabs is dropped on restore rather than coming back naming a surface no restore can produce, and the ordinary editor tab for the same document is left alone. A document tab is held back at the mobile publish boundary — no client holds its grant, and the wire has no tab kind for it — while an ordinary browser tab beside it still publishes. It is held back from the group projection that publishes tab order, recency and group activity as well as from the tab list itself, so no published group names a tab the phone is never sent. A browser page can be located by a workspace document instead of a URL, and the document is the whole of its stored identity. The grant and the orca-preview URL that document is served over are minted when the page mounts and replaced by a hard reload, so neither is ever written to the page's url, mirrored onto its tab, persisted or published: such a page's url is the blank URL from creation through restore, including when a session written elsewhere carries a grant URL in, and what the session carries is the worktree and path a restored page mints afresh against today's owners. Every door onto a page's url holds that line — creation, the title update, and the navigation commit alike — so a report about a document page cannot give it a URL it never had, and the title fallback and the loading affordance follow the url each door actually wrote. The mirror carries the document too, so a tab entry cannot go on naming a document its active page has left. Every guest in the app is policy-attached through one door: a workspace document takes a restricted profile there rather than a separate installer beside it, so the attachment bookkeeping that door owns — what registration refuses, and what teardown frees — covers a preview on the same terms as a browsing page, and a preview takes none of the browsing machinery that door installs. That authority answers from the moment the embedder hands the guest over rather than only after a later navigation: the guest binds to the grant it is already showing, so the tools reach the document the reader opened and not just one they navigated to. A read the host reports as truncated or over-cap is refused rather than served partially, and a document outside the paired worktree is refused with a message naming that boundary instead of a bare read failure. The rendered document reaches nothing off-machine on its own: every served response carries a self-only content security policy, the preview session cancels any request that is not in-document, subframes cannot navigate outside the grant, a guest no document has yet bound to a grant may not navigate at all, the guest gathers no ICE candidates, and an SSH path that canonicalizes outside the grant root is refused before it is read. The one route out is a link the reader presses: a trusted click on an anchor, reported by the preview's own preload from a guest still bound to a live grant, leaves through the configured browser destination and captured source route — and only after the reader confirms the exact destination URL, so a document cannot spend a single stray press exfiltrating what it can read into a link it authored. The preview hands its guest that focus itself whenever it is the surface the reader is in — a browsing page gets it from the chrome around it, and a preview has no chrome to get it from — and it does so only then, so a preview mounted behind a terminal or an editor never takes the keyboard from what the reader is actually in. It offers again when the window itself takes focus back and nothing in the embedder has claimed that focus, because another app coming to the front lands focus on the embedder rather than the guest and the route out would otherwise stay shut until something remounted the pane — while the same window focus also arrives when the reader presses a tab, that being the guest's own blur returning, and taking focus back from there would fight the reader for their own click. Nothing else does. A navigation or popup the document starts by itself is swallowed whatever else is happening, including immediately after a genuine press elsewhere in the document, so a page that can read its grant cannot hand it to a browser tab; a middle click opens nothing; and a fragment link is answered inside the document. A preview attach carries the preview preload and no renderer-supplied one, and no other attach path can acquire it. A subresource the workspace will not send degrades the document to a notice naming that file, never to a failure panel over a page that rendered. A grant outlives neither the tab that owns it nor the renderer document that minted it, and only the trusted renderer can mint or revoke one. For the browser creations this gate still owns, owner-pinned creation returns the canonical host page identity before navigation readiness; delayed navigation cannot turn a created page into an unidentifiable failure or a duplicate retry. Capability rejection before host mutation must preserve the original error, issue no RPC, surface a failure toast, and remove only a caller-declared newly-created empty split. Post-create reconciliation failure requires exact rollback; ambiguous rollback rejects without local fallback.", - "oracle": "Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2090 (sources2088/2089): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2086 (sources2082/2083): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2076 (sources2073/2074): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime-tests/terminal-handles-part-02.spec.ts: recovers a moved SSH pane through the tab it now sits in, not the one its lease froze; reports a plain expired orphan; does not report a pane whose only recent lease was superseded; does not report a pane whose only recent lease had its relay id recycled; picks the eligible orphan over a superseded predecessor that matches first; collects the same tabs the per-tab reader reports, in one sweep of the leases; reports no candidate when no lease names any of the worktree tabs. src/main/runtime/orca-runtime-tests/runtime-availability.spec.ts: starts unavailable with no authoritative window; reports the configured Windows terminal shell on status; reports floating workspace availability from settings on status; polls floating tabs with targeted PTY liveness and no repo/provider inventory; hydrates persisted tabs when the store cannot report repos; advertises browser screencast only when a renderer window is available; routes mobile Codex reset consumption through the account mutation coordinator; maps a definite pre-provider rejection into an authoritative current snapshot. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Frozen current literal-import graph reaches these changed test bytes; unresolved local and computed edges remain debt, and current reachability is not historical execution or equivalent replacement evidence. Historical prior account (preserved verbatim): Audit2043: Remove the registration-wait, webview-security, preview-authorization, guest-lifecycle and grant-IPC unit suites and the sibling-directory assertion reference. Runtime and browser capability consumers also lose removed imported examples. Remaining document-policy, file-reader and grant-registry assertions do not replace those alarms. Preserve the 27 independent dated receipts at their original unchanged selectors; reduced prospective unit selectors have no fresh result or equivalent replacement claim. Historical prior account (preserved verbatim): Audit1973: Delete the browser RPC forwarding/schema/scalar suite and its prospective selector. Preserve all27 unrelated dated receipts; no actual browser operation alarm is replaced. Whole original changed dated receipts are retired, never narrowed or transferred. This metadata review claims no fresh execution, equivalent replacement, provider/PTY, live remote/mobile, rendered, cross-platform, soak or measured-budget result. Historical prior account (preserved verbatim): Audit1925 (sources1922/1923): The complete terminal-file-link-actions suite is removed. Lose supplied local/remote menu-row inventories, browser label/order/download/reveal callback forwarding, platform-copy and source-group pinning examples. No OS reveal/download, real remote preview or browser navigation was exercised; the other real document-preview sources are not equivalent replacements. Preserve meaningful remaining selectors/assertions and unchanged dated receipts within their original scope. Reduced selectors have no fresh gate execution evidence in this metadata packet. No equivalent replacement, physical watcher/PTY/provider, live SSH/remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): Audit1709 retires changed-source assertion and execution scope without equivalent replacement coverage. Existing unchanged-selector receipts remain scoped to their original sources. Historical prior-source oracle: Audit1687 retires changed-source assertion and execution scope without equivalent replacement coverage. Existing unchanged-selector receipts remain scoped to their original sources. Historical prior-source oracle: Audit1421 narrows renderer unit coverage as recorded in coverageNotes. Prior oracle descriptions are historical for the changed suite. The retained unchanged-source receipts are the only current execution evidence; reduced-source assertions await validation. Historical oracle account (not a current claim for changed sources): Retained unchanged-selector receipts are the only current execution evidence. Reduced-source assertions await validation. Historical prior oracle: The retained unchanged-source receipts are the only current execution evidence; reduced-source assertions await validation. Historical oracle account (not a current claim for changed sources): In paired Electron, write an HTML fixture that declares its own title on the host, invoke the Explorer preview action on the client, and require the document text to be readable out of the orca-preview guest before judging any absence. With that presence established, require the client to hold exactly one browser workspace more than its baseline and that workspace to be the document one: page and tab url blank, the document path mirrored onto both, the tab named by the document's title, the chip naming the file, no editor row of the retired preview species anywhere, and the guest URL carrying the orca-preview scheme. Ask the host through its own page registry as well as through the tab snapshot, and in the same run open an ordinary URL browser tab from the same client and require that one to arrive in both — the presence precondition without which “the host gained nothing” is satisfied just as well by an oracle that cannot see browser pages at all. Require the preview to sit in a group other than the source editor's while the active group and tab remain the source editor's. Then click away to the terminal, click the preview tab, require it to reactivate and still render, close it with its own X, and require the document tab to be gone while the host still holds only the URL tab and the source group, source editor and terminal survive. Quit the client with a document tab open and relaunch it on the same profile: require the same workspace row to come back, blank and named by the document, rendering the document again over a grant URL that differs from the one that was quit, with no preview-scheme or document-named page anywhere in what the host holds. Prove the halves are live by flipping one product property at a time and requiring the run to fail: publish document workspaces to the host like ordinary ones, and stop mirroring the document onto the workspace row. Have the fixture document attempt its own egress on every load — an unattended window.open and location.href to an off-machine URL, plus an inline ICE gathering probe — and require the same baseline counts and a candidate count of zero, so the document's own attempts are measured rather than assumed. Then, as a separate phase after the close oracle has already run, bring the client window to the front, press the document's heading with a real mouse event, and require the document to report that the same press drove it to attempt a second window.open and location.href while both browser counts stay at that phase's baseline and nothing routes — the case a recent-input gate cannot distinguish from the press's own effect. Only then press the target=_blank link with a real mouse event and require both a recorded routing call that returned success and a browser count above that baseline, with the preview tab still open. Drive the preload's click policy as a unit oracle over a real document: a dispatched click, a trusted press on an external anchor, an anchor reached through what it wraps, an SVG animated href, a sibling preview link, fragment and percent-encoded fragment targets, a bare hash, and a middle click. Create a browser page located by a workspace document, handing creation a live grant URL, and require its stored url, its mirrored tab url and the written session payload all to be blank with no orca-preview string anywhere in what was written, while an ordinary page created the same way keeps the URL it was given and asks for the address bar the document page never does. Parse the written page and tab through the session schema and require the document to survive both halves. Hydrate them back and require the document page to return blank and still named — including when its page row was salvaged away and only the tab's own copy remains, and when a foreign session carried a grant URL into both rows. Drive the mirror across a page switch out of the document and back, and across a repair in which the document is the only mirrored field that differs. Name a document page from its document and require the tab to take that name, name it with an empty title and require the file, name it with a live grant URL and require the file again with no preview scheme anywhere in the written session, and require an ordinary blank browser tab beside it to still be called New Tab. Dispatch a title update out of a rendered preview's own guest and require it to reach the page state while the identity chip still reads the document's workspace-relative path. Attach a browsing guest and a workspace-document guest through the same method in one run and require the browsing one to take clicked-link routing, popup handling and auth-identity detach tracking while the document guest takes none of them, stays inside the grant it is showing, denies every window it asks for, and is dropped from the page-keyed document registry by the same teardown that frees its id for a later attach. Register a browsing guest and attach a workspace-document guest in one run against the real manager, require the one door to answer each page with the guest of its own half, and require the document page to be absent from the browsing map and from its enumeration. Drive both browsing registration entry points with a page the document half already holds and require them to register nothing, and drive the mint channel with a page the browsing half already holds and require it to refuse; and drive the offscreen one with a guest that is missing and with one already destroyed, requiring the same refusal. Arm a grab on a live preview target, drive the unregister channel at that same target in the window before the queued operation runs, and require the grab to reach the guest anyway — then drive the same sequence for an ordinary browser page and require its grab state to be disposed after all. Hold one viewport-bridge op open, queue a second behind it, swap the page's guest while that second op waits, and require the injection to land in the guest the page has then. Revoke a grant after a tool has run against its page and require that page's grab state to be cancelled and disposed. Ask a tool for a document page whose guest has not attached, require the request to park in the registration wait, attach the guest, and require the same request to arm on it; require a page nothing ever renders to answer not-ready once that wait elapses. With a document open, ask a tool for a browsing page id and require it to be answered by the browsing half or not at all, with the same channel reaching the document guest under the page it really renders. Drive open-externally for a document whose per-file owner is remote while the workspace-scoped owner is unresolved, for a runtime-owned worktree whose preview tab carries no runtime id of its own, and for a worktree that resolves no runtime owner while the tab still carries one, requiring the download route in each; and for an owner that cannot be resolved at all, and for an unknown workspace root while nothing names another host, requiring a refusal that neither opens nor downloads. Drive the headless backend with a page the document half already holds and require it to reject, destroy the window, and unregister nothing — then shut the backend down and require it still to have unregistered nothing. Navigate a bound preview guest at a second grant through both latch events and require it to stay on the grant it bound to. Mount a preview while a renderer drag is already in flight and require its guest to be click-through at the moment it is appended, not a turn later. Render the editor panel shell in each remaining tab mode and require the path header exactly where the surface does not already name itself. Drive the preview action and require a browser tab located by the document rather than an editor tab, require a second open of the same document to activate the tab it is already in, and require closing that tab to revoke its grant while a URL tab closed beside it revokes none. Publish a worktree holding a document tab and a URL tab and require only the URL tab to reach the mobile snapshot. Install the shared partition policies for a preview partition and for an ordinary browsing partition in the same run, fire each one's own will-download listener, and require the preview's to cancel while the browsing one still reaches the download router — then require the preview protocol installer to be what asks for that deny. In the same run, require the cancelled download to raise a reader-facing notice and the routed one to raise none. require the guest registry to name the bound grant for a live preview guest and nothing for a contents that is not one, has committed no document, or is gone. Drive the shell with a refusal and require one fixed sentence, still one row after three more refusals, standing beside an asset failure rather than being counted with it, gone behind the failure panel, and ignored when it names another preview's grant. Drive the main-side report gate directly for a sender that is no preview guest, a guest with no bound or a revoked grant, a genuine press Electron's webview focus flag misreports as unfocused, and non-web URLs; drive the reader-facing confirmation for accept, cancel, and a confirmed tab the browser refuses; and drive will-attach-webview in both preload directions. Run the per-owner reader, grant-containment, scheme-admission, guest-policy, and plan-routing contracts as unit oracles, including a host-reported truncation, an over-cap binary, and an out-of-worktree paired path. Drive the reader-facing component with the payloads the reader can actually produce — the entry document fails only as truncated or unreadable, a subresource additionally as a refused format — and require the asset case to leave the guest mounted. Drive the closed-tab cleanup hook, the window installer, and the grant IPC handlers directly, requiring the grant to be released when the preview tab closes, cleared at window creation and on a cross-document main-frame navigation, and refused to any sender that is not the trusted renderer. For the browser creations this gate still owns, run the unchanged contract oracle for direct create and side-preview callers with absent status, unknown capabilities, and a mixed-version host, requiring the original unsupported error or visible toast, zero RPCs, and no retained new split; hold a real navigation response beyond the 15-second client deadline after host creation and require the first RPC to return the exact host inventory page ID, one host page, and no retry; repeat reconciliation faults against headless serve and retain the separate exact-page reconciliation rollback oracle. Audit2452 removes the whole fake-effect browser-close routing suite. Active selectors and assertion references no longer select it. Its requested-worktree default close, sibling-page close and explicit missing-page typed reply alarms are intentionally retired without equivalent replacement. Prior dated receipts remain unchanged and scoped to their original sources; no fresh execution of the reduced gate, rendered browser, live remote, mobile or cross-platform validation is claimed.", + "oracle": "Audit3108: doc-preview-grants.test.ts now retains only the stale grant-rejection race: a late rejected grant request must not evict a newer grant registry entry, witnessed by later revocation of grant-2. Retire stable minted-location and outside-workspace POSIX/Windows request-projection alarms without replacement. The direct nonempty grant selector remains unchanged; no real grant-server/file authorization, SSH/HTML delivery or native-focus result is claimed. Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2090 (sources2088/2089): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2086 (sources2082/2083): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2076 (sources2073/2074): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime-tests/terminal-handles-part-02.spec.ts: recovers a moved SSH pane through the tab it now sits in, not the one its lease froze; reports a plain expired orphan; does not report a pane whose only recent lease was superseded; does not report a pane whose only recent lease had its relay id recycled; picks the eligible orphan over a superseded predecessor that matches first; collects the same tabs the per-tab reader reports, in one sweep of the leases; reports no candidate when no lease names any of the worktree tabs. src/main/runtime/orca-runtime-tests/runtime-availability.spec.ts: starts unavailable with no authoritative window; reports the configured Windows terminal shell on status; reports floating workspace availability from settings on status; polls floating tabs with targeted PTY liveness and no repo/provider inventory; hydrates persisted tabs when the store cannot report repos; advertises browser screencast only when a renderer window is available; routes mobile Codex reset consumption through the account mutation coordinator; maps a definite pre-provider rejection into an authoritative current snapshot. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Frozen current literal-import graph reaches these changed test bytes; unresolved local and computed edges remain debt, and current reachability is not historical execution or equivalent replacement evidence. Historical prior account (preserved verbatim): Audit2043: Remove the registration-wait, webview-security, preview-authorization, guest-lifecycle and grant-IPC unit suites and the sibling-directory assertion reference. Runtime and browser capability consumers also lose removed imported examples. Remaining document-policy, file-reader and grant-registry assertions do not replace those alarms. Preserve the 27 independent dated receipts at their original unchanged selectors; reduced prospective unit selectors have no fresh result or equivalent replacement claim. Historical prior account (preserved verbatim): Audit1973: Delete the browser RPC forwarding/schema/scalar suite and its prospective selector. Preserve all27 unrelated dated receipts; no actual browser operation alarm is replaced. Whole original changed dated receipts are retired, never narrowed or transferred. This metadata review claims no fresh execution, equivalent replacement, provider/PTY, live remote/mobile, rendered, cross-platform, soak or measured-budget result. Historical prior account (preserved verbatim): Audit1925 (sources1922/1923): The complete terminal-file-link-actions suite is removed. Lose supplied local/remote menu-row inventories, browser label/order/download/reveal callback forwarding, platform-copy and source-group pinning examples. No OS reveal/download, real remote preview or browser navigation was exercised; the other real document-preview sources are not equivalent replacements. Preserve meaningful remaining selectors/assertions and unchanged dated receipts within their original scope. Reduced selectors have no fresh gate execution evidence in this metadata packet. No equivalent replacement, physical watcher/PTY/provider, live SSH/remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): Audit1709 retires changed-source assertion and execution scope without equivalent replacement coverage. Existing unchanged-selector receipts remain scoped to their original sources. Historical prior-source oracle: Audit1687 retires changed-source assertion and execution scope without equivalent replacement coverage. Existing unchanged-selector receipts remain scoped to their original sources. Historical prior-source oracle: Audit1421 narrows renderer unit coverage as recorded in coverageNotes. Prior oracle descriptions are historical for the changed suite. The retained unchanged-source receipts are the only current execution evidence; reduced-source assertions await validation. Historical oracle account (not a current claim for changed sources): Retained unchanged-selector receipts are the only current execution evidence. Reduced-source assertions await validation. Historical prior oracle: The retained unchanged-source receipts are the only current execution evidence; reduced-source assertions await validation. Historical oracle account (not a current claim for changed sources): In paired Electron, write an HTML fixture that declares its own title on the host, invoke the Explorer preview action on the client, and require the document text to be readable out of the orca-preview guest before judging any absence. With that presence established, require the client to hold exactly one browser workspace more than its baseline and that workspace to be the document one: page and tab url blank, the document path mirrored onto both, the tab named by the document's title, the chip naming the file, no editor row of the retired preview species anywhere, and the guest URL carrying the orca-preview scheme. Ask the host through its own page registry as well as through the tab snapshot, and in the same run open an ordinary URL browser tab from the same client and require that one to arrive in both — the presence precondition without which “the host gained nothing” is satisfied just as well by an oracle that cannot see browser pages at all. Require the preview to sit in a group other than the source editor's while the active group and tab remain the source editor's. Then click away to the terminal, click the preview tab, require it to reactivate and still render, close it with its own X, and require the document tab to be gone while the host still holds only the URL tab and the source group, source editor and terminal survive. Quit the client with a document tab open and relaunch it on the same profile: require the same workspace row to come back, blank and named by the document, rendering the document again over a grant URL that differs from the one that was quit, with no preview-scheme or document-named page anywhere in what the host holds. Prove the halves are live by flipping one product property at a time and requiring the run to fail: publish document workspaces to the host like ordinary ones, and stop mirroring the document onto the workspace row. Have the fixture document attempt its own egress on every load — an unattended window.open and location.href to an off-machine URL, plus an inline ICE gathering probe — and require the same baseline counts and a candidate count of zero, so the document's own attempts are measured rather than assumed. Then, as a separate phase after the close oracle has already run, bring the client window to the front, press the document's heading with a real mouse event, and require the document to report that the same press drove it to attempt a second window.open and location.href while both browser counts stay at that phase's baseline and nothing routes — the case a recent-input gate cannot distinguish from the press's own effect. Only then press the target=_blank link with a real mouse event and require both a recorded routing call that returned success and a browser count above that baseline, with the preview tab still open. Drive the preload's click policy as a unit oracle over a real document: a dispatched click, a trusted press on an external anchor, an anchor reached through what it wraps, an SVG animated href, a sibling preview link, fragment and percent-encoded fragment targets, a bare hash, and a middle click. Create a browser page located by a workspace document, handing creation a live grant URL, and require its stored url, its mirrored tab url and the written session payload all to be blank with no orca-preview string anywhere in what was written, while an ordinary page created the same way keeps the URL it was given and asks for the address bar the document page never does. Parse the written page and tab through the session schema and require the document to survive both halves. Hydrate them back and require the document page to return blank and still named — including when its page row was salvaged away and only the tab's own copy remains, and when a foreign session carried a grant URL into both rows. Drive the mirror across a page switch out of the document and back, and across a repair in which the document is the only mirrored field that differs. Name a document page from its document and require the tab to take that name, name it with an empty title and require the file, name it with a live grant URL and require the file again with no preview scheme anywhere in the written session, and require an ordinary blank browser tab beside it to still be called New Tab. Dispatch a title update out of a rendered preview's own guest and require it to reach the page state while the identity chip still reads the document's workspace-relative path. Attach a browsing guest and a workspace-document guest through the same method in one run and require the browsing one to take clicked-link routing, popup handling and auth-identity detach tracking while the document guest takes none of them, stays inside the grant it is showing, denies every window it asks for, and is dropped from the page-keyed document registry by the same teardown that frees its id for a later attach. Register a browsing guest and attach a workspace-document guest in one run against the real manager, require the one door to answer each page with the guest of its own half, and require the document page to be absent from the browsing map and from its enumeration. Drive both browsing registration entry points with a page the document half already holds and require them to register nothing, and drive the mint channel with a page the browsing half already holds and require it to refuse; and drive the offscreen one with a guest that is missing and with one already destroyed, requiring the same refusal. Arm a grab on a live preview target, drive the unregister channel at that same target in the window before the queued operation runs, and require the grab to reach the guest anyway — then drive the same sequence for an ordinary browser page and require its grab state to be disposed after all. Hold one viewport-bridge op open, queue a second behind it, swap the page's guest while that second op waits, and require the injection to land in the guest the page has then. Revoke a grant after a tool has run against its page and require that page's grab state to be cancelled and disposed. Ask a tool for a document page whose guest has not attached, require the request to park in the registration wait, attach the guest, and require the same request to arm on it; require a page nothing ever renders to answer not-ready once that wait elapses. With a document open, ask a tool for a browsing page id and require it to be answered by the browsing half or not at all, with the same channel reaching the document guest under the page it really renders. Drive open-externally for a document whose per-file owner is remote while the workspace-scoped owner is unresolved, for a runtime-owned worktree whose preview tab carries no runtime id of its own, and for a worktree that resolves no runtime owner while the tab still carries one, requiring the download route in each; and for an owner that cannot be resolved at all, and for an unknown workspace root while nothing names another host, requiring a refusal that neither opens nor downloads. Drive the headless backend with a page the document half already holds and require it to reject, destroy the window, and unregister nothing — then shut the backend down and require it still to have unregistered nothing. Navigate a bound preview guest at a second grant through both latch events and require it to stay on the grant it bound to. Mount a preview while a renderer drag is already in flight and require its guest to be click-through at the moment it is appended, not a turn later. Render the editor panel shell in each remaining tab mode and require the path header exactly where the surface does not already name itself. Drive the preview action and require a browser tab located by the document rather than an editor tab, require a second open of the same document to activate the tab it is already in, and require closing that tab to revoke its grant while a URL tab closed beside it revokes none. Publish a worktree holding a document tab and a URL tab and require only the URL tab to reach the mobile snapshot. Install the shared partition policies for a preview partition and for an ordinary browsing partition in the same run, fire each one's own will-download listener, and require the preview's to cancel while the browsing one still reaches the download router — then require the preview protocol installer to be what asks for that deny. In the same run, require the cancelled download to raise a reader-facing notice and the routed one to raise none. require the guest registry to name the bound grant for a live preview guest and nothing for a contents that is not one, has committed no document, or is gone. Drive the shell with a refusal and require one fixed sentence, still one row after three more refusals, standing beside an asset failure rather than being counted with it, gone behind the failure panel, and ignored when it names another preview's grant. Drive the main-side report gate directly for a sender that is no preview guest, a guest with no bound or a revoked grant, a genuine press Electron's webview focus flag misreports as unfocused, and non-web URLs; drive the reader-facing confirmation for accept, cancel, and a confirmed tab the browser refuses; and drive will-attach-webview in both preload directions. Run the per-owner reader, grant-containment, scheme-admission, guest-policy, and plan-routing contracts as unit oracles, including a host-reported truncation, an over-cap binary, and an out-of-worktree paired path. Drive the reader-facing component with the payloads the reader can actually produce — the entry document fails only as truncated or unreadable, a subresource additionally as a refused format — and require the asset case to leave the guest mounted. Drive the closed-tab cleanup hook, the window installer, and the grant IPC handlers directly, requiring the grant to be released when the preview tab closes, cleared at window creation and on a cross-document main-frame navigation, and refused to any sender that is not the trusted renderer. For the browser creations this gate still owns, run the unchanged contract oracle for direct create and side-preview callers with absent status, unknown capabilities, and a mixed-version host, requiring the original unsupported error or visible toast, zero RPCs, and no retained new split; hold a real navigation response beyond the 15-second client deadline after host creation and require the first RPC to return the exact host inventory page ID, one host page, and no retry; repeat reconciliation faults against headless serve and retain the separate exact-page reconciliation rollback oracle. Audit2452 removes the whole fake-effect browser-close routing suite. Active selectors and assertion references no longer select it. Its requested-worktree default close, sibling-page close and explicit missing-page typed reply alarms are intentionally retired without equivalent replacement. Prior dated receipts remain unchanged and scoped to their original sources; no fresh execution of the reduced gate, rendered browser, live remote, mobile or cross-platform validation is claimed.", "commands": [ "pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/browser/client-pages/orca-runtime-browser.test.ts src/renderer/src/runtime/web-session-tabs-sync/navigation/web-session-tabs-sync-focus-intent.test.ts src/renderer/src/runtime/web-session-tabs-sync/placement/web-session-tabs-sync-browser-tabs.test.ts", "pnpm exec vitest run --config config/vitest.config.ts src/main/browser/document-preview/doc-preview-grant-registry.test.ts src/main/browser/document-preview/doc-preview-file-reader.test.ts src/main/browser/document-preview/doc-preview-guest-policy.test.ts src/main/browser/document-preview/doc-preview-failure-notice.test.ts src/shared/document-preview/doc-preview-scheme.test.ts src/renderer/src/lib/browser/documents/doc-preview-grants.test.ts src/renderer/src/components/browser-pane/workspace-doc/doc-preview-external-link-confirmation.test.ts", @@ -4949,7 +4955,8 @@ "D01 candidate audit retires this complete dated receipt because a named test source changes in the candidate overlay. It supplies no new execution or equivalent-coverage claim. Original receipt verbatim:\n{\n \"date\": \"2026-08-27\",\n \"runner\": \"local\",\n \"platform\": \"macos\",\n \"command\": \"pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/browser-pane/workspace-doc/HtmlDocPreview.failure-message.test.tsx\",\n \"result\": \"failed\",\n \"durationSeconds\": 1.27,\n \"summary\": \"Candidate with the sole delta that every failure sets the blocking reason, asset or not, failed 4/14 on the asset-notice assertions — the same mutant the retired 2026-08-26 record measured at 3/10, re-run at the relocated path. A refused subresource must name itself over a document that stays mounted; only the entry document may take the page away.\",\n \"currentCommand\": \"pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/browser-pane/workspace-doc/HtmlDocPreview.failure-message.test.tsx\"\n }", "D01 candidate audit retires this complete dated receipt because a named test source changes in the candidate overlay. It supplies no new execution or equivalent-coverage claim. Original receipt verbatim:\n{\n \"date\": \"2026-08-27\",\n \"runner\": \"local\",\n \"platform\": \"macos\",\n \"command\": \"pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/browser-pane/workspace-doc/HtmlDocPreview.failure-message.test.tsx\",\n \"result\": \"passed\",\n \"durationSeconds\": 1.54,\n \"summary\": \"14/14 on the reader-facing failure suite at its relocated path. This and the red run below replace the 2026-08-26 pair recorded against the pre-relocation path (10/10 green, 3/10 red), re-measured today so the entry/subresource split keeps a red half rather than only a green one.\",\n \"currentCommand\": \"pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/browser-pane/workspace-doc/HtmlDocPreview.failure-message.test.tsx\"\n }", "D01 final candidate whole-registration policy removes retired module selectors and obsolete assertion descriptions prospectively. Existing unaffected receipts retain their original scope; reduced selectors have no new execution or equivalent replacement claim. Retired named modules: [\"src/preload/doc-preview-link-interception.test.ts\",\"src/renderer/src/components/browser-pane/workspace-doc/HtmlDocPreview.failure-message.test.tsx\"]. Retired compound assertion refs, preserved as historical data: [{\"file\":\"src/renderer/src/components/browser-pane/workspace-doc/doc-preview-external-link-confirmation.test.ts\",\"assertions\":[\"an external preview link shows the reader its exact destination and becomes a browser tab only after confirmation\",\"a declined confirmation opens nothing, and a confirmed tab that is refused or fails outright surfaces instead of being dropped\"]}]", - "Audit2452 removes the whole fake-effect browser-close routing suite. Active selectors and assertion references no longer select it. Its requested-worktree default close, sibling-page close and explicit missing-page typed reply alarms are intentionally retired without equivalent replacement. Prior dated receipts remain unchanged and scoped to their original sources; no fresh execution of the reduced gate, rendered browser, live remote, mobile or cross-platform validation is claimed. Retired assertion reference: {\"file\":\"src/renderer/src/hooks/useIpcEvents-close-routing-browser-pages.test.ts\",\"assertions\":[\"closing an absent renderer page returns browser_tab_not_found instead of an untyped failure\"]}" + "Audit2452 removes the whole fake-effect browser-close routing suite. Active selectors and assertion references no longer select it. Its requested-worktree default close, sibling-page close and explicit missing-page typed reply alarms are intentionally retired without equivalent replacement. Prior dated receipts remain unchanged and scoped to their original sources; no fresh execution of the reduced gate, rendered browser, live remote, mobile or cross-platform validation is claimed. Retired assertion reference: {\"file\":\"src/renderer/src/hooks/useIpcEvents-close-routing-browser-pages.test.ts\",\"assertions\":[\"closing an absent renderer page returns browser_tab_not_found instead of an untyped failure\"]}", + "Audit3108: doc-preview-grants.test.ts now retains only the stale grant-rejection race: a late rejected grant request must not evict a newer grant registry entry, witnessed by later revocation of grant-2. Retire stable minted-location and outside-workspace POSIX/Windows request-projection alarms without replacement. The direct nonempty grant selector remains unchanged; no real grant-server/file authorization, SSH/HTML delivery or native-focus result is claimed." ], "demotionRule": "Demote if a paired HTML preview creates a browser workspace on either side, renders from anything other than the orca-preview scheme, serves a read the host reported as truncated or over-cap, serves a document without the self-only content security policy, lets the preview session carry an off-machine request, reads an SSH path that canonicalizes outside its grant root, steals focus from the source editor when it opens, removes unrelated editor or terminal state on close, hides a document that rendered because one subresource was refused, leaves a grant readable after the tab or renderer that owns it is gone, mints one for a sender that is not the trusted renderer, opens a browser tab for a navigation the document started with no one at the keyboard, or lets the guest gather an ICE candidate; or if a paired browser creation this gate still owns produces duplicate client or host identities or loses its requested split." }, @@ -8557,13 +8564,13 @@ "providers": ["paired-runtime", "ssh"], "coveredPlatforms": ["macos", "linux"], "coveredProviders": [], - "coverageNotes": "Audit3096 source-only reduction (3087/3088): retire 69 authored/76 expanded cases, including complete recovery-portals and reconnect-banner suites. Intentionally lose dead/default TUI replay, generated alternate-frame style composition, reset/mode/dimension and legacy missing-mode-boundary alarms, UI notice/action/reveal policies, and isolated recovery lifecycle variants, without equivalent replacement. Retained registrations and callbacks are unchanged; headless cells are not pixels, and no fresh runtime, host, SSH, WSL, rendered-app or performance result is claimed. Audit3086 source-only reduction (3079/3080/3081): intentionally retire 93 authored/100 expanded mock-boundary cases, including the complete spawn-errors and SSH reconnect overlay suites, without replacement. Retired alarms include spawn classification/ownership, reply ceilings and renderer-write failure recovery, disconnect/detach fencing branches, authority facts, and overlay retry/visibility wiring. Retained callbacks are unchanged; no fresh execution, real PTY/SSH, rendered UI, or performance result is claimed. The direct side-effect-facts selector retains six cases: replay exclusion, live sequence handling, stale disposer ownership, one handoff drain, drain-before-snapshot, and stale replacement-snapshot refusal. Successful current-entry snapshot application is not witnessed by the retained snapshot case. Audit2432: The broad unit command loses the isolated BranchPicker open-change notification sample. Its unique true/false callback alarm is intentionally retired; reopening/status-refresh behavior was not exercised. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2425: The broad unit command loses the workspace-copy-status supplied readError forwarding sample. It did not exercise the branch-switch blocking promised by its title. This alarm is intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2417: The broad unit command loses two ordinary clean Git cherry-pick/revert success samples and two terminal startup foreground-read work-budget samples. These unique alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2412: The broad unit command loses the whole six-case fake-React-hook scroll-anchor suite, two generic draft-retention samples, a simple new-agent order sample, a real history-publication batching-count sample, an unmounted handoff abort/timer sample and three basic WSL preview/error samples. These alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2404: The broad unit command loses the standalone share-name lookup 503 propagation suite, initial deletion placement-kind sample, direct changed-mtime stale sample, first-pass rollback existence example and abandoned-preparation directory sample. These exact alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2397 review amendment: The broad unit command loses three standalone suites, two partial-case definitions and two URL table rows across package/download/placement tests. Keep initial wrong-port authorization, modified independent-copy digest refusal and abort-after-begin cancellation dispatch. The remaining alarms are deliberately retired; no equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2393 current-parent refresh2401: Remove the basic skill-install service alias sample and original public managed-remove receiptless refusal case. Preserve the upstream request ownership suite and transaction interruption coverage. No equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2389: The broad unit command loses the missing-preview suite, plain-global destination sample and prepublished-receipt recovery example. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2385: The broad unit command loses four authored walker/staging/protocol examples (six expanded cases); no equivalent replacement or fresh validation is claimed for the reduced suite. Audit2383: The unscoped Vitest command no longer includes the removed Antigravity catalogue suite; its exact provider-root/owner example has no equivalent replacement or fresh validation claim. Audit2377/2381: The unscoped Vitest command includes the reduced bundled-skill and native-discovery suites; the eight removed backup/legacy/catalogue/symlink/SSH-builder examples have no replacement-equivalence or fresh validation claim here. Audit2162: Reduced inventory-authority source intentionally loses the examples recorded in knownGaps; historical execution is not validation of changed bytes. Historical prior account (preserved verbatim): Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2090 (sources2088/2089): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2086 (sources2082/2083): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2076 (sources2073/2074): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime-tests/terminal-handles-part-02.spec.ts: recovers a moved SSH pane through the tab it now sits in, not the one its lease froze; reports a plain expired orphan; does not report a pane whose only recent lease was superseded; does not report a pane whose only recent lease had its relay id recycled; picks the eligible orphan over a superseded predecessor that matches first; collects the same tabs the per-tab reader reports, in one sweep of the leases; reports no candidate when no lease names any of the worktree tabs. src/main/runtime/orca-runtime-tests/runtime-availability.spec.ts: starts unavailable with no authoritative window; reports the configured Windows terminal shell on status; reports floating workspace availability from settings on status; polls floating tabs with targeted PTY liveness and no repo/provider inventory; hydrates persisted tabs when the store cannot report repos; advertises browser screencast only when a renderer window is available; routes mobile Codex reset consumption through the account mutation coordinator; maps a definite pre-provider rejection into an authoritative current snapshot. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Frozen current literal-import graph reaches these changed test bytes; unresolved local and computed edges remain debt, and current reachability is not historical execution or equivalent replacement evidence. Historical prior account (preserved verbatim): Audit2003: Remove SSH/absent-inventory attach refusal, later-subscriber retry, no-view adoption/takeback, provider-tail/unknown-read projections, failed-keystroke retry and simpler loss reattach examples. Keep the existing-subscriber inventory-ready retry alias only at its retained callback, plus retained held-input cancellation/replacement and overlapping attach/loss fences. The inventory driver also loses the whole empty-worktree-publication registration and folder-host/unverifiable scalar examples. Retire the entire dated10-case attach receipt; retain16 independent receipts only in their original scopes. No retained-memory or real-daemon measurement follows from supplied provider inventories. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, physical provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1991: Remove initial-snapshot sequence-domain, limited-tail/truncation and unknown-output-sequence aliases whose callbacks are removed. The source retains partial-chunk replay and requested-snapshot retry/admission at supplied snapshot/data seams, not equivalent replacement or measured retained-memory proof. Preserve the existing stream/pending-wait capacity aliases only to their retained owning multiplex callbacks with supplied PTY resolutions. Removing the sibling-PTY heartbeat dedup work-count sample does not establish a new decorative fanout budget; the unrelated-PTY cancellation fence survives. Preserve17 unrelated dated receipts. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, physical provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1983: Remove the reasonless-close selector and narrow census aliases to actual retained runtime and injected-inventory callbacks. The removed synthetic census-dedup and isolated pre-boundary timing cases receive no replacement credit; preserve17 unrelated dated receipts. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1939 (sources1934/1935): Delete the synthetic watcher-synchronization and partial-reconciliation suites. Retire all affected host-fact, capability-owner, activation-residue and retention-cap aliases because the remaining callbacks do not establish those full claims. Keep exact local hook/timer, byte-stream side effects, exit/disposal, scroll-intent cleanup and deterministic local rank/TTL progression callbacks within their mocked-host scope. No physical paired-host retention, resource budget or equivalent replacement evidence is assigned. The generic broad test command remains a runnable discovery command, never a dated execution receipt. Preserve meaningful remaining selectors/assertions and unchanged dated receipts within their original scope. Reduced selectors have no fresh gate execution evidence in this metadata packet. No equivalent replacement, physical watcher/PTY/provider, live SSH/remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): Audit1931 (sources1928/1929): Delete the complete hook-agent-status projection suite and its two behavioral assertion aliases. Supplied stored hook/title/resume/staleness/rename/question/generation/PTY-retirement/snapshot-version projections are intentionally lost. The separate osc-status-scan gate mentions this source only in existing historical notes and receives no mutation. No measured hidden-output retention, CPU/RSS or resource budget result is claimed by the deleted source or this audit. Preserve meaningful remaining selectors/assertions and unchanged dated receipts within their original scope. Reduced selectors have no fresh gate execution evidence in this metadata packet. No equivalent replacement, physical watcher/PTY/provider, live SSH/remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): Module ownership cleanup retires the modeled cold-park private watcher/render/work-count suites under the current test policy. Their assertions are no longer active evidence. Retained lifecycle tests and headed/headless journeys do not establish equivalent coverage for those removed harness alarms. Audit1640 removes low-value IPC, SSH, workspace and transcript-watcher tests without equivalent replacement coverage. Per-source reviews record retained public refusal, cancellation, execution-host and real-filesystem outcomes with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1634 removes low-value IPC, filesystem and runtime projections, argument inventories and duplicate examples without equivalent replacement coverage. Per-source reviews record retained cancellation, ownership, authorization, filesystem and SQLite boundaries with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1627 removes low-value mocked daemon projections, scalar tables and duplicate terminal examples without equivalent replacement coverage. Per-source reviews record retained terminal content preservation, process ownership refusal and recovery boundaries together with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Retained exact unchanged-source receipts remain the only current execution evidence. Reduced selectors have no fresh execution result. Audit1417 intentionally deletes src/renderer/src/components/terminal-pane/pty-connection-hidden-tui-snapshot-replay.spec.ts: Loses rich hidden snapshot sequence replay/grid resize and forced repaint after hidden snapshot alarms, including live-trigger deduplication. deletes src/renderer/src/components/terminal-pane/terminal-cold-park-verdict-loop.test.tsx: Loses modeled React oscillation alarm; real pane/watchers are not exercised. deletes src/renderer/src/runtime/remote-runtime-terminal-parse-backpressure.test.ts: Loses delayed credit until parsing, malformed frame/unknown stream handling, discarded transformed output recovery and failed ACK rearm alarms. No equivalent replacement coverage or fresh result is claimed. Historical coverage account: Audit1412 changes referenced sources. Retained unchanged-source receipts apply only to their unchanged commands; the reduced selectors have no new execution result. Historical coverage account (not a current claim for changed sources): This audit removes the browser response-after-manual-disconnect example. Its distinct in-flight response fencing alarm is lost; retained queued-call disconnect tests are not an equivalent replacement. Historical commands and results remain historical. Deterministic headed macOS runs launch an isolated Orca desktop server and a separate paired web client. A byte-identical headless run uses an isolated `orca serve` host. Both create six real paired host PTYs with bounded high-output scrollback, prove sustained output while all six client xterms are warm-mounted but hidden causes zero renderer scheduler work, then drive 180 timed real-PTY spinner frames through a second production `session.tabs.subscribeAll` transport and the real Zustand store. Each worktree must publish and apply only its exact initial-working and final-idle titles. Both topologies ordinary-park five xterms without enabling the lossy retention budget, assert bounded cells/heap/timer lag, then restore the bounded authoritative tail exactly once on the original PTY including output produced while parked and continued input/output. The headed oracle additionally keeps every remote target workspace and terminal unmounted in the host renderer before and after client recovery. Production-parity React contracts reproduce and remove the independent cold-park watcher/title feedback loop, including memo-cache discard, StrictMode cleanup replay, detached split-PTY replacement, and the zero-park fast path. A deterministic cross-boundary contract drives 24 real PTY trackers in distinct worktrees through 2,880 decorative spinner and bare-native redraw chunks and counts host publications, serialized bytes, renderer apply calls, and store mutations while preserving exact per-PTY raw chunks and per-worktree semantic transitions. Fake-clock continuation beyond the 30-minute stale boundary requires one deduplicated refresh per worktree every 15 minutes, globally spaced by at least 50 ms, with every mirrored working status still fresh. Exact-identical Pi plus rotating normalized Pi/Grok frames renew coarse working/permission state; rich prompt/tool/question fields retain their original 30-minute lease, and `stateStartedAt`/acknowledgement identity remain stable across title/hook source swaps. A separate headed desktop-client journey relaunches the host main process while retaining the daemon and a daemon-backgrounded PTY, then requires first-observation foreground sync and continued input/output on the same PTY. Unit coverage keeps layout versions out of snapshot output high-waters when a restored snapshot has no output sequence and retries an existing subscriber only after authoritative provider inventory proves the retained PTY exists. Separate headed/headless ACK-starvation tests recover one stalled stream without replacing its PTY. A headed output-drop oracle proves a successful snapshot probe cannot certify a stale live stream when the authoritative PTY sequence advanced beyond the client high-water. Unit coverage requires an unsequenced client to establish a first-probe baseline, remain attached at the same sequence, and recover only after a later probe advances. A capability-disabled run proves legacy hosts retain the prior lossy limit/TTL fallback. Unit tests cover exact-owner capability routing, raw-stream release, singleton side-effect facts with timed handoff cleanup, 64 simultaneous synthetic-title sources with zero decorative client events after convergence, per-client late-subscribe recovery, semantic bell/title transitions, local animation-frame preservation, legacy no-output-pause delivery gating with exact snapshot restore, provider-authoritative snapshots, 128 active streams plus retry after a 129th-stream capacity rejection, capacity-pressure backoff, full split-leaf remint reconciliation, truncation, and manual-disconnect queue fencing. Linux, Windows, live SSH, and production-scale paired hosts remain gaps. The audit removed the E2E parking override/debug-handle suite. Override exposure guards, delay/retention independence, TTL filtering and debug-handle forwarding alarms are lost. Retained real parking journeys do not establish equivalent test-harness configuration coverage. The test-value audit removes separate responsive-stream, intervening-control-frame and capacity-error classification examples. Retained multiplexer checks use fake clocks and captured transport callbacks; their per-stream isolation, deadline and probe-baseline assertions do not prove an actual host restart or equivalent replacement coverage. Historical run commands and results remain historical. The test-value audit removes the standalone retained/live metadata projection and additive-preference negative example from runtime-client-events.test.ts. Its remaining case checks partial-authority event admission through a captured callback; it does not establish full-pair projection, actual peer delivery or equivalent replacement coverage. Historical commands and results remain historical. The isolated accepted-handle-events observer suite is removed. Its runtime/worktree/pane membership, once-only delivery and listener-release ledger alarms are lost. Live hidden-retention evidence does not establish equivalent observer coverage. Audit1292: The entire host-session mirror empty-inventory settle suite is removed. Live-unpublished versus genuinely-empty hydration, same-ID revision response/in-flight fencing and cleared-tracking pending-probe invalidation alarms are lost. The singleton store and inventories were mocked; no real host census or resume delivery or equivalent replacement coverage is claimed. Audit1302: src/main/runtime/session-tabs-inventory-publication.test.ts: Keep actual runtime public inventory authority across renderer epochs/resync, fallback, aborts and invalid graph publishers. Remove copied nonempty publication, private scan counters/collector and known-host replacement, fake refresh that performs the restoration itself, environment capability flag, and private resume-store characterization whose fixture supplies reservation/rollback ordering. Lose isolated refresh/churn/receiver/capability and copied-payload wiring alarms; no equivalent replacement. Reduced selectors require fresh validation; prior full-suite receipts do not validate removed or changed coverage. No equivalent replacement or physical-provider claim. Audit1312 removes low-value imported specs from aggregate test drivers; old whole-driver execution receipts are archived. Retained registrations are unchanged. No equivalent replacement coverage is claimed. Audit1318: src/shared/remote-runtime/control/remote-runtime-shared-control-connection.test.ts: Retain real local encrypted WebSocket regressions for pre-ready socket replacement preserving a request, close-before-ready logical subscription cleanup, unrelated RPC surviving another deadline, and pending setup abort leaving a sibling pending. Host server is synthetic and uses production crypto; kept scenarios also retain internal diagnostics/memory assertions unchanged. Remove happy routing, authority-envelope, unknown-ID/log, cleanup enum, binary, keepalive/liveness and production-budget/private socket inventories; intentionally lose those alarms, no physical host authorization, independent crypto or remote provider claim. Reduced selectors need fresh validation; historical full-suite receipts do not validate the changed coverage. No equivalent replacement or physical-provider claim. Audit1346 removes the entire private-state-injected session-tabs rich-status boundary suite. Its stale task/question, neutral-title preservation, owner-change and provider-generation alarms are intentionally lost. Retained real terminal journeys do not establish equivalent replacement coverage. The prior mixed 42-contract execution receipt is historical and must not validate the reduced current selector; fresh validation remains required. Audit1352: focused Linux unit selections validated on source head b638e07d395b76af3ba6b03761a1a0fe7e5e026e. Historical statements above retain their original scope. Intentional test losses are recorded in knownGaps; these runs claim no physical-provider, p95, rendered E2E or cross-platform validation. Audit1360: focused Linux unit selections validated on source head 415c9cffc2d10024131ec4b6721767a22195de6d. Historical statements above retain their original scope. Intentional test losses are recorded in knownGaps; these runs claim no physical-provider, p95, rendered E2E or cross-platform validation. Audit1383: src/main/runtime/orca-runtime-tests/worktree-native-chat-setup.spec.ts reduced. Lose command-list/receipt/default/background activation matrices whose provider spawn returns canned IDs. Retained test proves actual tab allocation separation, not terminal startup. No equivalent replacement coverage is claimed. Existing exact unaffected receipts and their platform/provider/budget claims remain scoped to unchanged selectors. Changed optional selectors have no new execution result. Audit1391: src/renderer/src/components/terminal-pane/pty-connection-remote-pause-drop-notice.spec.ts reduced. Lose repeated quiet switches avoiding snapshots and legacy host without drop-report capability requesting a snapshot. Retained imported registrar uses fake transport/xterm writes, exercising real gap/restore lifecycle rather than actual terminal rendering. No equivalent replacement coverage is claimed. The existing primary-selector receipt and its claims remain scoped to their unchanged sources; the broad optional command has no new execution result. Audit1396: src/renderer/src/components/terminal-pane/terminal-parked-watcher-reconciliation.test.ts reduced. Retire standalone reconcile set output and positive untouchedFreshSpawn/workspaceOwner copying alarms; no native watcher execution claim. No equivalent replacement coverage is claimed. Existing exact unaffected receipts remain unchanged and apply only to their unchanged selectors. Changed optional selectors have no new execution result. Audit1401: src/main/runtime/orca-runtime-tests/mobile-session-tabs-duplicate-pty-repair.spec.ts removed. Loses listing-on-already-repaired-data alarm; it never established runtime repair invocation. src/main/runtime/orca-runtime-tests/mobile-session-tabs-split-agent-tab.spec.ts removed. Loses actual mobile split sibling shell versus recorded-agent resume command alarms; no equivalent coverage asserted. src/main/runtime/orca-runtime-tests/worktree-native-chat-setup.spec.ts removed. Loses separate setup/startup tab result in that manually assembled path. src/main/runtime/orca-runtime.test.ts reduced. Driver registration/import of a whole-deleted selected spec is removed; directly authored cases remain unchanged. No extra authored removal credit. No equivalent replacement coverage is claimed. Existing exact unaffected receipts remain unchanged and apply only to their unchanged selectors. Changed optional selectors have no new execution result. Audit1402: src/renderer/src/components/terminal-pane/pty-connection-park-reveal-model-snapshot.spec.ts reduced. Loses basic paired serialize/initial replay forwarding check; hidden alt-frame grid/precedence policy remains. No real terminal renderer claim. No equivalent replacement coverage is claimed. The existing primary-selector receipt and its claims remain scoped to their unchanged sources; the broad optional command has no new execution result. Audit1412: src/main/runtime/mobile-session-tabs-agent-status-heartbeat.test.ts reduced. Loses FIFO fairness/spacing, semantic bypass/cancellation, delayed-boundary scheduling and teardown timer-cleanup alarms. Retained fixed emission cases do not replace those outcomes. No equivalent replacement coverage is claimed.", + "coverageNotes": "Audit3209 composes approved sources3202/3206: deliberately retires seven authored/expanded cases in four whole suites without equivalent replacement. Work-item queries lose real GitHub/GitLab oversized ASCII secret-prefix empty-query and whitespace-before-trim refusal alarms; inputs share the imported size bound and exercise only its fast length branch, with no multibyte or actual provider/exposure guarantee. Skill sharing loses complete/partial managed-bundle and destination-ambiguity association checks plus three negative origin/path/scheme admission examples; these do not establish uploaded contents, arbitrary-URL fetching, authorization or execution. Retain exact originless-project direct-link fallback, cloud-delete confirmation, bundled-target repair/owner isolation and explicit Windows-host preference over stale WSL suites. Rejected3201 runtime-preference removal is excluded. No real cloud/network/host/disk, mobile or mixed-version execution validation is claimed. Audit3200 composes approved source3194: deliberately retires thirteen authored registrations/twenty-seven expanded cases in six whole automation host/list policy suites without equivalent replacement. Real RPC category/retryability and wrapped-timeout recognition, unscoped-failure/scoped-success health evidence precedence, exact-ID create selectors and per-run workspace omission, paired-web local/SSH/absent host catalog routing, incompatible/removed/unhydrated/offline execution health, runtime-before-nested-SSH recovery dispatch, and no-owned-focus/successor/foreign-list focus policy alarms are consciously lost. Retain exact20line orphan allow/refuse/precondition and exact90line cross-host same-ID search suites. No retry-timer/fence lifecycle, actual reconnect/network/write delivery, native focus, mobile/mixed-version runtime or disk persistence coverage is claimed. Audit3191 combines approved source3182/3187/3188: deliberately retires thirteen authored Vitest registrations and fifteen expanded cases, including five whole suites, without equivalent replacement. Attachment intake loses real portal/native-capture terminal interception and unowned-container refusal, immediate child-only committed availability/claim-ref negotiation and delivery, and direct-target over stable focused/background composer routing through disable/re-enable/remount and independent question focus. Exact destination/cache/draft and final-stat owner/workspace/File-release suites remain; they do not replace Surface recipient routing. Automation authoring loses destination runtime catalog membership, local/direct-SSH exclusion of paired-runtime repos, unknown-runtime empty catalog, logical project/host/setup/repo/path context payload, and missing/nonready setup refusal; these were genuine direct helper alarms, while exact schedule transformation, legacy schedule and setup-decision suites remain. Agent picker loses setup-chat/terminal/missing-installer/unsupported-or-unknown-host row projection samples and the ordinary unsearched menu variant; the entire original26-line resume recipe suite remains, including reported bypass versus default/absent permission modes, as does the exact search-result menu callback with its fixtures, model/effort commits and staged Arguments reopen outcome. Rejected predecessor3180 full recipe deletion is excluded. No actual native drag/cursor/focus/IME, upload bytes or disk/restart persistence, full automation save/scheduler/runtime transport, real resume-process flags/environment delivery, or native menu/rendered layout validation is claimed. Audit3178 combines source3169/3170/3175: deliberately retires eight authored units (six Vitest cases and two imperative custom relay scenarios), including two whole suites, without equivalent replacement. Voice Section loses per-model pending-delete isolation across interleaved A/B completion and the two-success refresh-call alarm; exact VoicePane delayed key-clear/newer enabled-toggle merge remains and does not replace row deletion coverage. Speech loses dedicated rating-scale/inclusive-ceiling, unsupported-versus-unmeasured, explicit/system-language precedence/locale alias, accuracy versus fast named/default/best-measured selection, and unmeasured/no-match examples; exact offered-user-pick versus retired-selection case and its fixture remain. Relay loses legacy ping-delivery count/liveness sampled before the silence deadline and grouped malformed Bearer/host-ID 401/429 routing checks; twelve real Worker/DurableObject/shipped-client scenarios remain, not equivalent replacement for those narrow alarms. Six prior speech cases are not all deleted: approved successor3175 keeps the original user-choice case. No actual credential/file persistence, native/GPU/engine/download delivery, production assignment policy or deployed-runtime validation is claimed by this reduction. Audit3165 combines source3160/3162: deliberately retires six authored/expanded cases across three whole suites without equivalent replacement. Launch/status losses: observed React-render pending/resuming coordination across settings and deferred offer read; stale-offer reread suppressing dialog reopen; held-local-chat recovery visibility with new-chat preferences off; disabled-local admission avoiding offer RPC despite an injected but unconsumed paired-tab fixture; and run-only lost-reply uncertainty reachability until direct viewed-run retirement. Launch probe does not prove arbitrary synchronous-store atomicity, the paired fixture is not remote runtime enrollment, and the status case directly marks viewed state rather than rendering the summary. Crew-hook losses: old-host method_not_found cache persists across party changes but is released by independently supplied connection generation/verified pairing status or pairing revision, with actual frame publication and teardown. These are real narrow coordination, admission, uncertainty and mixed-version cache alarms consciously lost. Exact web verified-runtime writer handoff guard remains; it does not replace those alarms or prove live host/native/mobile delivery. Audit3156 combines3147/3150/3152/3153/3154: deliberately retires39authored/40expanded native-chat recovery cases, eight whole suites and two orphan test-support files without equivalent replacement. Lost alarms: lost-reply unconfirmed reconciliation, skipped rows/counts and missed-frame repair, unknown/pending outcome and omitted-failure-list compatibility, uncertain history after dismissal, retry/refusal/dismiss lifecycle, hidden/consumed picker ownership, result-tree keyboard focus/disclosure and all-skipped retirement; unconfirmed-over-conflict guidance and failed-chat changes despite older host timestamps; nearest-listed ancestor/cyclic forest shape, descendant membership, host ordering/missing-host local fallback; skipped/readiness/admission counts, provisional skip/progress monotonicity, early per-chat verdicts with batch pending protection, older-host waiting, start-slot/delivery distinction, retry-over-failure and unknown-after-withdrawal attention; remote snooze/reconnect/reoffer, unseen mixed summary through open/close, watched completion retirement, new success beside old failure, failed-reread mixed-result preservation, filter/collapse completion resets, retry summary replacement and current-offer/history selection; cross-host workspace identity, rendered cyclic reachability, nested tri-state/toggle propagation, project eligibility isolation and collapse preserving selection. Exact fallback-list completion barrier, batched verdict/cleanup retention, stale-read versus dismissal publication race, and requested-but-never-rendered finished-run retirement remain; they do not replace retired alarms. Audit3146 combines source reviews3132/3133/3135/3138/3143: intentionally retire20authored/31expanded cases without equivalent replacement. Provider-session losses: structured-native terminal-resume exclusion, metadata-less completed identity, new-turn completion clearing, Pi provider-only/periodic/manual promotion, changed-transcript launch-config isolation, Pi/omp/prime-agent completed-session remote/manual-shutdown promotion, and quit/done precedence over heartbeat. Side-thread/question losses: finished-pane acquisition, hidden title/recap states, local/relay/relay-done conversation takeover with prompt/session/child resets, plain-message abandonment, compaction/session replacement and completion resets. Codex startup losses: incoming-owner cached child replacement, old-relay foreign live-session correction, completed foreign-root turn-fact permutations. Transcript losses: real temporary-JSONL partial sibling/final-child completion, unlabelled child attribution, compact cached replay preservation and100/1000completed-child roster retention/release. Compiler-ratchet losses: valid-line uncompiled-list parser grammar examples and injected-existence stale-path filtering; these did not exercise actual filesystem canonicalization or build exclusion. These are real lifecycle, ownership, replay, liveness and retention alarms, including recent#40246 regressions, deliberately lost. Retained conditional record replacement, clockless root/SSH owner isolation, persisted main-thread fork rejection, partial/final question-answer lifetime, cached-roster/missing-ID/live HTTP/durable startup boundaries and restarted-relay refusal/acceptance do not replace those losses. No native/SSH/WSL execution or equivalent coverage is claimed. Audit3128 scoped coverage reduction: Audit3121 removes VoiceDictationLanguageSetting.test.tsx (Spanish-to-es callback and unsupported-model Korean option presence) and voice-speech-model-rows.test.ts (provider/language-order/retired-on-disk list policy); these real narrow alarms are deliberately retired without replacement. VoiceSpeechModelSection per-model concurrent deletion remains unchanged. Audit3122 removes the direct absolute/parent-segment sparse-directory exception-type sample and the five-row IPC sparse-preset error-code/non-save table (two authored/six expanded cases). Those real typed-validation and IPC refusal/error-code alarms are deliberately retired. Keep both real symlink/junction floating-directory trust cases and the minimal RPC structured validation-reason serialization case. The RPC case does not replace IPC save/refusal behavior, typed normalization for both path inputs, actual Git sparse checkout or rendered localization. No equivalent replacement or fresh test/runtime/platform/remote/performance validation is claimed. Audit3124 removes ExperimentalPane.test.tsx (ordinary Pet switch callback), WorkspaceDirectorySetting.test.tsx (padded absolute saved-path normalization/no-write blur), and repository-search.perf.test.ts (navigation/selected-pane builder-call policy, fixture cardinality/nonempty entries and renamed project keyword inclusion). These real narrow alarms are retired without replacement; RepositoryPane.search.test.tsx search-to-sparse-editor request remains unchanged. Audit3129: resolver Windows case-insensitive and POSIX case-sensitive configured-env composition plus mocked-base launch-preflight Windows composition are intentionally no longer checked by the two deleted suites. No equivalent coverage claimed. Keep runtime-structured-agent-host-env.test.ts unchanged: configured Windows Claude-home account identity and host-account precedence remain checked. Audit3114 incorporates source3101: retire three structured Claude child-environment wrapper cases covering inherited stamp isolation/default and explicit entrypoint, Windows SDK-key canonicalization/default/duplicate-key order, and configured lookup/final environment/config-dir conjunction. Keep direct auth/session sanitation and Windows-versus-Linux overlay checks, actual executable lookup from supplied inherited PATH, native Windows child environment delivery, and stale option-mutation fencing. These are not equivalent replacements for the retired wrapper alarms. No fresh test/runtime, real login-shell probe, Claude SDK startup, remote/mixed-version, UI or performance result is claimed. Audit3114 incorporates source3105: retire 17 authored/20 expanded daemon launch-note cases, including the entire two-case SessionLaunchNote suite. Deliberately lose split-marker carry across same-token re-arm, stale-token retirement refusal, foreground tri-state and serial settlement, omitted-note/no-incarnation mixed-version policy, sticky retirement, first-incarnation/replacement launch preservation and held-launch precedence. Keep only the unchanged unresolved foreground-read race against a later finished attach. Supplied notes/foreground and runtime calls do not establish actual daemon/main restart, SSH, native Windows observation, mobile UI, equivalent replacement or fresh runtime/performance validation. Audit3114 incorporates source3109: retire six authored/35 expanded pricing cases: 21 accepted model-name examples, 10 unsupported/future-model fail-closed examples, malformed TTL clamp, unknown-model estimate refusal, flat-model long-context disregard and oversized long-context clamp. Keep mixed five-minute/one-hour write allocation and short/all-long/mixed long-context allocation with original fixed oracles. Real parser/refusal/bounds alarms are knowingly lost without equivalent replacement; retained tests do not validate provider rates, actual billing or request threshold classification. Preserve the archived usage-scan-append source-freeze receipt without transferring historical execution/performance credit. No fresh runtime result is claimed. Audit3108 source-only reduction (3094/3095/3100): retire 27 authored/30 expanded cases, including complete markdown view-state, file-preview link-open and CLI agent-server-route suites, without replacement. Deliberate losses include preview visibility/reference lifetime and same-path owners; SSH stat, directory/missing-target, explicit-null owner, nonmarkdown line/column, local URI routing, remote-to-client guard and same-file reuse; document-preview source-owner/folder/reuse routing, stable grant location and outside-workspace POSIX/Windows request projection; and verified remote CLI send/check refusal, suggested --on argv/copy, shell no-probe bypass, unverified-launch admission and older-peer refusal. Retain two markdown source-runtime/qualified-reveal alarms, one stale grant-rejection fence and two remote read/mutation evidence policies, with original callbacks. Final last-wins reveal did not prove transient cancellation; CLI prerequisite did not prove no real send, and envelope tests do not execute server refusal. No fresh runtime, rendered UI, actual file/SSH/paired transport, authorization, mixed-version or performance result is claimed. Audit3096 source-only reduction (3087/3088): retire 69 authored/76 expanded cases, including complete recovery-portals and reconnect-banner suites. Intentionally lose dead/default TUI replay, generated alternate-frame style composition, reset/mode/dimension and legacy missing-mode-boundary alarms, UI notice/action/reveal policies, and isolated recovery lifecycle variants, without equivalent replacement. Retained registrations and callbacks are unchanged; headless cells are not pixels, and no fresh runtime, host, SSH, WSL, rendered-app or performance result is claimed. Audit3086 source-only reduction (3079/3080/3081): intentionally retire 93 authored/100 expanded mock-boundary cases, including the complete spawn-errors and SSH reconnect overlay suites, without replacement. Retired alarms include spawn classification/ownership, reply ceilings and renderer-write failure recovery, disconnect/detach fencing branches, authority facts, and overlay retry/visibility wiring. Retained callbacks are unchanged; no fresh execution, real PTY/SSH, rendered UI, or performance result is claimed. The direct side-effect-facts selector retains six cases: replay exclusion, live sequence handling, stale disposer ownership, one handoff drain, drain-before-snapshot, and stale replacement-snapshot refusal. Successful current-entry snapshot application is not witnessed by the retained snapshot case. Audit2432: The broad unit command loses the isolated BranchPicker open-change notification sample. Its unique true/false callback alarm is intentionally retired; reopening/status-refresh behavior was not exercised. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2425: The broad unit command loses the workspace-copy-status supplied readError forwarding sample. It did not exercise the branch-switch blocking promised by its title. This alarm is intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2417: The broad unit command loses two ordinary clean Git cherry-pick/revert success samples and two terminal startup foreground-read work-budget samples. These unique alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2412: The broad unit command loses the whole six-case fake-React-hook scroll-anchor suite, two generic draft-retention samples, a simple new-agent order sample, a real history-publication batching-count sample, an unmounted handoff abort/timer sample and three basic WSL preview/error samples. These alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2404: The broad unit command loses the standalone share-name lookup 503 propagation suite, initial deletion placement-kind sample, direct changed-mtime stale sample, first-pass rollback existence example and abandoned-preparation directory sample. These exact alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2397 review amendment: The broad unit command loses three standalone suites, two partial-case definitions and two URL table rows across package/download/placement tests. Keep initial wrong-port authorization, modified independent-copy digest refusal and abort-after-begin cancellation dispatch. The remaining alarms are deliberately retired; no equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2393 current-parent refresh2401: Remove the basic skill-install service alias sample and original public managed-remove receiptless refusal case. Preserve the upstream request ownership suite and transaction interruption coverage. No equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2389: The broad unit command loses the missing-preview suite, plain-global destination sample and prepublished-receipt recovery example. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2385: The broad unit command loses four authored walker/staging/protocol examples (six expanded cases); no equivalent replacement or fresh validation is claimed for the reduced suite. Audit2383: The unscoped Vitest command no longer includes the removed Antigravity catalogue suite; its exact provider-root/owner example has no equivalent replacement or fresh validation claim. Audit2377/2381: The unscoped Vitest command includes the reduced bundled-skill and native-discovery suites; the eight removed backup/legacy/catalogue/symlink/SSH-builder examples have no replacement-equivalence or fresh validation claim here. Audit2162: Reduced inventory-authority source intentionally loses the examples recorded in knownGaps; historical execution is not validation of changed bytes. Historical prior account (preserved verbatim): Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2090 (sources2088/2089): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2086 (sources2082/2083): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2076 (sources2073/2074): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime-tests/terminal-handles-part-02.spec.ts: recovers a moved SSH pane through the tab it now sits in, not the one its lease froze; reports a plain expired orphan; does not report a pane whose only recent lease was superseded; does not report a pane whose only recent lease had its relay id recycled; picks the eligible orphan over a superseded predecessor that matches first; collects the same tabs the per-tab reader reports, in one sweep of the leases; reports no candidate when no lease names any of the worktree tabs. src/main/runtime/orca-runtime-tests/runtime-availability.spec.ts: starts unavailable with no authoritative window; reports the configured Windows terminal shell on status; reports floating workspace availability from settings on status; polls floating tabs with targeted PTY liveness and no repo/provider inventory; hydrates persisted tabs when the store cannot report repos; advertises browser screencast only when a renderer window is available; routes mobile Codex reset consumption through the account mutation coordinator; maps a definite pre-provider rejection into an authoritative current snapshot. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Frozen current literal-import graph reaches these changed test bytes; unresolved local and computed edges remain debt, and current reachability is not historical execution or equivalent replacement evidence. Historical prior account (preserved verbatim): Audit2003: Remove SSH/absent-inventory attach refusal, later-subscriber retry, no-view adoption/takeback, provider-tail/unknown-read projections, failed-keystroke retry and simpler loss reattach examples. Keep the existing-subscriber inventory-ready retry alias only at its retained callback, plus retained held-input cancellation/replacement and overlapping attach/loss fences. The inventory driver also loses the whole empty-worktree-publication registration and folder-host/unverifiable scalar examples. Retire the entire dated10-case attach receipt; retain16 independent receipts only in their original scopes. No retained-memory or real-daemon measurement follows from supplied provider inventories. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, physical provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1991: Remove initial-snapshot sequence-domain, limited-tail/truncation and unknown-output-sequence aliases whose callbacks are removed. The source retains partial-chunk replay and requested-snapshot retry/admission at supplied snapshot/data seams, not equivalent replacement or measured retained-memory proof. Preserve the existing stream/pending-wait capacity aliases only to their retained owning multiplex callbacks with supplied PTY resolutions. Removing the sibling-PTY heartbeat dedup work-count sample does not establish a new decorative fanout budget; the unrelated-PTY cancellation fence survives. Preserve17 unrelated dated receipts. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, physical provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1983: Remove the reasonless-close selector and narrow census aliases to actual retained runtime and injected-inventory callbacks. The removed synthetic census-dedup and isolated pre-boundary timing cases receive no replacement credit; preserve17 unrelated dated receipts. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1939 (sources1934/1935): Delete the synthetic watcher-synchronization and partial-reconciliation suites. Retire all affected host-fact, capability-owner, activation-residue and retention-cap aliases because the remaining callbacks do not establish those full claims. Keep exact local hook/timer, byte-stream side effects, exit/disposal, scroll-intent cleanup and deterministic local rank/TTL progression callbacks within their mocked-host scope. No physical paired-host retention, resource budget or equivalent replacement evidence is assigned. The generic broad test command remains a runnable discovery command, never a dated execution receipt. Preserve meaningful remaining selectors/assertions and unchanged dated receipts within their original scope. Reduced selectors have no fresh gate execution evidence in this metadata packet. No equivalent replacement, physical watcher/PTY/provider, live SSH/remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): Audit1931 (sources1928/1929): Delete the complete hook-agent-status projection suite and its two behavioral assertion aliases. Supplied stored hook/title/resume/staleness/rename/question/generation/PTY-retirement/snapshot-version projections are intentionally lost. The separate osc-status-scan gate mentions this source only in existing historical notes and receives no mutation. No measured hidden-output retention, CPU/RSS or resource budget result is claimed by the deleted source or this audit. Preserve meaningful remaining selectors/assertions and unchanged dated receipts within their original scope. Reduced selectors have no fresh gate execution evidence in this metadata packet. No equivalent replacement, physical watcher/PTY/provider, live SSH/remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): Module ownership cleanup retires the modeled cold-park private watcher/render/work-count suites under the current test policy. Their assertions are no longer active evidence. Retained lifecycle tests and headed/headless journeys do not establish equivalent coverage for those removed harness alarms. Audit1640 removes low-value IPC, SSH, workspace and transcript-watcher tests without equivalent replacement coverage. Per-source reviews record retained public refusal, cancellation, execution-host and real-filesystem outcomes with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1634 removes low-value IPC, filesystem and runtime projections, argument inventories and duplicate examples without equivalent replacement coverage. Per-source reviews record retained cancellation, ownership, authorization, filesystem and SQLite boundaries with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1627 removes low-value mocked daemon projections, scalar tables and duplicate terminal examples without equivalent replacement coverage. Per-source reviews record retained terminal content preservation, process ownership refusal and recovery boundaries together with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Retained exact unchanged-source receipts remain the only current execution evidence. Reduced selectors have no fresh execution result. Audit1417 intentionally deletes src/renderer/src/components/terminal-pane/pty-connection-hidden-tui-snapshot-replay.spec.ts: Loses rich hidden snapshot sequence replay/grid resize and forced repaint after hidden snapshot alarms, including live-trigger deduplication. deletes src/renderer/src/components/terminal-pane/terminal-cold-park-verdict-loop.test.tsx: Loses modeled React oscillation alarm; real pane/watchers are not exercised. deletes src/renderer/src/runtime/remote-runtime-terminal-parse-backpressure.test.ts: Loses delayed credit until parsing, malformed frame/unknown stream handling, discarded transformed output recovery and failed ACK rearm alarms. No equivalent replacement coverage or fresh result is claimed. Historical coverage account: Audit1412 changes referenced sources. Retained unchanged-source receipts apply only to their unchanged commands; the reduced selectors have no new execution result. Historical coverage account (not a current claim for changed sources): This audit removes the browser response-after-manual-disconnect example. Its distinct in-flight response fencing alarm is lost; retained queued-call disconnect tests are not an equivalent replacement. Historical commands and results remain historical. Deterministic headed macOS runs launch an isolated Orca desktop server and a separate paired web client. A byte-identical headless run uses an isolated `orca serve` host. Both create six real paired host PTYs with bounded high-output scrollback, prove sustained output while all six client xterms are warm-mounted but hidden causes zero renderer scheduler work, then drive 180 timed real-PTY spinner frames through a second production `session.tabs.subscribeAll` transport and the real Zustand store. Each worktree must publish and apply only its exact initial-working and final-idle titles. Both topologies ordinary-park five xterms without enabling the lossy retention budget, assert bounded cells/heap/timer lag, then restore the bounded authoritative tail exactly once on the original PTY including output produced while parked and continued input/output. The headed oracle additionally keeps every remote target workspace and terminal unmounted in the host renderer before and after client recovery. Production-parity React contracts reproduce and remove the independent cold-park watcher/title feedback loop, including memo-cache discard, StrictMode cleanup replay, detached split-PTY replacement, and the zero-park fast path. A deterministic cross-boundary contract drives 24 real PTY trackers in distinct worktrees through 2,880 decorative spinner and bare-native redraw chunks and counts host publications, serialized bytes, renderer apply calls, and store mutations while preserving exact per-PTY raw chunks and per-worktree semantic transitions. Fake-clock continuation beyond the 30-minute stale boundary requires one deduplicated refresh per worktree every 15 minutes, globally spaced by at least 50 ms, with every mirrored working status still fresh. Exact-identical Pi plus rotating normalized Pi/Grok frames renew coarse working/permission state; rich prompt/tool/question fields retain their original 30-minute lease, and `stateStartedAt`/acknowledgement identity remain stable across title/hook source swaps. A separate headed desktop-client journey relaunches the host main process while retaining the daemon and a daemon-backgrounded PTY, then requires first-observation foreground sync and continued input/output on the same PTY. Unit coverage keeps layout versions out of snapshot output high-waters when a restored snapshot has no output sequence and retries an existing subscriber only after authoritative provider inventory proves the retained PTY exists. Separate headed/headless ACK-starvation tests recover one stalled stream without replacing its PTY. A headed output-drop oracle proves a successful snapshot probe cannot certify a stale live stream when the authoritative PTY sequence advanced beyond the client high-water. Unit coverage requires an unsequenced client to establish a first-probe baseline, remain attached at the same sequence, and recover only after a later probe advances. A capability-disabled run proves legacy hosts retain the prior lossy limit/TTL fallback. Unit tests cover exact-owner capability routing, raw-stream release, singleton side-effect facts with timed handoff cleanup, 64 simultaneous synthetic-title sources with zero decorative client events after convergence, per-client late-subscribe recovery, semantic bell/title transitions, local animation-frame preservation, legacy no-output-pause delivery gating with exact snapshot restore, provider-authoritative snapshots, 128 active streams plus retry after a 129th-stream capacity rejection, capacity-pressure backoff, full split-leaf remint reconciliation, truncation, and manual-disconnect queue fencing. Linux, Windows, live SSH, and production-scale paired hosts remain gaps. The audit removed the E2E parking override/debug-handle suite. Override exposure guards, delay/retention independence, TTL filtering and debug-handle forwarding alarms are lost. Retained real parking journeys do not establish equivalent test-harness configuration coverage. The test-value audit removes separate responsive-stream, intervening-control-frame and capacity-error classification examples. Retained multiplexer checks use fake clocks and captured transport callbacks; their per-stream isolation, deadline and probe-baseline assertions do not prove an actual host restart or equivalent replacement coverage. Historical run commands and results remain historical. The test-value audit removes the standalone retained/live metadata projection and additive-preference negative example from runtime-client-events.test.ts. Its remaining case checks partial-authority event admission through a captured callback; it does not establish full-pair projection, actual peer delivery or equivalent replacement coverage. Historical commands and results remain historical. The isolated accepted-handle-events observer suite is removed. Its runtime/worktree/pane membership, once-only delivery and listener-release ledger alarms are lost. Live hidden-retention evidence does not establish equivalent observer coverage. Audit1292: The entire host-session mirror empty-inventory settle suite is removed. Live-unpublished versus genuinely-empty hydration, same-ID revision response/in-flight fencing and cleared-tracking pending-probe invalidation alarms are lost. The singleton store and inventories were mocked; no real host census or resume delivery or equivalent replacement coverage is claimed. Audit1302: src/main/runtime/session-tabs-inventory-publication.test.ts: Keep actual runtime public inventory authority across renderer epochs/resync, fallback, aborts and invalid graph publishers. Remove copied nonempty publication, private scan counters/collector and known-host replacement, fake refresh that performs the restoration itself, environment capability flag, and private resume-store characterization whose fixture supplies reservation/rollback ordering. Lose isolated refresh/churn/receiver/capability and copied-payload wiring alarms; no equivalent replacement. Reduced selectors require fresh validation; prior full-suite receipts do not validate removed or changed coverage. No equivalent replacement or physical-provider claim. Audit1312 removes low-value imported specs from aggregate test drivers; old whole-driver execution receipts are archived. Retained registrations are unchanged. No equivalent replacement coverage is claimed. Audit1318: src/shared/remote-runtime/control/remote-runtime-shared-control-connection.test.ts: Retain real local encrypted WebSocket regressions for pre-ready socket replacement preserving a request, close-before-ready logical subscription cleanup, unrelated RPC surviving another deadline, and pending setup abort leaving a sibling pending. Host server is synthetic and uses production crypto; kept scenarios also retain internal diagnostics/memory assertions unchanged. Remove happy routing, authority-envelope, unknown-ID/log, cleanup enum, binary, keepalive/liveness and production-budget/private socket inventories; intentionally lose those alarms, no physical host authorization, independent crypto or remote provider claim. Reduced selectors need fresh validation; historical full-suite receipts do not validate the changed coverage. No equivalent replacement or physical-provider claim. Audit1346 removes the entire private-state-injected session-tabs rich-status boundary suite. Its stale task/question, neutral-title preservation, owner-change and provider-generation alarms are intentionally lost. Retained real terminal journeys do not establish equivalent replacement coverage. The prior mixed 42-contract execution receipt is historical and must not validate the reduced current selector; fresh validation remains required. Audit1352: focused Linux unit selections validated on source head b638e07d395b76af3ba6b03761a1a0fe7e5e026e. Historical statements above retain their original scope. Intentional test losses are recorded in knownGaps; these runs claim no physical-provider, p95, rendered E2E or cross-platform validation. Audit1360: focused Linux unit selections validated on source head 415c9cffc2d10024131ec4b6721767a22195de6d. Historical statements above retain their original scope. Intentional test losses are recorded in knownGaps; these runs claim no physical-provider, p95, rendered E2E or cross-platform validation. Audit1383: src/main/runtime/orca-runtime-tests/worktree-native-chat-setup.spec.ts reduced. Lose command-list/receipt/default/background activation matrices whose provider spawn returns canned IDs. Retained test proves actual tab allocation separation, not terminal startup. No equivalent replacement coverage is claimed. Existing exact unaffected receipts and their platform/provider/budget claims remain scoped to unchanged selectors. Changed optional selectors have no new execution result. Audit1391: src/renderer/src/components/terminal-pane/pty-connection-remote-pause-drop-notice.spec.ts reduced. Lose repeated quiet switches avoiding snapshots and legacy host without drop-report capability requesting a snapshot. Retained imported registrar uses fake transport/xterm writes, exercising real gap/restore lifecycle rather than actual terminal rendering. No equivalent replacement coverage is claimed. The existing primary-selector receipt and its claims remain scoped to their unchanged sources; the broad optional command has no new execution result. Audit1396: src/renderer/src/components/terminal-pane/terminal-parked-watcher-reconciliation.test.ts reduced. Retire standalone reconcile set output and positive untouchedFreshSpawn/workspaceOwner copying alarms; no native watcher execution claim. No equivalent replacement coverage is claimed. Existing exact unaffected receipts remain unchanged and apply only to their unchanged selectors. Changed optional selectors have no new execution result. Audit1401: src/main/runtime/orca-runtime-tests/mobile-session-tabs-duplicate-pty-repair.spec.ts removed. Loses listing-on-already-repaired-data alarm; it never established runtime repair invocation. src/main/runtime/orca-runtime-tests/mobile-session-tabs-split-agent-tab.spec.ts removed. Loses actual mobile split sibling shell versus recorded-agent resume command alarms; no equivalent coverage asserted. src/main/runtime/orca-runtime-tests/worktree-native-chat-setup.spec.ts removed. Loses separate setup/startup tab result in that manually assembled path. src/main/runtime/orca-runtime.test.ts reduced. Driver registration/import of a whole-deleted selected spec is removed; directly authored cases remain unchanged. No extra authored removal credit. No equivalent replacement coverage is claimed. Existing exact unaffected receipts remain unchanged and apply only to their unchanged selectors. Changed optional selectors have no new execution result. Audit1402: src/renderer/src/components/terminal-pane/pty-connection-park-reveal-model-snapshot.spec.ts reduced. Loses basic paired serialize/initial replay forwarding check; hidden alt-frame grid/precedence policy remains. No real terminal renderer claim. No equivalent replacement coverage is claimed. The existing primary-selector receipt and its claims remain scoped to their unchanged sources; the broad optional command has no new execution result. Audit1412: src/main/runtime/mobile-session-tabs-agent-status-heartbeat.test.ts reduced. Loses FIFO fairness/spacing, semantic bypass/cancellation, delayed-boundary scheduling and teardown timer-cleanup alarms. Retained fixed emission cases do not replace those outcomes. No equivalent replacement coverage is claimed.", "motivatingLinks": [ "https://github.com/stablyai/orca/issues/8652", "https://github.com/stablyai/orca/pull/10625" ], "invariant": "A host advertising terminal.paired-parking.v1 keeps the PTY and bounded authoritative history alive while an ordinary hidden-view park destroys the client xterm and releases its raw per-PTY stream. Reveal must restore up to the requested 5,000 rows, parked-time side effects/output, the same PTY identity, and continued input/output. Parked watcher synchronization compares parking semantics rather than fresh object identity, owns setup and cleanup across StrictMode replay, reconciles real PTY/layout changes, and performs no terminal-state scan when nothing is parked. After a host main-process relaunch, unknown local delivery-sync state must not be treated as proof that a surviving daemon PTY is already foregrounded. An empty headed session-tab inventory is authoritative only after the current renderer graph generation publishes a complete inventory and every execution host answers the PTY census; unpublished, resync-pending, transport-failed, and partially scoped inventories remain unverifiable, while genuinely authoritative empty and non-empty inventories settle and a scope-less legacy empty keeps its pre-authority best-effort settle so outdated hosts retain agent auto-resume. The unpublished-empty regression must keep the resume dispatch parked with exactly one daemon process/writer; restoring unconditional empty hydration must release one dispatch and create two live writers. If subscription precedes provider readiness, authoritative inventory must reconsider that existing subscriber without spawning, resizing, or changing reconnect state. A snapshot without an output high-water must keep it unknown rather than borrowing a layout version that can suppress newer live output. Hosts without the capability must gate hidden raw output before xterm scheduling and repaint from the authoritative snapshot on reveal while retaining the existing limit/TTL force-parking fallback. After the first semantic title state, decorative spinner frequency must add zero paired client-event frames and zero full session-tabs work between status-freshness leases regardless of hidden worktree count. Continuous working or permission evidence may refresh each affected worktree once per 15 minutes through one globally spaced FIFO so current and legacy viewers do not decay before 30 minutes; sibling PTYs share that worktree refresh, while local title animation, raw output, and semantic title, status, bell, completion, and query facts remain intact. A paired terminal stream whose delivery credits stop progressing must replace only that stream; command silence first probes authoritative state and replaces the stream if the probe times out or proves the PTY advanced beyond the client's delivered output sequence. When no comparable delivery high-water exists, the first sequenced probe establishes a baseline and only later advancement proves staleness. A same-sequence snapshot remains valid proof of a responsive silent command. A successful status probe may replace a pre-ready shared-control socket without rejecting or duplicating calls already waiting for that transport. Manual disconnect must retain pairing while preventing queued or passive calls and subscriptions from recreating transport until explicit Connect. A paired pane reconnecting to a relaunched host that has not yet published its window graph (an unpublished frame, bare or client-projected) must stay in recovery rather than retire, and the host's first published snapshot carrying the surface must reattach it; a published frame lacking the surface still retires it. The placeholder is only ever sent before the host's graph first publishes; afterwards a worktree with no tabs gets a real empty answer, pushed once to any client that asked during startup, so a paired client opening a never-opened host worktree still gets its first terminal.", - "oracle": "Audit3096 source-only reduction (3087/3088): retire 69 authored/76 expanded cases, including complete recovery-portals and reconnect-banner suites. Intentionally lose dead/default TUI replay, generated alternate-frame style composition, reset/mode/dimension and legacy missing-mode-boundary alarms, UI notice/action/reveal policies, and isolated recovery lifecycle variants, without equivalent replacement. Retained registrations and callbacks are unchanged; headless cells are not pixels, and no fresh runtime, host, SSH, WSL, rendered-app or performance result is claimed. Audit3086 source-only reduction (3079/3080/3081): intentionally retire 93 authored/100 expanded mock-boundary cases, including the complete spawn-errors and SSH reconnect overlay suites, without replacement. Retired alarms include spawn classification/ownership, reply ceilings and renderer-write failure recovery, disconnect/detach fencing branches, authority facts, and overlay retry/visibility wiring. Retained callbacks are unchanged; no fresh execution, real PTY/SSH, rendered UI, or performance result is claimed. The direct side-effect-facts selector retains six cases: replay exclusion, live sequence handling, stale disposer ownership, one handoff drain, drain-before-snapshot, and stale replacement-snapshot refusal. Successful current-entry snapshot application is not witnessed by the retained snapshot case. Audit2432: The broad unit command loses the isolated BranchPicker open-change notification sample. Its unique true/false callback alarm is intentionally retired; reopening/status-refresh behavior was not exercised. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2425: The broad unit command loses the workspace-copy-status supplied readError forwarding sample. It did not exercise the branch-switch blocking promised by its title. This alarm is intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2417: The broad unit command loses two ordinary clean Git cherry-pick/revert success samples and two terminal startup foreground-read work-budget samples. These unique alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2412: The broad unit command loses the whole six-case fake-React-hook scroll-anchor suite, two generic draft-retention samples, a simple new-agent order sample, a real history-publication batching-count sample, an unmounted handoff abort/timer sample and three basic WSL preview/error samples. These alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2404: The broad unit command loses the standalone share-name lookup 503 propagation suite, initial deletion placement-kind sample, direct changed-mtime stale sample, first-pass rollback existence example and abandoned-preparation directory sample. These exact alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2397 review amendment: The broad unit command loses three standalone suites, two partial-case definitions and two URL table rows across package/download/placement tests. Keep initial wrong-port authorization, modified independent-copy digest refusal and abort-after-begin cancellation dispatch. The remaining alarms are deliberately retired; no equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2393 current-parent refresh2401: Remove the basic skill-install service alias sample and original public managed-remove receiptless refusal case. Preserve the upstream request ownership suite and transaction interruption coverage. No equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2389: The broad unit command loses the missing-preview suite, plain-global destination sample and prepublished-receipt recovery example. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2385: The broad unit command loses four authored walker/staging/protocol examples (six expanded cases); no equivalent replacement or fresh validation is claimed for the reduced suite. Audit2383: The unscoped Vitest command no longer includes the removed Antigravity catalogue suite; its exact provider-root/owner example has no equivalent replacement or fresh validation claim. Audit2377/2381: The unscoped Vitest command includes the reduced bundled-skill and native-discovery suites; the eight removed backup/legacy/catalogue/symlink/SSH-builder examples have no replacement-equivalence or fresh validation claim here. Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2090 (sources2088/2089): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2086 (sources2082/2083): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2076 (sources2073/2074): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime-tests/terminal-handles-part-02.spec.ts: recovers a moved SSH pane through the tab it now sits in, not the one its lease froze; reports a plain expired orphan; does not report a pane whose only recent lease was superseded; does not report a pane whose only recent lease had its relay id recycled; picks the eligible orphan over a superseded predecessor that matches first; collects the same tabs the per-tab reader reports, in one sweep of the leases; reports no candidate when no lease names any of the worktree tabs. src/main/runtime/orca-runtime-tests/runtime-availability.spec.ts: starts unavailable with no authoritative window; reports the configured Windows terminal shell on status; reports floating workspace availability from settings on status; polls floating tabs with targeted PTY liveness and no repo/provider inventory; hydrates persisted tabs when the store cannot report repos; advertises browser screencast only when a renderer window is available; routes mobile Codex reset consumption through the account mutation coordinator; maps a definite pre-provider rejection into an authoritative current snapshot. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Frozen current literal-import graph reaches these changed test bytes; unresolved local and computed edges remain debt, and current reachability is not historical execution or equivalent replacement evidence. Historical prior account (preserved verbatim): Audit2003: Remove SSH/absent-inventory attach refusal, later-subscriber retry, no-view adoption/takeback, provider-tail/unknown-read projections, failed-keystroke retry and simpler loss reattach examples. Keep the existing-subscriber inventory-ready retry alias only at its retained callback, plus retained held-input cancellation/replacement and overlapping attach/loss fences. The inventory driver also loses the whole empty-worktree-publication registration and folder-host/unverifiable scalar examples. Retire the entire dated10-case attach receipt; retain16 independent receipts only in their original scopes. No retained-memory or real-daemon measurement follows from supplied provider inventories. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, physical provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1991: Remove initial-snapshot sequence-domain, limited-tail/truncation and unknown-output-sequence aliases whose callbacks are removed. The source retains partial-chunk replay and requested-snapshot retry/admission at supplied snapshot/data seams, not equivalent replacement or measured retained-memory proof. Preserve the existing stream/pending-wait capacity aliases only to their retained owning multiplex callbacks with supplied PTY resolutions. Removing the sibling-PTY heartbeat dedup work-count sample does not establish a new decorative fanout budget; the unrelated-PTY cancellation fence survives. Preserve17 unrelated dated receipts. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, physical provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1983: Remove the reasonless-close selector and narrow census aliases to actual retained runtime and injected-inventory callbacks. The removed synthetic census-dedup and isolated pre-boundary timing cases receive no replacement credit; preserve17 unrelated dated receipts. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1939 (sources1934/1935): Delete the synthetic watcher-synchronization and partial-reconciliation suites. Retire all affected host-fact, capability-owner, activation-residue and retention-cap aliases because the remaining callbacks do not establish those full claims. Keep exact local hook/timer, byte-stream side effects, exit/disposal, scroll-intent cleanup and deterministic local rank/TTL progression callbacks within their mocked-host scope. No physical paired-host retention, resource budget or equivalent replacement evidence is assigned. The generic broad test command remains a runnable discovery command, never a dated execution receipt. Preserve meaningful remaining selectors/assertions and unchanged dated receipts within their original scope. Reduced selectors have no fresh gate execution evidence in this metadata packet. No equivalent replacement, physical watcher/PTY/provider, live SSH/remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): Audit1931 (sources1928/1929): Delete the complete hook-agent-status projection suite and its two behavioral assertion aliases. Supplied stored hook/title/resume/staleness/rename/question/generation/PTY-retirement/snapshot-version projections are intentionally lost. The separate osc-status-scan gate mentions this source only in existing historical notes and receives no mutation. No measured hidden-output retention, CPU/RSS or resource budget result is claimed by the deleted source or this audit. Preserve meaningful remaining selectors/assertions and unchanged dated receipts within their original scope. Reduced selectors have no fresh gate execution evidence in this metadata packet. No equivalent replacement, physical watcher/PTY/provider, live SSH/remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): Retained exact unchanged-source receipts remain the only current execution evidence. Reduced selectors have no fresh execution result. Historical pre-audit oracle account for changed sources: The retained unchanged-source receipts are the only current execution evidence; reduced-source assertions await validation. Historical oracle account (not a current claim for changed sources): Existing exact unchanged-selector receipts remain the only current execution evidence. Changed source selectors have no fresh execution result. Historical prior-source oracle account: Existing exact unchanged-selector receipts remain the only current execution evidence. Changed source selectors have no fresh execution result. Historical prior-source oracle account: Run one byte-identical six-terminal oracle against an isolated headed desktop host and an isolated headless `orca serve` host. Stage at least 1,000,000 xterm cells, hide all six warm managers, emit an initial working title followed by 30 timed real-PTY spinner frames and a final idle title per worktree, and observe a second real session-tabs subscription plus the production renderer store. Require exactly two transport envelopes and two title mutations per worktree, no decorative title crossing either boundary, and positive decoded-envelope bytes. Enable ordinary parking with the lossy retention budget disabled, require exactly one mounted manager and five parked tabs, at most 45% retained cells, no more than 16 MiB heap growth, and under 500 ms timer drift. In headed mode, require the host renderer to remain on its original workspace with zero target terminal managers mounted throughout client park, reveal, and live I/O. While a tab is parked, require authoritative terminal.read to observe new PTY output; reveal it and require the original PTY, a marker within the requested 5,000-row history, the parked marker, and post-reveal input/output. Drive 24 real PTY title trackers in distinct worktrees through 40 decorative spinner frames each, then 40 spinner frames alternating with Cursor's bare native identity redraw, using fake clocks. Require all 2,880 raw chunks exactly and zero host session-tabs publications, serialized bytes, renderer apply calls, and renderer store mutations. Continue decorative evidence beyond 30 minutes, require exactly one refresh per worktree per 15-minute lease through a FIFO spaced by at least 50 ms, and require all 24 viewer statuses to remain working and fresh; then require one exact semantic idle transition and one visible-output chunk per PTY. Require ordinary and interior-Braille title changes to publish. Drive 64 host PTYs through ten 80 ms synthetic title frames, require zero paired client events after the first frame per PTY while all 640 local frames remain observable, attach a late client and require one current frame per PTY, then require semantic bell and idle transitions on both clients. Reconstruct a legacy subscribed stream with no outputPause capability, hide a chatty pane, require no hidden xterm writes, reveal it, and require one authoritative snapshot plus continued live output. Drop and acknowledge output only for one original paired-client stream, prove the fixture process consumed input while the host model advanced and the client stayed stale, then require the command snapshot probe to replace that stream, repaint exact fixture output, preserve authoritative PTY identity and target-tab cardinality, and resume live I/O. For a client without a delivered sequence, require the first numeric probe to establish a baseline without replacement, a same-sequence probe to remain attached, and a later advanced probe to replace only that stream. Withhold the first encrypted shared-control ready frame, start one RPC, trigger a status-probe refresh, and require two connections, one host delivery, successful response, and zero retained request bytes. Admit 128 active streams, reject the 129th as retryable, release one stream, then require the retry to attach and publish a snapshot without multiplying retained subscribers. Disable terminal.paired-parking.v1 and require the same oracle to fail before parking, while the legacy limit-one fallback separately passes. Also preserve truncated first paint, ACK-starved same-PTY recovery, responsive silent-command snapshot probes, dead-stream probe timeout recovery, and queued manual-disconnect fencing.", + "oracle": "Audit3209 composes approved sources3202/3206: deliberately retires seven authored/expanded cases in four whole suites without equivalent replacement. Work-item queries lose real GitHub/GitLab oversized ASCII secret-prefix empty-query and whitespace-before-trim refusal alarms; inputs share the imported size bound and exercise only its fast length branch, with no multibyte or actual provider/exposure guarantee. Skill sharing loses complete/partial managed-bundle and destination-ambiguity association checks plus three negative origin/path/scheme admission examples; these do not establish uploaded contents, arbitrary-URL fetching, authorization or execution. Retain exact originless-project direct-link fallback, cloud-delete confirmation, bundled-target repair/owner isolation and explicit Windows-host preference over stale WSL suites. Rejected3201 runtime-preference removal is excluded. No real cloud/network/host/disk, mobile or mixed-version execution validation is claimed. Audit3200 composes approved source3194: deliberately retires thirteen authored registrations/twenty-seven expanded cases in six whole automation host/list policy suites without equivalent replacement. Real RPC category/retryability and wrapped-timeout recognition, unscoped-failure/scoped-success health evidence precedence, exact-ID create selectors and per-run workspace omission, paired-web local/SSH/absent host catalog routing, incompatible/removed/unhydrated/offline execution health, runtime-before-nested-SSH recovery dispatch, and no-owned-focus/successor/foreign-list focus policy alarms are consciously lost. Retain exact20line orphan allow/refuse/precondition and exact90line cross-host same-ID search suites. No retry-timer/fence lifecycle, actual reconnect/network/write delivery, native focus, mobile/mixed-version runtime or disk persistence coverage is claimed. Audit3191 combines approved source3182/3187/3188: deliberately retires thirteen authored Vitest registrations and fifteen expanded cases, including five whole suites, without equivalent replacement. Attachment intake loses real portal/native-capture terminal interception and unowned-container refusal, immediate child-only committed availability/claim-ref negotiation and delivery, and direct-target over stable focused/background composer routing through disable/re-enable/remount and independent question focus. Exact destination/cache/draft and final-stat owner/workspace/File-release suites remain; they do not replace Surface recipient routing. Automation authoring loses destination runtime catalog membership, local/direct-SSH exclusion of paired-runtime repos, unknown-runtime empty catalog, logical project/host/setup/repo/path context payload, and missing/nonready setup refusal; these were genuine direct helper alarms, while exact schedule transformation, legacy schedule and setup-decision suites remain. Agent picker loses setup-chat/terminal/missing-installer/unsupported-or-unknown-host row projection samples and the ordinary unsearched menu variant; the entire original26-line resume recipe suite remains, including reported bypass versus default/absent permission modes, as does the exact search-result menu callback with its fixtures, model/effort commits and staged Arguments reopen outcome. Rejected predecessor3180 full recipe deletion is excluded. No actual native drag/cursor/focus/IME, upload bytes or disk/restart persistence, full automation save/scheduler/runtime transport, real resume-process flags/environment delivery, or native menu/rendered layout validation is claimed. Audit3178 combines source3169/3170/3175: deliberately retires eight authored units (six Vitest cases and two imperative custom relay scenarios), including two whole suites, without equivalent replacement. Voice Section loses per-model pending-delete isolation across interleaved A/B completion and the two-success refresh-call alarm; exact VoicePane delayed key-clear/newer enabled-toggle merge remains and does not replace row deletion coverage. Speech loses dedicated rating-scale/inclusive-ceiling, unsupported-versus-unmeasured, explicit/system-language precedence/locale alias, accuracy versus fast named/default/best-measured selection, and unmeasured/no-match examples; exact offered-user-pick versus retired-selection case and its fixture remain. Relay loses legacy ping-delivery count/liveness sampled before the silence deadline and grouped malformed Bearer/host-ID 401/429 routing checks; twelve real Worker/DurableObject/shipped-client scenarios remain, not equivalent replacement for those narrow alarms. Six prior speech cases are not all deleted: approved successor3175 keeps the original user-choice case. No actual credential/file persistence, native/GPU/engine/download delivery, production assignment policy or deployed-runtime validation is claimed by this reduction. Audit3165 combines source3160/3162: deliberately retires six authored/expanded cases across three whole suites without equivalent replacement. Launch/status losses: observed React-render pending/resuming coordination across settings and deferred offer read; stale-offer reread suppressing dialog reopen; held-local-chat recovery visibility with new-chat preferences off; disabled-local admission avoiding offer RPC despite an injected but unconsumed paired-tab fixture; and run-only lost-reply uncertainty reachability until direct viewed-run retirement. Launch probe does not prove arbitrary synchronous-store atomicity, the paired fixture is not remote runtime enrollment, and the status case directly marks viewed state rather than rendering the summary. Crew-hook losses: old-host method_not_found cache persists across party changes but is released by independently supplied connection generation/verified pairing status or pairing revision, with actual frame publication and teardown. These are real narrow coordination, admission, uncertainty and mixed-version cache alarms consciously lost. Exact web verified-runtime writer handoff guard remains; it does not replace those alarms or prove live host/native/mobile delivery. Audit3156 combines3147/3150/3152/3153/3154: deliberately retires39authored/40expanded native-chat recovery cases, eight whole suites and two orphan test-support files without equivalent replacement. Lost alarms: lost-reply unconfirmed reconciliation, skipped rows/counts and missed-frame repair, unknown/pending outcome and omitted-failure-list compatibility, uncertain history after dismissal, retry/refusal/dismiss lifecycle, hidden/consumed picker ownership, result-tree keyboard focus/disclosure and all-skipped retirement; unconfirmed-over-conflict guidance and failed-chat changes despite older host timestamps; nearest-listed ancestor/cyclic forest shape, descendant membership, host ordering/missing-host local fallback; skipped/readiness/admission counts, provisional skip/progress monotonicity, early per-chat verdicts with batch pending protection, older-host waiting, start-slot/delivery distinction, retry-over-failure and unknown-after-withdrawal attention; remote snooze/reconnect/reoffer, unseen mixed summary through open/close, watched completion retirement, new success beside old failure, failed-reread mixed-result preservation, filter/collapse completion resets, retry summary replacement and current-offer/history selection; cross-host workspace identity, rendered cyclic reachability, nested tri-state/toggle propagation, project eligibility isolation and collapse preserving selection. Exact fallback-list completion barrier, batched verdict/cleanup retention, stale-read versus dismissal publication race, and requested-but-never-rendered finished-run retirement remain; they do not replace retired alarms. Audit3146 combines source reviews3132/3133/3135/3138/3143: intentionally retire20authored/31expanded cases without equivalent replacement. Provider-session losses: structured-native terminal-resume exclusion, metadata-less completed identity, new-turn completion clearing, Pi provider-only/periodic/manual promotion, changed-transcript launch-config isolation, Pi/omp/prime-agent completed-session remote/manual-shutdown promotion, and quit/done precedence over heartbeat. Side-thread/question losses: finished-pane acquisition, hidden title/recap states, local/relay/relay-done conversation takeover with prompt/session/child resets, plain-message abandonment, compaction/session replacement and completion resets. Codex startup losses: incoming-owner cached child replacement, old-relay foreign live-session correction, completed foreign-root turn-fact permutations. Transcript losses: real temporary-JSONL partial sibling/final-child completion, unlabelled child attribution, compact cached replay preservation and100/1000completed-child roster retention/release. Compiler-ratchet losses: valid-line uncompiled-list parser grammar examples and injected-existence stale-path filtering; these did not exercise actual filesystem canonicalization or build exclusion. These are real lifecycle, ownership, replay, liveness and retention alarms, including recent#40246 regressions, deliberately lost. Retained conditional record replacement, clockless root/SSH owner isolation, persisted main-thread fork rejection, partial/final question-answer lifetime, cached-roster/missing-ID/live HTTP/durable startup boundaries and restarted-relay refusal/acceptance do not replace those losses. No native/SSH/WSL execution or equivalent coverage is claimed. Audit3128 scoped coverage reduction: Audit3121 removes VoiceDictationLanguageSetting.test.tsx (Spanish-to-es callback and unsupported-model Korean option presence) and voice-speech-model-rows.test.ts (provider/language-order/retired-on-disk list policy); these real narrow alarms are deliberately retired without replacement. VoiceSpeechModelSection per-model concurrent deletion remains unchanged. Audit3122 removes the direct absolute/parent-segment sparse-directory exception-type sample and the five-row IPC sparse-preset error-code/non-save table (two authored/six expanded cases). Those real typed-validation and IPC refusal/error-code alarms are deliberately retired. Keep both real symlink/junction floating-directory trust cases and the minimal RPC structured validation-reason serialization case. The RPC case does not replace IPC save/refusal behavior, typed normalization for both path inputs, actual Git sparse checkout or rendered localization. No equivalent replacement or fresh test/runtime/platform/remote/performance validation is claimed. Audit3124 removes ExperimentalPane.test.tsx (ordinary Pet switch callback), WorkspaceDirectorySetting.test.tsx (padded absolute saved-path normalization/no-write blur), and repository-search.perf.test.ts (navigation/selected-pane builder-call policy, fixture cardinality/nonempty entries and renamed project keyword inclusion). These real narrow alarms are retired without replacement; RepositoryPane.search.test.tsx search-to-sparse-editor request remains unchanged. Audit3129: resolver Windows case-insensitive and POSIX case-sensitive configured-env composition plus mocked-base launch-preflight Windows composition are intentionally no longer checked by the two deleted suites. No equivalent coverage claimed. Keep runtime-structured-agent-host-env.test.ts unchanged: configured Windows Claude-home account identity and host-account precedence remain checked. Audit3114 incorporates source3101: retire three structured Claude child-environment wrapper cases covering inherited stamp isolation/default and explicit entrypoint, Windows SDK-key canonicalization/default/duplicate-key order, and configured lookup/final environment/config-dir conjunction. Keep direct auth/session sanitation and Windows-versus-Linux overlay checks, actual executable lookup from supplied inherited PATH, native Windows child environment delivery, and stale option-mutation fencing. These are not equivalent replacements for the retired wrapper alarms. No fresh test/runtime, real login-shell probe, Claude SDK startup, remote/mixed-version, UI or performance result is claimed. Audit3114 incorporates source3105: retire 17 authored/20 expanded daemon launch-note cases, including the entire two-case SessionLaunchNote suite. Deliberately lose split-marker carry across same-token re-arm, stale-token retirement refusal, foreground tri-state and serial settlement, omitted-note/no-incarnation mixed-version policy, sticky retirement, first-incarnation/replacement launch preservation and held-launch precedence. Keep only the unchanged unresolved foreground-read race against a later finished attach. Supplied notes/foreground and runtime calls do not establish actual daemon/main restart, SSH, native Windows observation, mobile UI, equivalent replacement or fresh runtime/performance validation. Audit3114 incorporates source3109: retire six authored/35 expanded pricing cases: 21 accepted model-name examples, 10 unsupported/future-model fail-closed examples, malformed TTL clamp, unknown-model estimate refusal, flat-model long-context disregard and oversized long-context clamp. Keep mixed five-minute/one-hour write allocation and short/all-long/mixed long-context allocation with original fixed oracles. Real parser/refusal/bounds alarms are knowingly lost without equivalent replacement; retained tests do not validate provider rates, actual billing or request threshold classification. Preserve the archived usage-scan-append source-freeze receipt without transferring historical execution/performance credit. No fresh runtime result is claimed. Audit3108 source-only reduction (3094/3095/3100): retire 27 authored/30 expanded cases, including complete markdown view-state, file-preview link-open and CLI agent-server-route suites, without replacement. Deliberate losses include preview visibility/reference lifetime and same-path owners; SSH stat, directory/missing-target, explicit-null owner, nonmarkdown line/column, local URI routing, remote-to-client guard and same-file reuse; document-preview source-owner/folder/reuse routing, stable grant location and outside-workspace POSIX/Windows request projection; and verified remote CLI send/check refusal, suggested --on argv/copy, shell no-probe bypass, unverified-launch admission and older-peer refusal. Retain two markdown source-runtime/qualified-reveal alarms, one stale grant-rejection fence and two remote read/mutation evidence policies, with original callbacks. Final last-wins reveal did not prove transient cancellation; CLI prerequisite did not prove no real send, and envelope tests do not execute server refusal. No fresh runtime, rendered UI, actual file/SSH/paired transport, authorization, mixed-version or performance result is claimed. Audit3096 source-only reduction (3087/3088): retire 69 authored/76 expanded cases, including complete recovery-portals and reconnect-banner suites. Intentionally lose dead/default TUI replay, generated alternate-frame style composition, reset/mode/dimension and legacy missing-mode-boundary alarms, UI notice/action/reveal policies, and isolated recovery lifecycle variants, without equivalent replacement. Retained registrations and callbacks are unchanged; headless cells are not pixels, and no fresh runtime, host, SSH, WSL, rendered-app or performance result is claimed. Audit3086 source-only reduction (3079/3080/3081): intentionally retire 93 authored/100 expanded mock-boundary cases, including the complete spawn-errors and SSH reconnect overlay suites, without replacement. Retired alarms include spawn classification/ownership, reply ceilings and renderer-write failure recovery, disconnect/detach fencing branches, authority facts, and overlay retry/visibility wiring. Retained callbacks are unchanged; no fresh execution, real PTY/SSH, rendered UI, or performance result is claimed. The direct side-effect-facts selector retains six cases: replay exclusion, live sequence handling, stale disposer ownership, one handoff drain, drain-before-snapshot, and stale replacement-snapshot refusal. Successful current-entry snapshot application is not witnessed by the retained snapshot case. Audit2432: The broad unit command loses the isolated BranchPicker open-change notification sample. Its unique true/false callback alarm is intentionally retired; reopening/status-refresh behavior was not exercised. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2425: The broad unit command loses the workspace-copy-status supplied readError forwarding sample. It did not exercise the branch-switch blocking promised by its title. This alarm is intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2417: The broad unit command loses two ordinary clean Git cherry-pick/revert success samples and two terminal startup foreground-read work-budget samples. These unique alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2412: The broad unit command loses the whole six-case fake-React-hook scroll-anchor suite, two generic draft-retention samples, a simple new-agent order sample, a real history-publication batching-count sample, an unmounted handoff abort/timer sample and three basic WSL preview/error samples. These alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2404: The broad unit command loses the standalone share-name lookup 503 propagation suite, initial deletion placement-kind sample, direct changed-mtime stale sample, first-pass rollback existence example and abandoned-preparation directory sample. These exact alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2397 review amendment: The broad unit command loses three standalone suites, two partial-case definitions and two URL table rows across package/download/placement tests. Keep initial wrong-port authorization, modified independent-copy digest refusal and abort-after-begin cancellation dispatch. The remaining alarms are deliberately retired; no equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2393 current-parent refresh2401: Remove the basic skill-install service alias sample and original public managed-remove receiptless refusal case. Preserve the upstream request ownership suite and transaction interruption coverage. No equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2389: The broad unit command loses the missing-preview suite, plain-global destination sample and prepublished-receipt recovery example. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2385: The broad unit command loses four authored walker/staging/protocol examples (six expanded cases); no equivalent replacement or fresh validation is claimed for the reduced suite. Audit2383: The unscoped Vitest command no longer includes the removed Antigravity catalogue suite; its exact provider-root/owner example has no equivalent replacement or fresh validation claim. Audit2377/2381: The unscoped Vitest command includes the reduced bundled-skill and native-discovery suites; the eight removed backup/legacy/catalogue/symlink/SSH-builder examples have no replacement-equivalence or fresh validation claim here. Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2090 (sources2088/2089): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2086 (sources2082/2083): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2076 (sources2073/2074): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime-tests/terminal-handles-part-02.spec.ts: recovers a moved SSH pane through the tab it now sits in, not the one its lease froze; reports a plain expired orphan; does not report a pane whose only recent lease was superseded; does not report a pane whose only recent lease had its relay id recycled; picks the eligible orphan over a superseded predecessor that matches first; collects the same tabs the per-tab reader reports, in one sweep of the leases; reports no candidate when no lease names any of the worktree tabs. src/main/runtime/orca-runtime-tests/runtime-availability.spec.ts: starts unavailable with no authoritative window; reports the configured Windows terminal shell on status; reports floating workspace availability from settings on status; polls floating tabs with targeted PTY liveness and no repo/provider inventory; hydrates persisted tabs when the store cannot report repos; advertises browser screencast only when a renderer window is available; routes mobile Codex reset consumption through the account mutation coordinator; maps a definite pre-provider rejection into an authoritative current snapshot. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Frozen current literal-import graph reaches these changed test bytes; unresolved local and computed edges remain debt, and current reachability is not historical execution or equivalent replacement evidence. Historical prior account (preserved verbatim): Audit2003: Remove SSH/absent-inventory attach refusal, later-subscriber retry, no-view adoption/takeback, provider-tail/unknown-read projections, failed-keystroke retry and simpler loss reattach examples. Keep the existing-subscriber inventory-ready retry alias only at its retained callback, plus retained held-input cancellation/replacement and overlapping attach/loss fences. The inventory driver also loses the whole empty-worktree-publication registration and folder-host/unverifiable scalar examples. Retire the entire dated10-case attach receipt; retain16 independent receipts only in their original scopes. No retained-memory or real-daemon measurement follows from supplied provider inventories. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, physical provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1991: Remove initial-snapshot sequence-domain, limited-tail/truncation and unknown-output-sequence aliases whose callbacks are removed. The source retains partial-chunk replay and requested-snapshot retry/admission at supplied snapshot/data seams, not equivalent replacement or measured retained-memory proof. Preserve the existing stream/pending-wait capacity aliases only to their retained owning multiplex callbacks with supplied PTY resolutions. Removing the sibling-PTY heartbeat dedup work-count sample does not establish a new decorative fanout budget; the unrelated-PTY cancellation fence survives. Preserve17 unrelated dated receipts. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, physical provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1983: Remove the reasonless-close selector and narrow census aliases to actual retained runtime and injected-inventory callbacks. The removed synthetic census-dedup and isolated pre-boundary timing cases receive no replacement credit; preserve17 unrelated dated receipts. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1939 (sources1934/1935): Delete the synthetic watcher-synchronization and partial-reconciliation suites. Retire all affected host-fact, capability-owner, activation-residue and retention-cap aliases because the remaining callbacks do not establish those full claims. Keep exact local hook/timer, byte-stream side effects, exit/disposal, scroll-intent cleanup and deterministic local rank/TTL progression callbacks within their mocked-host scope. No physical paired-host retention, resource budget or equivalent replacement evidence is assigned. The generic broad test command remains a runnable discovery command, never a dated execution receipt. Preserve meaningful remaining selectors/assertions and unchanged dated receipts within their original scope. Reduced selectors have no fresh gate execution evidence in this metadata packet. No equivalent replacement, physical watcher/PTY/provider, live SSH/remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): Audit1931 (sources1928/1929): Delete the complete hook-agent-status projection suite and its two behavioral assertion aliases. Supplied stored hook/title/resume/staleness/rename/question/generation/PTY-retirement/snapshot-version projections are intentionally lost. The separate osc-status-scan gate mentions this source only in existing historical notes and receives no mutation. No measured hidden-output retention, CPU/RSS or resource budget result is claimed by the deleted source or this audit. Preserve meaningful remaining selectors/assertions and unchanged dated receipts within their original scope. Reduced selectors have no fresh gate execution evidence in this metadata packet. No equivalent replacement, physical watcher/PTY/provider, live SSH/remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): Retained exact unchanged-source receipts remain the only current execution evidence. Reduced selectors have no fresh execution result. Historical pre-audit oracle account for changed sources: The retained unchanged-source receipts are the only current execution evidence; reduced-source assertions await validation. Historical oracle account (not a current claim for changed sources): Existing exact unchanged-selector receipts remain the only current execution evidence. Changed source selectors have no fresh execution result. Historical prior-source oracle account: Existing exact unchanged-selector receipts remain the only current execution evidence. Changed source selectors have no fresh execution result. Historical prior-source oracle account: Run one byte-identical six-terminal oracle against an isolated headed desktop host and an isolated headless `orca serve` host. Stage at least 1,000,000 xterm cells, hide all six warm managers, emit an initial working title followed by 30 timed real-PTY spinner frames and a final idle title per worktree, and observe a second real session-tabs subscription plus the production renderer store. Require exactly two transport envelopes and two title mutations per worktree, no decorative title crossing either boundary, and positive decoded-envelope bytes. Enable ordinary parking with the lossy retention budget disabled, require exactly one mounted manager and five parked tabs, at most 45% retained cells, no more than 16 MiB heap growth, and under 500 ms timer drift. In headed mode, require the host renderer to remain on its original workspace with zero target terminal managers mounted throughout client park, reveal, and live I/O. While a tab is parked, require authoritative terminal.read to observe new PTY output; reveal it and require the original PTY, a marker within the requested 5,000-row history, the parked marker, and post-reveal input/output. Drive 24 real PTY title trackers in distinct worktrees through 40 decorative spinner frames each, then 40 spinner frames alternating with Cursor's bare native identity redraw, using fake clocks. Require all 2,880 raw chunks exactly and zero host session-tabs publications, serialized bytes, renderer apply calls, and renderer store mutations. Continue decorative evidence beyond 30 minutes, require exactly one refresh per worktree per 15-minute lease through a FIFO spaced by at least 50 ms, and require all 24 viewer statuses to remain working and fresh; then require one exact semantic idle transition and one visible-output chunk per PTY. Require ordinary and interior-Braille title changes to publish. Drive 64 host PTYs through ten 80 ms synthetic title frames, require zero paired client events after the first frame per PTY while all 640 local frames remain observable, attach a late client and require one current frame per PTY, then require semantic bell and idle transitions on both clients. Reconstruct a legacy subscribed stream with no outputPause capability, hide a chatty pane, require no hidden xterm writes, reveal it, and require one authoritative snapshot plus continued live output. Drop and acknowledge output only for one original paired-client stream, prove the fixture process consumed input while the host model advanced and the client stayed stale, then require the command snapshot probe to replace that stream, repaint exact fixture output, preserve authoritative PTY identity and target-tab cardinality, and resume live I/O. For a client without a delivered sequence, require the first numeric probe to establish a baseline without replacement, a same-sequence probe to remain attached, and a later advanced probe to replace only that stream. Withhold the first encrypted shared-control ready frame, start one RPC, trigger a status-probe refresh, and require two connections, one host delivery, successful response, and zero retained request bytes. Admit 128 active streams, reject the 129th as retryable, release one stream, then require the retry to attach and publish a snapshot without multiplying retained subscribers. Disable terminal.paired-parking.v1 and require the same oracle to fail before parking, while the legacy limit-one fallback separately passes. Also preserve truncated first paint, ACK-starved same-PTY recovery, responsive silent-command snapshot probes, dead-stream probe timeout recovery, and queued manual-disconnect fencing.", "commands": [ "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport-unpublished-host-graph.test.ts", "ORCA_BACKGROUND_LAUNCH=1 pnpm exec playwright test tests/e2e/paired-remote-terminal-host-quit-reconnect-input.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1", @@ -9034,7 +9041,19 @@ "Audit2425 removes use-workspace-copy-status original5, which returns a fixture-supplied readError string through statusReadError. No consumer blocker or attempted branch switch established refusal; the unique error-forwarding sample is intentionally retired. Other copy ownership and stale-refresh cases are not equivalent error-path coverage. No equivalent replacement or fresh validation is claimed.", "Audit2432 removes BranchPicker.test.tsx original3, which only asserted onOpenChange(true/false) with an always-mounted mocked Popover. It never reopened the picker or consumed the callback in the parent status-refresh owner, despite its title. Lose that unique open/close notification alarm. Retained blocker/collision recovery and asynchronous post-unmount outcome cases are not equivalent replacement coverage. No fresh validation of the reduced selector is claimed.", "Audit3086 source-only reduction (3079/3080/3081): intentionally retire 93 authored/100 expanded mock-boundary cases, including the complete spawn-errors and SSH reconnect overlay suites, without replacement. Retired alarms include spawn classification/ownership, reply ceilings and renderer-write failure recovery, disconnect/detach fencing branches, authority facts, and overlay retry/visibility wiring. Retained callbacks are unchanged; no fresh execution, real PTY/SSH, rendered UI, or performance result is claimed. The direct side-effect-facts selector retains six cases: replay exclusion, live sequence handling, stale disposer ownership, one handoff drain, drain-before-snapshot, and stale replacement-snapshot refusal. Successful current-entry snapshot application is not witnessed by the retained snapshot case.", - "Audit3096 source-only reduction (3087/3088): retire 69 authored/76 expanded cases, including complete recovery-portals and reconnect-banner suites. Intentionally lose dead/default TUI replay, generated alternate-frame style composition, reset/mode/dimension and legacy missing-mode-boundary alarms, UI notice/action/reveal policies, and isolated recovery lifecycle variants, without equivalent replacement. Retained registrations and callbacks are unchanged; headless cells are not pixels, and no fresh runtime, host, SSH, WSL, rendered-app or performance result is claimed." + "Audit3096 source-only reduction (3087/3088): retire 69 authored/76 expanded cases, including complete recovery-portals and reconnect-banner suites. Intentionally lose dead/default TUI replay, generated alternate-frame style composition, reset/mode/dimension and legacy missing-mode-boundary alarms, UI notice/action/reveal policies, and isolated recovery lifecycle variants, without equivalent replacement. Retained registrations and callbacks are unchanged; headless cells are not pixels, and no fresh runtime, host, SSH, WSL, rendered-app or performance result is claimed.", + "Audit3108 source-only reduction (3094/3095/3100): retire 27 authored/30 expanded cases, including complete markdown view-state, file-preview link-open and CLI agent-server-route suites, without replacement. Deliberate losses include preview visibility/reference lifetime and same-path owners; SSH stat, directory/missing-target, explicit-null owner, nonmarkdown line/column, local URI routing, remote-to-client guard and same-file reuse; document-preview source-owner/folder/reuse routing, stable grant location and outside-workspace POSIX/Windows request projection; and verified remote CLI send/check refusal, suggested --on argv/copy, shell no-probe bypass, unverified-launch admission and older-peer refusal. Retain two markdown source-runtime/qualified-reveal alarms, one stale grant-rejection fence and two remote read/mutation evidence policies, with original callbacks. Final last-wins reveal did not prove transient cancellation; CLI prerequisite did not prove no real send, and envelope tests do not execute server refusal. No fresh runtime, rendered UI, actual file/SSH/paired transport, authorization, mixed-version or performance result is claimed.", + "Audit3114 incorporates source3101: retire three structured Claude child-environment wrapper cases covering inherited stamp isolation/default and explicit entrypoint, Windows SDK-key canonicalization/default/duplicate-key order, and configured lookup/final environment/config-dir conjunction. Keep direct auth/session sanitation and Windows-versus-Linux overlay checks, actual executable lookup from supplied inherited PATH, native Windows child environment delivery, and stale option-mutation fencing. These are not equivalent replacements for the retired wrapper alarms. No fresh test/runtime, real login-shell probe, Claude SDK startup, remote/mixed-version, UI or performance result is claimed.", + "Audit3114 incorporates source3105: retire 17 authored/20 expanded daemon launch-note cases, including the entire two-case SessionLaunchNote suite. Deliberately lose split-marker carry across same-token re-arm, stale-token retirement refusal, foreground tri-state and serial settlement, omitted-note/no-incarnation mixed-version policy, sticky retirement, first-incarnation/replacement launch preservation and held-launch precedence. Keep only the unchanged unresolved foreground-read race against a later finished attach. Supplied notes/foreground and runtime calls do not establish actual daemon/main restart, SSH, native Windows observation, mobile UI, equivalent replacement or fresh runtime/performance validation.", + "Audit3114 incorporates source3109: retire six authored/35 expanded pricing cases: 21 accepted model-name examples, 10 unsupported/future-model fail-closed examples, malformed TTL clamp, unknown-model estimate refusal, flat-model long-context disregard and oversized long-context clamp. Keep mixed five-minute/one-hour write allocation and short/all-long/mixed long-context allocation with original fixed oracles. Real parser/refusal/bounds alarms are knowingly lost without equivalent replacement; retained tests do not validate provider rates, actual billing or request threshold classification. Preserve the archived usage-scan-append source-freeze receipt without transferring historical execution/performance credit. No fresh runtime result is claimed.", + "Audit3128 scoped coverage reduction: Audit3121 removes VoiceDictationLanguageSetting.test.tsx (Spanish-to-es callback and unsupported-model Korean option presence) and voice-speech-model-rows.test.ts (provider/language-order/retired-on-disk list policy); these real narrow alarms are deliberately retired without replacement. VoiceSpeechModelSection per-model concurrent deletion remains unchanged. Audit3122 removes the direct absolute/parent-segment sparse-directory exception-type sample and the five-row IPC sparse-preset error-code/non-save table (two authored/six expanded cases). Those real typed-validation and IPC refusal/error-code alarms are deliberately retired. Keep both real symlink/junction floating-directory trust cases and the minimal RPC structured validation-reason serialization case. The RPC case does not replace IPC save/refusal behavior, typed normalization for both path inputs, actual Git sparse checkout or rendered localization. No equivalent replacement or fresh test/runtime/platform/remote/performance validation is claimed. Audit3124 removes ExperimentalPane.test.tsx (ordinary Pet switch callback), WorkspaceDirectorySetting.test.tsx (padded absolute saved-path normalization/no-write blur), and repository-search.perf.test.ts (navigation/selected-pane builder-call policy, fixture cardinality/nonempty entries and renamed project keyword inclusion). These real narrow alarms are retired without replacement; RepositoryPane.search.test.tsx search-to-sparse-editor request remains unchanged. Audit3129: resolver Windows case-insensitive and POSIX case-sensitive configured-env composition plus mocked-base launch-preflight Windows composition are intentionally no longer checked by the two deleted suites. No equivalent coverage claimed. Keep runtime-structured-agent-host-env.test.ts unchanged: configured Windows Claude-home account identity and host-account precedence remain checked.", + "Audit3146 combines source reviews3132/3133/3135/3138/3143: intentionally retire20authored/31expanded cases without equivalent replacement. Provider-session losses: structured-native terminal-resume exclusion, metadata-less completed identity, new-turn completion clearing, Pi provider-only/periodic/manual promotion, changed-transcript launch-config isolation, Pi/omp/prime-agent completed-session remote/manual-shutdown promotion, and quit/done precedence over heartbeat. Side-thread/question losses: finished-pane acquisition, hidden title/recap states, local/relay/relay-done conversation takeover with prompt/session/child resets, plain-message abandonment, compaction/session replacement and completion resets. Codex startup losses: incoming-owner cached child replacement, old-relay foreign live-session correction, completed foreign-root turn-fact permutations. Transcript losses: real temporary-JSONL partial sibling/final-child completion, unlabelled child attribution, compact cached replay preservation and100/1000completed-child roster retention/release. Compiler-ratchet losses: valid-line uncompiled-list parser grammar examples and injected-existence stale-path filtering; these did not exercise actual filesystem canonicalization or build exclusion. These are real lifecycle, ownership, replay, liveness and retention alarms, including recent#40246 regressions, deliberately lost. Retained conditional record replacement, clockless root/SSH owner isolation, persisted main-thread fork rejection, partial/final question-answer lifetime, cached-roster/missing-ID/live HTTP/durable startup boundaries and restarted-relay refusal/acceptance do not replace those losses. No native/SSH/WSL execution or equivalent coverage is claimed.", + "Audit3156 combines3147/3150/3152/3153/3154: deliberately retires39authored/40expanded native-chat recovery cases, eight whole suites and two orphan test-support files without equivalent replacement. Lost alarms: lost-reply unconfirmed reconciliation, skipped rows/counts and missed-frame repair, unknown/pending outcome and omitted-failure-list compatibility, uncertain history after dismissal, retry/refusal/dismiss lifecycle, hidden/consumed picker ownership, result-tree keyboard focus/disclosure and all-skipped retirement; unconfirmed-over-conflict guidance and failed-chat changes despite older host timestamps; nearest-listed ancestor/cyclic forest shape, descendant membership, host ordering/missing-host local fallback; skipped/readiness/admission counts, provisional skip/progress monotonicity, early per-chat verdicts with batch pending protection, older-host waiting, start-slot/delivery distinction, retry-over-failure and unknown-after-withdrawal attention; remote snooze/reconnect/reoffer, unseen mixed summary through open/close, watched completion retirement, new success beside old failure, failed-reread mixed-result preservation, filter/collapse completion resets, retry summary replacement and current-offer/history selection; cross-host workspace identity, rendered cyclic reachability, nested tri-state/toggle propagation, project eligibility isolation and collapse preserving selection. Exact fallback-list completion barrier, batched verdict/cleanup retention, stale-read versus dismissal publication race, and requested-but-never-rendered finished-run retirement remain; they do not replace retired alarms.", + "Audit3165 combines source3160/3162: deliberately retires six authored/expanded cases across three whole suites without equivalent replacement. Launch/status losses: observed React-render pending/resuming coordination across settings and deferred offer read; stale-offer reread suppressing dialog reopen; held-local-chat recovery visibility with new-chat preferences off; disabled-local admission avoiding offer RPC despite an injected but unconsumed paired-tab fixture; and run-only lost-reply uncertainty reachability until direct viewed-run retirement. Launch probe does not prove arbitrary synchronous-store atomicity, the paired fixture is not remote runtime enrollment, and the status case directly marks viewed state rather than rendering the summary. Crew-hook losses: old-host method_not_found cache persists across party changes but is released by independently supplied connection generation/verified pairing status or pairing revision, with actual frame publication and teardown. These are real narrow coordination, admission, uncertainty and mixed-version cache alarms consciously lost. Exact web verified-runtime writer handoff guard remains; it does not replace those alarms or prove live host/native/mobile delivery.", + "Audit3178 combines source3169/3170/3175: deliberately retires eight authored units (six Vitest cases and two imperative custom relay scenarios), including two whole suites, without equivalent replacement. Voice Section loses per-model pending-delete isolation across interleaved A/B completion and the two-success refresh-call alarm; exact VoicePane delayed key-clear/newer enabled-toggle merge remains and does not replace row deletion coverage. Speech loses dedicated rating-scale/inclusive-ceiling, unsupported-versus-unmeasured, explicit/system-language precedence/locale alias, accuracy versus fast named/default/best-measured selection, and unmeasured/no-match examples; exact offered-user-pick versus retired-selection case and its fixture remain. Relay loses legacy ping-delivery count/liveness sampled before the silence deadline and grouped malformed Bearer/host-ID 401/429 routing checks; twelve real Worker/DurableObject/shipped-client scenarios remain, not equivalent replacement for those narrow alarms. Six prior speech cases are not all deleted: approved successor3175 keeps the original user-choice case. No actual credential/file persistence, native/GPU/engine/download delivery, production assignment policy or deployed-runtime validation is claimed by this reduction.", + "Audit3191 combines approved source3182/3187/3188: deliberately retires thirteen authored Vitest registrations and fifteen expanded cases, including five whole suites, without equivalent replacement. Attachment intake loses real portal/native-capture terminal interception and unowned-container refusal, immediate child-only committed availability/claim-ref negotiation and delivery, and direct-target over stable focused/background composer routing through disable/re-enable/remount and independent question focus. Exact destination/cache/draft and final-stat owner/workspace/File-release suites remain; they do not replace Surface recipient routing. Automation authoring loses destination runtime catalog membership, local/direct-SSH exclusion of paired-runtime repos, unknown-runtime empty catalog, logical project/host/setup/repo/path context payload, and missing/nonready setup refusal; these were genuine direct helper alarms, while exact schedule transformation, legacy schedule and setup-decision suites remain. Agent picker loses setup-chat/terminal/missing-installer/unsupported-or-unknown-host row projection samples and the ordinary unsearched menu variant; the entire original26-line resume recipe suite remains, including reported bypass versus default/absent permission modes, as does the exact search-result menu callback with its fixtures, model/effort commits and staged Arguments reopen outcome. Rejected predecessor3180 full recipe deletion is excluded. No actual native drag/cursor/focus/IME, upload bytes or disk/restart persistence, full automation save/scheduler/runtime transport, real resume-process flags/environment delivery, or native menu/rendered layout validation is claimed.", + "Audit3200 composes approved source3194: deliberately retires thirteen authored registrations/twenty-seven expanded cases in six whole automation host/list policy suites without equivalent replacement. Real RPC category/retryability and wrapped-timeout recognition, unscoped-failure/scoped-success health evidence precedence, exact-ID create selectors and per-run workspace omission, paired-web local/SSH/absent host catalog routing, incompatible/removed/unhydrated/offline execution health, runtime-before-nested-SSH recovery dispatch, and no-owned-focus/successor/foreign-list focus policy alarms are consciously lost. Retain exact20line orphan allow/refuse/precondition and exact90line cross-host same-ID search suites. No retry-timer/fence lifecycle, actual reconnect/network/write delivery, native focus, mobile/mixed-version runtime or disk persistence coverage is claimed.", + "Audit3209 composes approved sources3202/3206: deliberately retires seven authored/expanded cases in four whole suites without equivalent replacement. Work-item queries lose real GitHub/GitLab oversized ASCII secret-prefix empty-query and whitespace-before-trim refusal alarms; inputs share the imported size bound and exercise only its fast length branch, with no multibyte or actual provider/exposure guarantee. Skill sharing loses complete/partial managed-bundle and destination-ambiguity association checks plus three negative origin/path/scheme admission examples; these do not establish uploaded contents, arbitrary-URL fetching, authorization or execution. Retain exact originless-project direct-link fallback, cloud-delete confirmation, bundled-target repair/owner isolation and explicit Windows-host preference over stale WSL suites. Rejected3201 runtime-preference removal is excluded. No real cloud/network/host/disk, mobile or mixed-version execution validation is claimed." ], "demotionRule": "Keep experimental or demote to protection none if decorative title frequency changes paired client-event or session-tabs publication volume after convergence, a semantic fact is dropped, paired first paint is blank, passive work reconnects after manual disconnect, a capable hidden paired manager survives ordinary parking, a legacy hidden pane schedules raw xterm output or bypasses its fallback, reveal loses requested bounded history or live PTY identity, retained buffer cells do not fall, or either headed/headless scenario flakes." }, @@ -9212,7 +9231,7 @@ "providers": ["local", "daemon", "ssh", "remote-runtime"], "coveredPlatforms": ["macos"], "coveredProviders": [], - "coverageNotes": "Audit3096 source-only reduction (3087/3088): retire 69 authored/76 expanded cases, including complete recovery-portals and reconnect-banner suites. Intentionally lose dead/default TUI replay, generated alternate-frame style composition, reset/mode/dimension and legacy missing-mode-boundary alarms, UI notice/action/reveal policies, and isolated recovery lifecycle variants, without equivalent replacement. Retained registrations and callbacks are unchanged; headless cells are not pixels, and no fresh runtime, host, SSH, WSL, rendered-app or performance result is claimed. Audit3086 source-only reduction (3079/3080/3081): intentionally retire 93 authored/100 expanded mock-boundary cases, including the complete spawn-errors and SSH reconnect overlay suites, without replacement. Retired alarms include spawn classification/ownership, reply ceilings and renderer-write failure recovery, disconnect/detach fencing branches, authority facts, and overlay retry/visibility wiring. Retained callbacks are unchanged; no fresh execution, real PTY/SSH, rendered UI, or performance result is claimed. Module layout SSH policy: Retire the multiplexer private-clock saturation registration, the writer saturation transition-count registration and the changed-source dated writer/backpressure receipt. Retained byte delivery, lane order, fairness, settlement and cancellation cases are unvalidated by that historical receipt. No equivalent replacement, new execution, measured performance, live SSH/WSL or cross-platform proof is claimed. The unchanged WSL protocol receipt retains only its original command scope. Historical prior account (preserved verbatim): Audit2432: The broad unit command loses the isolated BranchPicker open-change notification sample. Its unique true/false callback alarm is intentionally retired; reopening/status-refresh behavior was not exercised. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2425: The broad unit command loses the workspace-copy-status supplied readError forwarding sample. It did not exercise the branch-switch blocking promised by its title. This alarm is intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2417: The broad unit command loses two ordinary clean Git cherry-pick/revert success samples and two terminal startup foreground-read work-budget samples. These unique alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2412: The broad unit command loses the whole six-case fake-React-hook scroll-anchor suite, two generic draft-retention samples, a simple new-agent order sample, a real history-publication batching-count sample, an unmounted handoff abort/timer sample and three basic WSL preview/error samples. These alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2404: The broad unit command loses the standalone share-name lookup 503 propagation suite, initial deletion placement-kind sample, direct changed-mtime stale sample, first-pass rollback existence example and abandoned-preparation directory sample. These exact alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2397 review amendment: The broad unit command loses three standalone suites, two partial-case definitions and two URL table rows across package/download/placement tests. Keep initial wrong-port authorization, modified independent-copy digest refusal and abort-after-begin cancellation dispatch. The remaining alarms are deliberately retired; no equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2393 current-parent refresh2401: Remove the basic skill-install service alias sample and original public managed-remove receiptless refusal case. Preserve the upstream request ownership suite and transaction interruption coverage. No equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2389: The broad unit command loses the missing-preview suite, plain-global destination sample and prepublished-receipt recovery example. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2385: The broad unit command loses four authored walker/staging/protocol examples (six expanded cases); no equivalent replacement or fresh validation is claimed for the reduced suite. Audit2383: The unscoped Vitest command no longer includes the removed Antigravity catalogue suite; its exact provider-root/owner example has no equivalent replacement or fresh validation claim. Audit2377/2381: The unscoped Vitest command includes the reduced bundled-skill and native-discovery suites; the eight removed backup/legacy/catalogue/symlink/SSH-builder examples have no replacement-equivalence or fresh validation claim here. Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2090 (sources2088/2089): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2086 (sources2082/2083): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2076 (sources2073/2074): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime-tests/terminal-handles-part-02.spec.ts: recovers a moved SSH pane through the tab it now sits in, not the one its lease froze; reports a plain expired orphan; does not report a pane whose only recent lease was superseded; does not report a pane whose only recent lease had its relay id recycled; picks the eligible orphan over a superseded predecessor that matches first; collects the same tabs the per-tab reader reports, in one sweep of the leases; reports no candidate when no lease names any of the worktree tabs. src/main/runtime/orca-runtime-tests/runtime-availability.spec.ts: starts unavailable with no authoritative window; reports the configured Windows terminal shell on status; reports floating workspace availability from settings on status; polls floating tabs with targeted PTY liveness and no repo/provider inventory; hydrates persisted tabs when the store cannot report repos; advertises browser screencast only when a renderer window is available; routes mobile Codex reset consumption through the account mutation coordinator; maps a definite pre-provider rejection into an authoritative current snapshot. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Frozen current literal-import graph reaches these changed test bytes; unresolved local and computed edges remain debt, and current reachability is not historical execution or equivalent replacement evidence. Historical prior account (preserved verbatim): Audit2070 (sources2068/2069): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime.test.ts: ordinary registration cleanup removes only await import('./orca-runtime-tests/hooks-and-hosted-review.spec'). src/main/ssh/ssh-multiplexer-transport-writer.test.ts: reports saturated epochs and their drain boundary exactly once. src/main/runtime/orca-runtime-tests/worktree-removal-archive-hook-gate.spec.ts: removes and records the waiver when the failure is explicitly overridden; removes without an override record when the hook succeeds; removes when the hook is configured but not requested; removes when no archive hook is configured; holds a desktop removal in the same repo until this one is accepted; joins a desktop removal of the same worktree accepted while this one waited. src/main/runtime/orca-runtime-tests/worktree-ps-agent-row-dismissal.spec.ts: drops the row as soon as the user dismisses it, without waiting for the PTY to exit; tells paired clients to republish on the transition and on the dismissal; rejoins a row through its %s handle after pane ownership clears. src/main/runtime/orca-runtime-tests/hooks-and-hosted-review.spec.ts: reports an error when the SSH filesystem provider is unavailable; reports an SSH orca.yaml as an error without reading any filesystem; reports ok for a local repo hook check; reads SSH issue commands as absent and drops writes without touching any filesystem; allows host integration slug helpers for SSH repos through provider-aware GitHub clients; routes runtime GitHub repo identity helpers through the selected WSL project runtime; routes runtime GitHub issue and work-item actions through the selected WSL project runtime; pins explicit origin preference on runtime open-by-number work item lookups; forwards check-details cancellation without local Git overrides. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Frozen current literal-import graph reaches these changed test bytes; unresolved local and computed edges remain debt, and current reachability is not historical execution or equivalent replacement evidence. The historical receipt/currentCommand selecting src/main/ssh/ssh-multiplexer-transport-writer.test.ts remains historical and is not a passing result for the reduced current command. Historical prior account (preserved verbatim): Audit1931 (sources1928/1929): Delete the complete tail-wait memo suite: its sole current authored callback checks supplied fromTail/blocked field values. Retire all three broader memoization/equivalence/eviction assertion aliases; they are not backed by retained source callbacks. No scan-work budget, sustained output, physical terminal or resource measurement is assigned to this removed test. Preserve meaningful remaining selectors/assertions and unchanged dated receipts within their original scope. Reduced selectors have no fresh gate execution evidence in this metadata packet. No equivalent replacement, physical watcher/PTY/provider, live SSH/remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): Audit1674 removes low-value test projections, mock wiring, private-state assertions, inventories and duplicate examples without equivalent replacement coverage. Per-source reviews record retained public behavior and refusal boundaries with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1634 removes low-value IPC, filesystem and runtime projections, argument inventories and duplicate examples without equivalent replacement coverage. Per-source reviews record retained cancellation, ownership, authorization, filesystem and SQLite boundaries with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Local macOS evidence covers main-process pending-output and projection-admission caps, saturated-tail wait detection, direct-SSH source retention/accounting, always-on V1 negotiation with legacy peer fallback, exact provider-generation pause ownership, renderer exit/data ordering, decoder input bounds, bounded reconnect scheduling, and WSL stdio transport settlement through deterministic unit contracts. A joined main/runtime oracle exercises renderer-sourced headed semantics and headless-model snapshot semantics without launching a live paired server. Separately, a macOS-hosted Docker OpenSSH run exercises only the deployed Linux relay and direct SSH provider with an exact 256 KiB source-credit plateau, concurrent PTY typing, fixed-size filesystem frames, Git churn, and owner-lease reconnect. Neither deterministic topology labels nor Docker SSH constitute live headed desktop, headless orca serve, or physical WSL evidence; local/daemon, prior-version daemons, Windows named pipes/ConPTY, folder workspaces, and mixed-version clients also remain uncovered. Audit1312 removes low-value imported specs from aggregate test drivers; old whole-driver execution receipts are archived. Retained registrations are unchanged. No equivalent replacement coverage is claimed. Audit1383: src/main/runtime/orca-runtime-tests/worktree-native-chat-setup.spec.ts reduced. Lose command-list/receipt/default/background activation matrices whose provider spawn returns canned IDs. Retained test proves actual tab allocation separation, not terminal startup. No equivalent replacement coverage is claimed. Existing exact unaffected receipts and their platform/provider/budget claims remain scoped to unchanged selectors. Changed optional selectors have no new execution result. Audit1401: src/main/runtime/orca-runtime-tests/mobile-session-tabs-duplicate-pty-repair.spec.ts removed. Loses listing-on-already-repaired-data alarm; it never established runtime repair invocation. src/main/runtime/orca-runtime-tests/mobile-session-tabs-split-agent-tab.spec.ts removed. Loses actual mobile split sibling shell versus recorded-agent resume command alarms; no equivalent coverage asserted. src/main/runtime/orca-runtime-tests/worktree-native-chat-setup.spec.ts removed. Loses separate setup/startup tab result in that manually assembled path. src/main/runtime/orca-runtime.test.ts reduced. Driver registration/import of a whole-deleted selected spec is removed; directly authored cases remain unchanged. No extra authored removal credit. No equivalent replacement coverage is claimed. Existing exact unaffected receipts remain unchanged and apply only to their unchanged selectors. Changed optional selectors have no new execution result.", + "coverageNotes": "Audit3209 composes approved sources3202/3206: deliberately retires seven authored/expanded cases in four whole suites without equivalent replacement. Work-item queries lose real GitHub/GitLab oversized ASCII secret-prefix empty-query and whitespace-before-trim refusal alarms; inputs share the imported size bound and exercise only its fast length branch, with no multibyte or actual provider/exposure guarantee. Skill sharing loses complete/partial managed-bundle and destination-ambiguity association checks plus three negative origin/path/scheme admission examples; these do not establish uploaded contents, arbitrary-URL fetching, authorization or execution. Retain exact originless-project direct-link fallback, cloud-delete confirmation, bundled-target repair/owner isolation and explicit Windows-host preference over stale WSL suites. Rejected3201 runtime-preference removal is excluded. No real cloud/network/host/disk, mobile or mixed-version execution validation is claimed. Audit3200 composes approved source3194: deliberately retires thirteen authored registrations/twenty-seven expanded cases in six whole automation host/list policy suites without equivalent replacement. Real RPC category/retryability and wrapped-timeout recognition, unscoped-failure/scoped-success health evidence precedence, exact-ID create selectors and per-run workspace omission, paired-web local/SSH/absent host catalog routing, incompatible/removed/unhydrated/offline execution health, runtime-before-nested-SSH recovery dispatch, and no-owned-focus/successor/foreign-list focus policy alarms are consciously lost. Retain exact20line orphan allow/refuse/precondition and exact90line cross-host same-ID search suites. No retry-timer/fence lifecycle, actual reconnect/network/write delivery, native focus, mobile/mixed-version runtime or disk persistence coverage is claimed. Audit3191 combines approved source3182/3187/3188: deliberately retires thirteen authored Vitest registrations and fifteen expanded cases, including five whole suites, without equivalent replacement. Attachment intake loses real portal/native-capture terminal interception and unowned-container refusal, immediate child-only committed availability/claim-ref negotiation and delivery, and direct-target over stable focused/background composer routing through disable/re-enable/remount and independent question focus. Exact destination/cache/draft and final-stat owner/workspace/File-release suites remain; they do not replace Surface recipient routing. Automation authoring loses destination runtime catalog membership, local/direct-SSH exclusion of paired-runtime repos, unknown-runtime empty catalog, logical project/host/setup/repo/path context payload, and missing/nonready setup refusal; these were genuine direct helper alarms, while exact schedule transformation, legacy schedule and setup-decision suites remain. Agent picker loses setup-chat/terminal/missing-installer/unsupported-or-unknown-host row projection samples and the ordinary unsearched menu variant; the entire original26-line resume recipe suite remains, including reported bypass versus default/absent permission modes, as does the exact search-result menu callback with its fixtures, model/effort commits and staged Arguments reopen outcome. Rejected predecessor3180 full recipe deletion is excluded. No actual native drag/cursor/focus/IME, upload bytes or disk/restart persistence, full automation save/scheduler/runtime transport, real resume-process flags/environment delivery, or native menu/rendered layout validation is claimed. Audit3178 combines source3169/3170/3175: deliberately retires eight authored units (six Vitest cases and two imperative custom relay scenarios), including two whole suites, without equivalent replacement. Voice Section loses per-model pending-delete isolation across interleaved A/B completion and the two-success refresh-call alarm; exact VoicePane delayed key-clear/newer enabled-toggle merge remains and does not replace row deletion coverage. Speech loses dedicated rating-scale/inclusive-ceiling, unsupported-versus-unmeasured, explicit/system-language precedence/locale alias, accuracy versus fast named/default/best-measured selection, and unmeasured/no-match examples; exact offered-user-pick versus retired-selection case and its fixture remain. Relay loses legacy ping-delivery count/liveness sampled before the silence deadline and grouped malformed Bearer/host-ID 401/429 routing checks; twelve real Worker/DurableObject/shipped-client scenarios remain, not equivalent replacement for those narrow alarms. Six prior speech cases are not all deleted: approved successor3175 keeps the original user-choice case. No actual credential/file persistence, native/GPU/engine/download delivery, production assignment policy or deployed-runtime validation is claimed by this reduction. Audit3165 combines source3160/3162: deliberately retires six authored/expanded cases across three whole suites without equivalent replacement. Launch/status losses: observed React-render pending/resuming coordination across settings and deferred offer read; stale-offer reread suppressing dialog reopen; held-local-chat recovery visibility with new-chat preferences off; disabled-local admission avoiding offer RPC despite an injected but unconsumed paired-tab fixture; and run-only lost-reply uncertainty reachability until direct viewed-run retirement. Launch probe does not prove arbitrary synchronous-store atomicity, the paired fixture is not remote runtime enrollment, and the status case directly marks viewed state rather than rendering the summary. Crew-hook losses: old-host method_not_found cache persists across party changes but is released by independently supplied connection generation/verified pairing status or pairing revision, with actual frame publication and teardown. These are real narrow coordination, admission, uncertainty and mixed-version cache alarms consciously lost. Exact web verified-runtime writer handoff guard remains; it does not replace those alarms or prove live host/native/mobile delivery. Audit3156 combines3147/3150/3152/3153/3154: deliberately retires39authored/40expanded native-chat recovery cases, eight whole suites and two orphan test-support files without equivalent replacement. Lost alarms: lost-reply unconfirmed reconciliation, skipped rows/counts and missed-frame repair, unknown/pending outcome and omitted-failure-list compatibility, uncertain history after dismissal, retry/refusal/dismiss lifecycle, hidden/consumed picker ownership, result-tree keyboard focus/disclosure and all-skipped retirement; unconfirmed-over-conflict guidance and failed-chat changes despite older host timestamps; nearest-listed ancestor/cyclic forest shape, descendant membership, host ordering/missing-host local fallback; skipped/readiness/admission counts, provisional skip/progress monotonicity, early per-chat verdicts with batch pending protection, older-host waiting, start-slot/delivery distinction, retry-over-failure and unknown-after-withdrawal attention; remote snooze/reconnect/reoffer, unseen mixed summary through open/close, watched completion retirement, new success beside old failure, failed-reread mixed-result preservation, filter/collapse completion resets, retry summary replacement and current-offer/history selection; cross-host workspace identity, rendered cyclic reachability, nested tri-state/toggle propagation, project eligibility isolation and collapse preserving selection. Exact fallback-list completion barrier, batched verdict/cleanup retention, stale-read versus dismissal publication race, and requested-but-never-rendered finished-run retirement remain; they do not replace retired alarms. Audit3146 combines source reviews3132/3133/3135/3138/3143: intentionally retire20authored/31expanded cases without equivalent replacement. Provider-session losses: structured-native terminal-resume exclusion, metadata-less completed identity, new-turn completion clearing, Pi provider-only/periodic/manual promotion, changed-transcript launch-config isolation, Pi/omp/prime-agent completed-session remote/manual-shutdown promotion, and quit/done precedence over heartbeat. Side-thread/question losses: finished-pane acquisition, hidden title/recap states, local/relay/relay-done conversation takeover with prompt/session/child resets, plain-message abandonment, compaction/session replacement and completion resets. Codex startup losses: incoming-owner cached child replacement, old-relay foreign live-session correction, completed foreign-root turn-fact permutations. Transcript losses: real temporary-JSONL partial sibling/final-child completion, unlabelled child attribution, compact cached replay preservation and100/1000completed-child roster retention/release. Compiler-ratchet losses: valid-line uncompiled-list parser grammar examples and injected-existence stale-path filtering; these did not exercise actual filesystem canonicalization or build exclusion. These are real lifecycle, ownership, replay, liveness and retention alarms, including recent#40246 regressions, deliberately lost. Retained conditional record replacement, clockless root/SSH owner isolation, persisted main-thread fork rejection, partial/final question-answer lifetime, cached-roster/missing-ID/live HTTP/durable startup boundaries and restarted-relay refusal/acceptance do not replace those losses. No native/SSH/WSL execution or equivalent coverage is claimed. Audit3128 scoped coverage reduction: Audit3121 removes VoiceDictationLanguageSetting.test.tsx (Spanish-to-es callback and unsupported-model Korean option presence) and voice-speech-model-rows.test.ts (provider/language-order/retired-on-disk list policy); these real narrow alarms are deliberately retired without replacement. VoiceSpeechModelSection per-model concurrent deletion remains unchanged. Audit3122 removes the direct absolute/parent-segment sparse-directory exception-type sample and the five-row IPC sparse-preset error-code/non-save table (two authored/six expanded cases). Those real typed-validation and IPC refusal/error-code alarms are deliberately retired. Keep both real symlink/junction floating-directory trust cases and the minimal RPC structured validation-reason serialization case. The RPC case does not replace IPC save/refusal behavior, typed normalization for both path inputs, actual Git sparse checkout or rendered localization. No equivalent replacement or fresh test/runtime/platform/remote/performance validation is claimed. Audit3124 removes ExperimentalPane.test.tsx (ordinary Pet switch callback), WorkspaceDirectorySetting.test.tsx (padded absolute saved-path normalization/no-write blur), and repository-search.perf.test.ts (navigation/selected-pane builder-call policy, fixture cardinality/nonempty entries and renamed project keyword inclusion). These real narrow alarms are retired without replacement; RepositoryPane.search.test.tsx search-to-sparse-editor request remains unchanged. Audit3129: resolver Windows case-insensitive and POSIX case-sensitive configured-env composition plus mocked-base launch-preflight Windows composition are intentionally no longer checked by the two deleted suites. No equivalent coverage claimed. Keep runtime-structured-agent-host-env.test.ts unchanged: configured Windows Claude-home account identity and host-account precedence remain checked. Audit3114 incorporates source3101: retire three structured Claude child-environment wrapper cases covering inherited stamp isolation/default and explicit entrypoint, Windows SDK-key canonicalization/default/duplicate-key order, and configured lookup/final environment/config-dir conjunction. Keep direct auth/session sanitation and Windows-versus-Linux overlay checks, actual executable lookup from supplied inherited PATH, native Windows child environment delivery, and stale option-mutation fencing. These are not equivalent replacements for the retired wrapper alarms. No fresh test/runtime, real login-shell probe, Claude SDK startup, remote/mixed-version, UI or performance result is claimed. Audit3114 incorporates source3105: retire 17 authored/20 expanded daemon launch-note cases, including the entire two-case SessionLaunchNote suite. Deliberately lose split-marker carry across same-token re-arm, stale-token retirement refusal, foreground tri-state and serial settlement, omitted-note/no-incarnation mixed-version policy, sticky retirement, first-incarnation/replacement launch preservation and held-launch precedence. Keep only the unchanged unresolved foreground-read race against a later finished attach. Supplied notes/foreground and runtime calls do not establish actual daemon/main restart, SSH, native Windows observation, mobile UI, equivalent replacement or fresh runtime/performance validation. Audit3114 incorporates source3109: retire six authored/35 expanded pricing cases: 21 accepted model-name examples, 10 unsupported/future-model fail-closed examples, malformed TTL clamp, unknown-model estimate refusal, flat-model long-context disregard and oversized long-context clamp. Keep mixed five-minute/one-hour write allocation and short/all-long/mixed long-context allocation with original fixed oracles. Real parser/refusal/bounds alarms are knowingly lost without equivalent replacement; retained tests do not validate provider rates, actual billing or request threshold classification. Preserve the archived usage-scan-append source-freeze receipt without transferring historical execution/performance credit. No fresh runtime result is claimed. Audit3108 source-only reduction (3094/3095/3100): retire 27 authored/30 expanded cases, including complete markdown view-state, file-preview link-open and CLI agent-server-route suites, without replacement. Deliberate losses include preview visibility/reference lifetime and same-path owners; SSH stat, directory/missing-target, explicit-null owner, nonmarkdown line/column, local URI routing, remote-to-client guard and same-file reuse; document-preview source-owner/folder/reuse routing, stable grant location and outside-workspace POSIX/Windows request projection; and verified remote CLI send/check refusal, suggested --on argv/copy, shell no-probe bypass, unverified-launch admission and older-peer refusal. Retain two markdown source-runtime/qualified-reveal alarms, one stale grant-rejection fence and two remote read/mutation evidence policies, with original callbacks. Final last-wins reveal did not prove transient cancellation; CLI prerequisite did not prove no real send, and envelope tests do not execute server refusal. No fresh runtime, rendered UI, actual file/SSH/paired transport, authorization, mixed-version or performance result is claimed. Audit3096 source-only reduction (3087/3088): retire 69 authored/76 expanded cases, including complete recovery-portals and reconnect-banner suites. Intentionally lose dead/default TUI replay, generated alternate-frame style composition, reset/mode/dimension and legacy missing-mode-boundary alarms, UI notice/action/reveal policies, and isolated recovery lifecycle variants, without equivalent replacement. Retained registrations and callbacks are unchanged; headless cells are not pixels, and no fresh runtime, host, SSH, WSL, rendered-app or performance result is claimed. Audit3086 source-only reduction (3079/3080/3081): intentionally retire 93 authored/100 expanded mock-boundary cases, including the complete spawn-errors and SSH reconnect overlay suites, without replacement. Retired alarms include spawn classification/ownership, reply ceilings and renderer-write failure recovery, disconnect/detach fencing branches, authority facts, and overlay retry/visibility wiring. Retained callbacks are unchanged; no fresh execution, real PTY/SSH, rendered UI, or performance result is claimed. Module layout SSH policy: Retire the multiplexer private-clock saturation registration, the writer saturation transition-count registration and the changed-source dated writer/backpressure receipt. Retained byte delivery, lane order, fairness, settlement and cancellation cases are unvalidated by that historical receipt. No equivalent replacement, new execution, measured performance, live SSH/WSL or cross-platform proof is claimed. The unchanged WSL protocol receipt retains only its original command scope. Historical prior account (preserved verbatim): Audit2432: The broad unit command loses the isolated BranchPicker open-change notification sample. Its unique true/false callback alarm is intentionally retired; reopening/status-refresh behavior was not exercised. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2425: The broad unit command loses the workspace-copy-status supplied readError forwarding sample. It did not exercise the branch-switch blocking promised by its title. This alarm is intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2417: The broad unit command loses two ordinary clean Git cherry-pick/revert success samples and two terminal startup foreground-read work-budget samples. These unique alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2412: The broad unit command loses the whole six-case fake-React-hook scroll-anchor suite, two generic draft-retention samples, a simple new-agent order sample, a real history-publication batching-count sample, an unmounted handoff abort/timer sample and three basic WSL preview/error samples. These alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2404: The broad unit command loses the standalone share-name lookup 503 propagation suite, initial deletion placement-kind sample, direct changed-mtime stale sample, first-pass rollback existence example and abandoned-preparation directory sample. These exact alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2397 review amendment: The broad unit command loses three standalone suites, two partial-case definitions and two URL table rows across package/download/placement tests. Keep initial wrong-port authorization, modified independent-copy digest refusal and abort-after-begin cancellation dispatch. The remaining alarms are deliberately retired; no equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2393 current-parent refresh2401: Remove the basic skill-install service alias sample and original public managed-remove receiptless refusal case. Preserve the upstream request ownership suite and transaction interruption coverage. No equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2389: The broad unit command loses the missing-preview suite, plain-global destination sample and prepublished-receipt recovery example. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2385: The broad unit command loses four authored walker/staging/protocol examples (six expanded cases); no equivalent replacement or fresh validation is claimed for the reduced suite. Audit2383: The unscoped Vitest command no longer includes the removed Antigravity catalogue suite; its exact provider-root/owner example has no equivalent replacement or fresh validation claim. Audit2377/2381: The unscoped Vitest command includes the reduced bundled-skill and native-discovery suites; the eight removed backup/legacy/catalogue/symlink/SSH-builder examples have no replacement-equivalence or fresh validation claim here. Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2090 (sources2088/2089): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2086 (sources2082/2083): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2076 (sources2073/2074): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime-tests/terminal-handles-part-02.spec.ts: recovers a moved SSH pane through the tab it now sits in, not the one its lease froze; reports a plain expired orphan; does not report a pane whose only recent lease was superseded; does not report a pane whose only recent lease had its relay id recycled; picks the eligible orphan over a superseded predecessor that matches first; collects the same tabs the per-tab reader reports, in one sweep of the leases; reports no candidate when no lease names any of the worktree tabs. src/main/runtime/orca-runtime-tests/runtime-availability.spec.ts: starts unavailable with no authoritative window; reports the configured Windows terminal shell on status; reports floating workspace availability from settings on status; polls floating tabs with targeted PTY liveness and no repo/provider inventory; hydrates persisted tabs when the store cannot report repos; advertises browser screencast only when a renderer window is available; routes mobile Codex reset consumption through the account mutation coordinator; maps a definite pre-provider rejection into an authoritative current snapshot. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Frozen current literal-import graph reaches these changed test bytes; unresolved local and computed edges remain debt, and current reachability is not historical execution or equivalent replacement evidence. Historical prior account (preserved verbatim): Audit2070 (sources2068/2069): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime.test.ts: ordinary registration cleanup removes only await import('./orca-runtime-tests/hooks-and-hosted-review.spec'). src/main/ssh/ssh-multiplexer-transport-writer.test.ts: reports saturated epochs and their drain boundary exactly once. src/main/runtime/orca-runtime-tests/worktree-removal-archive-hook-gate.spec.ts: removes and records the waiver when the failure is explicitly overridden; removes without an override record when the hook succeeds; removes when the hook is configured but not requested; removes when no archive hook is configured; holds a desktop removal in the same repo until this one is accepted; joins a desktop removal of the same worktree accepted while this one waited. src/main/runtime/orca-runtime-tests/worktree-ps-agent-row-dismissal.spec.ts: drops the row as soon as the user dismisses it, without waiting for the PTY to exit; tells paired clients to republish on the transition and on the dismissal; rejoins a row through its %s handle after pane ownership clears. src/main/runtime/orca-runtime-tests/hooks-and-hosted-review.spec.ts: reports an error when the SSH filesystem provider is unavailable; reports an SSH orca.yaml as an error without reading any filesystem; reports ok for a local repo hook check; reads SSH issue commands as absent and drops writes without touching any filesystem; allows host integration slug helpers for SSH repos through provider-aware GitHub clients; routes runtime GitHub repo identity helpers through the selected WSL project runtime; routes runtime GitHub issue and work-item actions through the selected WSL project runtime; pins explicit origin preference on runtime open-by-number work item lookups; forwards check-details cancellation without local Git overrides. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Frozen current literal-import graph reaches these changed test bytes; unresolved local and computed edges remain debt, and current reachability is not historical execution or equivalent replacement evidence. The historical receipt/currentCommand selecting src/main/ssh/ssh-multiplexer-transport-writer.test.ts remains historical and is not a passing result for the reduced current command. Historical prior account (preserved verbatim): Audit1931 (sources1928/1929): Delete the complete tail-wait memo suite: its sole current authored callback checks supplied fromTail/blocked field values. Retire all three broader memoization/equivalence/eviction assertion aliases; they are not backed by retained source callbacks. No scan-work budget, sustained output, physical terminal or resource measurement is assigned to this removed test. Preserve meaningful remaining selectors/assertions and unchanged dated receipts within their original scope. Reduced selectors have no fresh gate execution evidence in this metadata packet. No equivalent replacement, physical watcher/PTY/provider, live SSH/remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): Audit1674 removes low-value test projections, mock wiring, private-state assertions, inventories and duplicate examples without equivalent replacement coverage. Per-source reviews record retained public behavior and refusal boundaries with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1634 removes low-value IPC, filesystem and runtime projections, argument inventories and duplicate examples without equivalent replacement coverage. Per-source reviews record retained cancellation, ownership, authorization, filesystem and SQLite boundaries with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Local macOS evidence covers main-process pending-output and projection-admission caps, saturated-tail wait detection, direct-SSH source retention/accounting, always-on V1 negotiation with legacy peer fallback, exact provider-generation pause ownership, renderer exit/data ordering, decoder input bounds, bounded reconnect scheduling, and WSL stdio transport settlement through deterministic unit contracts. A joined main/runtime oracle exercises renderer-sourced headed semantics and headless-model snapshot semantics without launching a live paired server. Separately, a macOS-hosted Docker OpenSSH run exercises only the deployed Linux relay and direct SSH provider with an exact 256 KiB source-credit plateau, concurrent PTY typing, fixed-size filesystem frames, Git churn, and owner-lease reconnect. Neither deterministic topology labels nor Docker SSH constitute live headed desktop, headless orca serve, or physical WSL evidence; local/daemon, prior-version daemons, Windows named pipes/ConPTY, folder workspaces, and mixed-version clients also remain uncovered. Audit1312 removes low-value imported specs from aggregate test drivers; old whole-driver execution receipts are archived. Retained registrations are unchanged. No equivalent replacement coverage is claimed. Audit1383: src/main/runtime/orca-runtime-tests/worktree-native-chat-setup.spec.ts reduced. Lose command-list/receipt/default/background activation matrices whose provider spawn returns canned IDs. Retained test proves actual tab allocation separation, not terminal startup. No equivalent replacement coverage is claimed. Existing exact unaffected receipts and their platform/provider/budget claims remain scoped to unchanged selectors. Changed optional selectors have no new execution result. Audit1401: src/main/runtime/orca-runtime-tests/mobile-session-tabs-duplicate-pty-repair.spec.ts removed. Loses listing-on-already-repaired-data alarm; it never established runtime repair invocation. src/main/runtime/orca-runtime-tests/mobile-session-tabs-split-agent-tab.spec.ts removed. Loses actual mobile split sibling shell versus recorded-agent resume command alarms; no equivalent coverage asserted. src/main/runtime/orca-runtime-tests/worktree-native-chat-setup.spec.ts removed. Loses separate setup/startup tab result in that manually assembled path. src/main/runtime/orca-runtime.test.ts reduced. Driver registration/import of a whole-deleted selected spec is removed; directly authored cases remain unchanged. No extra authored removal credit. No equivalent replacement coverage is claimed. Existing exact unaffected receipts remain unchanged and apply only to their unchanged selectors. Changed optional selectors have no new execution result.", "motivatingLinks": [ "https://github.com/stablyai/orca/pull/6836", "https://github.com/stablyai/orca/pull/6858", @@ -9220,7 +9239,7 @@ "https://github.com/stablyai/orca/pull/7054" ], "invariant": "High-volume terminal output must stay bounded across daemon socket writes, SSH relay writer/decoder/source retention/reconnect, main model and projection admission, runtime metadata, detectors, and tail checks, main-to-renderer in-flight bytes, renderer scheduler queues, and hidden-output restore without starving focused input. Every new SSH session offers V1 and every same-build relay supports it; legacy delivery is reachable only when capability negotiation proves the peer cannot use V1. Negotiated SSH spans remain exact and contiguous through activation, exit, cancellation, recovery, desktop projection, and required remote replacement; provisional activation data cannot project, reconnect may release it only into the exact attempt's private recovery quarantine after contract validation, and exit seals that quarantine against later same-token frames until ordered admission or exact cancellation proof. Reconnect checkpoint capture freezes exact provider-generation/PTy admission, cancels queued old work, and waits for the running raw completion before exposing its accepted checkpoint; timeout or failure detaches only that PTy's old model, makes the checkpoint unavailable, and releases the bounded fence without closing the shared provider, while the same failure outside an active exact migration remains generation-fatal and overlapping reconnects preserve any earlier outstanding fence. Pending renderer projection IDs are capped and compacted across split remainders, exit preparation owns its renderer fence through finalization, exit-time cancellation transfers published projections before proof commit, generation close fences late proof while draining exact projection waiters, closed-generation identity compacts without weakening stale rejection, canceled source-delivery retirement retains at most one ordered token per PTY, and pause/resume targets only the exact provider generation. Additional subscribers cannot stall the owner, while the required legacy primary retains backpressure.", - "oracle": "Audit3096 source-only reduction (3087/3088): retire 69 authored/76 expanded cases, including complete recovery-portals and reconnect-banner suites. Intentionally lose dead/default TUI replay, generated alternate-frame style composition, reset/mode/dimension and legacy missing-mode-boundary alarms, UI notice/action/reveal policies, and isolated recovery lifecycle variants, without equivalent replacement. Retained registrations and callbacks are unchanged; headless cells are not pixels, and no fresh runtime, host, SSH, WSL, rendered-app or performance result is claimed. Audit3086 source-only reduction (3079/3080/3081): intentionally retire 93 authored/100 expanded mock-boundary cases, including the complete spawn-errors and SSH reconnect overlay suites, without replacement. Retired alarms include spawn classification/ownership, reply ceilings and renderer-write failure recovery, disconnect/detach fencing branches, authority facts, and overlay retry/visibility wiring. Retained callbacks are unchanged; no fresh execution, real PTY/SSH, rendered UI, or performance result is claimed. Module layout SSH policy: Retire the multiplexer private-clock saturation registration, the writer saturation transition-count registration and the changed-source dated writer/backpressure receipt. Retained byte delivery, lane order, fairness, settlement and cancellation cases are unvalidated by that historical receipt. No equivalent replacement, new execution, measured performance, live SSH/WSL or cross-platform proof is claimed. The unchanged WSL protocol receipt retains only its original command scope. Historical prior account (preserved verbatim): Audit2432: The broad unit command loses the isolated BranchPicker open-change notification sample. Its unique true/false callback alarm is intentionally retired; reopening/status-refresh behavior was not exercised. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2425: The broad unit command loses the workspace-copy-status supplied readError forwarding sample. It did not exercise the branch-switch blocking promised by its title. This alarm is intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2417: The broad unit command loses two ordinary clean Git cherry-pick/revert success samples and two terminal startup foreground-read work-budget samples. These unique alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2412: The broad unit command loses the whole six-case fake-React-hook scroll-anchor suite, two generic draft-retention samples, a simple new-agent order sample, a real history-publication batching-count sample, an unmounted handoff abort/timer sample and three basic WSL preview/error samples. These alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2404: The broad unit command loses the standalone share-name lookup 503 propagation suite, initial deletion placement-kind sample, direct changed-mtime stale sample, first-pass rollback existence example and abandoned-preparation directory sample. These exact alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2397 review amendment: The broad unit command loses three standalone suites, two partial-case definitions and two URL table rows across package/download/placement tests. Keep initial wrong-port authorization, modified independent-copy digest refusal and abort-after-begin cancellation dispatch. The remaining alarms are deliberately retired; no equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2393 current-parent refresh2401: Remove the basic skill-install service alias sample and original public managed-remove receiptless refusal case. Preserve the upstream request ownership suite and transaction interruption coverage. No equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2389: The broad unit command loses the missing-preview suite, plain-global destination sample and prepublished-receipt recovery example. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2385: The broad unit command loses four authored walker/staging/protocol examples (six expanded cases); no equivalent replacement or fresh validation is claimed for the reduced suite. Audit2383: The unscoped Vitest command no longer includes the removed Antigravity catalogue suite; its exact provider-root/owner example has no equivalent replacement or fresh validation claim. Audit2377/2381: The unscoped Vitest command includes the reduced bundled-skill and native-discovery suites; the eight removed backup/legacy/catalogue/symlink/SSH-builder examples have no replacement-equivalence or fresh validation claim here. Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2090 (sources2088/2089): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2086 (sources2082/2083): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2076 (sources2073/2074): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime-tests/terminal-handles-part-02.spec.ts: recovers a moved SSH pane through the tab it now sits in, not the one its lease froze; reports a plain expired orphan; does not report a pane whose only recent lease was superseded; does not report a pane whose only recent lease had its relay id recycled; picks the eligible orphan over a superseded predecessor that matches first; collects the same tabs the per-tab reader reports, in one sweep of the leases; reports no candidate when no lease names any of the worktree tabs. src/main/runtime/orca-runtime-tests/runtime-availability.spec.ts: starts unavailable with no authoritative window; reports the configured Windows terminal shell on status; reports floating workspace availability from settings on status; polls floating tabs with targeted PTY liveness and no repo/provider inventory; hydrates persisted tabs when the store cannot report repos; advertises browser screencast only when a renderer window is available; routes mobile Codex reset consumption through the account mutation coordinator; maps a definite pre-provider rejection into an authoritative current snapshot. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Frozen current literal-import graph reaches these changed test bytes; unresolved local and computed edges remain debt, and current reachability is not historical execution or equivalent replacement evidence. Historical prior account (preserved verbatim): Audit2070 (sources2068/2069): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime.test.ts: ordinary registration cleanup removes only await import('./orca-runtime-tests/hooks-and-hosted-review.spec'). src/main/ssh/ssh-multiplexer-transport-writer.test.ts: reports saturated epochs and their drain boundary exactly once. src/main/runtime/orca-runtime-tests/worktree-removal-archive-hook-gate.spec.ts: removes and records the waiver when the failure is explicitly overridden; removes without an override record when the hook succeeds; removes when the hook is configured but not requested; removes when no archive hook is configured; holds a desktop removal in the same repo until this one is accepted; joins a desktop removal of the same worktree accepted while this one waited. src/main/runtime/orca-runtime-tests/worktree-ps-agent-row-dismissal.spec.ts: drops the row as soon as the user dismisses it, without waiting for the PTY to exit; tells paired clients to republish on the transition and on the dismissal; rejoins a row through its %s handle after pane ownership clears. src/main/runtime/orca-runtime-tests/hooks-and-hosted-review.spec.ts: reports an error when the SSH filesystem provider is unavailable; reports an SSH orca.yaml as an error without reading any filesystem; reports ok for a local repo hook check; reads SSH issue commands as absent and drops writes without touching any filesystem; allows host integration slug helpers for SSH repos through provider-aware GitHub clients; routes runtime GitHub repo identity helpers through the selected WSL project runtime; routes runtime GitHub issue and work-item actions through the selected WSL project runtime; pins explicit origin preference on runtime open-by-number work item lookups; forwards check-details cancellation without local Git overrides. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Frozen current literal-import graph reaches these changed test bytes; unresolved local and computed edges remain debt, and current reachability is not historical execution or equivalent replacement evidence. The historical receipt/currentCommand selecting src/main/ssh/ssh-multiplexer-transport-writer.test.ts remains historical and is not a passing result for the reduced current command. Historical prior account (preserved verbatim): Audit1931 (sources1928/1929): Delete the complete tail-wait memo suite: its sole current authored callback checks supplied fromTail/blocked field values. Retire all three broader memoization/equivalence/eviction assertion aliases; they are not backed by retained source callbacks. No scan-work budget, sustained output, physical terminal or resource measurement is assigned to this removed test. Preserve meaningful remaining selectors/assertions and unchanged dated receipts within their original scope. Reduced selectors have no fresh gate execution evidence in this metadata packet. No equivalent replacement, physical watcher/PTY/provider, live SSH/remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): Audit1674 retires changed-source assertion and execution scope without equivalent replacement coverage. Existing unchanged-selector receipts remain scoped to their original sources. Historical prior-source oracle: Existing exact unchanged-selector receipts remain the only current execution evidence. Changed source selectors have no fresh execution result. Historical prior-source oracle account: The current executable slice injects main-process renderer backlog pressure, then asserts ordinary terminal-wait detection without a joined-tail allocation and with full prompt-family continuity, per-PTY and total pending-output caps, a 1,024-ID projection cap with split-remainder compaction, preserved sequenced-tail metadata, active-pending protection ahead of background trimming, exact provider-generation pause ownership, renderer exit/data ordering, and ACK-gated in-flight bounds. The negotiation seam proves every initial connection and reconnect offers V1, the same-build relay advertises V1 without launch flags, old clients remain token-free, and method-not-found peers fall back without installing source ACK publication. The joined source-intake/multiplex oracle blocks renderer or headless serialization, admits one snapshot-covered span and one trailing span, requires replacement reservation only after the authoritative sequence is known, advances upstream ACK eligibility exactly to the covered boundary after SnapshotEnd, and delivers then ACKs the trailing span through the ordinary live path without cancellation. Source-range ledger and multiplex seams additionally require cumulative byte ACK 40 then 100 for one 100-byte frame to release exact byte credit without early source settlement, admit a contiguous higher-generation recovered token while the prior token remains unsettled, and reject stale stream or source generations without releasing in-flight byte credit. Replacement reservation rolls back every earlier span on a later failure, commit requires the exact frozen transfer states, and an authoritatively reclaimed covered span rejects commit without local trim authority while rollback removes the reservation idempotently. The exit-deadline oracle publishes a source-backed desktop projection, advances a fake clock to cancellation, and requires one projection transfer, proof commit, preparation, and final exit with no provider close, retained obligation, duplicate finalization, or process-lifetime cancellation tombstone; a second controlled proof remains pending across generation close and must never publish final exit, while both paths release the renderer preparation lease exactly once. The model-migration oracle accepts span A, blocks span B's raw emulator completion, begins disconnect migration, and proves no checkpoint or reconnect attach can remain at A; releasing B advances the exact checkpoint to B and projects B once. Its fake-clock arm reaches the 10-second deadline, requires checkpoint-unavailable, one exact model reset, zero retained admission charge and timers, and no effect from late raw settlement. Its two-PTY failure arm rejects one running raw callback under an active exact migration and requires one checkpoint-unavailable result, one model reset, zero provider closes, retained sibling checkpoint and transport liveness, zero charges and timers, and an unaffected other generation; a non-migrating sibling oracle still requires generation close. The intake additionally closes 2,048 sequential provider generations into one exact range, rejects stale events across that range, and preserves an out-of-order live gap until its own close. Direct-SSH contracts additionally prove activation-response settlement before the first source frame, claim-gated projection under same-decoder-turn response/data delivery, exact early-ACK reservation through send settlement or same-token retry, recovery completion visible before lease-held frames transfers those frames only into the private quarantine and admits no output until exact checkpoint-to-recoveryEnd coverage, invalid-checkpoint restore retention through response settlement followed by fresh-token retry and one live source frame, isolated saturated-subscriber eviction with healthy owner liveness, preserved legacy-primary backpressure, one-write ownership across write(false)/drain, control selection ahead of queued ordinary PTY input with FIFO lanes and bounded fairness, liveness rebasing, failed-exit retention through late ACK or exact recovery, response-settlement cancellation authority, token-scoped exit cancellation, exact checkpoint-to-recoveryEnd continuity, stale-owner one-shot retry, no physical PTY teardown on recovery failure, exact provider-generation closure and once-only cleanup when recovery cancellation publication or proof rejects, 16 MiB-plus-1 MiB decoder caps, charged per-PTY/session retention budgets, and eight-wide isolated reattach. The live Electron perf oracle adds hidden-output floods, renderer scheduler queue depth, dropped-output-zero normal scenarios, and active key latency budgets before promotion.", + "oracle": "Audit3209 composes approved sources3202/3206: deliberately retires seven authored/expanded cases in four whole suites without equivalent replacement. Work-item queries lose real GitHub/GitLab oversized ASCII secret-prefix empty-query and whitespace-before-trim refusal alarms; inputs share the imported size bound and exercise only its fast length branch, with no multibyte or actual provider/exposure guarantee. Skill sharing loses complete/partial managed-bundle and destination-ambiguity association checks plus three negative origin/path/scheme admission examples; these do not establish uploaded contents, arbitrary-URL fetching, authorization or execution. Retain exact originless-project direct-link fallback, cloud-delete confirmation, bundled-target repair/owner isolation and explicit Windows-host preference over stale WSL suites. Rejected3201 runtime-preference removal is excluded. No real cloud/network/host/disk, mobile or mixed-version execution validation is claimed. Audit3200 composes approved source3194: deliberately retires thirteen authored registrations/twenty-seven expanded cases in six whole automation host/list policy suites without equivalent replacement. Real RPC category/retryability and wrapped-timeout recognition, unscoped-failure/scoped-success health evidence precedence, exact-ID create selectors and per-run workspace omission, paired-web local/SSH/absent host catalog routing, incompatible/removed/unhydrated/offline execution health, runtime-before-nested-SSH recovery dispatch, and no-owned-focus/successor/foreign-list focus policy alarms are consciously lost. Retain exact20line orphan allow/refuse/precondition and exact90line cross-host same-ID search suites. No retry-timer/fence lifecycle, actual reconnect/network/write delivery, native focus, mobile/mixed-version runtime or disk persistence coverage is claimed. Audit3191 combines approved source3182/3187/3188: deliberately retires thirteen authored Vitest registrations and fifteen expanded cases, including five whole suites, without equivalent replacement. Attachment intake loses real portal/native-capture terminal interception and unowned-container refusal, immediate child-only committed availability/claim-ref negotiation and delivery, and direct-target over stable focused/background composer routing through disable/re-enable/remount and independent question focus. Exact destination/cache/draft and final-stat owner/workspace/File-release suites remain; they do not replace Surface recipient routing. Automation authoring loses destination runtime catalog membership, local/direct-SSH exclusion of paired-runtime repos, unknown-runtime empty catalog, logical project/host/setup/repo/path context payload, and missing/nonready setup refusal; these were genuine direct helper alarms, while exact schedule transformation, legacy schedule and setup-decision suites remain. Agent picker loses setup-chat/terminal/missing-installer/unsupported-or-unknown-host row projection samples and the ordinary unsearched menu variant; the entire original26-line resume recipe suite remains, including reported bypass versus default/absent permission modes, as does the exact search-result menu callback with its fixtures, model/effort commits and staged Arguments reopen outcome. Rejected predecessor3180 full recipe deletion is excluded. No actual native drag/cursor/focus/IME, upload bytes or disk/restart persistence, full automation save/scheduler/runtime transport, real resume-process flags/environment delivery, or native menu/rendered layout validation is claimed. Audit3178 combines source3169/3170/3175: deliberately retires eight authored units (six Vitest cases and two imperative custom relay scenarios), including two whole suites, without equivalent replacement. Voice Section loses per-model pending-delete isolation across interleaved A/B completion and the two-success refresh-call alarm; exact VoicePane delayed key-clear/newer enabled-toggle merge remains and does not replace row deletion coverage. Speech loses dedicated rating-scale/inclusive-ceiling, unsupported-versus-unmeasured, explicit/system-language precedence/locale alias, accuracy versus fast named/default/best-measured selection, and unmeasured/no-match examples; exact offered-user-pick versus retired-selection case and its fixture remain. Relay loses legacy ping-delivery count/liveness sampled before the silence deadline and grouped malformed Bearer/host-ID 401/429 routing checks; twelve real Worker/DurableObject/shipped-client scenarios remain, not equivalent replacement for those narrow alarms. Six prior speech cases are not all deleted: approved successor3175 keeps the original user-choice case. No actual credential/file persistence, native/GPU/engine/download delivery, production assignment policy or deployed-runtime validation is claimed by this reduction. Audit3165 combines source3160/3162: deliberately retires six authored/expanded cases across three whole suites without equivalent replacement. Launch/status losses: observed React-render pending/resuming coordination across settings and deferred offer read; stale-offer reread suppressing dialog reopen; held-local-chat recovery visibility with new-chat preferences off; disabled-local admission avoiding offer RPC despite an injected but unconsumed paired-tab fixture; and run-only lost-reply uncertainty reachability until direct viewed-run retirement. Launch probe does not prove arbitrary synchronous-store atomicity, the paired fixture is not remote runtime enrollment, and the status case directly marks viewed state rather than rendering the summary. Crew-hook losses: old-host method_not_found cache persists across party changes but is released by independently supplied connection generation/verified pairing status or pairing revision, with actual frame publication and teardown. These are real narrow coordination, admission, uncertainty and mixed-version cache alarms consciously lost. Exact web verified-runtime writer handoff guard remains; it does not replace those alarms or prove live host/native/mobile delivery. Audit3156 combines3147/3150/3152/3153/3154: deliberately retires39authored/40expanded native-chat recovery cases, eight whole suites and two orphan test-support files without equivalent replacement. Lost alarms: lost-reply unconfirmed reconciliation, skipped rows/counts and missed-frame repair, unknown/pending outcome and omitted-failure-list compatibility, uncertain history after dismissal, retry/refusal/dismiss lifecycle, hidden/consumed picker ownership, result-tree keyboard focus/disclosure and all-skipped retirement; unconfirmed-over-conflict guidance and failed-chat changes despite older host timestamps; nearest-listed ancestor/cyclic forest shape, descendant membership, host ordering/missing-host local fallback; skipped/readiness/admission counts, provisional skip/progress monotonicity, early per-chat verdicts with batch pending protection, older-host waiting, start-slot/delivery distinction, retry-over-failure and unknown-after-withdrawal attention; remote snooze/reconnect/reoffer, unseen mixed summary through open/close, watched completion retirement, new success beside old failure, failed-reread mixed-result preservation, filter/collapse completion resets, retry summary replacement and current-offer/history selection; cross-host workspace identity, rendered cyclic reachability, nested tri-state/toggle propagation, project eligibility isolation and collapse preserving selection. Exact fallback-list completion barrier, batched verdict/cleanup retention, stale-read versus dismissal publication race, and requested-but-never-rendered finished-run retirement remain; they do not replace retired alarms. Audit3146 combines source reviews3132/3133/3135/3138/3143: intentionally retire20authored/31expanded cases without equivalent replacement. Provider-session losses: structured-native terminal-resume exclusion, metadata-less completed identity, new-turn completion clearing, Pi provider-only/periodic/manual promotion, changed-transcript launch-config isolation, Pi/omp/prime-agent completed-session remote/manual-shutdown promotion, and quit/done precedence over heartbeat. Side-thread/question losses: finished-pane acquisition, hidden title/recap states, local/relay/relay-done conversation takeover with prompt/session/child resets, plain-message abandonment, compaction/session replacement and completion resets. Codex startup losses: incoming-owner cached child replacement, old-relay foreign live-session correction, completed foreign-root turn-fact permutations. Transcript losses: real temporary-JSONL partial sibling/final-child completion, unlabelled child attribution, compact cached replay preservation and100/1000completed-child roster retention/release. Compiler-ratchet losses: valid-line uncompiled-list parser grammar examples and injected-existence stale-path filtering; these did not exercise actual filesystem canonicalization or build exclusion. These are real lifecycle, ownership, replay, liveness and retention alarms, including recent#40246 regressions, deliberately lost. Retained conditional record replacement, clockless root/SSH owner isolation, persisted main-thread fork rejection, partial/final question-answer lifetime, cached-roster/missing-ID/live HTTP/durable startup boundaries and restarted-relay refusal/acceptance do not replace those losses. No native/SSH/WSL execution or equivalent coverage is claimed. Audit3128 scoped coverage reduction: Audit3121 removes VoiceDictationLanguageSetting.test.tsx (Spanish-to-es callback and unsupported-model Korean option presence) and voice-speech-model-rows.test.ts (provider/language-order/retired-on-disk list policy); these real narrow alarms are deliberately retired without replacement. VoiceSpeechModelSection per-model concurrent deletion remains unchanged. Audit3122 removes the direct absolute/parent-segment sparse-directory exception-type sample and the five-row IPC sparse-preset error-code/non-save table (two authored/six expanded cases). Those real typed-validation and IPC refusal/error-code alarms are deliberately retired. Keep both real symlink/junction floating-directory trust cases and the minimal RPC structured validation-reason serialization case. The RPC case does not replace IPC save/refusal behavior, typed normalization for both path inputs, actual Git sparse checkout or rendered localization. No equivalent replacement or fresh test/runtime/platform/remote/performance validation is claimed. Audit3124 removes ExperimentalPane.test.tsx (ordinary Pet switch callback), WorkspaceDirectorySetting.test.tsx (padded absolute saved-path normalization/no-write blur), and repository-search.perf.test.ts (navigation/selected-pane builder-call policy, fixture cardinality/nonempty entries and renamed project keyword inclusion). These real narrow alarms are retired without replacement; RepositoryPane.search.test.tsx search-to-sparse-editor request remains unchanged. Audit3129: resolver Windows case-insensitive and POSIX case-sensitive configured-env composition plus mocked-base launch-preflight Windows composition are intentionally no longer checked by the two deleted suites. No equivalent coverage claimed. Keep runtime-structured-agent-host-env.test.ts unchanged: configured Windows Claude-home account identity and host-account precedence remain checked. Audit3114 incorporates source3101: retire three structured Claude child-environment wrapper cases covering inherited stamp isolation/default and explicit entrypoint, Windows SDK-key canonicalization/default/duplicate-key order, and configured lookup/final environment/config-dir conjunction. Keep direct auth/session sanitation and Windows-versus-Linux overlay checks, actual executable lookup from supplied inherited PATH, native Windows child environment delivery, and stale option-mutation fencing. These are not equivalent replacements for the retired wrapper alarms. No fresh test/runtime, real login-shell probe, Claude SDK startup, remote/mixed-version, UI or performance result is claimed. Audit3114 incorporates source3105: retire 17 authored/20 expanded daemon launch-note cases, including the entire two-case SessionLaunchNote suite. Deliberately lose split-marker carry across same-token re-arm, stale-token retirement refusal, foreground tri-state and serial settlement, omitted-note/no-incarnation mixed-version policy, sticky retirement, first-incarnation/replacement launch preservation and held-launch precedence. Keep only the unchanged unresolved foreground-read race against a later finished attach. Supplied notes/foreground and runtime calls do not establish actual daemon/main restart, SSH, native Windows observation, mobile UI, equivalent replacement or fresh runtime/performance validation. Audit3114 incorporates source3109: retire six authored/35 expanded pricing cases: 21 accepted model-name examples, 10 unsupported/future-model fail-closed examples, malformed TTL clamp, unknown-model estimate refusal, flat-model long-context disregard and oversized long-context clamp. Keep mixed five-minute/one-hour write allocation and short/all-long/mixed long-context allocation with original fixed oracles. Real parser/refusal/bounds alarms are knowingly lost without equivalent replacement; retained tests do not validate provider rates, actual billing or request threshold classification. Preserve the archived usage-scan-append source-freeze receipt without transferring historical execution/performance credit. No fresh runtime result is claimed. Audit3108 source-only reduction (3094/3095/3100): retire 27 authored/30 expanded cases, including complete markdown view-state, file-preview link-open and CLI agent-server-route suites, without replacement. Deliberate losses include preview visibility/reference lifetime and same-path owners; SSH stat, directory/missing-target, explicit-null owner, nonmarkdown line/column, local URI routing, remote-to-client guard and same-file reuse; document-preview source-owner/folder/reuse routing, stable grant location and outside-workspace POSIX/Windows request projection; and verified remote CLI send/check refusal, suggested --on argv/copy, shell no-probe bypass, unverified-launch admission and older-peer refusal. Retain two markdown source-runtime/qualified-reveal alarms, one stale grant-rejection fence and two remote read/mutation evidence policies, with original callbacks. Final last-wins reveal did not prove transient cancellation; CLI prerequisite did not prove no real send, and envelope tests do not execute server refusal. No fresh runtime, rendered UI, actual file/SSH/paired transport, authorization, mixed-version or performance result is claimed. Audit3096 source-only reduction (3087/3088): retire 69 authored/76 expanded cases, including complete recovery-portals and reconnect-banner suites. Intentionally lose dead/default TUI replay, generated alternate-frame style composition, reset/mode/dimension and legacy missing-mode-boundary alarms, UI notice/action/reveal policies, and isolated recovery lifecycle variants, without equivalent replacement. Retained registrations and callbacks are unchanged; headless cells are not pixels, and no fresh runtime, host, SSH, WSL, rendered-app or performance result is claimed. Audit3086 source-only reduction (3079/3080/3081): intentionally retire 93 authored/100 expanded mock-boundary cases, including the complete spawn-errors and SSH reconnect overlay suites, without replacement. Retired alarms include spawn classification/ownership, reply ceilings and renderer-write failure recovery, disconnect/detach fencing branches, authority facts, and overlay retry/visibility wiring. Retained callbacks are unchanged; no fresh execution, real PTY/SSH, rendered UI, or performance result is claimed. Module layout SSH policy: Retire the multiplexer private-clock saturation registration, the writer saturation transition-count registration and the changed-source dated writer/backpressure receipt. Retained byte delivery, lane order, fairness, settlement and cancellation cases are unvalidated by that historical receipt. No equivalent replacement, new execution, measured performance, live SSH/WSL or cross-platform proof is claimed. The unchanged WSL protocol receipt retains only its original command scope. Historical prior account (preserved verbatim): Audit2432: The broad unit command loses the isolated BranchPicker open-change notification sample. Its unique true/false callback alarm is intentionally retired; reopening/status-refresh behavior was not exercised. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2425: The broad unit command loses the workspace-copy-status supplied readError forwarding sample. It did not exercise the branch-switch blocking promised by its title. This alarm is intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2417: The broad unit command loses two ordinary clean Git cherry-pick/revert success samples and two terminal startup foreground-read work-budget samples. These unique alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2412: The broad unit command loses the whole six-case fake-React-hook scroll-anchor suite, two generic draft-retention samples, a simple new-agent order sample, a real history-publication batching-count sample, an unmounted handoff abort/timer sample and three basic WSL preview/error samples. These alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2404: The broad unit command loses the standalone share-name lookup 503 propagation suite, initial deletion placement-kind sample, direct changed-mtime stale sample, first-pass rollback existence example and abandoned-preparation directory sample. These exact alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2397 review amendment: The broad unit command loses three standalone suites, two partial-case definitions and two URL table rows across package/download/placement tests. Keep initial wrong-port authorization, modified independent-copy digest refusal and abort-after-begin cancellation dispatch. The remaining alarms are deliberately retired; no equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2393 current-parent refresh2401: Remove the basic skill-install service alias sample and original public managed-remove receiptless refusal case. Preserve the upstream request ownership suite and transaction interruption coverage. No equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2389: The broad unit command loses the missing-preview suite, plain-global destination sample and prepublished-receipt recovery example. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2385: The broad unit command loses four authored walker/staging/protocol examples (six expanded cases); no equivalent replacement or fresh validation is claimed for the reduced suite. Audit2383: The unscoped Vitest command no longer includes the removed Antigravity catalogue suite; its exact provider-root/owner example has no equivalent replacement or fresh validation claim. Audit2377/2381: The unscoped Vitest command includes the reduced bundled-skill and native-discovery suites; the eight removed backup/legacy/catalogue/symlink/SSH-builder examples have no replacement-equivalence or fresh validation claim here. Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2090 (sources2088/2089): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2086 (sources2082/2083): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2076 (sources2073/2074): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime-tests/terminal-handles-part-02.spec.ts: recovers a moved SSH pane through the tab it now sits in, not the one its lease froze; reports a plain expired orphan; does not report a pane whose only recent lease was superseded; does not report a pane whose only recent lease had its relay id recycled; picks the eligible orphan over a superseded predecessor that matches first; collects the same tabs the per-tab reader reports, in one sweep of the leases; reports no candidate when no lease names any of the worktree tabs. src/main/runtime/orca-runtime-tests/runtime-availability.spec.ts: starts unavailable with no authoritative window; reports the configured Windows terminal shell on status; reports floating workspace availability from settings on status; polls floating tabs with targeted PTY liveness and no repo/provider inventory; hydrates persisted tabs when the store cannot report repos; advertises browser screencast only when a renderer window is available; routes mobile Codex reset consumption through the account mutation coordinator; maps a definite pre-provider rejection into an authoritative current snapshot. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Frozen current literal-import graph reaches these changed test bytes; unresolved local and computed edges remain debt, and current reachability is not historical execution or equivalent replacement evidence. Historical prior account (preserved verbatim): Audit2070 (sources2068/2069): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime.test.ts: ordinary registration cleanup removes only await import('./orca-runtime-tests/hooks-and-hosted-review.spec'). src/main/ssh/ssh-multiplexer-transport-writer.test.ts: reports saturated epochs and their drain boundary exactly once. src/main/runtime/orca-runtime-tests/worktree-removal-archive-hook-gate.spec.ts: removes and records the waiver when the failure is explicitly overridden; removes without an override record when the hook succeeds; removes when the hook is configured but not requested; removes when no archive hook is configured; holds a desktop removal in the same repo until this one is accepted; joins a desktop removal of the same worktree accepted while this one waited. src/main/runtime/orca-runtime-tests/worktree-ps-agent-row-dismissal.spec.ts: drops the row as soon as the user dismisses it, without waiting for the PTY to exit; tells paired clients to republish on the transition and on the dismissal; rejoins a row through its %s handle after pane ownership clears. src/main/runtime/orca-runtime-tests/hooks-and-hosted-review.spec.ts: reports an error when the SSH filesystem provider is unavailable; reports an SSH orca.yaml as an error without reading any filesystem; reports ok for a local repo hook check; reads SSH issue commands as absent and drops writes without touching any filesystem; allows host integration slug helpers for SSH repos through provider-aware GitHub clients; routes runtime GitHub repo identity helpers through the selected WSL project runtime; routes runtime GitHub issue and work-item actions through the selected WSL project runtime; pins explicit origin preference on runtime open-by-number work item lookups; forwards check-details cancellation without local Git overrides. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Frozen current literal-import graph reaches these changed test bytes; unresolved local and computed edges remain debt, and current reachability is not historical execution or equivalent replacement evidence. The historical receipt/currentCommand selecting src/main/ssh/ssh-multiplexer-transport-writer.test.ts remains historical and is not a passing result for the reduced current command. Historical prior account (preserved verbatim): Audit1931 (sources1928/1929): Delete the complete tail-wait memo suite: its sole current authored callback checks supplied fromTail/blocked field values. Retire all three broader memoization/equivalence/eviction assertion aliases; they are not backed by retained source callbacks. No scan-work budget, sustained output, physical terminal or resource measurement is assigned to this removed test. Preserve meaningful remaining selectors/assertions and unchanged dated receipts within their original scope. Reduced selectors have no fresh gate execution evidence in this metadata packet. No equivalent replacement, physical watcher/PTY/provider, live SSH/remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): Audit1674 retires changed-source assertion and execution scope without equivalent replacement coverage. Existing unchanged-selector receipts remain scoped to their original sources. Historical prior-source oracle: Existing exact unchanged-selector receipts remain the only current execution evidence. Changed source selectors have no fresh execution result. Historical prior-source oracle account: The current executable slice injects main-process renderer backlog pressure, then asserts ordinary terminal-wait detection without a joined-tail allocation and with full prompt-family continuity, per-PTY and total pending-output caps, a 1,024-ID projection cap with split-remainder compaction, preserved sequenced-tail metadata, active-pending protection ahead of background trimming, exact provider-generation pause ownership, renderer exit/data ordering, and ACK-gated in-flight bounds. The negotiation seam proves every initial connection and reconnect offers V1, the same-build relay advertises V1 without launch flags, old clients remain token-free, and method-not-found peers fall back without installing source ACK publication. The joined source-intake/multiplex oracle blocks renderer or headless serialization, admits one snapshot-covered span and one trailing span, requires replacement reservation only after the authoritative sequence is known, advances upstream ACK eligibility exactly to the covered boundary after SnapshotEnd, and delivers then ACKs the trailing span through the ordinary live path without cancellation. Source-range ledger and multiplex seams additionally require cumulative byte ACK 40 then 100 for one 100-byte frame to release exact byte credit without early source settlement, admit a contiguous higher-generation recovered token while the prior token remains unsettled, and reject stale stream or source generations without releasing in-flight byte credit. Replacement reservation rolls back every earlier span on a later failure, commit requires the exact frozen transfer states, and an authoritatively reclaimed covered span rejects commit without local trim authority while rollback removes the reservation idempotently. The exit-deadline oracle publishes a source-backed desktop projection, advances a fake clock to cancellation, and requires one projection transfer, proof commit, preparation, and final exit with no provider close, retained obligation, duplicate finalization, or process-lifetime cancellation tombstone; a second controlled proof remains pending across generation close and must never publish final exit, while both paths release the renderer preparation lease exactly once. The model-migration oracle accepts span A, blocks span B's raw emulator completion, begins disconnect migration, and proves no checkpoint or reconnect attach can remain at A; releasing B advances the exact checkpoint to B and projects B once. Its fake-clock arm reaches the 10-second deadline, requires checkpoint-unavailable, one exact model reset, zero retained admission charge and timers, and no effect from late raw settlement. Its two-PTY failure arm rejects one running raw callback under an active exact migration and requires one checkpoint-unavailable result, one model reset, zero provider closes, retained sibling checkpoint and transport liveness, zero charges and timers, and an unaffected other generation; a non-migrating sibling oracle still requires generation close. The intake additionally closes 2,048 sequential provider generations into one exact range, rejects stale events across that range, and preserves an out-of-order live gap until its own close. Direct-SSH contracts additionally prove activation-response settlement before the first source frame, claim-gated projection under same-decoder-turn response/data delivery, exact early-ACK reservation through send settlement or same-token retry, recovery completion visible before lease-held frames transfers those frames only into the private quarantine and admits no output until exact checkpoint-to-recoveryEnd coverage, invalid-checkpoint restore retention through response settlement followed by fresh-token retry and one live source frame, isolated saturated-subscriber eviction with healthy owner liveness, preserved legacy-primary backpressure, one-write ownership across write(false)/drain, control selection ahead of queued ordinary PTY input with FIFO lanes and bounded fairness, liveness rebasing, failed-exit retention through late ACK or exact recovery, response-settlement cancellation authority, token-scoped exit cancellation, exact checkpoint-to-recoveryEnd continuity, stale-owner one-shot retry, no physical PTY teardown on recovery failure, exact provider-generation closure and once-only cleanup when recovery cancellation publication or proof rejects, 16 MiB-plus-1 MiB decoder caps, charged per-PTY/session retention budgets, and eight-wide isolated reattach. The live Electron perf oracle adds hidden-output floods, renderer scheduler queue depth, dropped-output-zero normal scenarios, and active key latency budgets before promotion.", "commands": [ "pnpm exec vitest run --config config/vitest.config.ts", "pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/construction/orca-runtime.test.ts", @@ -9363,7 +9382,19 @@ "Historical complete dated writer/backpressure receipt retired after its source changed, preserved verbatim including executed command and path-only currentCommand; not current validation:\n{\n \"date\": \"2026-07-29\",\n \"runner\": \"local\",\n \"platform\": \"macos\",\n \"command\": \"pnpm exec vitest run --config config/vitest.config.ts src/main/ssh/ssh-multiplexer-transport-writer.test.ts src/main/ssh/ssh-channel-multiplexer-backpressure.test.ts --reporter=dot\",\n \"result\": \"passed\",\n \"durationSeconds\": 6.89,\n \"summary\": \"Thirteen current-head deterministic files passed 150 tests across exit-sealed private recovery, stale-transfer cancellation authority, bounded latest-token retirement, restore retirement, fail-closed recovery cancellation, partial ACK and token rotation, reclaimed-span replacement, mux lane fairness, provisional activation, and exit-proof ordering; no live topology was exercised.\",\n \"currentCommand\": \"pnpm exec vitest run --config config/vitest.config.ts src/main/ssh/protocol/ssh-multiplexer-transport-writer.test.ts src/main/ssh/protocol/ssh-channel-multiplexer-backpressure.test.ts --reporter=dot\"\n }", "Historical provider scope before changed-source receipt retirement: [\"ssh\"]", "Audit3086 source-only reduction (3079/3080/3081): intentionally retire 93 authored/100 expanded mock-boundary cases, including the complete spawn-errors and SSH reconnect overlay suites, without replacement. Retired alarms include spawn classification/ownership, reply ceilings and renderer-write failure recovery, disconnect/detach fencing branches, authority facts, and overlay retry/visibility wiring. Retained callbacks are unchanged; no fresh execution, real PTY/SSH, rendered UI, or performance result is claimed.", - "Audit3096 source-only reduction (3087/3088): retire 69 authored/76 expanded cases, including complete recovery-portals and reconnect-banner suites. Intentionally lose dead/default TUI replay, generated alternate-frame style composition, reset/mode/dimension and legacy missing-mode-boundary alarms, UI notice/action/reveal policies, and isolated recovery lifecycle variants, without equivalent replacement. Retained registrations and callbacks are unchanged; headless cells are not pixels, and no fresh runtime, host, SSH, WSL, rendered-app or performance result is claimed." + "Audit3096 source-only reduction (3087/3088): retire 69 authored/76 expanded cases, including complete recovery-portals and reconnect-banner suites. Intentionally lose dead/default TUI replay, generated alternate-frame style composition, reset/mode/dimension and legacy missing-mode-boundary alarms, UI notice/action/reveal policies, and isolated recovery lifecycle variants, without equivalent replacement. Retained registrations and callbacks are unchanged; headless cells are not pixels, and no fresh runtime, host, SSH, WSL, rendered-app or performance result is claimed.", + "Audit3108 source-only reduction (3094/3095/3100): retire 27 authored/30 expanded cases, including complete markdown view-state, file-preview link-open and CLI agent-server-route suites, without replacement. Deliberate losses include preview visibility/reference lifetime and same-path owners; SSH stat, directory/missing-target, explicit-null owner, nonmarkdown line/column, local URI routing, remote-to-client guard and same-file reuse; document-preview source-owner/folder/reuse routing, stable grant location and outside-workspace POSIX/Windows request projection; and verified remote CLI send/check refusal, suggested --on argv/copy, shell no-probe bypass, unverified-launch admission and older-peer refusal. Retain two markdown source-runtime/qualified-reveal alarms, one stale grant-rejection fence and two remote read/mutation evidence policies, with original callbacks. Final last-wins reveal did not prove transient cancellation; CLI prerequisite did not prove no real send, and envelope tests do not execute server refusal. No fresh runtime, rendered UI, actual file/SSH/paired transport, authorization, mixed-version or performance result is claimed.", + "Audit3114 incorporates source3101: retire three structured Claude child-environment wrapper cases covering inherited stamp isolation/default and explicit entrypoint, Windows SDK-key canonicalization/default/duplicate-key order, and configured lookup/final environment/config-dir conjunction. Keep direct auth/session sanitation and Windows-versus-Linux overlay checks, actual executable lookup from supplied inherited PATH, native Windows child environment delivery, and stale option-mutation fencing. These are not equivalent replacements for the retired wrapper alarms. No fresh test/runtime, real login-shell probe, Claude SDK startup, remote/mixed-version, UI or performance result is claimed.", + "Audit3114 incorporates source3105: retire 17 authored/20 expanded daemon launch-note cases, including the entire two-case SessionLaunchNote suite. Deliberately lose split-marker carry across same-token re-arm, stale-token retirement refusal, foreground tri-state and serial settlement, omitted-note/no-incarnation mixed-version policy, sticky retirement, first-incarnation/replacement launch preservation and held-launch precedence. Keep only the unchanged unresolved foreground-read race against a later finished attach. Supplied notes/foreground and runtime calls do not establish actual daemon/main restart, SSH, native Windows observation, mobile UI, equivalent replacement or fresh runtime/performance validation.", + "Audit3114 incorporates source3109: retire six authored/35 expanded pricing cases: 21 accepted model-name examples, 10 unsupported/future-model fail-closed examples, malformed TTL clamp, unknown-model estimate refusal, flat-model long-context disregard and oversized long-context clamp. Keep mixed five-minute/one-hour write allocation and short/all-long/mixed long-context allocation with original fixed oracles. Real parser/refusal/bounds alarms are knowingly lost without equivalent replacement; retained tests do not validate provider rates, actual billing or request threshold classification. Preserve the archived usage-scan-append source-freeze receipt without transferring historical execution/performance credit. No fresh runtime result is claimed.", + "Audit3128 scoped coverage reduction: Audit3121 removes VoiceDictationLanguageSetting.test.tsx (Spanish-to-es callback and unsupported-model Korean option presence) and voice-speech-model-rows.test.ts (provider/language-order/retired-on-disk list policy); these real narrow alarms are deliberately retired without replacement. VoiceSpeechModelSection per-model concurrent deletion remains unchanged. Audit3122 removes the direct absolute/parent-segment sparse-directory exception-type sample and the five-row IPC sparse-preset error-code/non-save table (two authored/six expanded cases). Those real typed-validation and IPC refusal/error-code alarms are deliberately retired. Keep both real symlink/junction floating-directory trust cases and the minimal RPC structured validation-reason serialization case. The RPC case does not replace IPC save/refusal behavior, typed normalization for both path inputs, actual Git sparse checkout or rendered localization. No equivalent replacement or fresh test/runtime/platform/remote/performance validation is claimed. Audit3124 removes ExperimentalPane.test.tsx (ordinary Pet switch callback), WorkspaceDirectorySetting.test.tsx (padded absolute saved-path normalization/no-write blur), and repository-search.perf.test.ts (navigation/selected-pane builder-call policy, fixture cardinality/nonempty entries and renamed project keyword inclusion). These real narrow alarms are retired without replacement; RepositoryPane.search.test.tsx search-to-sparse-editor request remains unchanged. Audit3129: resolver Windows case-insensitive and POSIX case-sensitive configured-env composition plus mocked-base launch-preflight Windows composition are intentionally no longer checked by the two deleted suites. No equivalent coverage claimed. Keep runtime-structured-agent-host-env.test.ts unchanged: configured Windows Claude-home account identity and host-account precedence remain checked.", + "Audit3146 combines source reviews3132/3133/3135/3138/3143: intentionally retire20authored/31expanded cases without equivalent replacement. Provider-session losses: structured-native terminal-resume exclusion, metadata-less completed identity, new-turn completion clearing, Pi provider-only/periodic/manual promotion, changed-transcript launch-config isolation, Pi/omp/prime-agent completed-session remote/manual-shutdown promotion, and quit/done precedence over heartbeat. Side-thread/question losses: finished-pane acquisition, hidden title/recap states, local/relay/relay-done conversation takeover with prompt/session/child resets, plain-message abandonment, compaction/session replacement and completion resets. Codex startup losses: incoming-owner cached child replacement, old-relay foreign live-session correction, completed foreign-root turn-fact permutations. Transcript losses: real temporary-JSONL partial sibling/final-child completion, unlabelled child attribution, compact cached replay preservation and100/1000completed-child roster retention/release. Compiler-ratchet losses: valid-line uncompiled-list parser grammar examples and injected-existence stale-path filtering; these did not exercise actual filesystem canonicalization or build exclusion. These are real lifecycle, ownership, replay, liveness and retention alarms, including recent#40246 regressions, deliberately lost. Retained conditional record replacement, clockless root/SSH owner isolation, persisted main-thread fork rejection, partial/final question-answer lifetime, cached-roster/missing-ID/live HTTP/durable startup boundaries and restarted-relay refusal/acceptance do not replace those losses. No native/SSH/WSL execution or equivalent coverage is claimed.", + "Audit3156 combines3147/3150/3152/3153/3154: deliberately retires39authored/40expanded native-chat recovery cases, eight whole suites and two orphan test-support files without equivalent replacement. Lost alarms: lost-reply unconfirmed reconciliation, skipped rows/counts and missed-frame repair, unknown/pending outcome and omitted-failure-list compatibility, uncertain history after dismissal, retry/refusal/dismiss lifecycle, hidden/consumed picker ownership, result-tree keyboard focus/disclosure and all-skipped retirement; unconfirmed-over-conflict guidance and failed-chat changes despite older host timestamps; nearest-listed ancestor/cyclic forest shape, descendant membership, host ordering/missing-host local fallback; skipped/readiness/admission counts, provisional skip/progress monotonicity, early per-chat verdicts with batch pending protection, older-host waiting, start-slot/delivery distinction, retry-over-failure and unknown-after-withdrawal attention; remote snooze/reconnect/reoffer, unseen mixed summary through open/close, watched completion retirement, new success beside old failure, failed-reread mixed-result preservation, filter/collapse completion resets, retry summary replacement and current-offer/history selection; cross-host workspace identity, rendered cyclic reachability, nested tri-state/toggle propagation, project eligibility isolation and collapse preserving selection. Exact fallback-list completion barrier, batched verdict/cleanup retention, stale-read versus dismissal publication race, and requested-but-never-rendered finished-run retirement remain; they do not replace retired alarms.", + "Audit3165 combines source3160/3162: deliberately retires six authored/expanded cases across three whole suites without equivalent replacement. Launch/status losses: observed React-render pending/resuming coordination across settings and deferred offer read; stale-offer reread suppressing dialog reopen; held-local-chat recovery visibility with new-chat preferences off; disabled-local admission avoiding offer RPC despite an injected but unconsumed paired-tab fixture; and run-only lost-reply uncertainty reachability until direct viewed-run retirement. Launch probe does not prove arbitrary synchronous-store atomicity, the paired fixture is not remote runtime enrollment, and the status case directly marks viewed state rather than rendering the summary. Crew-hook losses: old-host method_not_found cache persists across party changes but is released by independently supplied connection generation/verified pairing status or pairing revision, with actual frame publication and teardown. These are real narrow coordination, admission, uncertainty and mixed-version cache alarms consciously lost. Exact web verified-runtime writer handoff guard remains; it does not replace those alarms or prove live host/native/mobile delivery.", + "Audit3178 combines source3169/3170/3175: deliberately retires eight authored units (six Vitest cases and two imperative custom relay scenarios), including two whole suites, without equivalent replacement. Voice Section loses per-model pending-delete isolation across interleaved A/B completion and the two-success refresh-call alarm; exact VoicePane delayed key-clear/newer enabled-toggle merge remains and does not replace row deletion coverage. Speech loses dedicated rating-scale/inclusive-ceiling, unsupported-versus-unmeasured, explicit/system-language precedence/locale alias, accuracy versus fast named/default/best-measured selection, and unmeasured/no-match examples; exact offered-user-pick versus retired-selection case and its fixture remain. Relay loses legacy ping-delivery count/liveness sampled before the silence deadline and grouped malformed Bearer/host-ID 401/429 routing checks; twelve real Worker/DurableObject/shipped-client scenarios remain, not equivalent replacement for those narrow alarms. Six prior speech cases are not all deleted: approved successor3175 keeps the original user-choice case. No actual credential/file persistence, native/GPU/engine/download delivery, production assignment policy or deployed-runtime validation is claimed by this reduction.", + "Audit3191 combines approved source3182/3187/3188: deliberately retires thirteen authored Vitest registrations and fifteen expanded cases, including five whole suites, without equivalent replacement. Attachment intake loses real portal/native-capture terminal interception and unowned-container refusal, immediate child-only committed availability/claim-ref negotiation and delivery, and direct-target over stable focused/background composer routing through disable/re-enable/remount and independent question focus. Exact destination/cache/draft and final-stat owner/workspace/File-release suites remain; they do not replace Surface recipient routing. Automation authoring loses destination runtime catalog membership, local/direct-SSH exclusion of paired-runtime repos, unknown-runtime empty catalog, logical project/host/setup/repo/path context payload, and missing/nonready setup refusal; these were genuine direct helper alarms, while exact schedule transformation, legacy schedule and setup-decision suites remain. Agent picker loses setup-chat/terminal/missing-installer/unsupported-or-unknown-host row projection samples and the ordinary unsearched menu variant; the entire original26-line resume recipe suite remains, including reported bypass versus default/absent permission modes, as does the exact search-result menu callback with its fixtures, model/effort commits and staged Arguments reopen outcome. Rejected predecessor3180 full recipe deletion is excluded. No actual native drag/cursor/focus/IME, upload bytes or disk/restart persistence, full automation save/scheduler/runtime transport, real resume-process flags/environment delivery, or native menu/rendered layout validation is claimed.", + "Audit3200 composes approved source3194: deliberately retires thirteen authored registrations/twenty-seven expanded cases in six whole automation host/list policy suites without equivalent replacement. Real RPC category/retryability and wrapped-timeout recognition, unscoped-failure/scoped-success health evidence precedence, exact-ID create selectors and per-run workspace omission, paired-web local/SSH/absent host catalog routing, incompatible/removed/unhydrated/offline execution health, runtime-before-nested-SSH recovery dispatch, and no-owned-focus/successor/foreign-list focus policy alarms are consciously lost. Retain exact20line orphan allow/refuse/precondition and exact90line cross-host same-ID search suites. No retry-timer/fence lifecycle, actual reconnect/network/write delivery, native focus, mobile/mixed-version runtime or disk persistence coverage is claimed.", + "Audit3209 composes approved sources3202/3206: deliberately retires seven authored/expanded cases in four whole suites without equivalent replacement. Work-item queries lose real GitHub/GitLab oversized ASCII secret-prefix empty-query and whitespace-before-trim refusal alarms; inputs share the imported size bound and exercise only its fast length branch, with no multibyte or actual provider/exposure guarantee. Skill sharing loses complete/partial managed-bundle and destination-ambiguity association checks plus three negative origin/path/scheme admission examples; these do not establish uploaded contents, arbitrary-URL fetching, authorization or execution. Retain exact originless-project direct-link fallback, cloud-delete confirmation, bundled-target repair/owner isolation and explicit Windows-host preference over stale WSL suites. Rejected3201 runtime-preference removal is excluded. No real cloud/network/host/disk, mobile or mixed-version execution validation is claimed." ], "demotionRule": "Cannot promote without metric artifacts and bounded-byte assertions." }, @@ -12739,14 +12770,14 @@ "providers": ["local", "remote-runtime", "ssh"], "coveredPlatforms": ["macos", "linux"], "coveredProviders": ["local", "remote-runtime", "ssh"], - "coverageNotes": "Audit3096 source-only reduction (3087/3088): retire 69 authored/76 expanded cases, including complete recovery-portals and reconnect-banner suites. Intentionally lose dead/default TUI replay, generated alternate-frame style composition, reset/mode/dimension and legacy missing-mode-boundary alarms, UI notice/action/reveal policies, and isolated recovery lifecycle variants, without equivalent replacement. Retained registrations and callbacks are unchanged; headless cells are not pixels, and no fresh runtime, host, SSH, WSL, rendered-app or performance result is claimed. Audit3086 source-only reduction (3079/3080/3081): intentionally retire 93 authored/100 expanded mock-boundary cases, including the complete spawn-errors and SSH reconnect overlay suites, without replacement. Retired alarms include spawn classification/ownership, reply ceilings and renderer-write failure recovery, disconnect/detach fencing branches, authority facts, and overlay retry/visibility wiring. Retained callbacks are unchanged; no fresh execution, real PTY/SSH, rendered UI, or performance result is claimed. Audit2432: The broad unit command loses the isolated BranchPicker open-change notification sample. Its unique true/false callback alarm is intentionally retired; reopening/status-refresh behavior was not exercised. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2425: The broad unit command loses the workspace-copy-status supplied readError forwarding sample. It did not exercise the branch-switch blocking promised by its title. This alarm is intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2417: The broad unit command loses two ordinary clean Git cherry-pick/revert success samples and two terminal startup foreground-read work-budget samples. These unique alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2412: The broad unit command loses the whole six-case fake-React-hook scroll-anchor suite, two generic draft-retention samples, a simple new-agent order sample, a real history-publication batching-count sample, an unmounted handoff abort/timer sample and three basic WSL preview/error samples. These alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2404: The broad unit command loses the standalone share-name lookup 503 propagation suite, initial deletion placement-kind sample, direct changed-mtime stale sample, first-pass rollback existence example and abandoned-preparation directory sample. These exact alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2397 review amendment: The broad unit command loses three standalone suites, two partial-case definitions and two URL table rows across package/download/placement tests. Keep initial wrong-port authorization, modified independent-copy digest refusal and abort-after-begin cancellation dispatch. The remaining alarms are deliberately retired; no equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2393 current-parent refresh2401: Remove the basic skill-install service alias sample and original public managed-remove receiptless refusal case. Preserve the upstream request ownership suite and transaction interruption coverage. No equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2389: The broad unit command loses the missing-preview suite, plain-global destination sample and prepublished-receipt recovery example. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2385: The broad unit command loses four authored walker/staging/protocol examples (six expanded cases); no equivalent replacement or fresh validation is claimed for the reduced suite. Audit2383: The unscoped Vitest command no longer includes the removed Antigravity catalogue suite; its exact provider-root/owner example has no equivalent replacement or fresh validation claim. Audit2377/2381: The unscoped Vitest command includes the reduced bundled-skill and native-discovery suites; the eight removed backup/legacy/catalogue/symlink/SSH-builder examples have no replacement-equivalence or fresh validation claim here. Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2090 (sources2088/2089): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2086 (sources2082/2083): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2076 (sources2073/2074): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime-tests/terminal-handles-part-02.spec.ts: recovers a moved SSH pane through the tab it now sits in, not the one its lease froze; reports a plain expired orphan; does not report a pane whose only recent lease was superseded; does not report a pane whose only recent lease had its relay id recycled; picks the eligible orphan over a superseded predecessor that matches first; collects the same tabs the per-tab reader reports, in one sweep of the leases; reports no candidate when no lease names any of the worktree tabs. src/main/runtime/orca-runtime-tests/runtime-availability.spec.ts: starts unavailable with no authoritative window; reports the configured Windows terminal shell on status; reports floating workspace availability from settings on status; polls floating tabs with targeted PTY liveness and no repo/provider inventory; hydrates persisted tabs when the store cannot report repos; advertises browser screencast only when a renderer window is available; routes mobile Codex reset consumption through the account mutation coordinator; maps a definite pre-provider rejection into an authoritative current snapshot. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Frozen current literal-import graph reaches these changed test bytes; unresolved local and computed edges remain debt, and current reachability is not historical execution or equivalent replacement evidence. Historical prior account (preserved verbatim): Audit2056 (sources2054/2055): Intentionally retire these low-value alarms without replacement: src/renderer/src/runtime/files/watching/runtime-file-client-watch.test.ts: delivers remote file changes to listeners for the same worktree. src/main/runtime/orca-runtime.test.ts: ordinary registration cleanup removes only await import('./orca-runtime-tests/mobile-session-tabs-part-14.spec'). src/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-03.spec.ts: arms the stale-title timer for a seeded working title; arms the Command Code scrape from the noted spawn command; prefers the tracked title over a stale renderer lastTitle in the hydration seed; writes recent output into the current runtime output map; uses a later title handler replacement with the runtime receiver; calls the current injected listener with the runtime receiver; keeps optional reconciliation lazy after its callback is removed. src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-14.spec.ts: lists them, so a paired client can mirror a migrated editor; closes one by retiring it from the host session; keeps an unsaved draft unless the close is forced; shares aggregate work but leaves a replacement pending promise alone; lets a targeted refresh finish while an aggregate refresh waits; refuses a close when the store lacks %s before the guard; keeps a later missing %s on the original caught failure path. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Exact retired assertionRefs, preserved as historical objects only: {\n \"file\": \"src/renderer/src/runtime/files/watching/runtime-file-client-watch.test.ts\",\n \"assertions\": [\n \"terminal watcher error and setup failure evict the shared entry before retrying callbacks run\",\n \"an old stream end cannot evict the replacement stream, which still delivers to its listener\",\n \"two same-worktree listeners share a synthetic subscription until the final stop unsubscribes and sends unwatch\"\n ]\n } Historical prior account (preserved verbatim): Audit1973: Delete the standalone mocked watcher cleanup suite and its entire sole-file prospective command. Retire the removed file-command transport-abort alias; preserve the independent cancellation suite and final-overflow/error/end cleanup callback, and13 unrelated receipt objects. Whole original changed dated receipts are retired, never narrowed or transferred. This metadata review claims no fresh execution, equivalent replacement, provider/PTY, live remote/mobile, rendered, cross-platform, soak or measured-budget result. Historical prior account (preserved verbatim): Audit1931 (sources1928/1929): Partial runtime files-watch suite retains controlled Windows close-event waiting, shared-client survival, late physical-exit ownership/deadline cleanup and shutdown joining. Its combined Windows close/deadline/late-exit alias remains backed by unchanged callbacks. Retire native-error-close, pre-publication setup ownership and failed-delete rearm aliases; associated delegation, failure forwarding, removal routing and recovery examples are lost. These tests inject watch/subscription seams and do not observe an actual native watcher or physical process. Preserve meaningful remaining selectors/assertions and unchanged dated receipts within their original scope. Reduced selectors have no fresh gate execution evidence in this metadata packet. No equivalent replacement, physical watcher/PTY/provider, live SSH/remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): Audit1925 (sources1922/1923): Partial runtime watcher-host suite loses mocked option/event/overflow/resubscription forwarding, supplied teardown-error propagation, aborted-signal/no-call and private ten-thousand-waiter-count inventories. Retire the 10,000-caller bound and failed-recovery-subscriber-ending assertion aliases. Keep same-root owner cancellation, pre-ready replacement, held root-close join, stale-generation recovery delivery and initial failed-root ownership mappings backed by retained real-host callbacks with injected subscription/error/physical-exit promises. No actual native watcher, process termination or resource bound was observed. Preserve meaningful remaining selectors/assertions and unchanged dated receipts within their original scope. Reduced selectors have no fresh gate execution evidence in this metadata packet. No equivalent replacement, physical watcher/PTY/provider, live SSH/remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): Audit1683 removes low-value test projections, mock wiring, private-state assertions, inventories and duplicate examples without equivalent replacement coverage. Per-source reviews record retained public behavior and refusal boundaries with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1645 removes low-value test projections, mock wiring, private-state assertions, inventories and duplicate examples without equivalent replacement coverage. Per-source reviews record retained public behavior and refusal boundaries with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1640 removes low-value IPC, SSH, workspace and transcript-watcher tests without equivalent replacement coverage. Per-source reviews record retained public refusal, cancellation, execution-host and real-filesystem outcomes with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1634 removes low-value IPC, filesystem and runtime projections, argument inventories and duplicate examples without equivalent replacement coverage. Per-source reviews record retained cancellation, ownership, authorization, filesystem and SQLite boundaries with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1627 removes low-value mocked daemon projections, scalar tables and duplicate terminal examples without equivalent replacement coverage. Per-source reviews record retained terminal content preservation, process ownership refusal and recovery boundaries together with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1623 removes low-value mocked daemon projections, scalar tables and duplicate terminal examples without equivalent replacement coverage. Per-source reviews record retained terminal content preservation, process ownership refusal and recovery boundaries together with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1516 removes package-electron-runtime-contract.test.mjs, a copied release-workflow platform and marker matrix. Its workflow wiring alarm is intentionally retired; no actual packaged watcher delivery was exercised and no equivalent replacement is claimed. Unaffected dated execution receipts retain their original scope; changed optional selectors have no fresh full-gate execution result. This audit removes the paired-web stopped-during-outage and late-ready direct-branch examples. The retained pre-ready cancellation, failed-unwatch retry and replay-continuity cases are not equivalent replacements for those ordering alarms. Current web-runtime-client.test.ts assertions below name only its retained pre-ready callback case; replay cases remain in their separate suite. Historical commands and results remain historical. Deterministic tests cover one shared healthy child per runtime process plus at most four bounded fault-quarantine children, native desktop, paired-runtime, and WSL snapshot processes sharing the same eight-physical-child reservation with typed serialized event-driven capacity recovery, including recursive re-wait when crash recovery reclaims an announced slot, one quarantine attempt per watch lifetime, generation-scoped cancellation, bounded termination with removable deadline waiters, replacement-crawl errors that cannot be blessed by a late readiness ack, pre-ready paired-web cancellation registered before an unbounded capacity wait, already-resolved and late physical-exit retry of a rejected paired-web teardown, physical desktop-install and local/SSH PTY teardown, stale-generation rejection, per-child stat bounds, final-overflow RPC delivery, and renderer eviction before terminal callbacks can retry. Destructive local and SSH removal fences both ID-derived and resolved-cwd terminal roots, including sibling-root/cwd combinations with reverse admission rollback, closes descendant relay watches before parent deletion, enumerates authoritative provider/cwd ownership, falls back to daemon spawn cwd before OSC 7, and keeps daemon/relay immediate shutdown pending until native exit or a bounded fail-closed error; a dead relay PID discovered during attach also settles concurrent shutdown before its stale entry is reaped, while Windows runtime watcher deadlines retain one removable physical-close waiter, treat Node's error-close path as positive physical-exit proof, and clear root ownership on late close. The relay policy test maps a standard repository's base, Git common directory, and worktree roots to one healthy supervisor, then proves a shared-child failure recovers those roots in separate quarantine supervisors with overflow and resumed events. Abortable capacity, quarantine, runtime-root, relay, SSH, and relay pre-install setup waits attach one reaction to each shared promise and explicitly remove 10,000 cancelled caller closures while one anchor remains. Built-entry macOS harnesses kill the desktop/runtime and SSH relay watcher children, then require automatic resubscription and later events while the host process and relay PTY survive. SSH bundles the child boundary beside relay.js, requires both artifacts for install completeness, and preserves registration-owned same-root cancellation. The test-value audit corrects the active renderer watch command/file reference to the existing runtime-file-client-watch.test.ts, whose three cases are retained unchanged. They observe synthetic subscription retry/fanout and unsubscribe/unwatch calls, not actual preload/main bookkeeping or physical watcher-process cleanup. The separate read/preview client suite loses forwarding, supplied-error and negative-only examples, retaining binary detection and Unicode SVG decoding. Historical evidence commands/results are unchanged. Test-value audit1293 removes src/main/providers/local-pty/local-pty-provider-session-inventory.test.ts (2 authored cases). Their isolated assertions no longer run; surviving tests are not claimed as equivalent coverage. Fresh execution against the candidate SHA is required. Audit1312 removes low-value imported specs from aggregate test drivers; old whole-driver execution receipts are archived. Retained registrations are unchanged. No equivalent replacement coverage is claimed. Audit1383: src/main/runtime/orca-runtime-tests/worktree-native-chat-setup.spec.ts reduced. Lose command-list/receipt/default/background activation matrices whose provider spawn returns canned IDs. Retained test proves actual tab allocation separation, not terminal startup. No equivalent replacement coverage is claimed. Existing exact unaffected receipts and their platform/provider/budget claims remain scoped to unchanged selectors. Changed optional selectors have no new execution result. Audit1401: src/main/runtime/orca-runtime-tests/mobile-session-tabs-duplicate-pty-repair.spec.ts removed. Loses listing-on-already-repaired-data alarm; it never established runtime repair invocation. src/main/runtime/orca-runtime-tests/mobile-session-tabs-split-agent-tab.spec.ts removed. Loses actual mobile split sibling shell versus recorded-agent resume command alarms; no equivalent coverage asserted. src/main/runtime/orca-runtime-tests/worktree-native-chat-setup.spec.ts removed. Loses separate setup/startup tab result in that manually assembled path. src/main/runtime/orca-runtime.test.ts reduced. Driver registration/import of a whole-deleted selected spec is removed; directly authored cases remain unchanged. No extra authored removal credit. No equivalent replacement coverage is claimed. Existing exact unaffected receipts remain unchanged and apply only to their unchanged selectors. Changed optional selectors have no new execution result. Audit1412: src/main/workspaces/removal/watcher-removal-gate.test.ts reduced. Loses exact removal-error compatibility with renderer predicate under shared message constants. Kept public refusal outcomes do not establish that renderer classification. No equivalent replacement coverage is claimed. Existing exact unaffected receipts remain unchanged and apply only to their unchanged selectors. Changed optional selectors have no new execution result.", + "coverageNotes": "Audit3209 composes approved sources3202/3206: deliberately retires seven authored/expanded cases in four whole suites without equivalent replacement. Work-item queries lose real GitHub/GitLab oversized ASCII secret-prefix empty-query and whitespace-before-trim refusal alarms; inputs share the imported size bound and exercise only its fast length branch, with no multibyte or actual provider/exposure guarantee. Skill sharing loses complete/partial managed-bundle and destination-ambiguity association checks plus three negative origin/path/scheme admission examples; these do not establish uploaded contents, arbitrary-URL fetching, authorization or execution. Retain exact originless-project direct-link fallback, cloud-delete confirmation, bundled-target repair/owner isolation and explicit Windows-host preference over stale WSL suites. Rejected3201 runtime-preference removal is excluded. No real cloud/network/host/disk, mobile or mixed-version execution validation is claimed. Audit3200 composes approved source3194: deliberately retires thirteen authored registrations/twenty-seven expanded cases in six whole automation host/list policy suites without equivalent replacement. Real RPC category/retryability and wrapped-timeout recognition, unscoped-failure/scoped-success health evidence precedence, exact-ID create selectors and per-run workspace omission, paired-web local/SSH/absent host catalog routing, incompatible/removed/unhydrated/offline execution health, runtime-before-nested-SSH recovery dispatch, and no-owned-focus/successor/foreign-list focus policy alarms are consciously lost. Retain exact20line orphan allow/refuse/precondition and exact90line cross-host same-ID search suites. No retry-timer/fence lifecycle, actual reconnect/network/write delivery, native focus, mobile/mixed-version runtime or disk persistence coverage is claimed. Audit3191 combines approved source3182/3187/3188: deliberately retires thirteen authored Vitest registrations and fifteen expanded cases, including five whole suites, without equivalent replacement. Attachment intake loses real portal/native-capture terminal interception and unowned-container refusal, immediate child-only committed availability/claim-ref negotiation and delivery, and direct-target over stable focused/background composer routing through disable/re-enable/remount and independent question focus. Exact destination/cache/draft and final-stat owner/workspace/File-release suites remain; they do not replace Surface recipient routing. Automation authoring loses destination runtime catalog membership, local/direct-SSH exclusion of paired-runtime repos, unknown-runtime empty catalog, logical project/host/setup/repo/path context payload, and missing/nonready setup refusal; these were genuine direct helper alarms, while exact schedule transformation, legacy schedule and setup-decision suites remain. Agent picker loses setup-chat/terminal/missing-installer/unsupported-or-unknown-host row projection samples and the ordinary unsearched menu variant; the entire original26-line resume recipe suite remains, including reported bypass versus default/absent permission modes, as does the exact search-result menu callback with its fixtures, model/effort commits and staged Arguments reopen outcome. Rejected predecessor3180 full recipe deletion is excluded. No actual native drag/cursor/focus/IME, upload bytes or disk/restart persistence, full automation save/scheduler/runtime transport, real resume-process flags/environment delivery, or native menu/rendered layout validation is claimed. Audit3178 combines source3169/3170/3175: deliberately retires eight authored units (six Vitest cases and two imperative custom relay scenarios), including two whole suites, without equivalent replacement. Voice Section loses per-model pending-delete isolation across interleaved A/B completion and the two-success refresh-call alarm; exact VoicePane delayed key-clear/newer enabled-toggle merge remains and does not replace row deletion coverage. Speech loses dedicated rating-scale/inclusive-ceiling, unsupported-versus-unmeasured, explicit/system-language precedence/locale alias, accuracy versus fast named/default/best-measured selection, and unmeasured/no-match examples; exact offered-user-pick versus retired-selection case and its fixture remain. Relay loses legacy ping-delivery count/liveness sampled before the silence deadline and grouped malformed Bearer/host-ID 401/429 routing checks; twelve real Worker/DurableObject/shipped-client scenarios remain, not equivalent replacement for those narrow alarms. Six prior speech cases are not all deleted: approved successor3175 keeps the original user-choice case. No actual credential/file persistence, native/GPU/engine/download delivery, production assignment policy or deployed-runtime validation is claimed by this reduction. Audit3165 combines source3160/3162: deliberately retires six authored/expanded cases across three whole suites without equivalent replacement. Launch/status losses: observed React-render pending/resuming coordination across settings and deferred offer read; stale-offer reread suppressing dialog reopen; held-local-chat recovery visibility with new-chat preferences off; disabled-local admission avoiding offer RPC despite an injected but unconsumed paired-tab fixture; and run-only lost-reply uncertainty reachability until direct viewed-run retirement. Launch probe does not prove arbitrary synchronous-store atomicity, the paired fixture is not remote runtime enrollment, and the status case directly marks viewed state rather than rendering the summary. Crew-hook losses: old-host method_not_found cache persists across party changes but is released by independently supplied connection generation/verified pairing status or pairing revision, with actual frame publication and teardown. These are real narrow coordination, admission, uncertainty and mixed-version cache alarms consciously lost. Exact web verified-runtime writer handoff guard remains; it does not replace those alarms or prove live host/native/mobile delivery. Audit3156 combines3147/3150/3152/3153/3154: deliberately retires39authored/40expanded native-chat recovery cases, eight whole suites and two orphan test-support files without equivalent replacement. Lost alarms: lost-reply unconfirmed reconciliation, skipped rows/counts and missed-frame repair, unknown/pending outcome and omitted-failure-list compatibility, uncertain history after dismissal, retry/refusal/dismiss lifecycle, hidden/consumed picker ownership, result-tree keyboard focus/disclosure and all-skipped retirement; unconfirmed-over-conflict guidance and failed-chat changes despite older host timestamps; nearest-listed ancestor/cyclic forest shape, descendant membership, host ordering/missing-host local fallback; skipped/readiness/admission counts, provisional skip/progress monotonicity, early per-chat verdicts with batch pending protection, older-host waiting, start-slot/delivery distinction, retry-over-failure and unknown-after-withdrawal attention; remote snooze/reconnect/reoffer, unseen mixed summary through open/close, watched completion retirement, new success beside old failure, failed-reread mixed-result preservation, filter/collapse completion resets, retry summary replacement and current-offer/history selection; cross-host workspace identity, rendered cyclic reachability, nested tri-state/toggle propagation, project eligibility isolation and collapse preserving selection. Exact fallback-list completion barrier, batched verdict/cleanup retention, stale-read versus dismissal publication race, and requested-but-never-rendered finished-run retirement remain; they do not replace retired alarms. Audit3146 combines source reviews3132/3133/3135/3138/3143: intentionally retire20authored/31expanded cases without equivalent replacement. Provider-session losses: structured-native terminal-resume exclusion, metadata-less completed identity, new-turn completion clearing, Pi provider-only/periodic/manual promotion, changed-transcript launch-config isolation, Pi/omp/prime-agent completed-session remote/manual-shutdown promotion, and quit/done precedence over heartbeat. Side-thread/question losses: finished-pane acquisition, hidden title/recap states, local/relay/relay-done conversation takeover with prompt/session/child resets, plain-message abandonment, compaction/session replacement and completion resets. Codex startup losses: incoming-owner cached child replacement, old-relay foreign live-session correction, completed foreign-root turn-fact permutations. Transcript losses: real temporary-JSONL partial sibling/final-child completion, unlabelled child attribution, compact cached replay preservation and100/1000completed-child roster retention/release. Compiler-ratchet losses: valid-line uncompiled-list parser grammar examples and injected-existence stale-path filtering; these did not exercise actual filesystem canonicalization or build exclusion. These are real lifecycle, ownership, replay, liveness and retention alarms, including recent#40246 regressions, deliberately lost. Retained conditional record replacement, clockless root/SSH owner isolation, persisted main-thread fork rejection, partial/final question-answer lifetime, cached-roster/missing-ID/live HTTP/durable startup boundaries and restarted-relay refusal/acceptance do not replace those losses. No native/SSH/WSL execution or equivalent coverage is claimed. Audit3128 scoped coverage reduction: Audit3121 removes VoiceDictationLanguageSetting.test.tsx (Spanish-to-es callback and unsupported-model Korean option presence) and voice-speech-model-rows.test.ts (provider/language-order/retired-on-disk list policy); these real narrow alarms are deliberately retired without replacement. VoiceSpeechModelSection per-model concurrent deletion remains unchanged. Audit3122 removes the direct absolute/parent-segment sparse-directory exception-type sample and the five-row IPC sparse-preset error-code/non-save table (two authored/six expanded cases). Those real typed-validation and IPC refusal/error-code alarms are deliberately retired. Keep both real symlink/junction floating-directory trust cases and the minimal RPC structured validation-reason serialization case. The RPC case does not replace IPC save/refusal behavior, typed normalization for both path inputs, actual Git sparse checkout or rendered localization. No equivalent replacement or fresh test/runtime/platform/remote/performance validation is claimed. Audit3124 removes ExperimentalPane.test.tsx (ordinary Pet switch callback), WorkspaceDirectorySetting.test.tsx (padded absolute saved-path normalization/no-write blur), and repository-search.perf.test.ts (navigation/selected-pane builder-call policy, fixture cardinality/nonempty entries and renamed project keyword inclusion). These real narrow alarms are retired without replacement; RepositoryPane.search.test.tsx search-to-sparse-editor request remains unchanged. Audit3129: resolver Windows case-insensitive and POSIX case-sensitive configured-env composition plus mocked-base launch-preflight Windows composition are intentionally no longer checked by the two deleted suites. No equivalent coverage claimed. Keep runtime-structured-agent-host-env.test.ts unchanged: configured Windows Claude-home account identity and host-account precedence remain checked. Audit3114 incorporates source3101: retire three structured Claude child-environment wrapper cases covering inherited stamp isolation/default and explicit entrypoint, Windows SDK-key canonicalization/default/duplicate-key order, and configured lookup/final environment/config-dir conjunction. Keep direct auth/session sanitation and Windows-versus-Linux overlay checks, actual executable lookup from supplied inherited PATH, native Windows child environment delivery, and stale option-mutation fencing. These are not equivalent replacements for the retired wrapper alarms. No fresh test/runtime, real login-shell probe, Claude SDK startup, remote/mixed-version, UI or performance result is claimed. Audit3114 incorporates source3105: retire 17 authored/20 expanded daemon launch-note cases, including the entire two-case SessionLaunchNote suite. Deliberately lose split-marker carry across same-token re-arm, stale-token retirement refusal, foreground tri-state and serial settlement, omitted-note/no-incarnation mixed-version policy, sticky retirement, first-incarnation/replacement launch preservation and held-launch precedence. Keep only the unchanged unresolved foreground-read race against a later finished attach. Supplied notes/foreground and runtime calls do not establish actual daemon/main restart, SSH, native Windows observation, mobile UI, equivalent replacement or fresh runtime/performance validation. Audit3114 incorporates source3109: retire six authored/35 expanded pricing cases: 21 accepted model-name examples, 10 unsupported/future-model fail-closed examples, malformed TTL clamp, unknown-model estimate refusal, flat-model long-context disregard and oversized long-context clamp. Keep mixed five-minute/one-hour write allocation and short/all-long/mixed long-context allocation with original fixed oracles. Real parser/refusal/bounds alarms are knowingly lost without equivalent replacement; retained tests do not validate provider rates, actual billing or request threshold classification. Preserve the archived usage-scan-append source-freeze receipt without transferring historical execution/performance credit. No fresh runtime result is claimed. Audit3108 source-only reduction (3094/3095/3100): retire 27 authored/30 expanded cases, including complete markdown view-state, file-preview link-open and CLI agent-server-route suites, without replacement. Deliberate losses include preview visibility/reference lifetime and same-path owners; SSH stat, directory/missing-target, explicit-null owner, nonmarkdown line/column, local URI routing, remote-to-client guard and same-file reuse; document-preview source-owner/folder/reuse routing, stable grant location and outside-workspace POSIX/Windows request projection; and verified remote CLI send/check refusal, suggested --on argv/copy, shell no-probe bypass, unverified-launch admission and older-peer refusal. Retain two markdown source-runtime/qualified-reveal alarms, one stale grant-rejection fence and two remote read/mutation evidence policies, with original callbacks. Final last-wins reveal did not prove transient cancellation; CLI prerequisite did not prove no real send, and envelope tests do not execute server refusal. No fresh runtime, rendered UI, actual file/SSH/paired transport, authorization, mixed-version or performance result is claimed. Audit3096 source-only reduction (3087/3088): retire 69 authored/76 expanded cases, including complete recovery-portals and reconnect-banner suites. Intentionally lose dead/default TUI replay, generated alternate-frame style composition, reset/mode/dimension and legacy missing-mode-boundary alarms, UI notice/action/reveal policies, and isolated recovery lifecycle variants, without equivalent replacement. Retained registrations and callbacks are unchanged; headless cells are not pixels, and no fresh runtime, host, SSH, WSL, rendered-app or performance result is claimed. Audit3086 source-only reduction (3079/3080/3081): intentionally retire 93 authored/100 expanded mock-boundary cases, including the complete spawn-errors and SSH reconnect overlay suites, without replacement. Retired alarms include spawn classification/ownership, reply ceilings and renderer-write failure recovery, disconnect/detach fencing branches, authority facts, and overlay retry/visibility wiring. Retained callbacks are unchanged; no fresh execution, real PTY/SSH, rendered UI, or performance result is claimed. Audit2432: The broad unit command loses the isolated BranchPicker open-change notification sample. Its unique true/false callback alarm is intentionally retired; reopening/status-refresh behavior was not exercised. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2425: The broad unit command loses the workspace-copy-status supplied readError forwarding sample. It did not exercise the branch-switch blocking promised by its title. This alarm is intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2417: The broad unit command loses two ordinary clean Git cherry-pick/revert success samples and two terminal startup foreground-read work-budget samples. These unique alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2412: The broad unit command loses the whole six-case fake-React-hook scroll-anchor suite, two generic draft-retention samples, a simple new-agent order sample, a real history-publication batching-count sample, an unmounted handoff abort/timer sample and three basic WSL preview/error samples. These alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2404: The broad unit command loses the standalone share-name lookup 503 propagation suite, initial deletion placement-kind sample, direct changed-mtime stale sample, first-pass rollback existence example and abandoned-preparation directory sample. These exact alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2397 review amendment: The broad unit command loses three standalone suites, two partial-case definitions and two URL table rows across package/download/placement tests. Keep initial wrong-port authorization, modified independent-copy digest refusal and abort-after-begin cancellation dispatch. The remaining alarms are deliberately retired; no equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2393 current-parent refresh2401: Remove the basic skill-install service alias sample and original public managed-remove receiptless refusal case. Preserve the upstream request ownership suite and transaction interruption coverage. No equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2389: The broad unit command loses the missing-preview suite, plain-global destination sample and prepublished-receipt recovery example. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2385: The broad unit command loses four authored walker/staging/protocol examples (six expanded cases); no equivalent replacement or fresh validation is claimed for the reduced suite. Audit2383: The unscoped Vitest command no longer includes the removed Antigravity catalogue suite; its exact provider-root/owner example has no equivalent replacement or fresh validation claim. Audit2377/2381: The unscoped Vitest command includes the reduced bundled-skill and native-discovery suites; the eight removed backup/legacy/catalogue/symlink/SSH-builder examples have no replacement-equivalence or fresh validation claim here. Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2090 (sources2088/2089): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2086 (sources2082/2083): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2076 (sources2073/2074): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime-tests/terminal-handles-part-02.spec.ts: recovers a moved SSH pane through the tab it now sits in, not the one its lease froze; reports a plain expired orphan; does not report a pane whose only recent lease was superseded; does not report a pane whose only recent lease had its relay id recycled; picks the eligible orphan over a superseded predecessor that matches first; collects the same tabs the per-tab reader reports, in one sweep of the leases; reports no candidate when no lease names any of the worktree tabs. src/main/runtime/orca-runtime-tests/runtime-availability.spec.ts: starts unavailable with no authoritative window; reports the configured Windows terminal shell on status; reports floating workspace availability from settings on status; polls floating tabs with targeted PTY liveness and no repo/provider inventory; hydrates persisted tabs when the store cannot report repos; advertises browser screencast only when a renderer window is available; routes mobile Codex reset consumption through the account mutation coordinator; maps a definite pre-provider rejection into an authoritative current snapshot. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Frozen current literal-import graph reaches these changed test bytes; unresolved local and computed edges remain debt, and current reachability is not historical execution or equivalent replacement evidence. Historical prior account (preserved verbatim): Audit2056 (sources2054/2055): Intentionally retire these low-value alarms without replacement: src/renderer/src/runtime/files/watching/runtime-file-client-watch.test.ts: delivers remote file changes to listeners for the same worktree. src/main/runtime/orca-runtime.test.ts: ordinary registration cleanup removes only await import('./orca-runtime-tests/mobile-session-tabs-part-14.spec'). src/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-03.spec.ts: arms the stale-title timer for a seeded working title; arms the Command Code scrape from the noted spawn command; prefers the tracked title over a stale renderer lastTitle in the hydration seed; writes recent output into the current runtime output map; uses a later title handler replacement with the runtime receiver; calls the current injected listener with the runtime receiver; keeps optional reconciliation lazy after its callback is removed. src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-14.spec.ts: lists them, so a paired client can mirror a migrated editor; closes one by retiring it from the host session; keeps an unsaved draft unless the close is forced; shares aggregate work but leaves a replacement pending promise alone; lets a targeted refresh finish while an aggregate refresh waits; refuses a close when the store lacks %s before the guard; keeps a later missing %s on the original caught failure path. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Exact retired assertionRefs, preserved as historical objects only: {\n \"file\": \"src/renderer/src/runtime/files/watching/runtime-file-client-watch.test.ts\",\n \"assertions\": [\n \"terminal watcher error and setup failure evict the shared entry before retrying callbacks run\",\n \"an old stream end cannot evict the replacement stream, which still delivers to its listener\",\n \"two same-worktree listeners share a synthetic subscription until the final stop unsubscribes and sends unwatch\"\n ]\n } Historical prior account (preserved verbatim): Audit1973: Delete the standalone mocked watcher cleanup suite and its entire sole-file prospective command. Retire the removed file-command transport-abort alias; preserve the independent cancellation suite and final-overflow/error/end cleanup callback, and13 unrelated receipt objects. Whole original changed dated receipts are retired, never narrowed or transferred. This metadata review claims no fresh execution, equivalent replacement, provider/PTY, live remote/mobile, rendered, cross-platform, soak or measured-budget result. Historical prior account (preserved verbatim): Audit1931 (sources1928/1929): Partial runtime files-watch suite retains controlled Windows close-event waiting, shared-client survival, late physical-exit ownership/deadline cleanup and shutdown joining. Its combined Windows close/deadline/late-exit alias remains backed by unchanged callbacks. Retire native-error-close, pre-publication setup ownership and failed-delete rearm aliases; associated delegation, failure forwarding, removal routing and recovery examples are lost. These tests inject watch/subscription seams and do not observe an actual native watcher or physical process. Preserve meaningful remaining selectors/assertions and unchanged dated receipts within their original scope. Reduced selectors have no fresh gate execution evidence in this metadata packet. No equivalent replacement, physical watcher/PTY/provider, live SSH/remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): Audit1925 (sources1922/1923): Partial runtime watcher-host suite loses mocked option/event/overflow/resubscription forwarding, supplied teardown-error propagation, aborted-signal/no-call and private ten-thousand-waiter-count inventories. Retire the 10,000-caller bound and failed-recovery-subscriber-ending assertion aliases. Keep same-root owner cancellation, pre-ready replacement, held root-close join, stale-generation recovery delivery and initial failed-root ownership mappings backed by retained real-host callbacks with injected subscription/error/physical-exit promises. No actual native watcher, process termination or resource bound was observed. Preserve meaningful remaining selectors/assertions and unchanged dated receipts within their original scope. Reduced selectors have no fresh gate execution evidence in this metadata packet. No equivalent replacement, physical watcher/PTY/provider, live SSH/remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): Audit1683 removes low-value test projections, mock wiring, private-state assertions, inventories and duplicate examples without equivalent replacement coverage. Per-source reviews record retained public behavior and refusal boundaries with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1645 removes low-value test projections, mock wiring, private-state assertions, inventories and duplicate examples without equivalent replacement coverage. Per-source reviews record retained public behavior and refusal boundaries with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1640 removes low-value IPC, SSH, workspace and transcript-watcher tests without equivalent replacement coverage. Per-source reviews record retained public refusal, cancellation, execution-host and real-filesystem outcomes with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1634 removes low-value IPC, filesystem and runtime projections, argument inventories and duplicate examples without equivalent replacement coverage. Per-source reviews record retained cancellation, ownership, authorization, filesystem and SQLite boundaries with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1627 removes low-value mocked daemon projections, scalar tables and duplicate terminal examples without equivalent replacement coverage. Per-source reviews record retained terminal content preservation, process ownership refusal and recovery boundaries together with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1623 removes low-value mocked daemon projections, scalar tables and duplicate terminal examples without equivalent replacement coverage. Per-source reviews record retained terminal content preservation, process ownership refusal and recovery boundaries together with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1516 removes package-electron-runtime-contract.test.mjs, a copied release-workflow platform and marker matrix. Its workflow wiring alarm is intentionally retired; no actual packaged watcher delivery was exercised and no equivalent replacement is claimed. Unaffected dated execution receipts retain their original scope; changed optional selectors have no fresh full-gate execution result. This audit removes the paired-web stopped-during-outage and late-ready direct-branch examples. The retained pre-ready cancellation, failed-unwatch retry and replay-continuity cases are not equivalent replacements for those ordering alarms. Current web-runtime-client.test.ts assertions below name only its retained pre-ready callback case; replay cases remain in their separate suite. Historical commands and results remain historical. Deterministic tests cover one shared healthy child per runtime process plus at most four bounded fault-quarantine children, native desktop, paired-runtime, and WSL snapshot processes sharing the same eight-physical-child reservation with typed serialized event-driven capacity recovery, including recursive re-wait when crash recovery reclaims an announced slot, one quarantine attempt per watch lifetime, generation-scoped cancellation, bounded termination with removable deadline waiters, replacement-crawl errors that cannot be blessed by a late readiness ack, pre-ready paired-web cancellation registered before an unbounded capacity wait, already-resolved and late physical-exit retry of a rejected paired-web teardown, physical desktop-install and local/SSH PTY teardown, stale-generation rejection, per-child stat bounds, final-overflow RPC delivery, and renderer eviction before terminal callbacks can retry. Destructive local and SSH removal fences both ID-derived and resolved-cwd terminal roots, including sibling-root/cwd combinations with reverse admission rollback, closes descendant relay watches before parent deletion, enumerates authoritative provider/cwd ownership, falls back to daemon spawn cwd before OSC 7, and keeps daemon/relay immediate shutdown pending until native exit or a bounded fail-closed error; a dead relay PID discovered during attach also settles concurrent shutdown before its stale entry is reaped, while Windows runtime watcher deadlines retain one removable physical-close waiter, treat Node's error-close path as positive physical-exit proof, and clear root ownership on late close. The relay policy test maps a standard repository's base, Git common directory, and worktree roots to one healthy supervisor, then proves a shared-child failure recovers those roots in separate quarantine supervisors with overflow and resumed events. Abortable capacity, quarantine, runtime-root, relay, SSH, and relay pre-install setup waits attach one reaction to each shared promise and explicitly remove 10,000 cancelled caller closures while one anchor remains. Built-entry macOS harnesses kill the desktop/runtime and SSH relay watcher children, then require automatic resubscription and later events while the host process and relay PTY survive. SSH bundles the child boundary beside relay.js, requires both artifacts for install completeness, and preserves registration-owned same-root cancellation. The test-value audit corrects the active renderer watch command/file reference to the existing runtime-file-client-watch.test.ts, whose three cases are retained unchanged. They observe synthetic subscription retry/fanout and unsubscribe/unwatch calls, not actual preload/main bookkeeping or physical watcher-process cleanup. The separate read/preview client suite loses forwarding, supplied-error and negative-only examples, retaining binary detection and Unicode SVG decoding. Historical evidence commands/results are unchanged. Test-value audit1293 removes src/main/providers/local-pty/local-pty-provider-session-inventory.test.ts (2 authored cases). Their isolated assertions no longer run; surviving tests are not claimed as equivalent coverage. Fresh execution against the candidate SHA is required. Audit1312 removes low-value imported specs from aggregate test drivers; old whole-driver execution receipts are archived. Retained registrations are unchanged. No equivalent replacement coverage is claimed. Audit1383: src/main/runtime/orca-runtime-tests/worktree-native-chat-setup.spec.ts reduced. Lose command-list/receipt/default/background activation matrices whose provider spawn returns canned IDs. Retained test proves actual tab allocation separation, not terminal startup. No equivalent replacement coverage is claimed. Existing exact unaffected receipts and their platform/provider/budget claims remain scoped to unchanged selectors. Changed optional selectors have no new execution result. Audit1401: src/main/runtime/orca-runtime-tests/mobile-session-tabs-duplicate-pty-repair.spec.ts removed. Loses listing-on-already-repaired-data alarm; it never established runtime repair invocation. src/main/runtime/orca-runtime-tests/mobile-session-tabs-split-agent-tab.spec.ts removed. Loses actual mobile split sibling shell versus recorded-agent resume command alarms; no equivalent coverage asserted. src/main/runtime/orca-runtime-tests/worktree-native-chat-setup.spec.ts removed. Loses separate setup/startup tab result in that manually assembled path. src/main/runtime/orca-runtime.test.ts reduced. Driver registration/import of a whole-deleted selected spec is removed; directly authored cases remain unchanged. No extra authored removal credit. No equivalent replacement coverage is claimed. Existing exact unaffected receipts remain unchanged and apply only to their unchanged selectors. Changed optional selectors have no new execution result. Audit1412: src/main/workspaces/removal/watcher-removal-gate.test.ts reduced. Loses exact removal-error compatibility with renderer predicate under shared message constants. Kept public refusal outcomes do not establish that renderer classification. No equivalent replacement coverage is claimed. Existing exact unaffected receipts remain unchanged and apply only to their unchanged selectors. Changed optional selectors have no new execution result.", "motivatingLinks": [ "https://github.com/stablyai/orca/issues/5308", "https://github.com/stablyai/orca/issues/7547", "https://github.com/stablyai/orca/issues/8212" ], "invariant": "Local runtime and SSH relay roots share one watcher child per host process while healthy and use at most four quarantine children after shard failure; native desktop, paired-runtime, and direct WSL snapshot children consume the same process-wide eight-child reservation and retry transient exhaustion without permanently disabling a root. Cancellation remains owned by its child generation and settles only after acknowledgement or bounded physical exit; paired-web retains cleanup ownership and can cancel before readiness even while capacity is exhausted, retries a failed unwatch after already-resolved or late physical exit without duplicating stream termination, replacements never overlap a still-retiring generation, and aborted or timed-out callers detach immediately even while queued behind same-root relay teardown. Destructive local and SSH cleanup holds one containment-aware watcher/terminal removal fence through descendant watcher and PTY physical exit plus parent Git/filesystem deletion; daemon and relay kill requests retain ownership until the actual subprocess exit callback or an equivalent positive dead-PID proof and propagate rejected signals or a bounded failure otherwise. A crash-fused shared shard moves affected roots into the bounded quarantine pool, a second fused quarantine ends those watch lifetimes, interrupted setup emits overflow after recovery, metadata work stays bounded, and the SSH relay, PTYs, Git, and other filesystem operations never load the watcher native addon or share its fault boundary.", - "oracle": "Audit3096 source-only reduction (3087/3088): retire 69 authored/76 expanded cases, including complete recovery-portals and reconnect-banner suites. Intentionally lose dead/default TUI replay, generated alternate-frame style composition, reset/mode/dimension and legacy missing-mode-boundary alarms, UI notice/action/reveal policies, and isolated recovery lifecycle variants, without equivalent replacement. Retained registrations and callbacks are unchanged; headless cells are not pixels, and no fresh runtime, host, SSH, WSL, rendered-app or performance result is claimed. Audit3086 source-only reduction (3079/3080/3081): intentionally retire 93 authored/100 expanded mock-boundary cases, including the complete spawn-errors and SSH reconnect overlay suites, without replacement. Retired alarms include spawn classification/ownership, reply ceilings and renderer-write failure recovery, disconnect/detach fencing branches, authority facts, and overlay retry/visibility wiring. Retained callbacks are unchanged; no fresh execution, real PTY/SSH, rendered UI, or performance result is claimed. Audit2432: The broad unit command loses the isolated BranchPicker open-change notification sample. Its unique true/false callback alarm is intentionally retired; reopening/status-refresh behavior was not exercised. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2425: The broad unit command loses the workspace-copy-status supplied readError forwarding sample. It did not exercise the branch-switch blocking promised by its title. This alarm is intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2417: The broad unit command loses two ordinary clean Git cherry-pick/revert success samples and two terminal startup foreground-read work-budget samples. These unique alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2412: The broad unit command loses the whole six-case fake-React-hook scroll-anchor suite, two generic draft-retention samples, a simple new-agent order sample, a real history-publication batching-count sample, an unmounted handoff abort/timer sample and three basic WSL preview/error samples. These alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2404: The broad unit command loses the standalone share-name lookup 503 propagation suite, initial deletion placement-kind sample, direct changed-mtime stale sample, first-pass rollback existence example and abandoned-preparation directory sample. These exact alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2397 review amendment: The broad unit command loses three standalone suites, two partial-case definitions and two URL table rows across package/download/placement tests. Keep initial wrong-port authorization, modified independent-copy digest refusal and abort-after-begin cancellation dispatch. The remaining alarms are deliberately retired; no equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2393 current-parent refresh2401: Remove the basic skill-install service alias sample and original public managed-remove receiptless refusal case. Preserve the upstream request ownership suite and transaction interruption coverage. No equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2389: The broad unit command loses the missing-preview suite, plain-global destination sample and prepublished-receipt recovery example. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2385: The broad unit command loses four authored walker/staging/protocol examples (six expanded cases); no equivalent replacement or fresh validation is claimed for the reduced suite. Audit2383: The unscoped Vitest command no longer includes the removed Antigravity catalogue suite; its exact provider-root/owner example has no equivalent replacement or fresh validation claim. Audit2377/2381: The unscoped Vitest command includes the reduced bundled-skill and native-discovery suites; the eight removed backup/legacy/catalogue/symlink/SSH-builder examples have no replacement-equivalence or fresh validation claim here. Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2090 (sources2088/2089): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2086 (sources2082/2083): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2076 (sources2073/2074): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime-tests/terminal-handles-part-02.spec.ts: recovers a moved SSH pane through the tab it now sits in, not the one its lease froze; reports a plain expired orphan; does not report a pane whose only recent lease was superseded; does not report a pane whose only recent lease had its relay id recycled; picks the eligible orphan over a superseded predecessor that matches first; collects the same tabs the per-tab reader reports, in one sweep of the leases; reports no candidate when no lease names any of the worktree tabs. src/main/runtime/orca-runtime-tests/runtime-availability.spec.ts: starts unavailable with no authoritative window; reports the configured Windows terminal shell on status; reports floating workspace availability from settings on status; polls floating tabs with targeted PTY liveness and no repo/provider inventory; hydrates persisted tabs when the store cannot report repos; advertises browser screencast only when a renderer window is available; routes mobile Codex reset consumption through the account mutation coordinator; maps a definite pre-provider rejection into an authoritative current snapshot. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Frozen current literal-import graph reaches these changed test bytes; unresolved local and computed edges remain debt, and current reachability is not historical execution or equivalent replacement evidence. Historical prior account (preserved verbatim): Audit2056 (sources2054/2055): Intentionally retire these low-value alarms without replacement: src/renderer/src/runtime/files/watching/runtime-file-client-watch.test.ts: delivers remote file changes to listeners for the same worktree. src/main/runtime/orca-runtime.test.ts: ordinary registration cleanup removes only await import('./orca-runtime-tests/mobile-session-tabs-part-14.spec'). src/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-03.spec.ts: arms the stale-title timer for a seeded working title; arms the Command Code scrape from the noted spawn command; prefers the tracked title over a stale renderer lastTitle in the hydration seed; writes recent output into the current runtime output map; uses a later title handler replacement with the runtime receiver; calls the current injected listener with the runtime receiver; keeps optional reconciliation lazy after its callback is removed. src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-14.spec.ts: lists them, so a paired client can mirror a migrated editor; closes one by retiring it from the host session; keeps an unsaved draft unless the close is forced; shares aggregate work but leaves a replacement pending promise alone; lets a targeted refresh finish while an aggregate refresh waits; refuses a close when the store lacks %s before the guard; keeps a later missing %s on the original caught failure path. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Exact retired assertionRefs, preserved as historical objects only: {\n \"file\": \"src/renderer/src/runtime/files/watching/runtime-file-client-watch.test.ts\",\n \"assertions\": [\n \"terminal watcher error and setup failure evict the shared entry before retrying callbacks run\",\n \"an old stream end cannot evict the replacement stream, which still delivers to its listener\",\n \"two same-worktree listeners share a synthetic subscription until the final stop unsubscribes and sends unwatch\"\n ]\n } Historical prior account (preserved verbatim): Audit1973: Delete the standalone mocked watcher cleanup suite and its entire sole-file prospective command. Retire the removed file-command transport-abort alias; preserve the independent cancellation suite and final-overflow/error/end cleanup callback, and13 unrelated receipt objects. Whole original changed dated receipts are retired, never narrowed or transferred. This metadata review claims no fresh execution, equivalent replacement, provider/PTY, live remote/mobile, rendered, cross-platform, soak or measured-budget result. Historical prior account (preserved verbatim): Audit1931 (sources1928/1929): Partial runtime files-watch suite retains controlled Windows close-event waiting, shared-client survival, late physical-exit ownership/deadline cleanup and shutdown joining. Its combined Windows close/deadline/late-exit alias remains backed by unchanged callbacks. Retire native-error-close, pre-publication setup ownership and failed-delete rearm aliases; associated delegation, failure forwarding, removal routing and recovery examples are lost. These tests inject watch/subscription seams and do not observe an actual native watcher or physical process. Preserve meaningful remaining selectors/assertions and unchanged dated receipts within their original scope. Reduced selectors have no fresh gate execution evidence in this metadata packet. No equivalent replacement, physical watcher/PTY/provider, live SSH/remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): Audit1925 (sources1922/1923): Partial runtime watcher-host suite loses mocked option/event/overflow/resubscription forwarding, supplied teardown-error propagation, aborted-signal/no-call and private ten-thousand-waiter-count inventories. Retire the 10,000-caller bound and failed-recovery-subscriber-ending assertion aliases. Keep same-root owner cancellation, pre-ready replacement, held root-close join, stale-generation recovery delivery and initial failed-root ownership mappings backed by retained real-host callbacks with injected subscription/error/physical-exit promises. No actual native watcher, process termination or resource bound was observed. Preserve meaningful remaining selectors/assertions and unchanged dated receipts within their original scope. Reduced selectors have no fresh gate execution evidence in this metadata packet. No equivalent replacement, physical watcher/PTY/provider, live SSH/remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): Audit1683 retires changed-source assertion and execution scope without equivalent replacement coverage. Existing unchanged-selector receipts remain scoped to their original sources. Historical prior-source oracle: Existing exact unchanged-selector receipts remain the only current execution evidence. Changed source selectors have no fresh execution result. Historical prior-source oracle account: Existing exact unchanged-selector receipts remain the only current execution evidence. Changed source selectors have no fresh execution result. Historical prior-source oracle account: Fill the global watcher-child reservation, require native desktop, paired-runtime, and WSL setup to retain typed transient capacity and retry after one serialized release, then cancel pending desktop and paired-client watches and require no retry. Hold one live anchor while aborting 10,000 callers at the capacity, quarantine-assignment, runtime-root, relay-setup, and SSH-registration layers; require exactly one explicit waiter and one base-promise reaction to remain, then zero after settlement. Hold an old relay unsubscribe, queue one same-root setup leader and one anchor, then abort 10,000 joiners; require every cancellation to settle before teardown releases, exactly one anchor waiter, and only one later physical install. Advance the former paired-web callback deadline while capacity remains full, require cancellation ownership to stay live, publish the server token before ready, and require files.unwatch to abort setup before a later slot release can install a native root. Reject the first ready-watch unwatch with a physical-exit promise, resolve that exit later, and require a fresh physical unwatch attempt, registry release, and exactly one stream end. Fill one healthy shared child with multiple roots, map a standard SSH repository's base, Git common directory, and worktree roots to one relay supervisor, then inject IPC disconnect-before-exit, queued and active cancellation, operations during termination, kill-without-exit, repeated unkillable generations, initial and recovery timeouts, and shard failure. During local and SSH deletion, attempt a late terminal spawn whose worktree identity and cwd name different roots, enumerate a non-prefix remote PTY by authoritative worktree ownership, withhold daemon/relay exit callbacks, make attach positively prove a concurrent-shutdown PID dead, and make the provider unavailable; require every acquired admission to roll back on rejection, dead-PID proof to settle physical exit before reaping, timeout to retain ownership, and Git/filesystem deletion never to start. Require bounded watcher process count, physical-exit settlement, healthy-root recovery, stale-generation rejection, overflow plus later events, and fail-closed destructive cleanup. Verify relay build hashes and remote install probes require both relay.js and relay-watcher.js. Launch the built relay with a real PTY and Parcel watch, kill only the watcher child, and require the same relay PID and PTY to answer before a replacement child delivers overflow and a post-crash event.", + "oracle": "Audit3209 composes approved sources3202/3206: deliberately retires seven authored/expanded cases in four whole suites without equivalent replacement. Work-item queries lose real GitHub/GitLab oversized ASCII secret-prefix empty-query and whitespace-before-trim refusal alarms; inputs share the imported size bound and exercise only its fast length branch, with no multibyte or actual provider/exposure guarantee. Skill sharing loses complete/partial managed-bundle and destination-ambiguity association checks plus three negative origin/path/scheme admission examples; these do not establish uploaded contents, arbitrary-URL fetching, authorization or execution. Retain exact originless-project direct-link fallback, cloud-delete confirmation, bundled-target repair/owner isolation and explicit Windows-host preference over stale WSL suites. Rejected3201 runtime-preference removal is excluded. No real cloud/network/host/disk, mobile or mixed-version execution validation is claimed. Audit3200 composes approved source3194: deliberately retires thirteen authored registrations/twenty-seven expanded cases in six whole automation host/list policy suites without equivalent replacement. Real RPC category/retryability and wrapped-timeout recognition, unscoped-failure/scoped-success health evidence precedence, exact-ID create selectors and per-run workspace omission, paired-web local/SSH/absent host catalog routing, incompatible/removed/unhydrated/offline execution health, runtime-before-nested-SSH recovery dispatch, and no-owned-focus/successor/foreign-list focus policy alarms are consciously lost. Retain exact20line orphan allow/refuse/precondition and exact90line cross-host same-ID search suites. No retry-timer/fence lifecycle, actual reconnect/network/write delivery, native focus, mobile/mixed-version runtime or disk persistence coverage is claimed. Audit3191 combines approved source3182/3187/3188: deliberately retires thirteen authored Vitest registrations and fifteen expanded cases, including five whole suites, without equivalent replacement. Attachment intake loses real portal/native-capture terminal interception and unowned-container refusal, immediate child-only committed availability/claim-ref negotiation and delivery, and direct-target over stable focused/background composer routing through disable/re-enable/remount and independent question focus. Exact destination/cache/draft and final-stat owner/workspace/File-release suites remain; they do not replace Surface recipient routing. Automation authoring loses destination runtime catalog membership, local/direct-SSH exclusion of paired-runtime repos, unknown-runtime empty catalog, logical project/host/setup/repo/path context payload, and missing/nonready setup refusal; these were genuine direct helper alarms, while exact schedule transformation, legacy schedule and setup-decision suites remain. Agent picker loses setup-chat/terminal/missing-installer/unsupported-or-unknown-host row projection samples and the ordinary unsearched menu variant; the entire original26-line resume recipe suite remains, including reported bypass versus default/absent permission modes, as does the exact search-result menu callback with its fixtures, model/effort commits and staged Arguments reopen outcome. Rejected predecessor3180 full recipe deletion is excluded. No actual native drag/cursor/focus/IME, upload bytes or disk/restart persistence, full automation save/scheduler/runtime transport, real resume-process flags/environment delivery, or native menu/rendered layout validation is claimed. Audit3178 combines source3169/3170/3175: deliberately retires eight authored units (six Vitest cases and two imperative custom relay scenarios), including two whole suites, without equivalent replacement. Voice Section loses per-model pending-delete isolation across interleaved A/B completion and the two-success refresh-call alarm; exact VoicePane delayed key-clear/newer enabled-toggle merge remains and does not replace row deletion coverage. Speech loses dedicated rating-scale/inclusive-ceiling, unsupported-versus-unmeasured, explicit/system-language precedence/locale alias, accuracy versus fast named/default/best-measured selection, and unmeasured/no-match examples; exact offered-user-pick versus retired-selection case and its fixture remain. Relay loses legacy ping-delivery count/liveness sampled before the silence deadline and grouped malformed Bearer/host-ID 401/429 routing checks; twelve real Worker/DurableObject/shipped-client scenarios remain, not equivalent replacement for those narrow alarms. Six prior speech cases are not all deleted: approved successor3175 keeps the original user-choice case. No actual credential/file persistence, native/GPU/engine/download delivery, production assignment policy or deployed-runtime validation is claimed by this reduction. Audit3165 combines source3160/3162: deliberately retires six authored/expanded cases across three whole suites without equivalent replacement. Launch/status losses: observed React-render pending/resuming coordination across settings and deferred offer read; stale-offer reread suppressing dialog reopen; held-local-chat recovery visibility with new-chat preferences off; disabled-local admission avoiding offer RPC despite an injected but unconsumed paired-tab fixture; and run-only lost-reply uncertainty reachability until direct viewed-run retirement. Launch probe does not prove arbitrary synchronous-store atomicity, the paired fixture is not remote runtime enrollment, and the status case directly marks viewed state rather than rendering the summary. Crew-hook losses: old-host method_not_found cache persists across party changes but is released by independently supplied connection generation/verified pairing status or pairing revision, with actual frame publication and teardown. These are real narrow coordination, admission, uncertainty and mixed-version cache alarms consciously lost. Exact web verified-runtime writer handoff guard remains; it does not replace those alarms or prove live host/native/mobile delivery. Audit3156 combines3147/3150/3152/3153/3154: deliberately retires39authored/40expanded native-chat recovery cases, eight whole suites and two orphan test-support files without equivalent replacement. Lost alarms: lost-reply unconfirmed reconciliation, skipped rows/counts and missed-frame repair, unknown/pending outcome and omitted-failure-list compatibility, uncertain history after dismissal, retry/refusal/dismiss lifecycle, hidden/consumed picker ownership, result-tree keyboard focus/disclosure and all-skipped retirement; unconfirmed-over-conflict guidance and failed-chat changes despite older host timestamps; nearest-listed ancestor/cyclic forest shape, descendant membership, host ordering/missing-host local fallback; skipped/readiness/admission counts, provisional skip/progress monotonicity, early per-chat verdicts with batch pending protection, older-host waiting, start-slot/delivery distinction, retry-over-failure and unknown-after-withdrawal attention; remote snooze/reconnect/reoffer, unseen mixed summary through open/close, watched completion retirement, new success beside old failure, failed-reread mixed-result preservation, filter/collapse completion resets, retry summary replacement and current-offer/history selection; cross-host workspace identity, rendered cyclic reachability, nested tri-state/toggle propagation, project eligibility isolation and collapse preserving selection. Exact fallback-list completion barrier, batched verdict/cleanup retention, stale-read versus dismissal publication race, and requested-but-never-rendered finished-run retirement remain; they do not replace retired alarms. Audit3146 combines source reviews3132/3133/3135/3138/3143: intentionally retire20authored/31expanded cases without equivalent replacement. Provider-session losses: structured-native terminal-resume exclusion, metadata-less completed identity, new-turn completion clearing, Pi provider-only/periodic/manual promotion, changed-transcript launch-config isolation, Pi/omp/prime-agent completed-session remote/manual-shutdown promotion, and quit/done precedence over heartbeat. Side-thread/question losses: finished-pane acquisition, hidden title/recap states, local/relay/relay-done conversation takeover with prompt/session/child resets, plain-message abandonment, compaction/session replacement and completion resets. Codex startup losses: incoming-owner cached child replacement, old-relay foreign live-session correction, completed foreign-root turn-fact permutations. Transcript losses: real temporary-JSONL partial sibling/final-child completion, unlabelled child attribution, compact cached replay preservation and100/1000completed-child roster retention/release. Compiler-ratchet losses: valid-line uncompiled-list parser grammar examples and injected-existence stale-path filtering; these did not exercise actual filesystem canonicalization or build exclusion. These are real lifecycle, ownership, replay, liveness and retention alarms, including recent#40246 regressions, deliberately lost. Retained conditional record replacement, clockless root/SSH owner isolation, persisted main-thread fork rejection, partial/final question-answer lifetime, cached-roster/missing-ID/live HTTP/durable startup boundaries and restarted-relay refusal/acceptance do not replace those losses. No native/SSH/WSL execution or equivalent coverage is claimed. Audit3128 scoped coverage reduction: Audit3121 removes VoiceDictationLanguageSetting.test.tsx (Spanish-to-es callback and unsupported-model Korean option presence) and voice-speech-model-rows.test.ts (provider/language-order/retired-on-disk list policy); these real narrow alarms are deliberately retired without replacement. VoiceSpeechModelSection per-model concurrent deletion remains unchanged. Audit3122 removes the direct absolute/parent-segment sparse-directory exception-type sample and the five-row IPC sparse-preset error-code/non-save table (two authored/six expanded cases). Those real typed-validation and IPC refusal/error-code alarms are deliberately retired. Keep both real symlink/junction floating-directory trust cases and the minimal RPC structured validation-reason serialization case. The RPC case does not replace IPC save/refusal behavior, typed normalization for both path inputs, actual Git sparse checkout or rendered localization. No equivalent replacement or fresh test/runtime/platform/remote/performance validation is claimed. Audit3124 removes ExperimentalPane.test.tsx (ordinary Pet switch callback), WorkspaceDirectorySetting.test.tsx (padded absolute saved-path normalization/no-write blur), and repository-search.perf.test.ts (navigation/selected-pane builder-call policy, fixture cardinality/nonempty entries and renamed project keyword inclusion). These real narrow alarms are retired without replacement; RepositoryPane.search.test.tsx search-to-sparse-editor request remains unchanged. Audit3129: resolver Windows case-insensitive and POSIX case-sensitive configured-env composition plus mocked-base launch-preflight Windows composition are intentionally no longer checked by the two deleted suites. No equivalent coverage claimed. Keep runtime-structured-agent-host-env.test.ts unchanged: configured Windows Claude-home account identity and host-account precedence remain checked. Audit3114 incorporates source3101: retire three structured Claude child-environment wrapper cases covering inherited stamp isolation/default and explicit entrypoint, Windows SDK-key canonicalization/default/duplicate-key order, and configured lookup/final environment/config-dir conjunction. Keep direct auth/session sanitation and Windows-versus-Linux overlay checks, actual executable lookup from supplied inherited PATH, native Windows child environment delivery, and stale option-mutation fencing. These are not equivalent replacements for the retired wrapper alarms. No fresh test/runtime, real login-shell probe, Claude SDK startup, remote/mixed-version, UI or performance result is claimed. Audit3114 incorporates source3105: retire 17 authored/20 expanded daemon launch-note cases, including the entire two-case SessionLaunchNote suite. Deliberately lose split-marker carry across same-token re-arm, stale-token retirement refusal, foreground tri-state and serial settlement, omitted-note/no-incarnation mixed-version policy, sticky retirement, first-incarnation/replacement launch preservation and held-launch precedence. Keep only the unchanged unresolved foreground-read race against a later finished attach. Supplied notes/foreground and runtime calls do not establish actual daemon/main restart, SSH, native Windows observation, mobile UI, equivalent replacement or fresh runtime/performance validation. Audit3114 incorporates source3109: retire six authored/35 expanded pricing cases: 21 accepted model-name examples, 10 unsupported/future-model fail-closed examples, malformed TTL clamp, unknown-model estimate refusal, flat-model long-context disregard and oversized long-context clamp. Keep mixed five-minute/one-hour write allocation and short/all-long/mixed long-context allocation with original fixed oracles. Real parser/refusal/bounds alarms are knowingly lost without equivalent replacement; retained tests do not validate provider rates, actual billing or request threshold classification. Preserve the archived usage-scan-append source-freeze receipt without transferring historical execution/performance credit. No fresh runtime result is claimed. Audit3108 source-only reduction (3094/3095/3100): retire 27 authored/30 expanded cases, including complete markdown view-state, file-preview link-open and CLI agent-server-route suites, without replacement. Deliberate losses include preview visibility/reference lifetime and same-path owners; SSH stat, directory/missing-target, explicit-null owner, nonmarkdown line/column, local URI routing, remote-to-client guard and same-file reuse; document-preview source-owner/folder/reuse routing, stable grant location and outside-workspace POSIX/Windows request projection; and verified remote CLI send/check refusal, suggested --on argv/copy, shell no-probe bypass, unverified-launch admission and older-peer refusal. Retain two markdown source-runtime/qualified-reveal alarms, one stale grant-rejection fence and two remote read/mutation evidence policies, with original callbacks. Final last-wins reveal did not prove transient cancellation; CLI prerequisite did not prove no real send, and envelope tests do not execute server refusal. No fresh runtime, rendered UI, actual file/SSH/paired transport, authorization, mixed-version or performance result is claimed. Audit3096 source-only reduction (3087/3088): retire 69 authored/76 expanded cases, including complete recovery-portals and reconnect-banner suites. Intentionally lose dead/default TUI replay, generated alternate-frame style composition, reset/mode/dimension and legacy missing-mode-boundary alarms, UI notice/action/reveal policies, and isolated recovery lifecycle variants, without equivalent replacement. Retained registrations and callbacks are unchanged; headless cells are not pixels, and no fresh runtime, host, SSH, WSL, rendered-app or performance result is claimed. Audit3086 source-only reduction (3079/3080/3081): intentionally retire 93 authored/100 expanded mock-boundary cases, including the complete spawn-errors and SSH reconnect overlay suites, without replacement. Retired alarms include spawn classification/ownership, reply ceilings and renderer-write failure recovery, disconnect/detach fencing branches, authority facts, and overlay retry/visibility wiring. Retained callbacks are unchanged; no fresh execution, real PTY/SSH, rendered UI, or performance result is claimed. Audit2432: The broad unit command loses the isolated BranchPicker open-change notification sample. Its unique true/false callback alarm is intentionally retired; reopening/status-refresh behavior was not exercised. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2425: The broad unit command loses the workspace-copy-status supplied readError forwarding sample. It did not exercise the branch-switch blocking promised by its title. This alarm is intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2417: The broad unit command loses two ordinary clean Git cherry-pick/revert success samples and two terminal startup foreground-read work-budget samples. These unique alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2412: The broad unit command loses the whole six-case fake-React-hook scroll-anchor suite, two generic draft-retention samples, a simple new-agent order sample, a real history-publication batching-count sample, an unmounted handoff abort/timer sample and three basic WSL preview/error samples. These alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2404: The broad unit command loses the standalone share-name lookup 503 propagation suite, initial deletion placement-kind sample, direct changed-mtime stale sample, first-pass rollback existence example and abandoned-preparation directory sample. These exact alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2397 review amendment: The broad unit command loses three standalone suites, two partial-case definitions and two URL table rows across package/download/placement tests. Keep initial wrong-port authorization, modified independent-copy digest refusal and abort-after-begin cancellation dispatch. The remaining alarms are deliberately retired; no equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2393 current-parent refresh2401: Remove the basic skill-install service alias sample and original public managed-remove receiptless refusal case. Preserve the upstream request ownership suite and transaction interruption coverage. No equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2389: The broad unit command loses the missing-preview suite, plain-global destination sample and prepublished-receipt recovery example. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2385: The broad unit command loses four authored walker/staging/protocol examples (six expanded cases); no equivalent replacement or fresh validation is claimed for the reduced suite. Audit2383: The unscoped Vitest command no longer includes the removed Antigravity catalogue suite; its exact provider-root/owner example has no equivalent replacement or fresh validation claim. Audit2377/2381: The unscoped Vitest command includes the reduced bundled-skill and native-discovery suites; the eight removed backup/legacy/catalogue/symlink/SSH-builder examples have no replacement-equivalence or fresh validation claim here. Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2090 (sources2088/2089): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2086 (sources2082/2083): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2076 (sources2073/2074): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime-tests/terminal-handles-part-02.spec.ts: recovers a moved SSH pane through the tab it now sits in, not the one its lease froze; reports a plain expired orphan; does not report a pane whose only recent lease was superseded; does not report a pane whose only recent lease had its relay id recycled; picks the eligible orphan over a superseded predecessor that matches first; collects the same tabs the per-tab reader reports, in one sweep of the leases; reports no candidate when no lease names any of the worktree tabs. src/main/runtime/orca-runtime-tests/runtime-availability.spec.ts: starts unavailable with no authoritative window; reports the configured Windows terminal shell on status; reports floating workspace availability from settings on status; polls floating tabs with targeted PTY liveness and no repo/provider inventory; hydrates persisted tabs when the store cannot report repos; advertises browser screencast only when a renderer window is available; routes mobile Codex reset consumption through the account mutation coordinator; maps a definite pre-provider rejection into an authoritative current snapshot. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Frozen current literal-import graph reaches these changed test bytes; unresolved local and computed edges remain debt, and current reachability is not historical execution or equivalent replacement evidence. Historical prior account (preserved verbatim): Audit2056 (sources2054/2055): Intentionally retire these low-value alarms without replacement: src/renderer/src/runtime/files/watching/runtime-file-client-watch.test.ts: delivers remote file changes to listeners for the same worktree. src/main/runtime/orca-runtime.test.ts: ordinary registration cleanup removes only await import('./orca-runtime-tests/mobile-session-tabs-part-14.spec'). src/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-03.spec.ts: arms the stale-title timer for a seeded working title; arms the Command Code scrape from the noted spawn command; prefers the tracked title over a stale renderer lastTitle in the hydration seed; writes recent output into the current runtime output map; uses a later title handler replacement with the runtime receiver; calls the current injected listener with the runtime receiver; keeps optional reconciliation lazy after its callback is removed. src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-14.spec.ts: lists them, so a paired client can mirror a migrated editor; closes one by retiring it from the host session; keeps an unsaved draft unless the close is forced; shares aggregate work but leaves a replacement pending promise alone; lets a targeted refresh finish while an aggregate refresh waits; refuses a close when the store lacks %s before the guard; keeps a later missing %s on the original caught failure path. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Exact retired assertionRefs, preserved as historical objects only: {\n \"file\": \"src/renderer/src/runtime/files/watching/runtime-file-client-watch.test.ts\",\n \"assertions\": [\n \"terminal watcher error and setup failure evict the shared entry before retrying callbacks run\",\n \"an old stream end cannot evict the replacement stream, which still delivers to its listener\",\n \"two same-worktree listeners share a synthetic subscription until the final stop unsubscribes and sends unwatch\"\n ]\n } Historical prior account (preserved verbatim): Audit1973: Delete the standalone mocked watcher cleanup suite and its entire sole-file prospective command. Retire the removed file-command transport-abort alias; preserve the independent cancellation suite and final-overflow/error/end cleanup callback, and13 unrelated receipt objects. Whole original changed dated receipts are retired, never narrowed or transferred. This metadata review claims no fresh execution, equivalent replacement, provider/PTY, live remote/mobile, rendered, cross-platform, soak or measured-budget result. Historical prior account (preserved verbatim): Audit1931 (sources1928/1929): Partial runtime files-watch suite retains controlled Windows close-event waiting, shared-client survival, late physical-exit ownership/deadline cleanup and shutdown joining. Its combined Windows close/deadline/late-exit alias remains backed by unchanged callbacks. Retire native-error-close, pre-publication setup ownership and failed-delete rearm aliases; associated delegation, failure forwarding, removal routing and recovery examples are lost. These tests inject watch/subscription seams and do not observe an actual native watcher or physical process. Preserve meaningful remaining selectors/assertions and unchanged dated receipts within their original scope. Reduced selectors have no fresh gate execution evidence in this metadata packet. No equivalent replacement, physical watcher/PTY/provider, live SSH/remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): Audit1925 (sources1922/1923): Partial runtime watcher-host suite loses mocked option/event/overflow/resubscription forwarding, supplied teardown-error propagation, aborted-signal/no-call and private ten-thousand-waiter-count inventories. Retire the 10,000-caller bound and failed-recovery-subscriber-ending assertion aliases. Keep same-root owner cancellation, pre-ready replacement, held root-close join, stale-generation recovery delivery and initial failed-root ownership mappings backed by retained real-host callbacks with injected subscription/error/physical-exit promises. No actual native watcher, process termination or resource bound was observed. Preserve meaningful remaining selectors/assertions and unchanged dated receipts within their original scope. Reduced selectors have no fresh gate execution evidence in this metadata packet. No equivalent replacement, physical watcher/PTY/provider, live SSH/remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): Audit1683 retires changed-source assertion and execution scope without equivalent replacement coverage. Existing unchanged-selector receipts remain scoped to their original sources. Historical prior-source oracle: Existing exact unchanged-selector receipts remain the only current execution evidence. Changed source selectors have no fresh execution result. Historical prior-source oracle account: Existing exact unchanged-selector receipts remain the only current execution evidence. Changed source selectors have no fresh execution result. Historical prior-source oracle account: Fill the global watcher-child reservation, require native desktop, paired-runtime, and WSL setup to retain typed transient capacity and retry after one serialized release, then cancel pending desktop and paired-client watches and require no retry. Hold one live anchor while aborting 10,000 callers at the capacity, quarantine-assignment, runtime-root, relay-setup, and SSH-registration layers; require exactly one explicit waiter and one base-promise reaction to remain, then zero after settlement. Hold an old relay unsubscribe, queue one same-root setup leader and one anchor, then abort 10,000 joiners; require every cancellation to settle before teardown releases, exactly one anchor waiter, and only one later physical install. Advance the former paired-web callback deadline while capacity remains full, require cancellation ownership to stay live, publish the server token before ready, and require files.unwatch to abort setup before a later slot release can install a native root. Reject the first ready-watch unwatch with a physical-exit promise, resolve that exit later, and require a fresh physical unwatch attempt, registry release, and exactly one stream end. Fill one healthy shared child with multiple roots, map a standard SSH repository's base, Git common directory, and worktree roots to one relay supervisor, then inject IPC disconnect-before-exit, queued and active cancellation, operations during termination, kill-without-exit, repeated unkillable generations, initial and recovery timeouts, and shard failure. During local and SSH deletion, attempt a late terminal spawn whose worktree identity and cwd name different roots, enumerate a non-prefix remote PTY by authoritative worktree ownership, withhold daemon/relay exit callbacks, make attach positively prove a concurrent-shutdown PID dead, and make the provider unavailable; require every acquired admission to roll back on rejection, dead-PID proof to settle physical exit before reaping, timeout to retain ownership, and Git/filesystem deletion never to start. Require bounded watcher process count, physical-exit settlement, healthy-root recovery, stale-generation rejection, overflow plus later events, and fail-closed destructive cleanup. Verify relay build hashes and remote install probes require both relay.js and relay-watcher.js. Launch the built relay with a real PTY and Parcel watch, kill only the watcher child, and require the same relay PID and PTY to answer before a replacement child delivers overflow and a post-crash event.", "commands": [ "pnpm exec vitest run --config config/vitest.config.ts src/main/ipc/filesystem/watcher-process/parcel-watcher-unsubscribe-timeout.test.ts --reporter=dot", "pnpm exec vitest run --config config/vitest.config.ts src/main/ipc/filesystem/watchers/filesystem-watcher.test.ts src/main/ipc/filesystem/watchers/filesystem-watcher-native-capacity.test.ts src/main/ipc/filesystem/watcher-process/parcel-watcher-child-registry.test.ts src/main/ipc/filesystem/watcher-process/parcel-watcher-child-launch.test.ts src/main/ipc/filesystem/watcher-process/parcel-watcher-process.test.ts src/main/ipc/filesystem/watcher-process/parcel-watcher-supervisor-capacity.test.ts src/main/ipc/filesystem/watcher-process/parcel-watcher-disconnect-termination.test.ts src/main/ipc/filesystem/watcher-process/runtime-watcher-pending-assignment.test.ts src/main/ipc/filesystem/watcher-process/parcel-watcher-event-delivery.test.ts src/main/ipc/filesystem/watchers/filesystem-watcher-local-unsubscribe.test.ts src/main/ipc/filesystem/watchers/filesystem-watcher-wsl.test.ts src/main/ipc/worktrees-delete-pty-teardown.test.ts src/main/ipc/worktrees-orphan-directory-cleanup.test.ts src/main/ipc/worktrees-remove-preflight.test.ts src/main/workspaces/removal/watcher-removal-gate.test.ts src/main/runtime/files/watch/orca-runtime-files-watch.test.ts src/main/runtime/workspaces/removal/worktree-teardown.test.ts src/main/runtime/construction/orca-runtime.test.ts src/main/runtime/rpc/methods/files/files.test.ts src/main/runtime/rpc/methods/files/files-watch-cancellation.test.ts src/renderer/src/web/web-runtime-client.test.ts src/shared/cross-platform-path.test.ts src/shared/physical-exit-tracker.test.ts src/shared/promise-settlement-waiters.test.ts src/main/ipc/pty/pty-spawn-cwd-fallback.test.ts src/main/providers/local-pty/local-pty-provider-shutdown.test.ts src/main/daemon/providers/adapter/testing/daemon-pty-adapter.test.ts src/main/daemon/pty-subprocess/testing/pty-subprocess.test.ts src/main/daemon/sessions/testing/session.test.ts src/main/daemon/terminal-host/testing/terminal-host.test.ts src/main/daemon/terminal-host/testing/terminal-host-session-reaping-leak.test.ts --reporter=dot", @@ -13165,7 +13196,19 @@ "Audit2425 removes use-workspace-copy-status original5, which returns a fixture-supplied readError string through statusReadError. No consumer blocker or attempted branch switch established refusal; the unique error-forwarding sample is intentionally retired. Other copy ownership and stale-refresh cases are not equivalent error-path coverage. No equivalent replacement or fresh validation is claimed.", "Audit2432 removes BranchPicker.test.tsx original3, which only asserted onOpenChange(true/false) with an always-mounted mocked Popover. It never reopened the picker or consumed the callback in the parent status-refresh owner, despite its title. Lose that unique open/close notification alarm. Retained blocker/collision recovery and asynchronous post-unmount outcome cases are not equivalent replacement coverage. No fresh validation of the reduced selector is claimed.", "Audit3086 source-only reduction (3079/3080/3081): intentionally retire 93 authored/100 expanded mock-boundary cases, including the complete spawn-errors and SSH reconnect overlay suites, without replacement. Retired alarms include spawn classification/ownership, reply ceilings and renderer-write failure recovery, disconnect/detach fencing branches, authority facts, and overlay retry/visibility wiring. Retained callbacks are unchanged; no fresh execution, real PTY/SSH, rendered UI, or performance result is claimed.", - "Audit3096 source-only reduction (3087/3088): retire 69 authored/76 expanded cases, including complete recovery-portals and reconnect-banner suites. Intentionally lose dead/default TUI replay, generated alternate-frame style composition, reset/mode/dimension and legacy missing-mode-boundary alarms, UI notice/action/reveal policies, and isolated recovery lifecycle variants, without equivalent replacement. Retained registrations and callbacks are unchanged; headless cells are not pixels, and no fresh runtime, host, SSH, WSL, rendered-app or performance result is claimed." + "Audit3096 source-only reduction (3087/3088): retire 69 authored/76 expanded cases, including complete recovery-portals and reconnect-banner suites. Intentionally lose dead/default TUI replay, generated alternate-frame style composition, reset/mode/dimension and legacy missing-mode-boundary alarms, UI notice/action/reveal policies, and isolated recovery lifecycle variants, without equivalent replacement. Retained registrations and callbacks are unchanged; headless cells are not pixels, and no fresh runtime, host, SSH, WSL, rendered-app or performance result is claimed.", + "Audit3108 source-only reduction (3094/3095/3100): retire 27 authored/30 expanded cases, including complete markdown view-state, file-preview link-open and CLI agent-server-route suites, without replacement. Deliberate losses include preview visibility/reference lifetime and same-path owners; SSH stat, directory/missing-target, explicit-null owner, nonmarkdown line/column, local URI routing, remote-to-client guard and same-file reuse; document-preview source-owner/folder/reuse routing, stable grant location and outside-workspace POSIX/Windows request projection; and verified remote CLI send/check refusal, suggested --on argv/copy, shell no-probe bypass, unverified-launch admission and older-peer refusal. Retain two markdown source-runtime/qualified-reveal alarms, one stale grant-rejection fence and two remote read/mutation evidence policies, with original callbacks. Final last-wins reveal did not prove transient cancellation; CLI prerequisite did not prove no real send, and envelope tests do not execute server refusal. No fresh runtime, rendered UI, actual file/SSH/paired transport, authorization, mixed-version or performance result is claimed.", + "Audit3114 incorporates source3101: retire three structured Claude child-environment wrapper cases covering inherited stamp isolation/default and explicit entrypoint, Windows SDK-key canonicalization/default/duplicate-key order, and configured lookup/final environment/config-dir conjunction. Keep direct auth/session sanitation and Windows-versus-Linux overlay checks, actual executable lookup from supplied inherited PATH, native Windows child environment delivery, and stale option-mutation fencing. These are not equivalent replacements for the retired wrapper alarms. No fresh test/runtime, real login-shell probe, Claude SDK startup, remote/mixed-version, UI or performance result is claimed.", + "Audit3114 incorporates source3105: retire 17 authored/20 expanded daemon launch-note cases, including the entire two-case SessionLaunchNote suite. Deliberately lose split-marker carry across same-token re-arm, stale-token retirement refusal, foreground tri-state and serial settlement, omitted-note/no-incarnation mixed-version policy, sticky retirement, first-incarnation/replacement launch preservation and held-launch precedence. Keep only the unchanged unresolved foreground-read race against a later finished attach. Supplied notes/foreground and runtime calls do not establish actual daemon/main restart, SSH, native Windows observation, mobile UI, equivalent replacement or fresh runtime/performance validation.", + "Audit3114 incorporates source3109: retire six authored/35 expanded pricing cases: 21 accepted model-name examples, 10 unsupported/future-model fail-closed examples, malformed TTL clamp, unknown-model estimate refusal, flat-model long-context disregard and oversized long-context clamp. Keep mixed five-minute/one-hour write allocation and short/all-long/mixed long-context allocation with original fixed oracles. Real parser/refusal/bounds alarms are knowingly lost without equivalent replacement; retained tests do not validate provider rates, actual billing or request threshold classification. Preserve the archived usage-scan-append source-freeze receipt without transferring historical execution/performance credit. No fresh runtime result is claimed.", + "Audit3128 scoped coverage reduction: Audit3121 removes VoiceDictationLanguageSetting.test.tsx (Spanish-to-es callback and unsupported-model Korean option presence) and voice-speech-model-rows.test.ts (provider/language-order/retired-on-disk list policy); these real narrow alarms are deliberately retired without replacement. VoiceSpeechModelSection per-model concurrent deletion remains unchanged. Audit3122 removes the direct absolute/parent-segment sparse-directory exception-type sample and the five-row IPC sparse-preset error-code/non-save table (two authored/six expanded cases). Those real typed-validation and IPC refusal/error-code alarms are deliberately retired. Keep both real symlink/junction floating-directory trust cases and the minimal RPC structured validation-reason serialization case. The RPC case does not replace IPC save/refusal behavior, typed normalization for both path inputs, actual Git sparse checkout or rendered localization. No equivalent replacement or fresh test/runtime/platform/remote/performance validation is claimed. Audit3124 removes ExperimentalPane.test.tsx (ordinary Pet switch callback), WorkspaceDirectorySetting.test.tsx (padded absolute saved-path normalization/no-write blur), and repository-search.perf.test.ts (navigation/selected-pane builder-call policy, fixture cardinality/nonempty entries and renamed project keyword inclusion). These real narrow alarms are retired without replacement; RepositoryPane.search.test.tsx search-to-sparse-editor request remains unchanged. Audit3129: resolver Windows case-insensitive and POSIX case-sensitive configured-env composition plus mocked-base launch-preflight Windows composition are intentionally no longer checked by the two deleted suites. No equivalent coverage claimed. Keep runtime-structured-agent-host-env.test.ts unchanged: configured Windows Claude-home account identity and host-account precedence remain checked.", + "Audit3146 combines source reviews3132/3133/3135/3138/3143: intentionally retire20authored/31expanded cases without equivalent replacement. Provider-session losses: structured-native terminal-resume exclusion, metadata-less completed identity, new-turn completion clearing, Pi provider-only/periodic/manual promotion, changed-transcript launch-config isolation, Pi/omp/prime-agent completed-session remote/manual-shutdown promotion, and quit/done precedence over heartbeat. Side-thread/question losses: finished-pane acquisition, hidden title/recap states, local/relay/relay-done conversation takeover with prompt/session/child resets, plain-message abandonment, compaction/session replacement and completion resets. Codex startup losses: incoming-owner cached child replacement, old-relay foreign live-session correction, completed foreign-root turn-fact permutations. Transcript losses: real temporary-JSONL partial sibling/final-child completion, unlabelled child attribution, compact cached replay preservation and100/1000completed-child roster retention/release. Compiler-ratchet losses: valid-line uncompiled-list parser grammar examples and injected-existence stale-path filtering; these did not exercise actual filesystem canonicalization or build exclusion. These are real lifecycle, ownership, replay, liveness and retention alarms, including recent#40246 regressions, deliberately lost. Retained conditional record replacement, clockless root/SSH owner isolation, persisted main-thread fork rejection, partial/final question-answer lifetime, cached-roster/missing-ID/live HTTP/durable startup boundaries and restarted-relay refusal/acceptance do not replace those losses. No native/SSH/WSL execution or equivalent coverage is claimed.", + "Audit3156 combines3147/3150/3152/3153/3154: deliberately retires39authored/40expanded native-chat recovery cases, eight whole suites and two orphan test-support files without equivalent replacement. Lost alarms: lost-reply unconfirmed reconciliation, skipped rows/counts and missed-frame repair, unknown/pending outcome and omitted-failure-list compatibility, uncertain history after dismissal, retry/refusal/dismiss lifecycle, hidden/consumed picker ownership, result-tree keyboard focus/disclosure and all-skipped retirement; unconfirmed-over-conflict guidance and failed-chat changes despite older host timestamps; nearest-listed ancestor/cyclic forest shape, descendant membership, host ordering/missing-host local fallback; skipped/readiness/admission counts, provisional skip/progress monotonicity, early per-chat verdicts with batch pending protection, older-host waiting, start-slot/delivery distinction, retry-over-failure and unknown-after-withdrawal attention; remote snooze/reconnect/reoffer, unseen mixed summary through open/close, watched completion retirement, new success beside old failure, failed-reread mixed-result preservation, filter/collapse completion resets, retry summary replacement and current-offer/history selection; cross-host workspace identity, rendered cyclic reachability, nested tri-state/toggle propagation, project eligibility isolation and collapse preserving selection. Exact fallback-list completion barrier, batched verdict/cleanup retention, stale-read versus dismissal publication race, and requested-but-never-rendered finished-run retirement remain; they do not replace retired alarms.", + "Audit3165 combines source3160/3162: deliberately retires six authored/expanded cases across three whole suites without equivalent replacement. Launch/status losses: observed React-render pending/resuming coordination across settings and deferred offer read; stale-offer reread suppressing dialog reopen; held-local-chat recovery visibility with new-chat preferences off; disabled-local admission avoiding offer RPC despite an injected but unconsumed paired-tab fixture; and run-only lost-reply uncertainty reachability until direct viewed-run retirement. Launch probe does not prove arbitrary synchronous-store atomicity, the paired fixture is not remote runtime enrollment, and the status case directly marks viewed state rather than rendering the summary. Crew-hook losses: old-host method_not_found cache persists across party changes but is released by independently supplied connection generation/verified pairing status or pairing revision, with actual frame publication and teardown. These are real narrow coordination, admission, uncertainty and mixed-version cache alarms consciously lost. Exact web verified-runtime writer handoff guard remains; it does not replace those alarms or prove live host/native/mobile delivery.", + "Audit3178 combines source3169/3170/3175: deliberately retires eight authored units (six Vitest cases and two imperative custom relay scenarios), including two whole suites, without equivalent replacement. Voice Section loses per-model pending-delete isolation across interleaved A/B completion and the two-success refresh-call alarm; exact VoicePane delayed key-clear/newer enabled-toggle merge remains and does not replace row deletion coverage. Speech loses dedicated rating-scale/inclusive-ceiling, unsupported-versus-unmeasured, explicit/system-language precedence/locale alias, accuracy versus fast named/default/best-measured selection, and unmeasured/no-match examples; exact offered-user-pick versus retired-selection case and its fixture remain. Relay loses legacy ping-delivery count/liveness sampled before the silence deadline and grouped malformed Bearer/host-ID 401/429 routing checks; twelve real Worker/DurableObject/shipped-client scenarios remain, not equivalent replacement for those narrow alarms. Six prior speech cases are not all deleted: approved successor3175 keeps the original user-choice case. No actual credential/file persistence, native/GPU/engine/download delivery, production assignment policy or deployed-runtime validation is claimed by this reduction.", + "Audit3191 combines approved source3182/3187/3188: deliberately retires thirteen authored Vitest registrations and fifteen expanded cases, including five whole suites, without equivalent replacement. Attachment intake loses real portal/native-capture terminal interception and unowned-container refusal, immediate child-only committed availability/claim-ref negotiation and delivery, and direct-target over stable focused/background composer routing through disable/re-enable/remount and independent question focus. Exact destination/cache/draft and final-stat owner/workspace/File-release suites remain; they do not replace Surface recipient routing. Automation authoring loses destination runtime catalog membership, local/direct-SSH exclusion of paired-runtime repos, unknown-runtime empty catalog, logical project/host/setup/repo/path context payload, and missing/nonready setup refusal; these were genuine direct helper alarms, while exact schedule transformation, legacy schedule and setup-decision suites remain. Agent picker loses setup-chat/terminal/missing-installer/unsupported-or-unknown-host row projection samples and the ordinary unsearched menu variant; the entire original26-line resume recipe suite remains, including reported bypass versus default/absent permission modes, as does the exact search-result menu callback with its fixtures, model/effort commits and staged Arguments reopen outcome. Rejected predecessor3180 full recipe deletion is excluded. No actual native drag/cursor/focus/IME, upload bytes or disk/restart persistence, full automation save/scheduler/runtime transport, real resume-process flags/environment delivery, or native menu/rendered layout validation is claimed.", + "Audit3200 composes approved source3194: deliberately retires thirteen authored registrations/twenty-seven expanded cases in six whole automation host/list policy suites without equivalent replacement. Real RPC category/retryability and wrapped-timeout recognition, unscoped-failure/scoped-success health evidence precedence, exact-ID create selectors and per-run workspace omission, paired-web local/SSH/absent host catalog routing, incompatible/removed/unhydrated/offline execution health, runtime-before-nested-SSH recovery dispatch, and no-owned-focus/successor/foreign-list focus policy alarms are consciously lost. Retain exact20line orphan allow/refuse/precondition and exact90line cross-host same-ID search suites. No retry-timer/fence lifecycle, actual reconnect/network/write delivery, native focus, mobile/mixed-version runtime or disk persistence coverage is claimed.", + "Audit3209 composes approved sources3202/3206: deliberately retires seven authored/expanded cases in four whole suites without equivalent replacement. Work-item queries lose real GitHub/GitLab oversized ASCII secret-prefix empty-query and whitespace-before-trim refusal alarms; inputs share the imported size bound and exercise only its fast length branch, with no multibyte or actual provider/exposure guarantee. Skill sharing loses complete/partial managed-bundle and destination-ambiguity association checks plus three negative origin/path/scheme admission examples; these do not establish uploaded contents, arbitrary-URL fetching, authorization or execution. Retain exact originless-project direct-link fallback, cloud-delete confirmation, bundled-target repair/owner isolation and explicit Windows-host preference over stale WSL suites. Rejected3201 runtime-preference removal is excluded. No real cloud/network/host/disk, mobile or mixed-version execution validation is claimed." ], "demotionRule": "Demote or quarantine if the fault harness flakes without a product or harness bug, if healthy operation exceeds one runtime watcher child, if total physical operation exceeds eight children including retiring generations, if quarantine children outlive their roots or repeat after fusing, if event delivery becomes unbounded, or if metadata/stat work returns to the serve process." }, @@ -14409,10 +14452,10 @@ "providers": ["paired-runtime"], "coveredPlatforms": ["linux"], "coveredProviders": ["paired-runtime"], - "coverageNotes": "Audit3096 source-only reduction (3087/3088): retire 69 authored/76 expanded cases, including complete recovery-portals and reconnect-banner suites. Intentionally lose dead/default TUI replay, generated alternate-frame style composition, reset/mode/dimension and legacy missing-mode-boundary alarms, UI notice/action/reveal policies, and isolated recovery lifecycle variants, without equivalent replacement. Retained registrations and callbacks are unchanged; headless cells are not pixels, and no fresh runtime, host, SSH, WSL, rendered-app or performance result is claimed. Audit3086 source-only reduction (3079/3080/3081): intentionally retire 93 authored/100 expanded mock-boundary cases, including the complete spawn-errors and SSH reconnect overlay suites, without replacement. Retired alarms include spawn classification/ownership, reply ceilings and renderer-write failure recovery, disconnect/detach fencing branches, authority facts, and overlay retry/visibility wiring. Retained callbacks are unchanged; no fresh execution, real PTY/SSH, rendered UI, or performance result is claimed. Audit2432: The broad unit command loses the isolated BranchPicker open-change notification sample. Its unique true/false callback alarm is intentionally retired; reopening/status-refresh behavior was not exercised. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2425: The broad unit command loses the workspace-copy-status supplied readError forwarding sample. It did not exercise the branch-switch blocking promised by its title. This alarm is intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2417: The broad unit command loses two ordinary clean Git cherry-pick/revert success samples and two terminal startup foreground-read work-budget samples. These unique alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2412: The broad unit command loses the whole six-case fake-React-hook scroll-anchor suite, two generic draft-retention samples, a simple new-agent order sample, a real history-publication batching-count sample, an unmounted handoff abort/timer sample and three basic WSL preview/error samples. These alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2404: The broad unit command loses the standalone share-name lookup 503 propagation suite, initial deletion placement-kind sample, direct changed-mtime stale sample, first-pass rollback existence example and abandoned-preparation directory sample. These exact alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2397 review amendment: The broad unit command loses three standalone suites, two partial-case definitions and two URL table rows across package/download/placement tests. Keep initial wrong-port authorization, modified independent-copy digest refusal and abort-after-begin cancellation dispatch. The remaining alarms are deliberately retired; no equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2393 current-parent refresh2401: Remove the basic skill-install service alias sample and original public managed-remove receiptless refusal case. Preserve the upstream request ownership suite and transaction interruption coverage. No equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2389: The broad unit command loses the missing-preview suite, plain-global destination sample and prepublished-receipt recovery example. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2385: The broad unit command loses four authored walker/staging/protocol examples (six expanded cases); no equivalent replacement or fresh validation is claimed for the reduced suite. Audit2383: The unscoped Vitest command no longer includes the removed Antigravity catalogue suite; its exact provider-root/owner example has no equivalent replacement or fresh validation claim. Audit2377/2381: The unscoped Vitest command includes the reduced bundled-skill and native-discovery suites; the eight removed backup/legacy/catalogue/symlink/SSH-builder examples have no replacement-equivalence or fresh validation claim here. Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit1579 removes workflow/manifest/regex/private binary-header and diagnostic metric inventories, fixture selectors, injected forwarding/platform/signature/process examples, unproven overlap and internal churn counters without equivalent replacement coverage. Retains actual Git trust/diffs; filesystem hash/ELF-region/native discovery; child CLI module repair; compiler/lock/publication/rollback and synthetic Electron install/cache ownership; executable shell quoting/exit; controlled notary/timer cleanup; local patched extractor file/AST freshness; real Chromium/WebKit CSP/sandbox/HTTPS image/referrer/link/preservation controls under parsed Android headers. Five unchanged setup-pnpm/VM request-cleanup definitions reviewed and not rerun. GitHub, installer/archive, OS metric, client, native delegate, compressor, builder and Apple boundaries injected or absent where recorded. No actual native PTY, shipped full/native app, real Actions/cache/npm signature authority, downloaded Electron archive, real objdump/linker/native CLI/AppImage, signing/NSIS/notary/upload/updater or live freeze proof. Historical scope before this audit: Published Linux 1.4.188 desktop against current source in both directions; scheduled weekly and manually runnable. No required PR check.", + "coverageNotes": "Audit3209 composes approved sources3202/3206: deliberately retires seven authored/expanded cases in four whole suites without equivalent replacement. Work-item queries lose real GitHub/GitLab oversized ASCII secret-prefix empty-query and whitespace-before-trim refusal alarms; inputs share the imported size bound and exercise only its fast length branch, with no multibyte or actual provider/exposure guarantee. Skill sharing loses complete/partial managed-bundle and destination-ambiguity association checks plus three negative origin/path/scheme admission examples; these do not establish uploaded contents, arbitrary-URL fetching, authorization or execution. Retain exact originless-project direct-link fallback, cloud-delete confirmation, bundled-target repair/owner isolation and explicit Windows-host preference over stale WSL suites. Rejected3201 runtime-preference removal is excluded. No real cloud/network/host/disk, mobile or mixed-version execution validation is claimed. Audit3200 composes approved source3194: deliberately retires thirteen authored registrations/twenty-seven expanded cases in six whole automation host/list policy suites without equivalent replacement. Real RPC category/retryability and wrapped-timeout recognition, unscoped-failure/scoped-success health evidence precedence, exact-ID create selectors and per-run workspace omission, paired-web local/SSH/absent host catalog routing, incompatible/removed/unhydrated/offline execution health, runtime-before-nested-SSH recovery dispatch, and no-owned-focus/successor/foreign-list focus policy alarms are consciously lost. Retain exact20line orphan allow/refuse/precondition and exact90line cross-host same-ID search suites. No retry-timer/fence lifecycle, actual reconnect/network/write delivery, native focus, mobile/mixed-version runtime or disk persistence coverage is claimed. Audit3191 combines approved source3182/3187/3188: deliberately retires thirteen authored Vitest registrations and fifteen expanded cases, including five whole suites, without equivalent replacement. Attachment intake loses real portal/native-capture terminal interception and unowned-container refusal, immediate child-only committed availability/claim-ref negotiation and delivery, and direct-target over stable focused/background composer routing through disable/re-enable/remount and independent question focus. Exact destination/cache/draft and final-stat owner/workspace/File-release suites remain; they do not replace Surface recipient routing. Automation authoring loses destination runtime catalog membership, local/direct-SSH exclusion of paired-runtime repos, unknown-runtime empty catalog, logical project/host/setup/repo/path context payload, and missing/nonready setup refusal; these were genuine direct helper alarms, while exact schedule transformation, legacy schedule and setup-decision suites remain. Agent picker loses setup-chat/terminal/missing-installer/unsupported-or-unknown-host row projection samples and the ordinary unsearched menu variant; the entire original26-line resume recipe suite remains, including reported bypass versus default/absent permission modes, as does the exact search-result menu callback with its fixtures, model/effort commits and staged Arguments reopen outcome. Rejected predecessor3180 full recipe deletion is excluded. No actual native drag/cursor/focus/IME, upload bytes or disk/restart persistence, full automation save/scheduler/runtime transport, real resume-process flags/environment delivery, or native menu/rendered layout validation is claimed. Audit3178 combines source3169/3170/3175: deliberately retires eight authored units (six Vitest cases and two imperative custom relay scenarios), including two whole suites, without equivalent replacement. Voice Section loses per-model pending-delete isolation across interleaved A/B completion and the two-success refresh-call alarm; exact VoicePane delayed key-clear/newer enabled-toggle merge remains and does not replace row deletion coverage. Speech loses dedicated rating-scale/inclusive-ceiling, unsupported-versus-unmeasured, explicit/system-language precedence/locale alias, accuracy versus fast named/default/best-measured selection, and unmeasured/no-match examples; exact offered-user-pick versus retired-selection case and its fixture remain. Relay loses legacy ping-delivery count/liveness sampled before the silence deadline and grouped malformed Bearer/host-ID 401/429 routing checks; twelve real Worker/DurableObject/shipped-client scenarios remain, not equivalent replacement for those narrow alarms. Six prior speech cases are not all deleted: approved successor3175 keeps the original user-choice case. No actual credential/file persistence, native/GPU/engine/download delivery, production assignment policy or deployed-runtime validation is claimed by this reduction. Audit3165 combines source3160/3162: deliberately retires six authored/expanded cases across three whole suites without equivalent replacement. Launch/status losses: observed React-render pending/resuming coordination across settings and deferred offer read; stale-offer reread suppressing dialog reopen; held-local-chat recovery visibility with new-chat preferences off; disabled-local admission avoiding offer RPC despite an injected but unconsumed paired-tab fixture; and run-only lost-reply uncertainty reachability until direct viewed-run retirement. Launch probe does not prove arbitrary synchronous-store atomicity, the paired fixture is not remote runtime enrollment, and the status case directly marks viewed state rather than rendering the summary. Crew-hook losses: old-host method_not_found cache persists across party changes but is released by independently supplied connection generation/verified pairing status or pairing revision, with actual frame publication and teardown. These are real narrow coordination, admission, uncertainty and mixed-version cache alarms consciously lost. Exact web verified-runtime writer handoff guard remains; it does not replace those alarms or prove live host/native/mobile delivery. Audit3156 combines3147/3150/3152/3153/3154: deliberately retires39authored/40expanded native-chat recovery cases, eight whole suites and two orphan test-support files without equivalent replacement. Lost alarms: lost-reply unconfirmed reconciliation, skipped rows/counts and missed-frame repair, unknown/pending outcome and omitted-failure-list compatibility, uncertain history after dismissal, retry/refusal/dismiss lifecycle, hidden/consumed picker ownership, result-tree keyboard focus/disclosure and all-skipped retirement; unconfirmed-over-conflict guidance and failed-chat changes despite older host timestamps; nearest-listed ancestor/cyclic forest shape, descendant membership, host ordering/missing-host local fallback; skipped/readiness/admission counts, provisional skip/progress monotonicity, early per-chat verdicts with batch pending protection, older-host waiting, start-slot/delivery distinction, retry-over-failure and unknown-after-withdrawal attention; remote snooze/reconnect/reoffer, unseen mixed summary through open/close, watched completion retirement, new success beside old failure, failed-reread mixed-result preservation, filter/collapse completion resets, retry summary replacement and current-offer/history selection; cross-host workspace identity, rendered cyclic reachability, nested tri-state/toggle propagation, project eligibility isolation and collapse preserving selection. Exact fallback-list completion barrier, batched verdict/cleanup retention, stale-read versus dismissal publication race, and requested-but-never-rendered finished-run retirement remain; they do not replace retired alarms. Audit3146 combines source reviews3132/3133/3135/3138/3143: intentionally retire20authored/31expanded cases without equivalent replacement. Provider-session losses: structured-native terminal-resume exclusion, metadata-less completed identity, new-turn completion clearing, Pi provider-only/periodic/manual promotion, changed-transcript launch-config isolation, Pi/omp/prime-agent completed-session remote/manual-shutdown promotion, and quit/done precedence over heartbeat. Side-thread/question losses: finished-pane acquisition, hidden title/recap states, local/relay/relay-done conversation takeover with prompt/session/child resets, plain-message abandonment, compaction/session replacement and completion resets. Codex startup losses: incoming-owner cached child replacement, old-relay foreign live-session correction, completed foreign-root turn-fact permutations. Transcript losses: real temporary-JSONL partial sibling/final-child completion, unlabelled child attribution, compact cached replay preservation and100/1000completed-child roster retention/release. Compiler-ratchet losses: valid-line uncompiled-list parser grammar examples and injected-existence stale-path filtering; these did not exercise actual filesystem canonicalization or build exclusion. These are real lifecycle, ownership, replay, liveness and retention alarms, including recent#40246 regressions, deliberately lost. Retained conditional record replacement, clockless root/SSH owner isolation, persisted main-thread fork rejection, partial/final question-answer lifetime, cached-roster/missing-ID/live HTTP/durable startup boundaries and restarted-relay refusal/acceptance do not replace those losses. No native/SSH/WSL execution or equivalent coverage is claimed. Audit3128 scoped coverage reduction: Audit3121 removes VoiceDictationLanguageSetting.test.tsx (Spanish-to-es callback and unsupported-model Korean option presence) and voice-speech-model-rows.test.ts (provider/language-order/retired-on-disk list policy); these real narrow alarms are deliberately retired without replacement. VoiceSpeechModelSection per-model concurrent deletion remains unchanged. Audit3122 removes the direct absolute/parent-segment sparse-directory exception-type sample and the five-row IPC sparse-preset error-code/non-save table (two authored/six expanded cases). Those real typed-validation and IPC refusal/error-code alarms are deliberately retired. Keep both real symlink/junction floating-directory trust cases and the minimal RPC structured validation-reason serialization case. The RPC case does not replace IPC save/refusal behavior, typed normalization for both path inputs, actual Git sparse checkout or rendered localization. No equivalent replacement or fresh test/runtime/platform/remote/performance validation is claimed. Audit3124 removes ExperimentalPane.test.tsx (ordinary Pet switch callback), WorkspaceDirectorySetting.test.tsx (padded absolute saved-path normalization/no-write blur), and repository-search.perf.test.ts (navigation/selected-pane builder-call policy, fixture cardinality/nonempty entries and renamed project keyword inclusion). These real narrow alarms are retired without replacement; RepositoryPane.search.test.tsx search-to-sparse-editor request remains unchanged. Audit3129: resolver Windows case-insensitive and POSIX case-sensitive configured-env composition plus mocked-base launch-preflight Windows composition are intentionally no longer checked by the two deleted suites. No equivalent coverage claimed. Keep runtime-structured-agent-host-env.test.ts unchanged: configured Windows Claude-home account identity and host-account precedence remain checked. Audit3114 incorporates source3101: retire three structured Claude child-environment wrapper cases covering inherited stamp isolation/default and explicit entrypoint, Windows SDK-key canonicalization/default/duplicate-key order, and configured lookup/final environment/config-dir conjunction. Keep direct auth/session sanitation and Windows-versus-Linux overlay checks, actual executable lookup from supplied inherited PATH, native Windows child environment delivery, and stale option-mutation fencing. These are not equivalent replacements for the retired wrapper alarms. No fresh test/runtime, real login-shell probe, Claude SDK startup, remote/mixed-version, UI or performance result is claimed. Audit3114 incorporates source3105: retire 17 authored/20 expanded daemon launch-note cases, including the entire two-case SessionLaunchNote suite. Deliberately lose split-marker carry across same-token re-arm, stale-token retirement refusal, foreground tri-state and serial settlement, omitted-note/no-incarnation mixed-version policy, sticky retirement, first-incarnation/replacement launch preservation and held-launch precedence. Keep only the unchanged unresolved foreground-read race against a later finished attach. Supplied notes/foreground and runtime calls do not establish actual daemon/main restart, SSH, native Windows observation, mobile UI, equivalent replacement or fresh runtime/performance validation. Audit3114 incorporates source3109: retire six authored/35 expanded pricing cases: 21 accepted model-name examples, 10 unsupported/future-model fail-closed examples, malformed TTL clamp, unknown-model estimate refusal, flat-model long-context disregard and oversized long-context clamp. Keep mixed five-minute/one-hour write allocation and short/all-long/mixed long-context allocation with original fixed oracles. Real parser/refusal/bounds alarms are knowingly lost without equivalent replacement; retained tests do not validate provider rates, actual billing or request threshold classification. Preserve the archived usage-scan-append source-freeze receipt without transferring historical execution/performance credit. No fresh runtime result is claimed. Audit3108 source-only reduction (3094/3095/3100): retire 27 authored/30 expanded cases, including complete markdown view-state, file-preview link-open and CLI agent-server-route suites, without replacement. Deliberate losses include preview visibility/reference lifetime and same-path owners; SSH stat, directory/missing-target, explicit-null owner, nonmarkdown line/column, local URI routing, remote-to-client guard and same-file reuse; document-preview source-owner/folder/reuse routing, stable grant location and outside-workspace POSIX/Windows request projection; and verified remote CLI send/check refusal, suggested --on argv/copy, shell no-probe bypass, unverified-launch admission and older-peer refusal. Retain two markdown source-runtime/qualified-reveal alarms, one stale grant-rejection fence and two remote read/mutation evidence policies, with original callbacks. Final last-wins reveal did not prove transient cancellation; CLI prerequisite did not prove no real send, and envelope tests do not execute server refusal. No fresh runtime, rendered UI, actual file/SSH/paired transport, authorization, mixed-version or performance result is claimed. Audit3096 source-only reduction (3087/3088): retire 69 authored/76 expanded cases, including complete recovery-portals and reconnect-banner suites. Intentionally lose dead/default TUI replay, generated alternate-frame style composition, reset/mode/dimension and legacy missing-mode-boundary alarms, UI notice/action/reveal policies, and isolated recovery lifecycle variants, without equivalent replacement. Retained registrations and callbacks are unchanged; headless cells are not pixels, and no fresh runtime, host, SSH, WSL, rendered-app or performance result is claimed. Audit3086 source-only reduction (3079/3080/3081): intentionally retire 93 authored/100 expanded mock-boundary cases, including the complete spawn-errors and SSH reconnect overlay suites, without replacement. Retired alarms include spawn classification/ownership, reply ceilings and renderer-write failure recovery, disconnect/detach fencing branches, authority facts, and overlay retry/visibility wiring. Retained callbacks are unchanged; no fresh execution, real PTY/SSH, rendered UI, or performance result is claimed. Audit2432: The broad unit command loses the isolated BranchPicker open-change notification sample. Its unique true/false callback alarm is intentionally retired; reopening/status-refresh behavior was not exercised. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2425: The broad unit command loses the workspace-copy-status supplied readError forwarding sample. It did not exercise the branch-switch blocking promised by its title. This alarm is intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2417: The broad unit command loses two ordinary clean Git cherry-pick/revert success samples and two terminal startup foreground-read work-budget samples. These unique alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2412: The broad unit command loses the whole six-case fake-React-hook scroll-anchor suite, two generic draft-retention samples, a simple new-agent order sample, a real history-publication batching-count sample, an unmounted handoff abort/timer sample and three basic WSL preview/error samples. These alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2404: The broad unit command loses the standalone share-name lookup 503 propagation suite, initial deletion placement-kind sample, direct changed-mtime stale sample, first-pass rollback existence example and abandoned-preparation directory sample. These exact alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2397 review amendment: The broad unit command loses three standalone suites, two partial-case definitions and two URL table rows across package/download/placement tests. Keep initial wrong-port authorization, modified independent-copy digest refusal and abort-after-begin cancellation dispatch. The remaining alarms are deliberately retired; no equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2393 current-parent refresh2401: Remove the basic skill-install service alias sample and original public managed-remove receiptless refusal case. Preserve the upstream request ownership suite and transaction interruption coverage. No equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2389: The broad unit command loses the missing-preview suite, plain-global destination sample and prepublished-receipt recovery example. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2385: The broad unit command loses four authored walker/staging/protocol examples (six expanded cases); no equivalent replacement or fresh validation is claimed for the reduced suite. Audit2383: The unscoped Vitest command no longer includes the removed Antigravity catalogue suite; its exact provider-root/owner example has no equivalent replacement or fresh validation claim. Audit2377/2381: The unscoped Vitest command includes the reduced bundled-skill and native-discovery suites; the eight removed backup/legacy/catalogue/symlink/SSH-builder examples have no replacement-equivalence or fresh validation claim here. Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit1579 removes workflow/manifest/regex/private binary-header and diagnostic metric inventories, fixture selectors, injected forwarding/platform/signature/process examples, unproven overlap and internal churn counters without equivalent replacement coverage. Retains actual Git trust/diffs; filesystem hash/ELF-region/native discovery; child CLI module repair; compiler/lock/publication/rollback and synthetic Electron install/cache ownership; executable shell quoting/exit; controlled notary/timer cleanup; local patched extractor file/AST freshness; real Chromium/WebKit CSP/sandbox/HTTPS image/referrer/link/preservation controls under parsed Android headers. Five unchanged setup-pnpm/VM request-cleanup definitions reviewed and not rerun. GitHub, installer/archive, OS metric, client, native delegate, compressor, builder and Apple boundaries injected or absent where recorded. No actual native PTY, shipped full/native app, real Actions/cache/npm signature authority, downloaded Electron archive, real objdump/linker/native CLI/AppImage, signing/NSIS/notary/upload/updater or live freeze proof. Historical scope before this audit: Published Linux 1.4.188 desktop against current source in both directions; scheduled weekly and manually runnable. No required PR check.", "motivatingLinks": ["https://github.com/stablyai/orca/actions/runs/34069063016"], "invariant": "A paired client and host without client-hosted browser capabilities retain server-hosted browser placement across supported version skew.", - "oracle": "Audit3096 source-only reduction (3087/3088): retire 69 authored/76 expanded cases, including complete recovery-portals and reconnect-banner suites. Intentionally lose dead/default TUI replay, generated alternate-frame style composition, reset/mode/dimension and legacy missing-mode-boundary alarms, UI notice/action/reveal policies, and isolated recovery lifecycle variants, without equivalent replacement. Retained registrations and callbacks are unchanged; headless cells are not pixels, and no fresh runtime, host, SSH, WSL, rendered-app or performance result is claimed. Audit3086 source-only reduction (3079/3080/3081): intentionally retire 93 authored/100 expanded mock-boundary cases, including the complete spawn-errors and SSH reconnect overlay suites, without replacement. Retired alarms include spawn classification/ownership, reply ceilings and renderer-write failure recovery, disconnect/detach fencing branches, authority facts, and overlay retry/visibility wiring. Retained callbacks are unchanged; no fresh execution, real PTY/SSH, rendered UI, or performance result is claimed. Audit2432: The broad unit command loses the isolated BranchPicker open-change notification sample. Its unique true/false callback alarm is intentionally retired; reopening/status-refresh behavior was not exercised. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2425: The broad unit command loses the workspace-copy-status supplied readError forwarding sample. It did not exercise the branch-switch blocking promised by its title. This alarm is intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2417: The broad unit command loses two ordinary clean Git cherry-pick/revert success samples and two terminal startup foreground-read work-budget samples. These unique alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2412: The broad unit command loses the whole six-case fake-React-hook scroll-anchor suite, two generic draft-retention samples, a simple new-agent order sample, a real history-publication batching-count sample, an unmounted handoff abort/timer sample and three basic WSL preview/error samples. These alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2404: The broad unit command loses the standalone share-name lookup 503 propagation suite, initial deletion placement-kind sample, direct changed-mtime stale sample, first-pass rollback existence example and abandoned-preparation directory sample. These exact alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2397 review amendment: The broad unit command loses three standalone suites, two partial-case definitions and two URL table rows across package/download/placement tests. Keep initial wrong-port authorization, modified independent-copy digest refusal and abort-after-begin cancellation dispatch. The remaining alarms are deliberately retired; no equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2393 current-parent refresh2401: Remove the basic skill-install service alias sample and original public managed-remove receiptless refusal case. Preserve the upstream request ownership suite and transaction interruption coverage. No equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2389: The broad unit command loses the missing-preview suite, plain-global destination sample and prepublished-receipt recovery example. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2385: The broad unit command loses four authored walker/staging/protocol examples (six expanded cases); no equivalent replacement or fresh validation is claimed for the reduced suite. Audit2383: The unscoped Vitest command no longer includes the removed Antigravity catalogue suite; its exact provider-root/owner example has no equivalent replacement or fresh validation claim. Audit2377/2381: The unscoped Vitest command includes the reduced bundled-skill and native-discovery suites; the eight removed backup/legacy/catalogue/symlink/SSH-builder examples have no replacement-equivalence or fresh validation claim here. Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Require both existing named browser placement scenarios to pass three times with one attempt, zero skips, zero failures, and no report errors.", + "oracle": "Audit3209 composes approved sources3202/3206: deliberately retires seven authored/expanded cases in four whole suites without equivalent replacement. Work-item queries lose real GitHub/GitLab oversized ASCII secret-prefix empty-query and whitespace-before-trim refusal alarms; inputs share the imported size bound and exercise only its fast length branch, with no multibyte or actual provider/exposure guarantee. Skill sharing loses complete/partial managed-bundle and destination-ambiguity association checks plus three negative origin/path/scheme admission examples; these do not establish uploaded contents, arbitrary-URL fetching, authorization or execution. Retain exact originless-project direct-link fallback, cloud-delete confirmation, bundled-target repair/owner isolation and explicit Windows-host preference over stale WSL suites. Rejected3201 runtime-preference removal is excluded. No real cloud/network/host/disk, mobile or mixed-version execution validation is claimed. Audit3200 composes approved source3194: deliberately retires thirteen authored registrations/twenty-seven expanded cases in six whole automation host/list policy suites without equivalent replacement. Real RPC category/retryability and wrapped-timeout recognition, unscoped-failure/scoped-success health evidence precedence, exact-ID create selectors and per-run workspace omission, paired-web local/SSH/absent host catalog routing, incompatible/removed/unhydrated/offline execution health, runtime-before-nested-SSH recovery dispatch, and no-owned-focus/successor/foreign-list focus policy alarms are consciously lost. Retain exact20line orphan allow/refuse/precondition and exact90line cross-host same-ID search suites. No retry-timer/fence lifecycle, actual reconnect/network/write delivery, native focus, mobile/mixed-version runtime or disk persistence coverage is claimed. Audit3191 combines approved source3182/3187/3188: deliberately retires thirteen authored Vitest registrations and fifteen expanded cases, including five whole suites, without equivalent replacement. Attachment intake loses real portal/native-capture terminal interception and unowned-container refusal, immediate child-only committed availability/claim-ref negotiation and delivery, and direct-target over stable focused/background composer routing through disable/re-enable/remount and independent question focus. Exact destination/cache/draft and final-stat owner/workspace/File-release suites remain; they do not replace Surface recipient routing. Automation authoring loses destination runtime catalog membership, local/direct-SSH exclusion of paired-runtime repos, unknown-runtime empty catalog, logical project/host/setup/repo/path context payload, and missing/nonready setup refusal; these were genuine direct helper alarms, while exact schedule transformation, legacy schedule and setup-decision suites remain. Agent picker loses setup-chat/terminal/missing-installer/unsupported-or-unknown-host row projection samples and the ordinary unsearched menu variant; the entire original26-line resume recipe suite remains, including reported bypass versus default/absent permission modes, as does the exact search-result menu callback with its fixtures, model/effort commits and staged Arguments reopen outcome. Rejected predecessor3180 full recipe deletion is excluded. No actual native drag/cursor/focus/IME, upload bytes or disk/restart persistence, full automation save/scheduler/runtime transport, real resume-process flags/environment delivery, or native menu/rendered layout validation is claimed. Audit3178 combines source3169/3170/3175: deliberately retires eight authored units (six Vitest cases and two imperative custom relay scenarios), including two whole suites, without equivalent replacement. Voice Section loses per-model pending-delete isolation across interleaved A/B completion and the two-success refresh-call alarm; exact VoicePane delayed key-clear/newer enabled-toggle merge remains and does not replace row deletion coverage. Speech loses dedicated rating-scale/inclusive-ceiling, unsupported-versus-unmeasured, explicit/system-language precedence/locale alias, accuracy versus fast named/default/best-measured selection, and unmeasured/no-match examples; exact offered-user-pick versus retired-selection case and its fixture remain. Relay loses legacy ping-delivery count/liveness sampled before the silence deadline and grouped malformed Bearer/host-ID 401/429 routing checks; twelve real Worker/DurableObject/shipped-client scenarios remain, not equivalent replacement for those narrow alarms. Six prior speech cases are not all deleted: approved successor3175 keeps the original user-choice case. No actual credential/file persistence, native/GPU/engine/download delivery, production assignment policy or deployed-runtime validation is claimed by this reduction. Audit3165 combines source3160/3162: deliberately retires six authored/expanded cases across three whole suites without equivalent replacement. Launch/status losses: observed React-render pending/resuming coordination across settings and deferred offer read; stale-offer reread suppressing dialog reopen; held-local-chat recovery visibility with new-chat preferences off; disabled-local admission avoiding offer RPC despite an injected but unconsumed paired-tab fixture; and run-only lost-reply uncertainty reachability until direct viewed-run retirement. Launch probe does not prove arbitrary synchronous-store atomicity, the paired fixture is not remote runtime enrollment, and the status case directly marks viewed state rather than rendering the summary. Crew-hook losses: old-host method_not_found cache persists across party changes but is released by independently supplied connection generation/verified pairing status or pairing revision, with actual frame publication and teardown. These are real narrow coordination, admission, uncertainty and mixed-version cache alarms consciously lost. Exact web verified-runtime writer handoff guard remains; it does not replace those alarms or prove live host/native/mobile delivery. Audit3156 combines3147/3150/3152/3153/3154: deliberately retires39authored/40expanded native-chat recovery cases, eight whole suites and two orphan test-support files without equivalent replacement. Lost alarms: lost-reply unconfirmed reconciliation, skipped rows/counts and missed-frame repair, unknown/pending outcome and omitted-failure-list compatibility, uncertain history after dismissal, retry/refusal/dismiss lifecycle, hidden/consumed picker ownership, result-tree keyboard focus/disclosure and all-skipped retirement; unconfirmed-over-conflict guidance and failed-chat changes despite older host timestamps; nearest-listed ancestor/cyclic forest shape, descendant membership, host ordering/missing-host local fallback; skipped/readiness/admission counts, provisional skip/progress monotonicity, early per-chat verdicts with batch pending protection, older-host waiting, start-slot/delivery distinction, retry-over-failure and unknown-after-withdrawal attention; remote snooze/reconnect/reoffer, unseen mixed summary through open/close, watched completion retirement, new success beside old failure, failed-reread mixed-result preservation, filter/collapse completion resets, retry summary replacement and current-offer/history selection; cross-host workspace identity, rendered cyclic reachability, nested tri-state/toggle propagation, project eligibility isolation and collapse preserving selection. Exact fallback-list completion barrier, batched verdict/cleanup retention, stale-read versus dismissal publication race, and requested-but-never-rendered finished-run retirement remain; they do not replace retired alarms. Audit3146 combines source reviews3132/3133/3135/3138/3143: intentionally retire20authored/31expanded cases without equivalent replacement. Provider-session losses: structured-native terminal-resume exclusion, metadata-less completed identity, new-turn completion clearing, Pi provider-only/periodic/manual promotion, changed-transcript launch-config isolation, Pi/omp/prime-agent completed-session remote/manual-shutdown promotion, and quit/done precedence over heartbeat. Side-thread/question losses: finished-pane acquisition, hidden title/recap states, local/relay/relay-done conversation takeover with prompt/session/child resets, plain-message abandonment, compaction/session replacement and completion resets. Codex startup losses: incoming-owner cached child replacement, old-relay foreign live-session correction, completed foreign-root turn-fact permutations. Transcript losses: real temporary-JSONL partial sibling/final-child completion, unlabelled child attribution, compact cached replay preservation and100/1000completed-child roster retention/release. Compiler-ratchet losses: valid-line uncompiled-list parser grammar examples and injected-existence stale-path filtering; these did not exercise actual filesystem canonicalization or build exclusion. These are real lifecycle, ownership, replay, liveness and retention alarms, including recent#40246 regressions, deliberately lost. Retained conditional record replacement, clockless root/SSH owner isolation, persisted main-thread fork rejection, partial/final question-answer lifetime, cached-roster/missing-ID/live HTTP/durable startup boundaries and restarted-relay refusal/acceptance do not replace those losses. No native/SSH/WSL execution or equivalent coverage is claimed. Audit3128 scoped coverage reduction: Audit3121 removes VoiceDictationLanguageSetting.test.tsx (Spanish-to-es callback and unsupported-model Korean option presence) and voice-speech-model-rows.test.ts (provider/language-order/retired-on-disk list policy); these real narrow alarms are deliberately retired without replacement. VoiceSpeechModelSection per-model concurrent deletion remains unchanged. Audit3122 removes the direct absolute/parent-segment sparse-directory exception-type sample and the five-row IPC sparse-preset error-code/non-save table (two authored/six expanded cases). Those real typed-validation and IPC refusal/error-code alarms are deliberately retired. Keep both real symlink/junction floating-directory trust cases and the minimal RPC structured validation-reason serialization case. The RPC case does not replace IPC save/refusal behavior, typed normalization for both path inputs, actual Git sparse checkout or rendered localization. No equivalent replacement or fresh test/runtime/platform/remote/performance validation is claimed. Audit3124 removes ExperimentalPane.test.tsx (ordinary Pet switch callback), WorkspaceDirectorySetting.test.tsx (padded absolute saved-path normalization/no-write blur), and repository-search.perf.test.ts (navigation/selected-pane builder-call policy, fixture cardinality/nonempty entries and renamed project keyword inclusion). These real narrow alarms are retired without replacement; RepositoryPane.search.test.tsx search-to-sparse-editor request remains unchanged. Audit3129: resolver Windows case-insensitive and POSIX case-sensitive configured-env composition plus mocked-base launch-preflight Windows composition are intentionally no longer checked by the two deleted suites. No equivalent coverage claimed. Keep runtime-structured-agent-host-env.test.ts unchanged: configured Windows Claude-home account identity and host-account precedence remain checked. Audit3114 incorporates source3101: retire three structured Claude child-environment wrapper cases covering inherited stamp isolation/default and explicit entrypoint, Windows SDK-key canonicalization/default/duplicate-key order, and configured lookup/final environment/config-dir conjunction. Keep direct auth/session sanitation and Windows-versus-Linux overlay checks, actual executable lookup from supplied inherited PATH, native Windows child environment delivery, and stale option-mutation fencing. These are not equivalent replacements for the retired wrapper alarms. No fresh test/runtime, real login-shell probe, Claude SDK startup, remote/mixed-version, UI or performance result is claimed. Audit3114 incorporates source3105: retire 17 authored/20 expanded daemon launch-note cases, including the entire two-case SessionLaunchNote suite. Deliberately lose split-marker carry across same-token re-arm, stale-token retirement refusal, foreground tri-state and serial settlement, omitted-note/no-incarnation mixed-version policy, sticky retirement, first-incarnation/replacement launch preservation and held-launch precedence. Keep only the unchanged unresolved foreground-read race against a later finished attach. Supplied notes/foreground and runtime calls do not establish actual daemon/main restart, SSH, native Windows observation, mobile UI, equivalent replacement or fresh runtime/performance validation. Audit3114 incorporates source3109: retire six authored/35 expanded pricing cases: 21 accepted model-name examples, 10 unsupported/future-model fail-closed examples, malformed TTL clamp, unknown-model estimate refusal, flat-model long-context disregard and oversized long-context clamp. Keep mixed five-minute/one-hour write allocation and short/all-long/mixed long-context allocation with original fixed oracles. Real parser/refusal/bounds alarms are knowingly lost without equivalent replacement; retained tests do not validate provider rates, actual billing or request threshold classification. Preserve the archived usage-scan-append source-freeze receipt without transferring historical execution/performance credit. No fresh runtime result is claimed. Audit3108 source-only reduction (3094/3095/3100): retire 27 authored/30 expanded cases, including complete markdown view-state, file-preview link-open and CLI agent-server-route suites, without replacement. Deliberate losses include preview visibility/reference lifetime and same-path owners; SSH stat, directory/missing-target, explicit-null owner, nonmarkdown line/column, local URI routing, remote-to-client guard and same-file reuse; document-preview source-owner/folder/reuse routing, stable grant location and outside-workspace POSIX/Windows request projection; and verified remote CLI send/check refusal, suggested --on argv/copy, shell no-probe bypass, unverified-launch admission and older-peer refusal. Retain two markdown source-runtime/qualified-reveal alarms, one stale grant-rejection fence and two remote read/mutation evidence policies, with original callbacks. Final last-wins reveal did not prove transient cancellation; CLI prerequisite did not prove no real send, and envelope tests do not execute server refusal. No fresh runtime, rendered UI, actual file/SSH/paired transport, authorization, mixed-version or performance result is claimed. Audit3096 source-only reduction (3087/3088): retire 69 authored/76 expanded cases, including complete recovery-portals and reconnect-banner suites. Intentionally lose dead/default TUI replay, generated alternate-frame style composition, reset/mode/dimension and legacy missing-mode-boundary alarms, UI notice/action/reveal policies, and isolated recovery lifecycle variants, without equivalent replacement. Retained registrations and callbacks are unchanged; headless cells are not pixels, and no fresh runtime, host, SSH, WSL, rendered-app or performance result is claimed. Audit3086 source-only reduction (3079/3080/3081): intentionally retire 93 authored/100 expanded mock-boundary cases, including the complete spawn-errors and SSH reconnect overlay suites, without replacement. Retired alarms include spawn classification/ownership, reply ceilings and renderer-write failure recovery, disconnect/detach fencing branches, authority facts, and overlay retry/visibility wiring. Retained callbacks are unchanged; no fresh execution, real PTY/SSH, rendered UI, or performance result is claimed. Audit2432: The broad unit command loses the isolated BranchPicker open-change notification sample. Its unique true/false callback alarm is intentionally retired; reopening/status-refresh behavior was not exercised. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2425: The broad unit command loses the workspace-copy-status supplied readError forwarding sample. It did not exercise the branch-switch blocking promised by its title. This alarm is intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2417: The broad unit command loses two ordinary clean Git cherry-pick/revert success samples and two terminal startup foreground-read work-budget samples. These unique alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2412: The broad unit command loses the whole six-case fake-React-hook scroll-anchor suite, two generic draft-retention samples, a simple new-agent order sample, a real history-publication batching-count sample, an unmounted handoff abort/timer sample and three basic WSL preview/error samples. These alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2404: The broad unit command loses the standalone share-name lookup 503 propagation suite, initial deletion placement-kind sample, direct changed-mtime stale sample, first-pass rollback existence example and abandoned-preparation directory sample. These exact alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2397 review amendment: The broad unit command loses three standalone suites, two partial-case definitions and two URL table rows across package/download/placement tests. Keep initial wrong-port authorization, modified independent-copy digest refusal and abort-after-begin cancellation dispatch. The remaining alarms are deliberately retired; no equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2393 current-parent refresh2401: Remove the basic skill-install service alias sample and original public managed-remove receiptless refusal case. Preserve the upstream request ownership suite and transaction interruption coverage. No equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2389: The broad unit command loses the missing-preview suite, plain-global destination sample and prepublished-receipt recovery example. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2385: The broad unit command loses four authored walker/staging/protocol examples (six expanded cases); no equivalent replacement or fresh validation is claimed for the reduced suite. Audit2383: The unscoped Vitest command no longer includes the removed Antigravity catalogue suite; its exact provider-root/owner example has no equivalent replacement or fresh validation claim. Audit2377/2381: The unscoped Vitest command includes the reduced bundled-skill and native-discovery suites; the eight removed backup/legacy/catalogue/symlink/SSH-builder examples have no replacement-equivalence or fresh validation claim here. Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Require both existing named browser placement scenarios to pass three times with one attempt, zero skips, zero failures, and no report errors.", "commands": [ "gh workflow run packaged-browser-e2e.yml", "pnpm exec playwright test tests/e2e/packaged-mixed-version-browser-placement.spec.ts --config tests/playwright.config.ts --project=electron-headless --workers=1 --repeat-each=3 --retries=0", @@ -14479,7 +14522,19 @@ "Audit2425 removes use-workspace-copy-status original5, which returns a fixture-supplied readError string through statusReadError. No consumer blocker or attempted branch switch established refusal; the unique error-forwarding sample is intentionally retired. Other copy ownership and stale-refresh cases are not equivalent error-path coverage. No equivalent replacement or fresh validation is claimed.", "Audit2432 removes BranchPicker.test.tsx original3, which only asserted onOpenChange(true/false) with an always-mounted mocked Popover. It never reopened the picker or consumed the callback in the parent status-refresh owner, despite its title. Lose that unique open/close notification alarm. Retained blocker/collision recovery and asynchronous post-unmount outcome cases are not equivalent replacement coverage. No fresh validation of the reduced selector is claimed.", "Audit3086 source-only reduction (3079/3080/3081): intentionally retire 93 authored/100 expanded mock-boundary cases, including the complete spawn-errors and SSH reconnect overlay suites, without replacement. Retired alarms include spawn classification/ownership, reply ceilings and renderer-write failure recovery, disconnect/detach fencing branches, authority facts, and overlay retry/visibility wiring. Retained callbacks are unchanged; no fresh execution, real PTY/SSH, rendered UI, or performance result is claimed.", - "Audit3096 source-only reduction (3087/3088): retire 69 authored/76 expanded cases, including complete recovery-portals and reconnect-banner suites. Intentionally lose dead/default TUI replay, generated alternate-frame style composition, reset/mode/dimension and legacy missing-mode-boundary alarms, UI notice/action/reveal policies, and isolated recovery lifecycle variants, without equivalent replacement. Retained registrations and callbacks are unchanged; headless cells are not pixels, and no fresh runtime, host, SSH, WSL, rendered-app or performance result is claimed." + "Audit3096 source-only reduction (3087/3088): retire 69 authored/76 expanded cases, including complete recovery-portals and reconnect-banner suites. Intentionally lose dead/default TUI replay, generated alternate-frame style composition, reset/mode/dimension and legacy missing-mode-boundary alarms, UI notice/action/reveal policies, and isolated recovery lifecycle variants, without equivalent replacement. Retained registrations and callbacks are unchanged; headless cells are not pixels, and no fresh runtime, host, SSH, WSL, rendered-app or performance result is claimed.", + "Audit3108 source-only reduction (3094/3095/3100): retire 27 authored/30 expanded cases, including complete markdown view-state, file-preview link-open and CLI agent-server-route suites, without replacement. Deliberate losses include preview visibility/reference lifetime and same-path owners; SSH stat, directory/missing-target, explicit-null owner, nonmarkdown line/column, local URI routing, remote-to-client guard and same-file reuse; document-preview source-owner/folder/reuse routing, stable grant location and outside-workspace POSIX/Windows request projection; and verified remote CLI send/check refusal, suggested --on argv/copy, shell no-probe bypass, unverified-launch admission and older-peer refusal. Retain two markdown source-runtime/qualified-reveal alarms, one stale grant-rejection fence and two remote read/mutation evidence policies, with original callbacks. Final last-wins reveal did not prove transient cancellation; CLI prerequisite did not prove no real send, and envelope tests do not execute server refusal. No fresh runtime, rendered UI, actual file/SSH/paired transport, authorization, mixed-version or performance result is claimed.", + "Audit3114 incorporates source3101: retire three structured Claude child-environment wrapper cases covering inherited stamp isolation/default and explicit entrypoint, Windows SDK-key canonicalization/default/duplicate-key order, and configured lookup/final environment/config-dir conjunction. Keep direct auth/session sanitation and Windows-versus-Linux overlay checks, actual executable lookup from supplied inherited PATH, native Windows child environment delivery, and stale option-mutation fencing. These are not equivalent replacements for the retired wrapper alarms. No fresh test/runtime, real login-shell probe, Claude SDK startup, remote/mixed-version, UI or performance result is claimed.", + "Audit3114 incorporates source3105: retire 17 authored/20 expanded daemon launch-note cases, including the entire two-case SessionLaunchNote suite. Deliberately lose split-marker carry across same-token re-arm, stale-token retirement refusal, foreground tri-state and serial settlement, omitted-note/no-incarnation mixed-version policy, sticky retirement, first-incarnation/replacement launch preservation and held-launch precedence. Keep only the unchanged unresolved foreground-read race against a later finished attach. Supplied notes/foreground and runtime calls do not establish actual daemon/main restart, SSH, native Windows observation, mobile UI, equivalent replacement or fresh runtime/performance validation.", + "Audit3114 incorporates source3109: retire six authored/35 expanded pricing cases: 21 accepted model-name examples, 10 unsupported/future-model fail-closed examples, malformed TTL clamp, unknown-model estimate refusal, flat-model long-context disregard and oversized long-context clamp. Keep mixed five-minute/one-hour write allocation and short/all-long/mixed long-context allocation with original fixed oracles. Real parser/refusal/bounds alarms are knowingly lost without equivalent replacement; retained tests do not validate provider rates, actual billing or request threshold classification. Preserve the archived usage-scan-append source-freeze receipt without transferring historical execution/performance credit. No fresh runtime result is claimed.", + "Audit3128 scoped coverage reduction: Audit3121 removes VoiceDictationLanguageSetting.test.tsx (Spanish-to-es callback and unsupported-model Korean option presence) and voice-speech-model-rows.test.ts (provider/language-order/retired-on-disk list policy); these real narrow alarms are deliberately retired without replacement. VoiceSpeechModelSection per-model concurrent deletion remains unchanged. Audit3122 removes the direct absolute/parent-segment sparse-directory exception-type sample and the five-row IPC sparse-preset error-code/non-save table (two authored/six expanded cases). Those real typed-validation and IPC refusal/error-code alarms are deliberately retired. Keep both real symlink/junction floating-directory trust cases and the minimal RPC structured validation-reason serialization case. The RPC case does not replace IPC save/refusal behavior, typed normalization for both path inputs, actual Git sparse checkout or rendered localization. No equivalent replacement or fresh test/runtime/platform/remote/performance validation is claimed. Audit3124 removes ExperimentalPane.test.tsx (ordinary Pet switch callback), WorkspaceDirectorySetting.test.tsx (padded absolute saved-path normalization/no-write blur), and repository-search.perf.test.ts (navigation/selected-pane builder-call policy, fixture cardinality/nonempty entries and renamed project keyword inclusion). These real narrow alarms are retired without replacement; RepositoryPane.search.test.tsx search-to-sparse-editor request remains unchanged. Audit3129: resolver Windows case-insensitive and POSIX case-sensitive configured-env composition plus mocked-base launch-preflight Windows composition are intentionally no longer checked by the two deleted suites. No equivalent coverage claimed. Keep runtime-structured-agent-host-env.test.ts unchanged: configured Windows Claude-home account identity and host-account precedence remain checked.", + "Audit3146 combines source reviews3132/3133/3135/3138/3143: intentionally retire20authored/31expanded cases without equivalent replacement. Provider-session losses: structured-native terminal-resume exclusion, metadata-less completed identity, new-turn completion clearing, Pi provider-only/periodic/manual promotion, changed-transcript launch-config isolation, Pi/omp/prime-agent completed-session remote/manual-shutdown promotion, and quit/done precedence over heartbeat. Side-thread/question losses: finished-pane acquisition, hidden title/recap states, local/relay/relay-done conversation takeover with prompt/session/child resets, plain-message abandonment, compaction/session replacement and completion resets. Codex startup losses: incoming-owner cached child replacement, old-relay foreign live-session correction, completed foreign-root turn-fact permutations. Transcript losses: real temporary-JSONL partial sibling/final-child completion, unlabelled child attribution, compact cached replay preservation and100/1000completed-child roster retention/release. Compiler-ratchet losses: valid-line uncompiled-list parser grammar examples and injected-existence stale-path filtering; these did not exercise actual filesystem canonicalization or build exclusion. These are real lifecycle, ownership, replay, liveness and retention alarms, including recent#40246 regressions, deliberately lost. Retained conditional record replacement, clockless root/SSH owner isolation, persisted main-thread fork rejection, partial/final question-answer lifetime, cached-roster/missing-ID/live HTTP/durable startup boundaries and restarted-relay refusal/acceptance do not replace those losses. No native/SSH/WSL execution or equivalent coverage is claimed.", + "Audit3156 combines3147/3150/3152/3153/3154: deliberately retires39authored/40expanded native-chat recovery cases, eight whole suites and two orphan test-support files without equivalent replacement. Lost alarms: lost-reply unconfirmed reconciliation, skipped rows/counts and missed-frame repair, unknown/pending outcome and omitted-failure-list compatibility, uncertain history after dismissal, retry/refusal/dismiss lifecycle, hidden/consumed picker ownership, result-tree keyboard focus/disclosure and all-skipped retirement; unconfirmed-over-conflict guidance and failed-chat changes despite older host timestamps; nearest-listed ancestor/cyclic forest shape, descendant membership, host ordering/missing-host local fallback; skipped/readiness/admission counts, provisional skip/progress monotonicity, early per-chat verdicts with batch pending protection, older-host waiting, start-slot/delivery distinction, retry-over-failure and unknown-after-withdrawal attention; remote snooze/reconnect/reoffer, unseen mixed summary through open/close, watched completion retirement, new success beside old failure, failed-reread mixed-result preservation, filter/collapse completion resets, retry summary replacement and current-offer/history selection; cross-host workspace identity, rendered cyclic reachability, nested tri-state/toggle propagation, project eligibility isolation and collapse preserving selection. Exact fallback-list completion barrier, batched verdict/cleanup retention, stale-read versus dismissal publication race, and requested-but-never-rendered finished-run retirement remain; they do not replace retired alarms.", + "Audit3165 combines source3160/3162: deliberately retires six authored/expanded cases across three whole suites without equivalent replacement. Launch/status losses: observed React-render pending/resuming coordination across settings and deferred offer read; stale-offer reread suppressing dialog reopen; held-local-chat recovery visibility with new-chat preferences off; disabled-local admission avoiding offer RPC despite an injected but unconsumed paired-tab fixture; and run-only lost-reply uncertainty reachability until direct viewed-run retirement. Launch probe does not prove arbitrary synchronous-store atomicity, the paired fixture is not remote runtime enrollment, and the status case directly marks viewed state rather than rendering the summary. Crew-hook losses: old-host method_not_found cache persists across party changes but is released by independently supplied connection generation/verified pairing status or pairing revision, with actual frame publication and teardown. These are real narrow coordination, admission, uncertainty and mixed-version cache alarms consciously lost. Exact web verified-runtime writer handoff guard remains; it does not replace those alarms or prove live host/native/mobile delivery.", + "Audit3178 combines source3169/3170/3175: deliberately retires eight authored units (six Vitest cases and two imperative custom relay scenarios), including two whole suites, without equivalent replacement. Voice Section loses per-model pending-delete isolation across interleaved A/B completion and the two-success refresh-call alarm; exact VoicePane delayed key-clear/newer enabled-toggle merge remains and does not replace row deletion coverage. Speech loses dedicated rating-scale/inclusive-ceiling, unsupported-versus-unmeasured, explicit/system-language precedence/locale alias, accuracy versus fast named/default/best-measured selection, and unmeasured/no-match examples; exact offered-user-pick versus retired-selection case and its fixture remain. Relay loses legacy ping-delivery count/liveness sampled before the silence deadline and grouped malformed Bearer/host-ID 401/429 routing checks; twelve real Worker/DurableObject/shipped-client scenarios remain, not equivalent replacement for those narrow alarms. Six prior speech cases are not all deleted: approved successor3175 keeps the original user-choice case. No actual credential/file persistence, native/GPU/engine/download delivery, production assignment policy or deployed-runtime validation is claimed by this reduction.", + "Audit3191 combines approved source3182/3187/3188: deliberately retires thirteen authored Vitest registrations and fifteen expanded cases, including five whole suites, without equivalent replacement. Attachment intake loses real portal/native-capture terminal interception and unowned-container refusal, immediate child-only committed availability/claim-ref negotiation and delivery, and direct-target over stable focused/background composer routing through disable/re-enable/remount and independent question focus. Exact destination/cache/draft and final-stat owner/workspace/File-release suites remain; they do not replace Surface recipient routing. Automation authoring loses destination runtime catalog membership, local/direct-SSH exclusion of paired-runtime repos, unknown-runtime empty catalog, logical project/host/setup/repo/path context payload, and missing/nonready setup refusal; these were genuine direct helper alarms, while exact schedule transformation, legacy schedule and setup-decision suites remain. Agent picker loses setup-chat/terminal/missing-installer/unsupported-or-unknown-host row projection samples and the ordinary unsearched menu variant; the entire original26-line resume recipe suite remains, including reported bypass versus default/absent permission modes, as does the exact search-result menu callback with its fixtures, model/effort commits and staged Arguments reopen outcome. Rejected predecessor3180 full recipe deletion is excluded. No actual native drag/cursor/focus/IME, upload bytes or disk/restart persistence, full automation save/scheduler/runtime transport, real resume-process flags/environment delivery, or native menu/rendered layout validation is claimed.", + "Audit3200 composes approved source3194: deliberately retires thirteen authored registrations/twenty-seven expanded cases in six whole automation host/list policy suites without equivalent replacement. Real RPC category/retryability and wrapped-timeout recognition, unscoped-failure/scoped-success health evidence precedence, exact-ID create selectors and per-run workspace omission, paired-web local/SSH/absent host catalog routing, incompatible/removed/unhydrated/offline execution health, runtime-before-nested-SSH recovery dispatch, and no-owned-focus/successor/foreign-list focus policy alarms are consciously lost. Retain exact20line orphan allow/refuse/precondition and exact90line cross-host same-ID search suites. No retry-timer/fence lifecycle, actual reconnect/network/write delivery, native focus, mobile/mixed-version runtime or disk persistence coverage is claimed.", + "Audit3209 composes approved sources3202/3206: deliberately retires seven authored/expanded cases in four whole suites without equivalent replacement. Work-item queries lose real GitHub/GitLab oversized ASCII secret-prefix empty-query and whitespace-before-trim refusal alarms; inputs share the imported size bound and exercise only its fast length branch, with no multibyte or actual provider/exposure guarantee. Skill sharing loses complete/partial managed-bundle and destination-ambiguity association checks plus three negative origin/path/scheme admission examples; these do not establish uploaded contents, arbitrary-URL fetching, authorization or execution. Retain exact originless-project direct-link fallback, cloud-delete confirmation, bundled-target repair/owner isolation and explicit Windows-host preference over stale WSL suites. Rejected3201 runtime-preference removal is excluded. No real cloud/network/host/disk, mobile or mixed-version execution validation is claimed." ], "demotionRule": "Keep experimental if any direction skips or fails; do not extend timeouts or retry to green." }, diff --git a/config/render-path-translate-baseline.txt b/config/render-path-translate-baseline.txt index 0a7b19061a2..2da76433302 100644 --- a/config/render-path-translate-baseline.txt +++ b/config/render-path-translate-baseline.txt @@ -2,7 +2,7 @@ # This is a RATCHET: counts may only go DOWN. Use useTranslate()/useIntlLocale() from # @/i18n/use-translate. Prune after a fix: pnpm check:render-path-translate-ratchet --prune 2 src/renderer/src/components/agent/AgentLaunchPromptComposer.tsx -5 src/renderer/src/components/automations/use-external-automation-actions.ts +5 src/renderer/src/components/automations/external/use-external-automation-actions.ts 1 src/renderer/src/components/diff-comments/useDiffCommentDecorator.tsx 2 src/renderer/src/components/editor/markdown-preview/render-tree/use-markdown-preview-components.tsx 1 src/renderer/src/components/tab-group/useTabGroupCreationCommands.ts diff --git a/config/scripts/build/mobile-web-app/build-mobile-web-app-bundle.mjs b/config/scripts/build/mobile-web-app/build-mobile-web-app-bundle.mjs index 605d2ac7816..4b1a1d008b8 100644 --- a/config/scripts/build/mobile-web-app/build-mobile-web-app-bundle.mjs +++ b/config/scripts/build/mobile-web-app/build-mobile-web-app-bundle.mjs @@ -1,4 +1,4 @@ -import { readFile } from 'node:fs/promises' +import { readFile, readdir } from 'node:fs/promises' import { readRouteSnapshot } from '../../mobile-web-app/mobile-web-app-route-snapshot.mjs' import { MOBILE_WEB_APP_DEPENDENCY_PATH } from '../../mobile-web-app/mobile-web-app-bundle-dependencies.mjs' import { existsSync, realpathSync } from 'node:fs' @@ -457,6 +457,32 @@ export async function mobileWebAppModuleClosure(entryModules, { absWorkingDir } // One lazily imported chunk per UI language; the page fetches only the active one after init. const LOCALE_CATALOG_INPUT = /(^|\/)src\/i18n\/locales\/[^/]+\.json$/ +const localeCatalogDir = join(mobileDir, 'src', 'i18n', 'locales') + +// The same catalogs as JSON for the host to serve one at a time, to shells that skip the chunks; +// English is the page's inline fallback, so it has none. +export async function readLocaleCatalogs(directory = localeCatalogDir) { + const names = (await readdir(directory)) + .filter((name) => name.endsWith('.json') && name !== 'en.json') + .sort() + return Promise.all( + names.map(async (name) => { + // Minify: the host sends and the phone keeps the parsed object, not the source layout. + const bytes = Buffer.from( + JSON.stringify(JSON.parse(await readFile(join(directory, name), 'utf8'))), + 'utf8' + ) + const sha256 = sha256Hex(bytes) + return { + locale: name.slice(0, -'.json'.length), + bytes, + path: `catalogs/${sha256}.json`, + sha256, + byteLength: bytes.byteLength + } + }) + ) +} function localeCatalogOutputs(metafile) { return new Set( @@ -586,11 +612,13 @@ export async function buildMobileWebAppBundle({ desktopVersion, protocolWindow, { script, chunks, images, catalogChunks, entryStaticBytes, chunkCount, routeChunks, routeKeys }, + catalogs, scrollbarStyle ] = await Promise.all([ readDesktopVersion(), readProtocolWindow(), bundleMobileWebApp({ appDir }), + readLocaleCatalogs(), readFile(join(projectDir, 'src/shared/styles/scrollbar-sleek.css'), 'utf8').then((style) => // The shared desktop stylesheet can be checked out as CRLF on Windows. style.replace(/\r\n/g, '\n') @@ -598,9 +626,14 @@ export async function buildMobileWebAppBundle({ ]) // Names already hash final bytes, so hashedAsset must reproduce them. const scriptAsset = hashedAsset(script, 'js') + const catalogChunkSet = new Set(catalogChunks) const written = [ scriptAsset, - ...[...chunks, ...images].map(({ name, bytes }) => hashedAsset(bytes, extname(name).slice(1))) + ...[...chunks, ...images].map((output) => ({ + ...hashedAsset(output.bytes, extname(output.name).slice(1)), + // Shells that read catalogs from the host skip these; older shells download them as before. + ...(catalogChunkSet.has(output) ? { kind: 'catalog' } : {}) + })) ] // Root-absolute URLs survive nested routes; CSP allows only about: base. ESM entry/chunks load under existing self policy. @@ -624,6 +657,7 @@ export async function buildMobileWebAppBundle({ const { manifest } = await writeMobileWebBundleTree({ outDir, written: [indexAsset, ...written], + catalogs, desktopVersion, protocolWindow, routes: resolveMobileWebPageRoutes(routeKeys, pageRoutes), diff --git a/config/scripts/build/mobile-web-app/mobile-web-bundle-manifest.mjs b/config/scripts/build/mobile-web-app/mobile-web-bundle-manifest.mjs index 4504d345fd4..ad84a39bd02 100644 --- a/config/scripts/build/mobile-web-app/mobile-web-bundle-manifest.mjs +++ b/config/scripts/build/mobile-web-app/mobile-web-bundle-manifest.mjs @@ -133,6 +133,8 @@ async function compressWithBrotli(written) { export async function writeMobileWebBundleTree({ outDir, written, + // Host-only JSON outside `assets` and buildId, served one at a time over RPC. + catalogs = [], desktopVersion, protocolWindow, // Empty route list makes shell render every screen natively. @@ -143,14 +145,15 @@ export async function writeMobileWebBundleTree({ }) { const brotliCopies = brotli ? await compressWithBrotli(written) : new Map() const assets = written - .map(({ path, sha256, byteLength, contentType }) => { + .map(({ path, sha256, byteLength, contentType, kind }) => { const copy = brotliCopies.get(path) return { path, sha256, byteLength, contentType, - ...(copy === undefined ? {} : { brotliByteLength: copy.byteLength }) + ...(copy === undefined ? {} : { brotliByteLength: copy.byteLength }), + ...(kind === undefined ? {} : { kind }) } }) .sort((left, right) => (left.path < right.path ? -1 : left.path > right.path ? 1 : 0)) @@ -164,14 +167,27 @@ export async function writeMobileWebBundleTree({ entrypoint: MOBILE_WEB_BUNDLE_ENTRYPOINT, totalBytes: assets.reduce((total, asset) => total + asset.byteLength, 0), assets, - routes + routes, + ...(catalogs.length === 0 + ? {} + : { + catalogs: catalogs.map(({ locale, path, sha256, byteLength }) => ({ + locale, + path, + sha256, + byteLength + })) + }) } // Clear entire output or stale unreferenced assets ship inside asar. await rm(outDir, { recursive: true, force: true }) await mkdir(join(outDir, 'assets'), { recursive: true }) - for (const asset of written) { - await writeFile(join(outDir, asset.path), asset.bytes) + if (catalogs.length > 0) { + await mkdir(join(outDir, 'catalogs'), { recursive: true }) + } + for (const file of [...written, ...catalogs]) { + await writeFile(join(outDir, file.path), file.bytes) } for (const [path, copy] of brotliCopies) { await writeFile(join(outDir, mobileWebBundleBrotliPath(path)), copy) diff --git a/config/scripts/build/mobile-web-app/verify-mobile-web-app-bundle.mjs b/config/scripts/build/mobile-web-app/verify-mobile-web-app-bundle.mjs index b853a7d7a88..b6832054702 100644 --- a/config/scripts/build/mobile-web-app/verify-mobile-web-app-bundle.mjs +++ b/config/scripts/build/mobile-web-app/verify-mobile-web-app-bundle.mjs @@ -29,6 +29,8 @@ export function mobileWebAppBundleMaxAssets(routeCount, imageCount, catalogChunk // fetched only for the active language, never before the first route. Code keeps its own fence. export const MOBILE_WEB_APP_BUNDLE_MAX_CATALOG_CHUNKS = 10 export const MOBILE_WEB_APP_BUNDLE_MAX_CATALOG_BYTES = 3 * 1024 * 1024 +// The host sends a catalog's JSON in one reply, which must fit a 1 MiB relay frame once encrypted. +export const MOBILE_WEB_APP_HOST_CATALOG_MAX_BYTES = 384 * 1024 // Our own fence on the page's code, well inside the phone contract (32 MiB total, 10 MiB per asset in // manifest-contract.ts); it fails the build before the code weighs more than any one asset may. @@ -185,6 +187,23 @@ export async function verifyMobileWebAppBundle({ bundleDir = defaultBundleDir } `${String(MOBILE_WEB_APP_BUNDLE_MAX_CATALOG_BYTES)} bytes` ) } + // buildId leaves the host's JSON catalogs out, so a stale copy shows only here. + const hostCatalogsOf = (built) => JSON.stringify(built.catalogs ?? []) + if (hostCatalogsOf(first.manifest) !== hostCatalogsOf(second.manifest)) { + fail('host language catalogs are not reproducible') + } + if (hostCatalogsOf(first.manifest) !== hostCatalogsOf(manifest)) { + fail(`${bundleDir} is stale: its host language catalogs differ from a fresh build's`) + } + const oversized = (manifest.catalogs ?? []).find( + (catalog) => catalog.byteLength > MOBILE_WEB_APP_HOST_CATALOG_MAX_BYTES + ) + if (oversized) { + fail( + `the ${oversized.locale} host catalog is ${String(oversized.byteLength)} bytes, over the ` + + `${String(MOBILE_WEB_APP_HOST_CATALOG_MAX_BYTES)} one reply carries` + ) + } const budgetBytes = mobileWebAppBundleBudgetBytes(manifest) - first.catalogBytes if (budgetBytes > MOBILE_WEB_APP_BUNDLE_MAX_TOTAL_BYTES) { fail( diff --git a/config/scripts/ci/sharding/ci-shard-timings.json b/config/scripts/ci/sharding/ci-shard-timings.json index 8df31614436..aaa18a61795 100644 --- a/config/scripts/ci/sharding/ci-shard-timings.json +++ b/config/scripts/ci/sharding/ci-shard-timings.json @@ -4641,9 +4641,6 @@ "src/renderer/src/components/JiraIssueWorkspace.optimistic-edit.test.tsx": 2340, "src/renderer/src/components/JiraIssueWorkspace.status-queue.test.tsx": 1852, "src/renderer/src/components/JiraIssueWorkspace.transition-source.test.tsx": 1843, - "src/renderer/src/components/NativeChatRemoteResume.test.tsx": 8774, - "src/renderer/src/components/NativeChatResumeOnRestartGroups.selection.test.tsx": 2633, - "src/renderer/src/components/NativeChatResumeOnRestartGroups.test.tsx": 3472, "src/renderer/src/components/NewWorkspaceComposerCard.quick-file-drop.test.tsx": 4557, "src/renderer/src/components/NewWorkspaceComposerCard.set-location.test.tsx": 1301, "src/renderer/src/components/QuickOpen.selection.test.tsx": 1046, @@ -4675,53 +4672,44 @@ "src/renderer/src/components/artifacts/ArtifactPublishButton.test.tsx": 706, "src/renderer/src/components/artifacts/ArtifactsPage.test.tsx": 2052, "src/renderer/src/components/artifacts/artifact-publish-flow.test.ts": 114, - "src/renderer/src/components/automations/AutomationEditorPromptEditor.test.tsx": 396, + "src/renderer/src/components/automations/authoring/AutomationEditorPromptEditor.test.tsx": 396, "src/renderer/src/components/automations/AutomationPromptDisclosure.test.tsx": 893, "src/renderer/src/components/automations/AutomationRunsTable.test.tsx": 668, - "src/renderer/src/components/automations/AutomationSchedulePicker.test.ts": 431, - "src/renderer/src/components/automations/AutomationTimeField.test.tsx": 654, + "src/renderer/src/components/automations/authoring/AutomationSchedulePicker.test.ts": 431, + "src/renderer/src/components/automations/AutomationsPage.behavior.test.tsx": 3389, "src/renderer/src/components/automations/AutomationsPage.edit-destination.test.tsx": 2932, - "src/renderer/src/components/automations/AutomationsPage.run-navigation.test.tsx": 3056, + "src/renderer/src/components/automations/ExternalAutomationManagers.test.tsx": 852, - "src/renderer/src/components/automations/automation-captured-owner.test.ts": 379, - "src/renderer/src/components/automations/automation-create-projects.test.ts": 42, + "src/renderer/src/components/automations/hosts/automation-captured-owner.test.ts": 379, "src/renderer/src/components/automations/automation-host-cache-controller.test.ts": 411, - "src/renderer/src/components/automations/automation-host-cache-error.test.ts": 391, - "src/renderer/src/components/automations/automation-host-cache-health.test.ts": 52, - "src/renderer/src/components/automations/automation-host-cache.test.ts": 79, - "src/renderer/src/components/automations/automation-host-catalog-generation.test.ts": 258, - "src/renderer/src/components/automations/automation-host-client.test.ts": 374, + "src/renderer/src/components/automations/hosts/automation-host-cache.test.ts": 79, + "src/renderer/src/components/automations/automation-host-diagnostics.test.ts": 460, - "src/renderer/src/components/automations/automation-host-filter-resolution.test.ts": 256, - "src/renderer/src/components/automations/automation-host-health.test.ts": 47, + "src/renderer/src/components/automations/automation-host-invalidation-window-events.test.ts": 83, "src/renderer/src/components/automations/automation-host-invalidation.test.ts": 85, - "src/renderer/src/components/automations/automation-host-list-rows.test.ts": 419, - "src/renderer/src/components/automations/automation-host-recovery.test.ts": 51, + "src/renderer/src/components/automations/hosts/automation-host-list-rows.test.ts": 419, "src/renderer/src/components/automations/automation-host-scale-gates.test.ts": 638, - "src/renderer/src/components/automations/automation-host-scheduler.test.ts": 439, - "src/renderer/src/components/automations/automation-legacy-schedule-editing.test.ts": 449, - "src/renderer/src/components/automations/automation-list-focus-recovery.test.ts": 48, - "src/renderer/src/components/automations/automation-list-row-identity.test.ts": 626, - "src/renderer/src/components/automations/automation-list-search.test.ts": 75, + "src/renderer/src/components/automations/hosts/automation-host-scheduler.test.ts": 439, + "src/renderer/src/components/automations/authoring/automation-legacy-schedule-editing.test.ts": 449, + "src/renderer/src/components/automations/automation-list-view.test.ts": 257, - "src/renderer/src/components/automations/automation-run-context.test.ts": 58, - "src/renderer/src/components/automations/automation-run-history-keyboard-navigation.test.ts": 434, - "src/renderer/src/components/automations/automation-run-open-target.test.ts": 442, + "src/renderer/src/components/automations/runs/automation-run-history-keyboard-navigation.test.ts": 434, + "src/renderer/src/components/automations/runs/automation-run-open-target.test.ts": 442, "src/renderer/src/components/automations/automation-run-output-snapshot-equivalence.test.ts": 158, "src/renderer/src/components/automations/automation-run-output-snapshot.test.ts": 96, - "src/renderer/src/components/automations/automation-setup-decision.test.ts": 58, + "src/renderer/src/components/automations/authoring/automation-setup-decision.test.ts": 58, "src/renderer/src/components/automations/automation-usage-model.test.ts": 200, "src/renderer/src/components/automations/external-automation-list-entries.test.ts": 57, - "src/renderer/src/components/automations/external-automation-scope-gating.test.ts": 67, + "src/renderer/src/components/automations/external/external-automation-scope-gating.test.ts": 67, "src/renderer/src/components/automations/external-automation-scope-keys.test.ts": 53, - "src/renderer/src/components/automations/use-automation-host-catalog-readoption.test.tsx": 802, - "src/renderer/src/components/automations/use-automation-host-catalog.test.tsx": 920, - "src/renderer/src/components/automations/use-automation-list-focus-recovery.test.tsx": 229, - "src/renderer/src/components/automations/use-automation-list-search.test.tsx": 679, - "src/renderer/src/components/automations/use-automation-runs-dashboard-payload.test.tsx": 6692, - "src/renderer/src/components/automations/use-automation-runs-dashboard.test.tsx": 854, + "src/renderer/src/components/automations/hosts/use-automation-host-catalog-readoption.test.tsx": 802, + "src/renderer/src/components/automations/hosts/use-automation-host-catalog.test.tsx": 920, + + "src/renderer/src/components/automations/listing/use-automation-list-search.test.tsx": 679, + "src/renderer/src/components/automations/runs/use-automation-runs-dashboard-payload.test.tsx": 6692, + "src/renderer/src/components/automations/runs/use-automation-runs-dashboard.test.tsx": 854, "src/renderer/src/components/automations/use-selected-automation-run-history.test.tsx": 2104, "src/renderer/src/components/browser-favicon.test.tsx": 333, "src/renderer/src/components/browser-pane/ClientHostedBrowserPagePane.dead-guest.test.tsx": 6219, @@ -5135,15 +5123,9 @@ "src/renderer/src/components/mobile/WindowsFirewallNotice.test.tsx": 691, "src/renderer/src/components/mobile/paired-mobile-devices.test.ts": 192, "src/renderer/src/components/mobile/use-mobile-page-paired-devices.test.ts": 475, - "src/renderer/src/components/native-chat-launch-resume-decision.test.tsx": 1844, - "src/renderer/src/components/native-chat-resume-bulk-progress.test.tsx": 3261, - "src/renderer/src/components/native-chat-resume-failed-chat-watch.test.ts": 1954, - "src/renderer/src/components/native-chat-resume-failure-guidance.test.ts": 240, - "src/renderer/src/components/native-chat-resume-finished-run.test.tsx": 4173, - "src/renderer/src/components/native-chat-resume-on-restart-grouping.test.ts": 117, - "src/renderer/src/components/native-chat-resume-result-view.test.tsx": 2723, - "src/renderer/src/components/native-chat-resume-run.test.ts": 65, - "src/renderer/src/components/native-chat-resume-skipped-progress.test.tsx": 3009, + "src/renderer/src/components/native-chat-recovery/integration/native-chat-resume-bulk-progress.test.tsx": 3261, + "src/renderer/src/components/native-chat-recovery/offers/native-chat-resume-failed-chat-watch.test.ts": 1954, + "src/renderer/src/components/native-chat-recovery/integration/native-chat-resume-finished-run.test.tsx": 4173, "src/renderer/src/components/native-chat/messages/rows/NativeChatAgentMessageCard.test.tsx": 3700, "src/renderer/src/components/native-chat/tools/tasks/NativeChatBackgroundTaskRun.test.tsx": 242, "src/renderer/src/components/native-chat/tools/tasks/NativeChatBackgroundTasksStatus.test.tsx": 782, @@ -5155,7 +5137,7 @@ "src/renderer/src/components/native-chat/attachments/chips/NativeChatImageAttachmentPreview.test.tsx": 2818, "src/renderer/src/components/native-chat/media/visuals/NativeChatInlineVisual.link-placement.test.tsx": 2477, "src/renderer/src/components/native-chat/prompts/NativeChatInteractiveCard.test.tsx": 2881, - "src/renderer/src/components/native-chat/usage/NativeChatInterruptedContinue.test.tsx": 2719, + "src/renderer/src/components/native-chat/viewport/scroll/NativeChatJumpToLatest.test.tsx": 477, "src/renderer/src/components/native-chat/markdown/code/NativeChatMarkdown.code-wrap.test.tsx": 3123, "src/renderer/src/components/native-chat/media/images/NativeChatMarkdown.image-preview.test.tsx": 4346, @@ -5195,9 +5177,7 @@ "src/renderer/src/components/native-chat/selection-quotes/NativeChatSelectionQuote.test.tsx": 2370, "src/renderer/src/components/native-chat/surfaces/integration/NativeChatStructuredSession.approval-and-start-failure.test.tsx": 2922, "src/renderer/src/components/native-chat/surfaces/integration/NativeChatStructuredSession.availability-notice.test.tsx": 2764, - "src/renderer/src/components/native-chat/surfaces/integration/NativeChatStructuredSession.history-read-state.test.tsx": 4919, "src/renderer/src/components/native-chat/surfaces/integration/NativeChatStructuredSession.host-outage.test.tsx": 3552, - "src/renderer/src/components/native-chat/surfaces/integration/NativeChatStructuredSession.notice-card.test.tsx": 2911, "src/renderer/src/components/native-chat/surfaces/integration/NativeChatStructuredSession.refusal-notices.test.tsx": 3014, "src/renderer/src/components/native-chat/surfaces/integration/NativeChatStructuredSession.test.tsx": 4459, "src/renderer/src/components/native-chat/tools/tasks/NativeChatStructuredSessionStatus.test.tsx": 583, @@ -5241,7 +5221,6 @@ "src/renderer/src/components/native-chat/composer/focus/native-chat-composer-reveal-focus.test.tsx": 526, "src/renderer/src/components/native-chat/attachments/intake/native-chat-composer-workspace-file-drop.test.tsx": 1166, "src/renderer/src/components/native-chat/drafts/native-chat-draft-retention.test.ts": 1415, - "src/renderer/src/components/native-chat/attachments/intake/native-chat-element-file-drop.test.tsx": 2057, "src/renderer/src/components/native-chat/attachments/intake/native-chat-external-attachments-destination.test.tsx": 951, "src/renderer/src/components/native-chat/links/actions/native-chat-file-link-existence.test.ts": 1937, "src/renderer/src/components/native-chat/pane/actions/native-chat-header-ownership.test.tsx": 2796, @@ -5256,7 +5235,6 @@ "src/renderer/src/components/native-chat/native-chat-new-rows-marker.test.tsx": 581, "src/renderer/src/components/native-chat/pane/routing/native-chat-open-wake.test.ts": 1807, "src/renderer/src/components/native-chat/pane/ownership/native-chat-owner-selectors.test.tsx": 525, - "src/renderer/src/components/native-chat/attachments/intake/native-chat-pane-file-drop.test.tsx": 439, "src/renderer/src/components/native-chat/paste/native-chat-paste-routing.test.tsx": 2417, "src/renderer/src/components/native-chat/session/terminal/delivery/native-chat-pending.test.ts": 273, "src/renderer/src/components/native-chat/composer/editor/native-chat-prompt-document-text.test.ts": 219, @@ -5495,10 +5473,7 @@ "src/renderer/src/components/right-sidebar/hosted-review/provider-actions/useHostedReviewStackParent.test.tsx": 288, "src/renderer/src/components/right-sidebar/source-control/listing/useSourceControlSubmoduleStatus.test.tsx": 2076, "src/renderer/src/components/settings/accounts/AccountsPane.owner-scope.test.tsx": 4057, - "src/renderer/src/components/skills/setup/AgentSkillSetupPanel.freshness.test.tsx": 15418, - "src/renderer/src/components/skills/setup/AgentSkillSetupPanel.plan-status.test.tsx": 23334, - "src/renderer/src/components/skills/setup/AgentSkillSetupPanel.remote-availability.test.tsx": 5937, - "src/renderer/src/components/skills/setup/AgentSkillSetupPanel.test.tsx": 2315, + "src/renderer/src/components/settings/agents/AgentsPane.test.tsx": 3230, "src/renderer/src/components/settings/accounts/providers/AntigravityAccountsSection.test.tsx": 2722, "src/renderer/src/components/settings/appearance/chat/AppearanceChatContrastControls.draft.test.tsx": 795, @@ -5509,7 +5484,7 @@ "src/renderer/src/components/settings/chat/ChatPermissionSetting.test.tsx": 834, "src/renderer/src/components/settings/chat/ChatSettingsSection.navigation.test.tsx": 2540, "src/renderer/src/components/settings/chat/ChatSettingsSection.test.tsx": 2718, - "src/renderer/src/lib/skill-runtime-command.test.ts": 1670, + "src/renderer/src/lib/skills/runtime/skill-runtime-command.test.ts": 1670, "src/renderer/src/components/settings/virtual-machines/recipes/EphemeralVmsPane.test.tsx": 1025, "src/renderer/src/components/settings/accounts/sign-in/HostAccountSignInPrompt.test.tsx": 309, "src/renderer/src/components/settings/agents/launch/HostAgentLaunchSettings.test.tsx": 7498, @@ -5540,7 +5515,6 @@ "src/renderer/src/components/settings/developer-permissions/TerminalTccAttributionNotice.test.tsx": 401, "src/renderer/src/components/settings/voice/VoiceMicrophoneSetting.test.tsx": 957, "src/renderer/src/components/settings/voice/VoicePane.test.tsx": 1042, - "src/renderer/src/components/settings/voice/VoiceSpeechModelSection.test.tsx": 503, "src/renderer/src/components/settings/accounts/sign-in/account-add-cancel-target.test.ts": 217, "src/renderer/src/components/settings/accounts/usage/accounts-pane-opencode-credentials.test.ts": 519, "src/renderer/src/lib/agent-session/launch/agent-settings-update-queue.test.ts": 249, @@ -5690,22 +5664,18 @@ "src/renderer/src/components/sidebar/workspace-actions/parenting/worktree-parent-eligibility.test.ts": 68, "src/renderer/src/components/sidebar/worktree-list/listing/worktree-sort-label-ordering.test.ts": 114, "src/renderer/src/components/sidebar/wsl-host-offer-move.test.ts": 227, - "src/renderer/src/components/skills/SkillFreshnessUpdateDialog.test.tsx": 913, - "src/renderer/src/components/skills/SkillInstallDialog.test.tsx": 4429, - "src/renderer/src/components/skills/SkillInstallManagementDialog.test.tsx": 3300, - "src/renderer/src/components/skills/SkillSharedLinkRow.test.tsx": 817, + + "src/renderer/src/components/skills/installation/SkillInstallManagementDialog.test.tsx": 3300, + "src/renderer/src/components/skills/sharing/SkillSharedLinkRow.test.tsx": 817, "src/renderer/src/components/skills/SkillsPage.test.tsx": 3822, - "src/renderer/src/components/skills/skill-agent-filter.test.ts": 274, - "src/renderer/src/components/skills/skill-share-link.test.ts": 55, - "src/renderer/src/components/skills/skill-share-package-selection.test.ts": 49, - "src/renderer/src/components/skills/skills-filter.test.ts": 204, + "src/renderer/src/components/skills/catalog/skill-agent-filter.test.ts": 274, + "src/renderer/src/components/sparse/sparse-directory-entry-input.test.ts": 207, "src/renderer/src/components/stats/usage-daily-chart.test.tsx": 333, "src/renderer/src/components/stats/usage-overview-model.test.ts": 364, "src/renderer/src/components/status-bar/ClaudeSwitcherMenu.owner-lifetime.test.tsx": 2317, - "src/renderer/src/components/status-bar/NativeChatResumeStatusSegment.test.tsx": 2452, "src/renderer/src/components/status-bar/PortsStatusSegment.render-stability.test.tsx": 2161, - "src/renderer/src/components/status-bar/SkillUpdateStatusSegment.test.tsx": 594, + "src/renderer/src/components/status-bar/SshStatusSegment.large-host-list.test.tsx": 1838, "src/renderer/src/components/status-bar/StatusBarUsageChangeNotices.test.tsx": 785, "src/renderer/src/components/status-bar/UpdateStatusSegment.test.tsx": 2484, @@ -6172,8 +6142,7 @@ "src/renderer/src/hooks/editor-external-watch-overflow.test.ts": 1023, "src/renderer/src/hooks/editor-external-watch-selected-host.test.ts": 1988, "src/renderer/src/hooks/editor-runtime-file-watch.test.ts": 58, - "src/renderer/src/hooks/installed-agent-skill-discovery-cache.test.ts": 53, - "src/renderer/src/hooks/installed-agent-skill-discovery.test.ts": 74, + "src/renderer/src/hooks/ipc-events/agent-status-pane-routing-index-retention.test.ts": 4878, "src/renderer/src/hooks/ipc-events/agent-status-pending-retry-gate.test.ts": 466, "src/renderer/src/hooks/ipc-events/agent-status-terminal-title-tab-write.test.ts": 2247, @@ -6210,7 +6179,7 @@ "src/renderer/src/hooks/runtime-project-refresh-scheduler.test.ts": 65, "src/renderer/src/hooks/shortcut-label-cache.test.tsx": 2021, "src/renderer/src/hooks/unpaired-device-auth-notification.test.ts": 41, - "src/renderer/src/hooks/use-bundled-skill-install.test.tsx": 553, + "src/renderer/src/hooks/use-document-dark-theme.test.tsx": 350, "src/renderer/src/hooks/use-list-multi-selection.test.tsx": 545, "src/renderer/src/hooks/use-monaco-theme.test.tsx": 323, @@ -6236,7 +6205,7 @@ "src/renderer/src/hooks/useEphemeralVmRecipeOptions.test.tsx": 415, "src/renderer/src/hooks/useGitHubSlugMetadata.assignee-reuse.test.tsx": 233, "src/renderer/src/hooks/useImmediateMutation.test.ts": 618, - "src/renderer/src/hooks/useInstalledAgentSkills.react.test.tsx": 2093, + "src/renderer/src/hooks/skills/discovery/useInstalledAgentSkills.react.test.tsx": 2093, "src/renderer/src/hooks/useIpcEvents-agent-status-connection-attribution.test.ts": 5510, "src/renderer/src/hooks/useIpcEvents-agent-status-hook-titles.test.ts": 5621, "src/renderer/src/hooks/useIpcEvents-agent-status-pane-teardown.test.ts": 5268, @@ -6268,7 +6237,7 @@ "src/renderer/src/hooks/useReadOnScreenAttention.mixed-workspace.test.ts": 1725, "src/renderer/src/hooks/useReadOnScreenAttention.test.ts": 1915, "src/renderer/src/hooks/useRetiredWorktreeNames.test.ts": 593, - "src/renderer/src/hooks/useSkillFreshness.test.tsx": 554, + "src/renderer/src/hooks/useUnreadDockBadge.test.ts": 2126, "src/renderer/src/hooks/virtualized-hidden-row-measurement.test.ts": 199, "src/renderer/src/hooks/worktree-change-refresh-queue.test.ts": 59, @@ -6347,7 +6316,7 @@ "src/renderer/src/lib/browser/navigation/browser-link-profile-isolation.test.ts": 2511, "src/renderer/src/lib/browser/palette/browser-page-palette-activation.test.ts": 1983, "src/renderer/src/lib/browser/palette/browser-palette-page-entries.test.ts": 480, - "src/renderer/src/lib/bundled-skill-target.test.ts": 54, + "src/renderer/src/lib/skills/runtime/bundled-skill-target.test.ts": 54, "src/renderer/src/lib/source-control/checks/check-run-details-log-normalization-performance.test.ts": 846, "src/renderer/src/lib/source-control/checks/check-run-details-log-normalization.test.ts": 75, "src/renderer/src/lib/claude-account-switch-sessions.test.ts": 782, @@ -6378,15 +6347,12 @@ "src/renderer/src/runtime/hosts/platform/execution-host-facts.test.ts": 1796, "src/renderer/src/lib/feature-education-telemetry.test.ts": 52, "src/renderer/src/lib/feedback-image-attachments.test.ts": 557, - "src/renderer/src/lib/browser/documents/file-preview-link-open.test.ts": 2311, "src/renderer/src/lib/file-search-selection.test.ts": 51, "src/renderer/src/lib/find-query-bounds.test.ts": 45, "src/renderer/src/lib/finished-agent-resume-resurrection.test.ts": 1872, "src/renderer/src/lib/focus-terminal-tab-surface.split-focus.test.ts": 331, "src/renderer/src/lib/foreground-terminal-tabs.test.ts": 55, - "src/shared/new-workspace/github-links.test.ts": 76, "src/renderer/src/lib/work-items/github/github-source-runtime-context.test.ts": 62, - "src/shared/new-workspace/gitlab-links.test.ts": 56, "src/renderer/src/lib/hook-command-delayed-delivery.test.ts": 1904, "src/renderer/src/lib/host-chat-program.test.ts": 2419, "src/renderer/src/lib/host-mirror-handle-gap-drain.test.ts": 1706, @@ -6827,7 +6793,6 @@ "src/renderer/src/store/slices/editor/git/editor-git-status-reconciliation.test.ts": 870, "src/renderer/src/store/slices/editor/tabs/editor-layout-owner-records.test.ts": 2006, "src/renderer/src/store/slices/editor/markdown/editor-markdown-link-activation.test.ts": 953, - "src/renderer/src/store/slices/editor/markdown/editor-markdown-view-state.test.ts": 801, "src/renderer/src/store/slices/editor/git/editor-open-diff.test.ts": 1987, "src/renderer/src/store/slices/editor/tabs/editor-open-link-placement.test.ts": 1987, "src/renderer/src/store/slices/editor/tabs/editor-preview-tab-setting.test.ts": 1952, @@ -7996,7 +7961,7 @@ "tests/e2e/ai-vault-account-stream.unit.test.ts": 4506, "tests/e2e/ai-vault-manual-name-clear.unit.test.ts": 21206, "tests/e2e/automation-chat-reopen.unit.test.ts": 6262, - "tests/e2e/automation-save-fallback.unit.test.ts": 9065, + "tests/e2e/claude-agent-row-view.unit.test.ts": 1491, "tests/e2e/codex-child-approval-activity-row.unit.test.ts": 14886, "tests/e2e/completed-worker-retirement-resume.unit.test.ts": 38857, @@ -8032,7 +7997,7 @@ "tests/e2e/host-agent-launch-preferences-work.unit.test.ts": 3882, "tests/e2e/host-agent-launch-settings-hook-bookkeeping.unit.test.ts": 21972, "tests/e2e/host-cold-park-remote-subscriber.unit.test.ts": 5314, - "tests/e2e/journal-restored-consumers.unit.test.ts": 33933, + "tests/e2e/launch-agent-background-session-remote.unit.test.ts": 1016, "tests/e2e/launch-agent-in-new-tab-web-runtime.unit.test.ts": 14288, "tests/e2e/linear-cli-recovery.unit.test.ts": 7592, @@ -8044,7 +8009,7 @@ "tests/e2e/native-chat-rewind-boundary.unit.test.ts": 2977, "tests/e2e/native-chat-ssh-transcript.unit.test.ts": 1166, "tests/e2e/native-chat-startup-option-pickers.unit.test.ts": 9377, - "tests/e2e/native-chat-transcript-file-order.unit.test.ts": 1066, + "tests/e2e/native-chat-transcript-reasoning.unit.test.ts": 3341, "tests/e2e/nested-agent-idle-owner.unit.test.ts": 2469, "tests/e2e/omp-child-session-recovery.unit.test.ts": 2205, diff --git a/config/scripts/desktop-distribution/runtime-verification/verify-packaged-mobile-web-bundle.cjs b/config/scripts/desktop-distribution/runtime-verification/verify-packaged-mobile-web-bundle.cjs index 769e1c90235..46370dc1d46 100644 --- a/config/scripts/desktop-distribution/runtime-verification/verify-packaged-mobile-web-bundle.cjs +++ b/config/scripts/desktop-distribution/runtime-verification/verify-packaged-mobile-web-bundle.cjs @@ -106,6 +106,19 @@ function parseManifest(bundleDir) { } } } + if (manifest.catalogs !== undefined && !Array.isArray(manifest.catalogs)) { + throw failure('manifest catalogs is not a list') + } + for (const catalog of manifest.catalogs ?? []) { + if (typeof catalog !== 'object' || catalog === null || typeof catalog.locale !== 'string') { + throw failure('manifest catalog entry has no locale') + } + assertSafeRelativePath(catalog.path) + if (typeof catalog.sha256 !== 'string' || !SHA256_PATTERN.test(catalog.sha256)) { + throw failure(`manifest catalog ${catalog.path} has no sha256 digest`) + } + assertInteger(catalog.byteLength, `catalogs[${catalog.path}].byteLength`) + } if (!manifest.assets.some((asset) => asset.path === manifest.entrypoint)) { throw failure(`manifest entrypoint ${manifest.entrypoint} is not one of its assets`) } @@ -126,6 +139,11 @@ function parseManifest(bundleDir) { return manifest } +// Assets go to the phone; catalogs stay on the host, which serves one on request. +function servedFiles(manifest) { + return [...manifest.assets, ...(manifest.catalogs ?? [])] +} + function listBundleFiles(directory, prefix = '') { const found = [] for (const entry of readdirSync(directory, { withFileTypes: true })) { @@ -164,7 +182,7 @@ function assertNoUnlistedFiles(bundleDir, manifest) { const listed = new Set([ 'manifest.json', ...darkBuildMarkerFileNames(), - ...manifest.assets.map((asset) => asset.path), + ...servedFiles(manifest).map((file) => file.path), ...brotliCopies(manifest).map((asset) => brotliPath(asset)) ]) const strays = listBundleFiles(bundleDir).filter((path) => !listed.has(path)) @@ -180,7 +198,7 @@ function assertNoUnlistedFiles(bundleDir, manifest) { function assertMobileWebBundleBuilt(bundleDir = MOBILE_WEB_BUNDLE_DIR) { const manifest = parseManifest(bundleDir) assertNoUnlistedFiles(bundleDir, manifest) - for (const asset of manifest.assets) { + for (const asset of servedFiles(manifest)) { const assetPath = join(bundleDir, asset.path) const size = statSize(bundleDir, asset.path) if (size !== asset.byteLength) { diff --git a/config/scripts/localization/source-extraction/audit-localization-coverage.mjs b/config/scripts/localization/source-extraction/audit-localization-coverage.mjs index 6eaef1bb1b0..cd7cf997a7b 100644 --- a/config/scripts/localization/source-extraction/audit-localization-coverage.mjs +++ b/config/scripts/localization/source-extraction/audit-localization-coverage.mjs @@ -6,10 +6,11 @@ import process from 'node:process' // TypeScript 7 is a native CLI; AST consumers still need the legacy JavaScript API. import ts from 'typescript-api' import { isTestOnlySourcePath } from '../../static-analysis/process-boundaries/test-only-source-path.mjs' +import { isVisibleObjectKey } from './localization-visible-object-keys.mjs' const SOURCE_EXTENSIONS = new Set(['.ts', '.tsx', '.js', '.jsx', '.mts', '.cts']) const SKIP_PATH_PARTS = new Set(['.git', 'dist', 'node_modules', 'out', '__snapshots__', 'assets']) -const LOCALIZATION_CALL_NAMES = new Set(['t', 'translate']) +const LOCALIZATION_CALL_NAMES = new Set(['t', 'translate', 'translateMain']) const CLASS_PROPERTY_NAMES = new Set(['className', 'classNames']) // Why: the children of these elements are CSS or code, never copy a translator should see. const NON_COPY_JSX_ELEMENTS = new Set(['style', 'script']) @@ -35,25 +36,6 @@ const USER_VISIBLE_JSX_ATTRIBUTES = new Set([ 'toggleDescription', 'tooltip' ]) -const USER_VISIBLE_OBJECT_KEYS = new Set([ - 'accessibilityHint', - 'accessibilityLabel', - 'ariaLabel', - 'badge', - 'description', - 'emptyText', - 'error', - 'headerTitle', - 'helperText', - 'keywords', - 'label', - 'message', - 'placeholder', - 'subtitle', - 'title', - 'toggleDescription', - 'tooltip' -]) const USER_VISIBLE_FUNCTION_NAMES = new Set([ 'alert', 'confirm', @@ -331,7 +313,7 @@ function isInsideNonCopyJsxElement(node) { return Boolean(element && NON_COPY_JSX_ELEMENTS.has(element.openingElement.tagName.getText())) } -function classifyStringNode(node) { +function classifyStringNode(node, includeNativeDialogFields = false) { if ( hasAncestorObjectPropertyName(node, CLASS_PROPERTY_NAMES) || isInsideNonCopyJsxElement(node) @@ -369,12 +351,15 @@ function classifyStringNode(node) { } const objectPropertyName = nearestObjectPropertyName(node) - if (objectPropertyName && !USER_VISIBLE_OBJECT_KEYS.has(objectPropertyName)) { + if (objectPropertyName && !isVisibleObjectKey(objectPropertyName, includeNativeDialogFields)) { return undefined } const ancestorObjectPropertyName = nearestAncestorObjectPropertyName(node) - if (ancestorObjectPropertyName && !USER_VISIBLE_OBJECT_KEYS.has(ancestorObjectPropertyName)) { + if ( + ancestorObjectPropertyName && + !isVisibleObjectKey(ancestorObjectPropertyName, includeNativeDialogFields) + ) { return undefined } @@ -407,7 +392,12 @@ function areaForFile(relativePath) { return `renderer/${parts[0] ?? 'root'}` } -export function collectLocalizationCandidates(filePath, sourceText, root = process.cwd()) { +export function collectLocalizationCandidates( + filePath, + sourceText, + root = process.cwd(), + options = {} +) { const sourceKind = filePath.endsWith('.tsx') || filePath.endsWith('.jsx') ? ts.ScriptKind.TSX : ts.ScriptKind.TS const sourceFile = ts.createSourceFile( @@ -450,7 +440,7 @@ export function collectLocalizationCandidates(filePath, sourceText, root = proce ts.isNoSubstitutionTemplateLiteral(node) || ts.isTemplateExpression(node) ) { - const kind = classifyStringNode(node) + const kind = classifyStringNode(node, options.includeNativeDialogFields) if (kind) { for (const part of stringParts(node)) { pushReport(node, kind, part.text, part.dynamic) @@ -521,6 +511,7 @@ function parseArgs(argv) { allowlistPath: path.join('config', 'localization-coverage-allowlist.json'), check: false, format: 'summary', + includeNativeDialogFields: false, outputPath: null, sourceRoots: [] } @@ -531,6 +522,8 @@ function parseArgs(argv) { options.format = 'json' } else if (arg === '--markdown') { options.format = 'markdown' + } else if (arg === '--native-dialog-fields') { + options.includeNativeDialogFields = true } else if (arg === '--check') { options.check = true } else if (arg === '--allowlist') { @@ -616,7 +609,7 @@ export async function main(root = process.cwd(), argv = process.argv.slice(2)) { for (const filePath of files) { const sourceText = await fs.readFile(filePath, 'utf8') - reports.push(...collectLocalizationCandidates(filePath, sourceText, root)) + reports.push(...collectLocalizationCandidates(filePath, sourceText, root, options)) } if (options.check) { diff --git a/config/scripts/localization/source-extraction/audit-localization-native-dialogs.test.mjs b/config/scripts/localization/source-extraction/audit-localization-native-dialogs.test.mjs new file mode 100644 index 00000000000..be3dd5d8541 --- /dev/null +++ b/config/scripts/localization/source-extraction/audit-localization-native-dialogs.test.mjs @@ -0,0 +1,59 @@ +import { describe, expect, it, vi } from 'vitest' +import { mkdtemp, mkdir, rm, writeFile } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { collectLocalizationCandidates, main } from './audit-localization-coverage.mjs' + +const path = '/repo/src/main/startup/dialog.ts' +const source = ` + const options = { + message: translateMain('message', 'Translated message'), + detail: 'Untranslated detail', + buttons: ['Proceed', translateMain('cancel', 'Cancel')], + body: 'Untranslated body', + buttonLabel: 'Retry', + checkboxLabel: 'Remember choice' + } +` + +describe('native dialog localization coverage', () => { + it('finds untranslated native dialog fields while ignoring translated copy', () => { + const candidates = collectLocalizationCandidates(path, source, '/repo', { + includeNativeDialogFields: true + }) + expect(candidates.map(({ kind, text }) => [kind, text])).toEqual([ + ['object-property:detail', 'Untranslated detail'], + ['object-property:buttons', 'Proceed'], + ['object-property:body', 'Untranslated body'], + ['object-property:buttonLabel', 'Retry'], + ['object-property:checkboxLabel', 'Remember choice'] + ]) + }) + + it('does not change the existing renderer scan by default', () => { + expect(collectLocalizationCandidates(path, source, '/repo')).toEqual([]) + }) + + it('fails the opt-in check for a new native dialog literal', async () => { + const root = await mkdtemp(join(tmpdir(), 'orca-native-localization-')) + const report = vi.spyOn(console, 'error').mockImplementation(() => {}) + try { + await mkdir(join(root, 'src')) + await writeFile(join(root, 'src', 'dialog.ts'), "const options = { detail: 'Raw detail' }") + await writeFile(join(root, 'allowlist.json'), '[]') + await expect( + main(root, [ + '--check', + '--native-dialog-fields', + '--source-root', + 'src', + '--allowlist', + 'allowlist.json' + ]) + ).resolves.toBe(1) + } finally { + report.mockRestore() + await rm(root, { recursive: true, force: true }) + } + }) +}) diff --git a/config/scripts/localization/source-extraction/localization-visible-object-keys.mjs b/config/scripts/localization/source-extraction/localization-visible-object-keys.mjs new file mode 100644 index 00000000000..0e5b73ec6a9 --- /dev/null +++ b/config/scripts/localization/source-extraction/localization-visible-object-keys.mjs @@ -0,0 +1,33 @@ +const USER_VISIBLE_OBJECT_KEYS = new Set([ + 'accessibilityHint', + 'accessibilityLabel', + 'ariaLabel', + 'badge', + 'description', + 'emptyText', + 'error', + 'headerTitle', + 'helperText', + 'keywords', + 'label', + 'message', + 'placeholder', + 'subtitle', + 'title', + 'toggleDescription', + 'tooltip' +]) +const NATIVE_DIALOG_OBJECT_KEYS = new Set([ + 'detail', + 'buttons', + 'body', + 'buttonLabel', + 'checkboxLabel' +]) + +export function isVisibleObjectKey(name, includeNativeDialogFields) { + return ( + USER_VISIBLE_OBJECT_KEYS.has(name) || + (includeNativeDialogFields && NATIVE_DIALOG_OBJECT_KEYS.has(name)) + ) +} diff --git a/config/scripts/mobile-web-app/session/mobile-web-app-queued-messages-render.test.mjs b/config/scripts/mobile-web-app/session/mobile-web-app-queued-messages-render.test.mjs index caca85ce51a..864d07093c3 100644 --- a/config/scripts/mobile-web-app/session/mobile-web-app-queued-messages-render.test.mjs +++ b/config/scripts/mobile-web-app/session/mobile-web-app-queued-messages-render.test.mjs @@ -32,7 +32,7 @@ import { View } from 'react-native' import { GestureHandlerRootView } from 'react-native-gesture-handler' import { MobileNativeChatQueuedMessages } from './src/session/native-chat/input/MobileNativeChatQueuedMessages' import { MobileNativeChatComposer } from './src/session/native-chat/composer/MobileNativeChatComposer' -import { mobileQueuedMessageCards } from './src/session/mobile-structured-queued-message-cards' +import { mobileQueuedMessageCards } from './src/session/native-chat/input/mobile-structured-queued-message-cards' import { activateMobileUiLocale, translate } from './src/i18n/mobile-i18n' const [mode, locale] = location.hash.slice(1).split(':') diff --git a/config/scripts/orcad-distribution/server-bundle/orcad-mobile-web-bundle.mjs b/config/scripts/orcad-distribution/server-bundle/orcad-mobile-web-bundle.mjs index dd94c56f62e..7fa363a1907 100644 --- a/config/scripts/orcad-distribution/server-bundle/orcad-mobile-web-bundle.mjs +++ b/config/scripts/orcad-distribution/server-bundle/orcad-mobile-web-bundle.mjs @@ -19,7 +19,7 @@ export function stageOrcadMobileWebBundle(outputDir, bundleDir = MOBILE_WEB_BUND // The release template refuses the variable itself. assertNoDarkOutputOfOffSwitches([bundleDir]) assertMobileWebBundleBuilt(bundleDir) - // The guard refuses unlisted files, so the tree is the manifest, its assets and a dark marker. + // The guard refuses unlisted files, so the tree is the manifest, its assets and catalogs, and a dark marker. cpSync(bundleDir, join(outputDir, ...ORCAD_MOBILE_WEB_DIR.split('/')), { recursive: true }) } diff --git a/config/scripts/performance/renderer-projection/locale-collator-sort-benchmark.mjs b/config/scripts/performance/renderer-projection/locale-collator-sort-benchmark.mjs index 7253d22afb5..073a78ffaa5 100644 --- a/config/scripts/performance/renderer-projection/locale-collator-sort-benchmark.mjs +++ b/config/scripts/performance/renderer-projection/locale-collator-sort-benchmark.mjs @@ -18,7 +18,7 @@ const { sortJiraIssues } = await jiti.import( '../../../../src/renderer/src/components/jira-issue-sorter.ts' ) const { sortAutomationListViewItems } = await jiti.import( - '../../../../src/renderer/src/components/automations/automation-list-view.ts' + '../../../../src/renderer/src/components/automations/listing/automation-list-view.ts' ) const automationLocale = 'en-US' diff --git a/config/scripts/performance/skills-plugins/skill-source-inventory-benchmark.mjs b/config/scripts/performance/skills-plugins/skill-source-inventory-benchmark.mjs index d774eb03fe0..64b69c9a1e7 100644 --- a/config/scripts/performance/skills-plugins/skill-source-inventory-benchmark.mjs +++ b/config/scripts/performance/skills-plugins/skill-source-inventory-benchmark.mjs @@ -4,7 +4,7 @@ import { performance } from 'node:perf_hooks' import { transform } from 'esbuild' import { buildCounterbalancedSchedule } from '../measurement/counterbalanced-benchmark-schedule.mjs' -const path = 'src/renderer/src/components/skills/skill-source-inventory.ts' +const path = 'src/renderer/src/components/skills/catalog/skill-source-inventory.ts' const arms = {} for (const [name, source] of [ ['baseline', readFileSync(0, 'utf8')], diff --git a/config/scripts/preflight/changed-checks/check-changed-selection.mjs b/config/scripts/preflight/changed-checks/check-changed-selection.mjs index f8f576a27a5..0a28a818ae2 100644 --- a/config/scripts/preflight/changed-checks/check-changed-selection.mjs +++ b/config/scripts/preflight/changed-checks/check-changed-selection.mjs @@ -102,7 +102,33 @@ export const VERIFY_CHECKS = [ 'config/scripts/localization/source-extraction/audit-localization-coverage.mjs', '--check' ], - inputs: ['src/renderer/src/', LOCALES] + inputs: [ + 'src/renderer/src/', + LOCALES, + 'config/scripts/localization/source-extraction/audit-localization-coverage', + 'config/scripts/localization/source-extraction/localization-visible-object-keys' + ] + }, + { + name: 'startup and worktree localization coverage', + args: [ + 'config/scripts/localization/source-extraction/audit-localization-coverage.mjs', + '--check', + '--native-dialog-fields', + '--source-root', + 'src/main/startup', + '--source-root', + 'src/shared/worktree', + '--allowlist', + 'config/startup-worktree-localization-allowlist.json' + ], + inputs: [ + 'src/main/startup/', + 'src/shared/worktree/', + 'config/scripts/localization/source-extraction/audit-localization-coverage', + 'config/scripts/localization/source-extraction/localization-visible-object-keys', + 'config/startup-worktree-localization-allowlist.json' + ] }, { name: 'mobile localization', @@ -145,7 +171,8 @@ export const VERIFY_CHECKS = [ 'mobile/web-entry/', 'config/mobile-localization-coverage-allowlist.json', 'config/scripts/audit-localization-coverage', - 'config/scripts/localization/source-extraction/audit-localization-coverage' + 'config/scripts/localization/source-extraction/audit-localization-coverage', + 'config/scripts/localization/source-extraction/localization-visible-object-keys' ] }, { diff --git a/config/scripts/preflight/changed-checks/run-lint.mjs b/config/scripts/preflight/changed-checks/run-lint.mjs index e882fcb03d2..85e16fbc944 100644 --- a/config/scripts/preflight/changed-checks/run-lint.mjs +++ b/config/scripts/preflight/changed-checks/run-lint.mjs @@ -18,6 +18,7 @@ export const LINT_STEPS = [ 'check:test-file-runners', 'verify:localization-catalogs', 'verify:localization-coverage', + 'verify:startup-worktree-localization-coverage', 'verify:mobile-localization', 'verify:mobile-localization-coverage', 'lint:ast-grep-gates', diff --git a/config/scripts/static-analysis/ratchets/react-compiler/check-react-compiler-compat-ratchet.mjs b/config/scripts/static-analysis/ratchets/react-compiler/check-react-compiler-compat-ratchet.mjs index 714acf736a6..e4205589eba 100644 --- a/config/scripts/static-analysis/ratchets/react-compiler/check-react-compiler-compat-ratchet.mjs +++ b/config/scripts/static-analysis/ratchets/react-compiler/check-react-compiler-compat-ratchet.mjs @@ -27,6 +27,10 @@ import { renderLiveReadLines, renderStoreReadLines } from './react-compiler-hazards.mjs' +import { + UNCOMPILED_LIST, + readListedFiles +} from '../../../../build-plugins/react-compiler-uncompiled-files.mjs' // Runs React Compiler (analysis only, nothing is written) over the renderer so code that compiles // today keeps compiling, and code that would change behavior once compiled can't be added. @@ -34,8 +38,6 @@ import { const SCAN_ROOT = 'src/renderer/src' const BAILOUT_BASELINE = 'config/react-compiler-bailout-baseline.txt' const HAZARD_BASELINE = 'config/react-compiler-hazard-baseline.txt' -// The build leaves these files uncompiled, so their hazards cannot run. -const UNCOMPILED_LIST = 'config/react-compiler-uncompiled-files.txt' const COMMAND = 'pnpm check:react-compiler-compat-ratchet' const NOT_SHIPPED = /(?:^|\/)__(?:mocks|fixtures|tests)__\/|\.(?:test|spec|bench)\.[cm]?tsx?$|[.-]test-|[.-]fixtures?\.tsx?$/ @@ -101,18 +103,31 @@ function addTo(map, key, value) { map.set(key, [...(map.get(key) ?? []), value]) } +// The build leaves these files uncompiled, so their hazards cannot run. function readUncompiledFiles(root) { - const file = path.join(root, UNCOMPILED_LIST) - if (!fs.existsSync(file)) { - return new Set() + return fs.existsSync(path.join(root, UNCOMPILED_LIST)) + ? new Set(readListedFiles(UNCOMPILED_LIST, root)) + : new Set() +} + +// Why: the build matches the exact id, so `\`, `../`, a directory or another case would silently compile. +function isCanonicalFile(root, rel) { + try { + const file = path.join(root, rel) + return ( + !rel.includes('\\') && + path.posix.normalize(rel) === rel && + fs.statSync(file).isFile() && + fs.realpathSync.native(file) === path.join(fs.realpathSync.native(root), rel) + ) + } catch { + return false } - return new Set( - fs - .readFileSync(file, 'utf8') - .split('\n') - .map((line) => line.trim()) - .filter((line) => line && !line.startsWith('#')) - ) +} + +/** Listed paths that name no renderer file; a renamed file would silently compile. */ +export function findStaleUncompiledFiles(uncompiled, exists) { + return [...uncompiled].filter((rel) => !rel.startsWith(`${SCAN_ROOT}/`) || !exists(rel)) } /** Virtualizer hooks plus every hook that returns one, followed through wrappers of wrappers. */ @@ -210,12 +225,14 @@ async function scanFile(rel, text, result) { export async function scanRenderer(root = process.cwd()) { const sources = [...readTrackedSources(root, [SCAN_ROOT], isScannedPath)] + const uncompiled = readUncompiledFiles(root) const result = { files: 0, compiled: 0, diagnostics: new Map(), hazards: new Map(), - uncompiled: readUncompiledFiles(root), + uncompiled, + staleUncompiled: findStaleUncompiledFiles(uncompiled, (rel) => isCanonicalFile(root, rel)), virtualizerHooks: collectVirtualizerHooks(sources), liveReaders: collectLiveReaders(sources) } @@ -341,8 +358,15 @@ export async function main(root = process.cwd(), arg = undefined) { ) return 0 } + for (const rel of scan.staleUncompiled) { + console.error( + `::error::${UNCOMPILED_LIST}: ${rel} is not a renderer file. ` + + 'Point it at the renamed file, or remove it once the file is gone.' + ) + } const touched = listTouchedFiles(root) const ok = [ + scan.staleUncompiled.length === 0, check(root, 'bailout(s)', BAILOUT_BASELINE, bailouts, scan.diagnostics, touched), check(root, 'hazard(s)', HAZARD_BASELINE, hazards, scan.hazards, touched) ].every(Boolean) 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 7f9ba3b8138..784ad9f736e 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 @@ -36,6 +36,7 @@ const NODE_RUNTIME_INCLUDE = [ // Asserts an observer survives a forced collection; conservative retention would hide a lost one. '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/claude-transcript-catch-up.test.ts', 'src/main/claude/claude-transcript-duration.test.ts', 'tests/e2e/native-chat-startup-option-pickers.unit.test.ts', @@ -136,7 +137,7 @@ const NODE_RUNTIME_INCLUDE = [ 'src/main/gitlab/gitlab-known-host-retirement.test.ts', 'src/main/window/main-window-updater-deferred-setup.test.ts', 'src/renderer/src/components/terminal-pane/host-state/terminal-pane-host-state-memo.test.ts', - 'src/renderer/src/components/automations/use-automation-runs-dashboard-payload.test.tsx', + 'src/renderer/src/components/automations/runs/use-automation-runs-dashboard-payload.test.tsx', 'src/main/native-chat/agent-session-journal/**/*.test.ts', 'src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-terminal-writer-acquire.test.ts', 'src/main/runtime/agent-session/records/agent-session-conversation-name-store.test.ts', @@ -168,7 +169,12 @@ const NODE_RUNTIME_INCLUDE = [ 'src/main/claude/claude-agent-sdk-contract-pins.test.ts', 'config/scripts/orcad-distribution/server-bundle/profile-state-worker-smoke.test.mjs', 'config/scripts/desktop-distribution/runtime-verification/process-host-dev-rebuild.test.ts', - 'config/scripts/test-runtime/node-worker/vitest-node-runtime-pool.test.ts' + 'config/scripts/test-runtime/node-worker/vitest-node-runtime-pool.test.ts', + // Reopen the WAL-backed dismissal cache read-only through the row cache, which Bun on macOS cannot. + 'src/main/runtime/push/notifications/mobile-notification-dismissal-store.test.ts', + 'src/main/runtime/push/notifications/mobile-notification-dismissal-read-failure.test.ts', + 'src/main/ipc/notifications-subject-retirement.test.ts', + 'src/main/ipc/notifications-external-acknowledgement.test.ts' ] /** `filters` limits the SQLite import scan to the tests a filtered CLI run can select. */ diff --git a/config/startup-worktree-localization-allowlist.json b/config/startup-worktree-localization-allowlist.json new file mode 100644 index 00000000000..57d98c87207 --- /dev/null +++ b/config/startup-worktree-localization-allowlist.json @@ -0,0 +1,26 @@ +[ + { + "filePath": "src/main/startup/main-process-quit.ts", + "kind": "object-property:message", + "text": "before-quit allowed for update install", + "dynamic": false, + "count": 1, + "reason": "Updater lifecycle diagnostics are not displayed as UI copy." + }, + { + "filePath": "src/main/startup/main-process-quit.ts", + "kind": "object-property:message", + "text": "will-quit cleanup for update install; daemonTeardown=disconnect", + "dynamic": false, + "count": 1, + "reason": "Updater lifecycle diagnostics are not displayed as UI copy." + }, + { + "filePath": "src/main/startup/profile-state-recovery-preflight.ts", + "kind": "object-property:message", + "text": "Invalid profile-state recovery launch.", + "dynamic": false, + "count": 1, + "reason": "Existing recovery detail is user-visible and remains untranslated; tracked in issue 32207." + } +] diff --git a/config/vitest.config.ts b/config/vitest.config.ts index 7dc0f04c525..eab54372357 100644 --- a/config/vitest.config.ts +++ b/config/vitest.config.ts @@ -126,10 +126,12 @@ const bunProject = { } // Files whose state the per-file reset can undo share one worker's module cache instead of // re-importing thousands of modules each. ORCA_VITEST_ISOLATE_EVERY_FILE=1 turns it off. +// Windows workers that keep native addons (process tree, ConPTY) across files die of heap +// corruption (0xC0000374); production code loads them lazily, so the file scan can't see them. const runtimeProject = process.versions.bun ? bunProject : nodeProject const nodeRuntimeFiles = new Set(nodeRuntimeInclude.map((file) => file.replaceAll('\\', '/'))) const sharedWorkerFiles = - process.env.ORCA_VITEST_ISOLATE_EVERY_FILE === '1' + process.env.ORCA_VITEST_ISOLATE_EVERY_FILE === '1' || process.platform === 'win32' ? [] : filesSafeToShareWorker( process.cwd(), diff --git a/config/workspace-record-read-baseline.txt b/config/workspace-record-read-baseline.txt index ca14f9bf2ad..5e1fe0f7c63 100644 --- a/config/workspace-record-read-baseline.txt +++ b/config/workspace-record-read-baseline.txt @@ -22,7 +22,7 @@ 1 src/renderer/src/components/sidebar/worktree-list/navigation/pending-reveal-inputs.ts # reads a passed-in copy 1 src/renderer/src/components/sidebar/worktree-list/navigation/use-pending-reveal.ts # reads a passed-in copy 2 src/renderer/src/components/sidebar/worktree-list/viewport/VirtualizedWorktreeViewport.tsx # reads a passed-in copy -2 src/renderer/src/components/skills/skill-install-workspace-choices.ts # reads a passed-in copy +2 src/renderer/src/components/skills/installation/skill-install-workspace-choices.ts # reads a passed-in copy 1 src/renderer/src/components/terminal-pane/links/files/terminal-worktree-path-link.ts # P5b-2 must clear: loosely typed state param 1 src/renderer/src/components/workspace-space/space-window-state.ts # reads a passed-in copy 1 src/renderer/src/hooks/composer-state/composer-source-state.ts # P5b-2 must clear: composer store snapshot diff --git a/docs/assets/wechat-qr-group12.jpg b/docs/assets/wechat-qr-group12.jpg deleted file mode 100644 index 475c483ca76..00000000000 Binary files a/docs/assets/wechat-qr-group12.jpg and /dev/null differ diff --git a/docs/assets/wechat-qr-group13.jpg b/docs/assets/wechat-qr-group13.jpg deleted file mode 100644 index 48c67e4031b..00000000000 Binary files a/docs/assets/wechat-qr-group13.jpg and /dev/null differ diff --git a/docs/assets/wechat-qr-group14.jpg b/docs/assets/wechat-qr-group14.jpg deleted file mode 100644 index 76745e168d5..00000000000 Binary files a/docs/assets/wechat-qr-group14.jpg and /dev/null differ diff --git a/docs/assets/wechat-qr-group15.jpg b/docs/assets/wechat-qr-group15.jpg deleted file mode 100644 index 97ca38eb20b..00000000000 Binary files a/docs/assets/wechat-qr-group15.jpg and /dev/null differ diff --git a/docs/assets/wechat-qr-group16.jpg b/docs/assets/wechat-qr-group16.jpg deleted file mode 100644 index 158a50794cc..00000000000 Binary files a/docs/assets/wechat-qr-group16.jpg and /dev/null differ diff --git a/docs/assets/wechat-qr.jpg b/docs/assets/wechat-qr.jpg index 4b4f61e17f5..ecc8de57c7b 100644 Binary files a/docs/assets/wechat-qr.jpg and b/docs/assets/wechat-qr.jpg differ diff --git a/docs/development.md b/docs/development.md index 07cc3fd619d..56656dfe72e 100644 --- a/docs/development.md +++ b/docs/development.md @@ -53,5 +53,5 @@ pnpm dev:fresh [--keep] [--seed-from[=]] # temporary profile, rem - Slow main-process rebuilds: set `ORCA_DEV_MAIN_SOURCEMAPS=0` before `pnpm dev` when you don't need main-process source maps. - Renderer misbehaving in dev: set `ORCA_DEV_BUNDLED=0` to turn off bundled dev mode, and report it. -- Test passes alone but fails after others: add `// @orca-isolated-worker` to the file; `ORCA_VITEST_ISOLATE_EVERY_FILE=1` isolates every file to confirm a leak. +- Test passes alone but fails after others: add `// @orca-isolated-worker` to the file; `ORCA_VITEST_ISOLATE_EVERY_FILE=1` isolates every file to confirm a leak. Windows always isolates every file, because native addons kept across files corrupt the heap. - Slow typechecks: where supported, `pnpm tc` keeps incremental caches in `.cache/typecheck/`; delete it to force a fresh check. diff --git a/docs/readme/README.fr.md b/docs/readme/README.fr.md index 67a9b140ecb..67025f76663 100644 --- a/docs/readme/README.fr.md +++ b/docs/readme/README.fr.md @@ -249,11 +249,9 @@ Associez-la à l'app de bureau pour surveiller et piloter vos agents depuis votr - **Discord :** Rejoignez la communauté sur **[Discord](https://discord.gg/fzjDKHxv8Q)**. - **Twitter / X :** Suivez **[@orca_build](https://x.com/orca_build)** pour les news et annonces. -- **WeChat :** Scannez pour rejoindre un groupe WeChat de la communauté Orca. Si un groupe est complet, rejoignez-en un autre. +- **WeChat :** Scannez pour rejoindre un groupe WeChat de la communauté Orca. - QR code du groupe WeChat de la communauté Orca - QR code du groupe WeChat de la communauté Orca - QR code du groupe WeChat de la communauté Orca + QR code du groupe WeChat de la communauté Orca - **Feedback & idées :** On ship vite. Il manque quelque chose ? [Demandez une feature](https://github.com/stablyai/orca/issues). - **Confidentialité :** Voir la [doc confidentialité & télémétrie](https://www.onorca.dev/docs/telemetry) pour ce qu'Orca collecte en anonyme et comment désactiver la télémétrie. diff --git a/docs/readme/README.ko.md b/docs/readme/README.ko.md index 02ceb179d9c..d44ef909489 100644 --- a/docs/readme/README.ko.md +++ b/docs/readme/README.ko.md @@ -244,11 +244,9 @@ yay -S stably-orca-bin - **Discord:** **[Discord](https://discord.gg/fzjDKHxv8Q)** 커뮤니티에 참여하세요. - **Twitter / X:** 업데이트와 공지는 **[@orca_build](https://x.com/orca_build)** 를 팔로우하세요. -- **WeChat:** QR 코드를 스캔해 Orca 커뮤니티 WeChat 그룹에 참여하세요. 한 그룹이 가득 찼다면 다른 그룹에 참여하세요. +- **WeChat:** QR 코드를 스캔해 Orca 커뮤니티 WeChat 그룹에 참여하세요. - Orca 커뮤니티 WeChat 그룹 QR 코드 - Orca 커뮤니티 WeChat 그룹 QR 코드 - Orca 커뮤니티 WeChat 그룹 QR 코드 + Orca 커뮤니티 WeChat 그룹 QR 코드 - **피드백과 아이디어:** 우리는 빠르게 출시합니다. 필요한 기능이 있나요? [새 기능을 요청](https://github.com/stablyai/orca/issues)하세요. - **개인정보 보호:** Orca가 수집하는 익명 사용 데이터와 수집 거부 방법은 [개인정보 및 텔레메트리 문서](https://www.onorca.dev/docs/telemetry)를 참고하세요. diff --git a/docs/readme/README.ru.md b/docs/readme/README.ru.md index b9f35580121..576d8250409 100644 --- a/docs/readme/README.ru.md +++ b/docs/readme/README.ru.md @@ -245,11 +245,9 @@ yay -S stably-orca-bin - **Discord:** Присоединяйтесь к сообществу в **[Discord](https://discord.gg/fzjDKHxv8Q)**. - **Twitter / X:** Подпишитесь на **[@orca_build](https://x.com/orca_build)**, чтобы узнавать об обновлениях и анонсах. -- **WeChat:** Отсканируйте QR-код, чтобы присоединиться к группе сообщества Orca в WeChat. Если одна группа заполнена, присоединяйтесь к другой. +- **WeChat:** Отсканируйте QR-код, чтобы присоединиться к группе сообщества Orca в WeChat. - QR-код группы сообщества Orca в WeChat - QR-код группы сообщества Orca в WeChat - QR-код группы сообщества Orca в WeChat + QR-код группы сообщества Orca в WeChat - **Отзывы и идеи:** Мы быстро выпускаем обновления. Чего-то не хватает? [Предложите новую возможность](https://github.com/stablyai/orca/issues). - **Конфиденциальность:** В [документации о конфиденциальности и телеметрии](https://www.onorca.dev/docs/telemetry) описано, какие анонимные данные об использовании собирает Orca и как отказаться от их сбора. diff --git a/docs/readme/README.tr.md b/docs/readme/README.tr.md index de57ef3c8a4..c3952fa63b8 100644 --- a/docs/readme/README.tr.md +++ b/docs/readme/README.tr.md @@ -242,11 +242,9 @@ Ajanlarınızı telefonunuzdan izlemek ve yönlendirmek için masaüstü uygulam - **Discord:** Topluluğa **[Discord](https://discord.gg/fzjDKHxv8Q)** üzerinden katılın. - **Twitter / X:** Güncellemeler ve duyurular için **[@orca_build](https://x.com/orca_build)** hesabını takip edin. -- **WeChat:** Orca topluluğunun bir WeChat grubuna katılmak için karekodu okutun. Bir grup doluysa başka bir gruba katılabilirsiniz. +- **WeChat:** Orca topluluğunun bir WeChat grubuna katılmak için karekodu okutun. - Orca topluluğunun WeChat grubu karekodu - Orca topluluğunun WeChat grubu karekodu - Orca topluluğunun WeChat grubu karekodu + Orca topluluğunun WeChat grubu karekodu - **Geri bildirim ve fikirler:** Hızlı sürüm çıkarıyoruz. Eksik bulduğunuz bir şey mi var? [Yeni bir özellik isteyin](https://github.com/stablyai/orca/issues). - **Gizlilik:** Orca'nın hangi anonim kullanım verisini topladığını ve bunu nasıl kapatacağınızı [gizlilik ve telemetri dokümanlarında](https://www.onorca.dev/docs/telemetry) bulabilirsiniz. diff --git a/docs/readme/README.zh-CN.md b/docs/readme/README.zh-CN.md index 4d9dea01319..20cfaae5e8d 100644 --- a/docs/readme/README.zh-CN.md +++ b/docs/readme/README.zh-CN.md @@ -242,11 +242,9 @@ yay -S stably-orca-bin - **Discord:** 加入 **[Discord](https://discord.gg/fzjDKHxv8Q)** 社区。 - **Twitter / X:** 关注 **[@orca_build](https://x.com/orca_build)** 获取更新和公告。 -- **微信:** 扫码加入 Orca 社区微信群。如果一个群已满,可以加入其他群。 +- **微信:** 扫码加入 Orca 社区微信群。 - Orca 社区微信群二维码 - Orca 社区微信群二维码 - Orca 社区微信群二维码 + Orca 社区微信群二维码 - **反馈与想法:** 我们发布很快。缺少什么功能?[提交功能请求](https://github.com/stablyai/orca/issues)。 - **隐私:** 查看[隐私与遥测文档](https://www.onorca.dev/docs/telemetry),了解 Orca 收集哪些匿名使用数据以及如何退出。 diff --git a/mobile/rpc-foundation/pilot-scenarios.json b/mobile/rpc-foundation/pilot-scenarios.json index eeb45a4f5ee..e00d7a8080d 100644 --- a/mobile/rpc-foundation/pilot-scenarios.json +++ b/mobile/rpc-foundation/pilot-scenarios.json @@ -18029,7 +18029,7 @@ "id": "native-chat-write-accepted", "operation": "nativeChat.terminal-write", "family": "nativeChat.terminal-write", - "sites": ["mobile/src/session/native-chat/mobile-native-chat-send.ts"], + "sites": ["mobile/src/session/native-chat/composer/mobile-native-chat-send.ts"], "schedules": [], "steps": [ { @@ -18065,7 +18065,7 @@ "id": "native-chat-write-rejected", "operation": "nativeChat.terminal-write", "family": "nativeChat.terminal-write", - "sites": ["mobile/src/session/native-chat/mobile-native-chat-send.ts"], + "sites": ["mobile/src/session/native-chat/composer/mobile-native-chat-send.ts"], "schedules": [], "steps": [ { @@ -18101,7 +18101,7 @@ "id": "native-chat-write-delivery-unknown", "operation": "nativeChat.terminal-write", "family": "nativeChat.terminal-write", - "sites": ["mobile/src/session/native-chat/mobile-native-chat-send.ts"], + "sites": ["mobile/src/session/native-chat/composer/mobile-native-chat-send.ts"], "schedules": [], "steps": [ { @@ -18133,7 +18133,7 @@ "id": "native-chat-write-clear-line", "operation": "nativeChat.terminal-write", "family": "nativeChat.terminal-write", - "sites": ["mobile/src/session/native-chat/mobile-native-chat-send.ts"], + "sites": ["mobile/src/session/native-chat/composer/mobile-native-chat-send.ts"], "schedules": [], "steps": [ { @@ -18169,7 +18169,7 @@ "id": "native-chat-write-typed-command", "operation": "nativeChat.terminal-write", "family": "nativeChat.terminal-write", - "sites": ["mobile/src/session/native-chat/mobile-native-chat-send.ts"], + "sites": ["mobile/src/session/native-chat/composer/mobile-native-chat-send.ts"], "schedules": [], "steps": [ { @@ -18840,7 +18840,9 @@ "id": "structured-launch-unsupported", "operation": "agentSession.structured-launch", "family": "agentSession.structured-launch", - "sites": ["mobile/src/session/mobile-structured-agent-session-launch.ts"], + "sites": [ + "mobile/src/session/native-chat/agent-session/mobile-structured-agent-session-launch.ts" + ], "schedules": [], "steps": [ { @@ -18870,7 +18872,9 @@ "id": "structured-launch-support-refused", "operation": "agentSession.structured-launch", "family": "agentSession.structured-launch", - "sites": ["mobile/src/session/mobile-structured-agent-session-launch.ts"], + "sites": [ + "mobile/src/session/native-chat/agent-session/mobile-structured-agent-session-launch.ts" + ], "schedules": [], "steps": [ { @@ -18900,7 +18904,9 @@ "id": "structured-launch-created", "operation": "agentSession.structured-launch", "family": "agentSession.structured-launch", - "sites": ["mobile/src/session/mobile-structured-agent-session-launch.ts"], + "sites": [ + "mobile/src/session/native-chat/agent-session/mobile-structured-agent-session-launch.ts" + ], "schedules": [], "steps": [ { @@ -18951,7 +18957,9 @@ "id": "structured-launch-definitive-refusal", "operation": "agentSession.structured-launch", "family": "agentSession.structured-launch", - "sites": ["mobile/src/session/mobile-structured-agent-session-launch.ts"], + "sites": [ + "mobile/src/session/native-chat/agent-session/mobile-structured-agent-session-launch.ts" + ], "schedules": [], "steps": [ { @@ -19003,7 +19011,9 @@ "id": "structured-launch-replays-dropped-create", "operation": "agentSession.structured-launch", "family": "agentSession.structured-launch", - "sites": ["mobile/src/session/mobile-structured-agent-session-launch.ts"], + "sites": [ + "mobile/src/session/native-chat/agent-session/mobile-structured-agent-session-launch.ts" + ], "schedules": [], "steps": [ { @@ -19443,7 +19453,7 @@ "id": "native-chat-stop-accepted", "operation": "session.native-chat-stop", "family": "session.native-chat-stop", - "sites": ["mobile/src/session/native-chat/use-mobile-native-chat-stop.ts"], + "sites": ["mobile/src/session/native-chat/composer/use-mobile-native-chat-stop.ts"], "schedules": [], "steps": [ { @@ -19504,7 +19514,7 @@ "id": "native-chat-stop-both-rejected", "operation": "session.native-chat-stop", "family": "session.native-chat-stop", - "sites": ["mobile/src/session/native-chat/use-mobile-native-chat-stop.ts"], + "sites": ["mobile/src/session/native-chat/composer/use-mobile-native-chat-stop.ts"], "schedules": [], "steps": [ { @@ -19562,7 +19572,7 @@ "id": "native-chat-stop-delivery-unknown", "operation": "session.native-chat-stop", "family": "session.native-chat-stop", - "sites": ["mobile/src/session/native-chat/use-mobile-native-chat-stop.ts"], + "sites": ["mobile/src/session/native-chat/composer/use-mobile-native-chat-stop.ts"], "schedules": [], "steps": [ { @@ -19962,7 +19972,7 @@ "mobile/src/source-control/review/use-mobile-diff-review-comment-actions.ts", "mobile/src/source-control/review/use-mobile-diff-review-git-actions.ts", "mobile/src/source-control/review/use-mobile-diff-review-send-actions.ts", - "mobile/src/session/native-chat/mobile-native-chat-stale-input.ts" + "mobile/src/session/native-chat/composer/mobile-native-chat-stale-input.ts" ], "schedules": [], "steps": [ @@ -20039,7 +20049,7 @@ "mobile/src/source-control/review/use-mobile-diff-review-comment-actions.ts", "mobile/src/source-control/review/use-mobile-diff-review-git-actions.ts", "mobile/src/source-control/review/use-mobile-diff-review-send-actions.ts", - "mobile/src/session/native-chat/mobile-native-chat-stale-input.ts" + "mobile/src/session/native-chat/composer/mobile-native-chat-stale-input.ts" ], "schedules": [], "steps": [ @@ -20117,7 +20127,7 @@ "mobile/src/source-control/review/use-mobile-diff-review-comment-actions.ts", "mobile/src/source-control/review/use-mobile-diff-review-git-actions.ts", "mobile/src/source-control/review/use-mobile-diff-review-send-actions.ts", - "mobile/src/session/native-chat/mobile-native-chat-stale-input.ts" + "mobile/src/session/native-chat/composer/mobile-native-chat-stale-input.ts" ], "schedules": [], "steps": [ @@ -20152,7 +20162,7 @@ "mobile/src/source-control/review/use-mobile-diff-review-comment-actions.ts", "mobile/src/source-control/review/use-mobile-diff-review-git-actions.ts", "mobile/src/source-control/review/use-mobile-diff-review-send-actions.ts", - "mobile/src/session/native-chat/mobile-native-chat-stale-input.ts" + "mobile/src/session/native-chat/composer/mobile-native-chat-stale-input.ts" ], "schedules": [], "steps": [ @@ -20188,7 +20198,7 @@ "mobile/src/source-control/review/use-mobile-diff-review-comment-actions.ts", "mobile/src/source-control/review/use-mobile-diff-review-git-actions.ts", "mobile/src/source-control/review/use-mobile-diff-review-send-actions.ts", - "mobile/src/session/native-chat/mobile-native-chat-stale-input.ts" + "mobile/src/session/native-chat/composer/mobile-native-chat-stale-input.ts" ], "schedules": [], "steps": [ @@ -20224,7 +20234,7 @@ "mobile/src/source-control/review/use-mobile-diff-review-comment-actions.ts", "mobile/src/source-control/review/use-mobile-diff-review-git-actions.ts", "mobile/src/source-control/review/use-mobile-diff-review-send-actions.ts", - "mobile/src/session/native-chat/mobile-native-chat-stale-input.ts" + "mobile/src/session/native-chat/composer/mobile-native-chat-stale-input.ts" ], "schedules": [], "steps": [ @@ -20280,7 +20290,7 @@ "mobile/src/source-control/review/use-mobile-diff-review-comment-actions.ts", "mobile/src/source-control/review/use-mobile-diff-review-git-actions.ts", "mobile/src/source-control/review/use-mobile-diff-review-send-actions.ts", - "mobile/src/session/native-chat/mobile-native-chat-stale-input.ts" + "mobile/src/session/native-chat/composer/mobile-native-chat-stale-input.ts" ], "schedules": [], "steps": [ @@ -24889,7 +24899,7 @@ "mobile/src/source-control/review/use-mobile-diff-review-comment-actions.ts", "mobile/src/source-control/review/use-mobile-diff-review-git-actions.ts", "mobile/src/source-control/review/use-mobile-diff-review-send-actions.ts", - "mobile/src/session/native-chat/mobile-native-chat-stale-input.ts" + "mobile/src/session/native-chat/composer/mobile-native-chat-stale-input.ts" ], "schedules": [], "steps": [ @@ -24944,7 +24954,7 @@ "mobile/src/source-control/review/use-mobile-diff-review-comment-actions.ts", "mobile/src/source-control/review/use-mobile-diff-review-git-actions.ts", "mobile/src/source-control/review/use-mobile-diff-review-send-actions.ts", - "mobile/src/session/native-chat/mobile-native-chat-stale-input.ts" + "mobile/src/session/native-chat/composer/mobile-native-chat-stale-input.ts" ], "schedules": [], "steps": [ @@ -25018,7 +25028,9 @@ "id": "structured-agent-session-created", "operation": "agentSession.structured-launch", "family": "agentSession.structured-create", - "sites": ["mobile/src/session/mobile-structured-agent-session-launch.ts"], + "sites": [ + "mobile/src/session/native-chat/agent-session/mobile-structured-agent-session-launch.ts" + ], "schedules": [], "steps": [ { diff --git a/mobile/src/agent-history/MobileAgentSessionHistoryPanel.tsx b/mobile/src/agent-history/MobileAgentSessionHistoryPanel.tsx index fdbd7fc5ff8..08a2d65d451 100644 --- a/mobile/src/agent-history/MobileAgentSessionHistoryPanel.tsx +++ b/mobile/src/agent-history/MobileAgentSessionHistoryPanel.tsx @@ -1,5 +1,5 @@ import { openMobileAgentHistoryChat } from './open-mobile-agent-history-chat' -import { mobileStructuredSessionOpenMessage } from '../session/mobile-structured-session-open-message' +import { mobileStructuredSessionOpenMessage } from '../session/native-chat/agent-session/mobile-structured-session-open-message' import { prepareMobileHistoryResumeTarget } from './mobile-history-resume-target-preparation' import { useCallback, useEffect, useMemo, useRef, useState } from 'react' import { View } from 'react-native' diff --git a/mobile/src/agent-history/open-mobile-agent-history-chat.ts b/mobile/src/agent-history/open-mobile-agent-history-chat.ts index e435509888e..46705610706 100644 --- a/mobile/src/agent-history/open-mobile-agent-history-chat.ts +++ b/mobile/src/agent-history/open-mobile-agent-history-chat.ts @@ -4,7 +4,7 @@ import type { RpcClient } from '../transport/rpc/rpc-client-contract' import { openMobileStructuredSession, mobileStructuredSessionHref -} from '../session/open-mobile-structured-session' +} from '../session/native-chat/agent-session/open-mobile-structured-session' /** Consume native opens and ambiguous failures; only an explicit pre-effect refusal resumes in a terminal. */ export async function openMobileAgentHistoryChat(args: { diff --git a/mobile/src/agent-history/use-mobile-agent-history-state.ts b/mobile/src/agent-history/use-mobile-agent-history-state.ts index 5b8ebe2e2bc..122708bdeef 100644 --- a/mobile/src/agent-history/use-mobile-agent-history-state.ts +++ b/mobile/src/agent-history/use-mobile-agent-history-state.ts @@ -1,6 +1,6 @@ import { useCallback, useEffect, useMemo, useRef, useState, useSyncExternalStore } from 'react' import { useQueryClient } from '@tanstack/react-query' -import { mobileStructuredSessionStatusFeed } from '../session/mobile-structured-session-status-feed' +import { mobileStructuredSessionStatusFeed } from '../session/native-chat/agent-session/mobile-structured-session-status-feed' import type { AgentSessionConversationNames } from '../../../src/shared/agent-session/agent-session-conversation-names' import { useForceReconnect } from '../transport/connection/host-client-hooks' import { useWorkspaceClient } from '../worktree/use-workspace-client' diff --git a/mobile/src/agents/agent-list-model.test.ts b/mobile/src/agents/agent-list-model.test.ts index 1b8ccb3bc2d..0af7468eaaa 100644 --- a/mobile/src/agents/agent-list-model.test.ts +++ b/mobile/src/agents/agent-list-model.test.ts @@ -4,6 +4,7 @@ import type { ConnectionState } from '../transport/connection/connection-state' import type { HostWorktreeInfo } from '../worktree/home-worktree-info' import { buildAgentList, type AgentListSection } from './agent-list-model' import { + selectActiveAgents, selectAgentsNeedingYou, type AgentListInput, type AgentListRow, @@ -79,24 +80,22 @@ const statusView = (showWorkers: boolean, unreadOnly = false) => ({ describe('buildAgentList by status', () => { it('buckets agents by what they ask of the user, newest first, and folds idle ones', () => { - const list = buildAgentList( - input({ - mac: { - state: 'connected', - info: { - agents: entries([ - agent('asking', 'waiting'), - agent('older-run', 'working', { stateStartedAt: NOW - 5 * MINUTE }), - agent('newer-run', 'working', { stateStartedAt: NOW - 2 * MINUTE }), - agent('finished', 'done'), - // Silent past the 30-minute freshness window. - agent('quiet', 'working', { updatedAt: NOW - 31 * MINUTE }) - ]) - } + const host = input({ + mac: { + state: 'connected', + info: { + agents: entries([ + agent('asking', 'waiting'), + agent('older-run', 'working', { stateStartedAt: NOW - 5 * MINUTE }), + agent('newer-run', 'working', { stateStartedAt: NOW - 2 * MINUTE }), + agent('finished', 'done'), + // Silent past the 30-minute freshness window. + agent('quiet', 'working', { updatedAt: NOW - 31 * MINUTE }) + ]) } - }), - statusView(true) - ) + } + }) + const list = buildAgentList(host, statusView(true)) expect(shape(list.sections)).toEqual([ { kind: 'needs-you', rows: ['asking'], workers: [[]], idle: undefined }, { @@ -107,6 +106,7 @@ describe('buildAgentList by status', () => { }, { kind: 'done', rows: ['finished'], workers: [[]], idle: ['quiet'] } ]) + expect(panes(selectActiveAgents(host))).toEqual(['asking', 'newer-run', 'older-run']) }) it('nests workers under their coordinator and still lists the one that needs the user', () => { diff --git a/mobile/src/agents/agent-list-rows.ts b/mobile/src/agents/agent-list-rows.ts index a9490a5929b..fc44c14f64b 100644 --- a/mobile/src/agents/agent-list-rows.ts +++ b/mobile/src/agents/agent-list-rows.ts @@ -159,6 +159,18 @@ export function selectAgentsNeedingYou(input: AgentListInput): AgentListRow[] { .sort(byStatusThenRecent) } +/** Live agents that need the user or are working, workers included: Feed's Active rows. */ +export function selectActiveAgents(input: AgentListInput): AgentListRow[] { + return input.hosts + .flatMap((host) => everyRow(hostAgents(input, host.id).roots)) + .filter((row) => { + const group = agentStatusGroup(row.dotState) + return !row.stale && (group === 'needs-you' || group === 'working') + }) + .map(asTopLevel) + .sort(byStatusThenRecent) +} + export function countAgentsNeedingYouByHost( rows: readonly AgentListRow[] ): Readonly> { diff --git a/mobile/src/components/MobileStateView.tsx b/mobile/src/components/MobileStateView.tsx index ef692756a90..791e43c4789 100644 --- a/mobile/src/components/MobileStateView.tsx +++ b/mobile/src/components/MobileStateView.tsx @@ -22,6 +22,8 @@ type MobileStateViewProps = { loading?: boolean /** Keeps the content centred above a floating bottom bar. */ bottomInset?: number + /** Full-width content under the message, such as a list of choices. */ + children?: ReactNode } /** Every screen's loading, empty, no-match, error and offline state: icon, title, one sentence, one action. */ @@ -33,7 +35,8 @@ export function MobileStateView({ details, action, loading = false, - bottomInset = 0 + bottomInset = 0, + children }: MobileStateViewProps) { useMobileColorScheme() return ( @@ -49,6 +52,7 @@ export function MobileStateView({ {message ? {message} : null} {details ? : null} {action ? : null} + {children ? {children} : null} ) } @@ -187,6 +191,10 @@ export function MobileNoMatchState({ } const styles = themedStyleSheet(() => ({ + children: { + alignSelf: 'stretch', + marginTop: spacing.md + }, state: { flex: 1, alignItems: 'center', diff --git a/mobile/src/components/NewWorktreeModal.test.tsx b/mobile/src/components/NewWorktreeModal.test.tsx index b44507b5157..6da85abe6b3 100644 --- a/mobile/src/components/NewWorktreeModal.test.tsx +++ b/mobile/src/components/NewWorktreeModal.test.tsx @@ -64,6 +64,7 @@ vi.mock('../host-screen/host-list-queries', () => ({ import '../transport/hosts/host-descriptor-store' import { FakeSession } from '../transport/connection/mobile-endpoint-supervisor-test-fakes' +import { markRpcDeliveryUnknown } from '../transport/rpc/rpc-delivery-ambiguity' import '../../../src/shared/execution-host' import type { ExecutionHostId } from '../../../src/shared/execution-host' @@ -194,6 +195,108 @@ describe('NewWorktreeModal project targets', () => { ).toBe('/srv/orca') }) + it("offers only the folder host's copy of a repo when opened from a folder", async () => { + const serverRepo = { ...repos[0]!, path: '/srv/orca' } + const listing = (listed: unknown[]) => + vi.fn((method: string) => + method === 'repo.list' ? replied({ repos: listed }) : new Promise(() => {}) + ) + + await act(async () => { + renderer = create( + createElement(NewWorktreeModal, { + visible: true, + client: requestsOnly(listing(repos)), + serverClients: new Map([ + ['runtime:env-1', requestsOnly(listing([serverRepo]))] + ]), + hostId: 'host-1', + onCreated: () => {}, + onClose: () => {}, + openExternalUrl: () => {}, + folderLaunch: { + repoId: 'repo-1', + executionHostId: 'runtime:env-1', + name: 'payments', + parentWorkspace: 'folder:f-1', + submit: { begin: () => null, presenting: () => true } + } + }) + ) + }) + await flushUpdates() + + // The desktop's same-id repo is not offered: its store doesn't hold this folder. + expect(pickerItems(renderer, 'Run on').map((item) => item.detail)).toEqual(['/srv/orca']) + expect(runTargetPicker(renderer).props.selectedId).toBe('runtime:env-1') + }) + + async function submitFromFolder(createReply: () => Promise) { + const serverRepo = { ...repos[0]!, path: '/srv/orca' } + const server = requestsOnly( + vi.fn((method: string) => + method === 'repo.list' + ? replied({ repos: [serverRepo] }) + : method === 'worktree.create' + ? createReply() + : Promise.reject(new Error(`unexpected ${method}`)) + ) + ) + const settle = vi.fn() + + await act(async () => { + renderer = create( + createElement(NewWorktreeModal, { + visible: true, + client: requestsOnly(() => new Promise(() => {})), + serverClients: new Map([['runtime:env-1', server]]), + hostId: 'host-1', + onCreated: () => {}, + onClose: () => {}, + openExternalUrl: () => {}, + folderLaunch: { + repoId: 'repo-1', + executionHostId: 'runtime:env-1', + name: 'payments', + parentWorkspace: 'folder:f-1', + submit: { begin: () => ({ settle }), presenting: () => true } + } + }) + ) + }) + await flushUpdates() + const form = renderer.root.find((node) => typeof node.props.onCreate === 'function') + await act(async () => form.props.onCreate()) + await flushUpdates() + + const creates = vi + .mocked(server.sendRequest) + .mock.calls.filter(([method]) => method === 'worktree.create') + return { creates: creates.map(([, params]) => params), settle } + } + + it('creates from a folder attached to that folder, on its host', async () => { + const { creates, settle } = await submitFromFolder(() => + replied({ worktree: { id: 'repo-1::/srv/w/payments', displayName: 'payments' } }) + ) + expect(creates).toEqual([ + expect.objectContaining({ + repo: 'id:repo-1', + parentWorkspace: 'folder:f-1', + parentWorkspaceOrigin: 'manual' + }) + ]) + expect(settle).toHaveBeenCalledWith('created') + }) + + it("doesn't try another name when a folder create's reply is lost", async () => { + const { creates, settle } = await submitFromFolder(() => + Promise.reject(markRpcDeliveryUnknown(new Error('connection lost'))) + ) + expect(creates).toHaveLength(1) + expect(settle).toHaveBeenCalledWith('uncertain') + }) + it('ignores a stale repo list after the client changes', async () => { let resolveOldList: ((value: unknown) => void) | undefined const oldList = new Promise((resolve) => { diff --git a/mobile/src/components/NewWorktreeModal.tsx b/mobile/src/components/NewWorktreeModal.tsx index 11bf01b970f..ccae8181be7 100644 --- a/mobile/src/components/NewWorktreeModal.tsx +++ b/mobile/src/components/NewWorktreeModal.tsx @@ -1,4 +1,4 @@ -import { useMemo, useState } from 'react' +import { useEffect, useMemo, useRef, useState } from 'react' import { Keyboard } from 'react-native' import { getComposerRepoWorktreeBranches } from '../../../src/shared/composer-branch-selection' import { getRepoExecutionHostId, parseExecutionHostId } from '../../../src/shared/execution-host' @@ -71,14 +71,20 @@ function NewWorktreeModalContent(props: NewWorktreeModalProps) { existingWorktrees, openExternalUrl, onCreated, - onClose + onClose, + folderLaunch } = props const { repos, allRepos, selectedRepo, setSelectedRepo, loading, loadError, retryLoad } = useNewWorkspaceRepositories({ client: desktopClient, serverClients, hostId, - visible + visible, + ...(folderLaunch + ? { + initialRepo: { id: folderLaunch.repoId, executionHostId: folderLaunch.executionHostId } + } + : {}) }) // Route picked-repo operations to its host; desktop settings/accounts stay on desktop. const repoServer = selectedRepo ? serverOf(selectedRepo) : undefined @@ -126,6 +132,14 @@ function NewWorktreeModalContent(props: NewWorktreeModalProps) { worktreeBranches: selectedRepoWorktreeBranches, onError: setError }) + // The folder's name, seeded once per opening; the user's edits stand. + const seededFolderName = useRef(false) + useEffect(() => { + if (folderLaunch && !seededFolderName.current) { + seededFolderName.current = true + composer.setName(folderLaunch.name) + } + }, [composer, folderLaunch]) const selectedRepoIsGit = selectedRepo ? selectedRepo.kind !== 'folder' : true useWorktreeCreateBasePrefetch({ client: visible ? client : null, @@ -179,7 +193,19 @@ function NewWorktreeModalContent(props: NewWorktreeModalProps) { setNote((current) => (current === note ? '' : current)) onCreated(worktreeId, name, warning, repoServer) }, - onClose + onClose, + ...(folderLaunch + ? { + folderLaunch: { + ...folderLaunch.submit, + executionHostId: folderLaunch.executionHostId, + parent: { + parentWorkspace: folderLaunch.parentWorkspace, + parentWorkspaceOrigin: 'manual' as const + } + } + } + : {}) }) const sourceAvailability: SmartModeAvailabilityInput = { diff --git a/mobile/src/components/new-workspace-create-copy.ts b/mobile/src/components/new-workspace-create-copy.ts new file mode 100644 index 00000000000..77a9e3cf7e3 --- /dev/null +++ b/mobile/src/components/new-workspace-create-copy.ts @@ -0,0 +1,22 @@ +import { translate } from '../i18n/mobile-i18n' + +/** A create whose reply was lost, or whose resend was refused: it may exist, so another could be a second one. */ +export function uncertainCreateMessage(inFolder: boolean): string { + return inFolder + ? translate( + 'components.newWorkspaceCreateSubmit.uncertainFolderCreate', + 'This worktree may have been created. Check the folder before creating another.' + ) + : translate( + 'components.newWorkspaceCreateSubmit.uncertainCreate', + 'This workspace may have been created. Check your workspaces before creating another.' + ) +} + +/** The folder screen still owns a create for this repository. */ +export function folderCreateBusyMessage(): string { + return translate( + 'components.newWorkspaceCreateSubmit.folderCreateBusy', + 'A worktree in this repository is still being created or checked. It shows in the folder once it lands.' + ) +} diff --git a/mobile/src/components/new-worktree-modal-types.ts b/mobile/src/components/new-worktree-modal-types.ts index 54fa5d0f4a0..02a7a1e4f9d 100644 --- a/mobile/src/components/new-worktree-modal-types.ts +++ b/mobile/src/components/new-worktree-modal-types.ts @@ -18,6 +18,30 @@ export type MobileWorkspaceRepo = Pick > +/** Opened from a folder's empty state: that repo and name, created attached to the folder. */ +export type NewWorktreeFolderLaunch = { + repoId: string + /** The repo's host, so a same-id copy on another host isn't picked. */ + executionHostId: ExecutionHostId + name: string + /** The folder's workspace key, `folder:`. */ + parentWorkspace: string + submit: NewWorktreeFolderSubmit +} + +/** A folder's create, kept from admission until its outcome is known. */ +export type NewWorktreeFolderSubmission = { + settle: (outcome: 'created' | 'uncertain' | 'failed' | 'cancelled') => void +} + +/** How the folder screen owns its composer's creates. */ +export type NewWorktreeFolderSubmit = { + /** Admits a create for the picked repo before anything is sent; null while another is out for it. */ + begin: (repo: MobileWorkspaceRepo) => NewWorktreeFolderSubmission | null + /** False once the folder screen is left: the create runs on, without haptics. */ + presenting: () => boolean +} + export type NewWorktreeModalProps = { visible: boolean client: RpcClient | null @@ -37,6 +61,7 @@ export type NewWorktreeModalProps = { executionHost?: ExecutionHostId ) => void onClose: () => void + folderLaunch?: NewWorktreeFolderLaunch } export type SetupRunPolicy = 'ask' | 'run-by-default' | 'skip-by-default' diff --git a/mobile/src/components/use-new-workspace-create-submit.ts b/mobile/src/components/use-new-workspace-create-submit.ts index 13f5d3cd165..3ee45a87b10 100644 --- a/mobile/src/components/use-new-workspace-create-submit.ts +++ b/mobile/src/components/use-new-workspace-create-submit.ts @@ -3,7 +3,9 @@ import { useRef, useState, type Dispatch, type SetStateAction } from 'react' import type { PersistedTrustedOrcaHooks } from '../../../src/shared/orca-yaml-hook-types' import type { RetiredNameRegistry } from '../../../src/shared/worktree/retired-name-registry' import type { RpcClient } from '../transport/rpc/rpc-client-contract' +import { folderCreateBusyMessage, uncertainCreateMessage } from './new-workspace-create-copy' import { triggerError, triggerSuccess } from '../platform/haptics' +import type { WorktreeCreateParent } from '../tasks/worktree-create-retry' import { createBlankWorkspace } from '../tasks/blank-workspace-create' import { isMobileTuiAgentEnabled } from '../tasks/mobile-tui-agents' import { @@ -24,7 +26,14 @@ import { type NewWorktreeAgentOption, type NewWorktreeRuntimeSettings } from './new-worktree-agent-selection' -import type { MobileWorkspaceRepo, SetupRunPolicy } from './new-worktree-modal-types' +import type { + MobileWorkspaceRepo, + NewWorktreeFolderSubmission, + NewWorktreeFolderSubmit, + SetupRunPolicy +} from './new-worktree-modal-types' +import { getRepoExecutionHostId, type ExecutionHostId } from '../../../src/shared/execution-host' +import { isRpcDeliveryUnknown } from '../transport/rpc/rpc-delivery-ambiguity' import type { OrcaHookTrustPrompt } from './OrcaHookTrustDrawer' import type { NewWorktreeDrawerView } from './use-new-worktree-drawer-navigation' import { getSuggestedCreatureName } from './worktree-name-suggestion' @@ -65,6 +74,11 @@ export function useNewWorkspaceCreateSubmit(args: { setError: Dispatch> onCreated: (worktreeId: string, name: string, warning?: string) => void onClose: () => void + /** Opened from a folder: creates on that folder's host, attached to it, owned by the folder screen. */ + folderLaunch?: NewWorktreeFolderSubmit & { + executionHostId: ExecutionHostId + parent: WorktreeCreateParent + } }): { creating: boolean setupTrustPrompt: OrcaHookTrustPrompt | null @@ -86,7 +100,20 @@ export function useNewWorkspaceCreateSubmit(args: { createInFlightRef.current = true setCreating(true) args.setError('') + const folder = args.folderLaunch + // Admitted for the repo actually picked, before anything is sent; the folder screen owns it until it settles. + const admission = folder + ? getRepoExecutionHostId(selectedRepo) === folder.executionHostId + ? folder.begin(selectedRepo) + : null + : undefined + const presenting = (): boolean => folder?.presenting() ?? true + let outcome: Parameters[0] = 'cancelled' try { + if (admission === null) { + args.setError(folderCreateBusyMessage()) + return + } if (args.sshGate.requiresConnection) { args.setError(`Connect ${selectedRepo.displayName} before creating a workspace.`) return @@ -178,7 +205,8 @@ export function useNewWorkspaceCreateSubmit(args: { agentLaunchSupported: args.getAgentLaunchSupport(), branchIntentSupported: args.getBranchIntentSupport( selection.kind === 'branch' && selection.reuse ? 'open-existing-v2' : 'create-new' - ) + ), + parent: folder?.parent }) : await createBlankWorkspace({ client, @@ -189,20 +217,43 @@ export function useNewWorkspaceCreateSubmit(args: { comment: trimmedNote, setupDecision, worktreeCreateIdempotency: args.getWorktreeCreateCutoverSupport(), - agentLaunchSupported: args.getAgentLaunchSupport() + agentLaunchSupported: args.getAgentLaunchSupport(), + parent: folder?.parent }) if ('error' in result) { - triggerError() + // Refused on a resend after a lost reply: the first send may have created it. + outcome = result.replayed ? 'uncertain' : 'failed' + if (outcome === 'uncertain') { + // Not a failure to retry: creating again could make a second one. + args.setError(uncertainCreateMessage(folder !== undefined)) + return + } + if (presenting()) { + triggerError() + } args.setError(result.error) return } - triggerSuccess() + outcome = 'created' + if (presenting()) { + triggerSuccess() + } args.onClose() args.onCreated(result.worktreeId, result.name, result.warning) } catch (error) { - triggerError() + // A lost reply may still have created it. + outcome = isRpcDeliveryUnknown(error) ? 'uncertain' : 'failed' + if (folder && outcome === 'uncertain') { + // The folder screen refreshes and holds it until its list shows it; sending again could create a second one. + args.setError(uncertainCreateMessage(true)) + return + } + if (presenting()) { + triggerError() + } args.setError(error instanceof Error ? error.message : 'Failed to create workspace') } finally { + admission?.settle(outcome) createInFlightRef.current = false setCreating(false) } diff --git a/mobile/src/components/use-new-workspace-repositories.test.ts b/mobile/src/components/use-new-workspace-repositories.test.ts new file mode 100644 index 00000000000..14196e03e81 --- /dev/null +++ b/mobile/src/components/use-new-workspace-repositories.test.ts @@ -0,0 +1,74 @@ +import { act } from 'react-test-renderer' +import { afterEach, describe, expect, it, vi } from 'vitest' +import type { ExecutionHostId } from '../../../src/shared/execution-host' +import { FakeSession } from '../transport/connection/mobile-endpoint-supervisor-test-fakes' +import { hookMount, settleQueryNotifications } from '../test-support/rpc-recording/hook-mount' +import type { MobileWorkspaceRepo } from './new-worktree-modal-types' +import { useNewWorkspaceRepositories } from './use-new-workspace-repositories' + +vi.mock('react-native', () => ({ AppState: {} })) +const servers = vi.hoisted(() => { + const state: { repos: ReadonlyMap } = { repos: new Map() } + return state +}) +vi.mock('../worktree/use-server-repos', () => ({ useServerRepos: () => servers.repos })) +vi.mock('../worktree/use-last-visited-worktree-repo', () => ({ + useLastVisitedWorktreeRepoId: () => ({ loaded: true, repoId: 'api' }) +})) + +const SERVER: ExecutionHostId = 'runtime:env-1' +const repo = (executionHostId?: ExecutionHostId): MobileWorkspaceRepo => ({ + id: 'api', + displayName: 'api', + path: '/src/api', + kind: 'git', + ...(executionHostId ? { executionHostId } : {}) +}) + +function desktopListing(repos: MobileWorkspaceRepo[]) { + const client = new FakeSession('connected') + client.sendRequest.mockResolvedValue({ + id: '1', + ok: true, + result: { repos }, + _meta: { runtimeId: 'r' } + }) + return client +} + +let mounted: ReturnType | null = null +afterEach(async () => { + await mounted?.unmount() + mounted = null + servers.repos = new Map() +}) + +describe('useNewWorkspaceRepositories initial repo', () => { + it.each([ + { order: 'desktop first', desktopFirst: true }, + { order: 'server first', desktopFirst: false } + ])( + 'picks the named host’s copy of a repo id two hosts share ($order)', + async ({ desktopFirst }) => { + const client = desktopListing(desktopFirst ? [repo()] : []) + let picked: MobileWorkspaceRepo | null = null + mounted = hookMount(() => { + picked = useNewWorkspaceRepositories({ + client, + hostId: 'host-1', + visible: true, + initialRepo: { id: 'api', executionHostId: SERVER } + }).selectedRepo + }) + mounted.mount() + await settleQueryNotifications() + // The desktop's same-id repo must not stand in while the server's listing is on its way. + expect(picked).toBeNull() + + servers.repos = new Map([[SERVER, [repo(SERVER)]]]) + act(() => mounted?.update()) + await settleQueryNotifications() + expect(picked).toMatchObject({ id: 'api', executionHostId: SERVER }) + } + ) +}) diff --git a/mobile/src/components/use-new-workspace-repositories.ts b/mobile/src/components/use-new-workspace-repositories.ts index 4961b186ed2..15a0c14e57e 100644 --- a/mobile/src/components/use-new-workspace-repositories.ts +++ b/mobile/src/components/use-new-workspace-repositories.ts @@ -1,6 +1,6 @@ import { useEffect, useMemo, useState } from 'react' import { useQueryClient } from '@tanstack/react-query' -import type { ExecutionHostId } from '../../../src/shared/execution-host' +import { getRepoExecutionHostId, type ExecutionHostId } from '../../../src/shared/execution-host' import type { RpcClient } from '../transport/rpc/rpc-client-contract' import { cachedHostRepos } from '../host-screen/host-list-queries' import { listHostRepos } from '../worktree/server-repos' @@ -21,6 +21,8 @@ export function useNewWorkspaceRepositories(args: { serverClients?: ReadonlyMap hostId?: string visible: boolean + /** Picked once it is listed, in place of the last visited repo. */ + initialRepo?: { id: string; executionHostId: ExecutionHostId } }): { repos: MobileWorkspaceRepo[] allRepos: MobileWorkspaceRepo[] @@ -31,7 +33,7 @@ export function useNewWorkspaceRepositories(args: { loadError: string | null retryLoad: () => void } { - const { client, serverClients = NO_SERVER_CLIENTS, hostId, visible } = args + const { client, serverClients = NO_SERVER_CLIENTS, hostId, visible, initialRepo } = args const queryClient = useQueryClient() // The host list's repos, so the form opens with them while repo.list answers. const [initialRepos] = useState(() => cachedHostRepos(queryClient, hostId)) @@ -51,7 +53,15 @@ export function useNewWorkspaceRepositories(args: { : [...desktopRepos, ...[...serverRepos.values()].flat()], [desktopRepos, serverRepos] ) - const repos = useMemo(() => getNewWorkspaceDialogEligibleRepos(allRepos), [allRepos]) + const initialRepoId = initialRepo?.id + const initialRepoHost = initialRepo?.executionHostId + // Opened for one host's folder: every picker offers only that host, whose store holds the folder. + const repos = useMemo(() => { + const eligible = getNewWorkspaceDialogEligibleRepos(allRepos) + return initialRepoHost + ? eligible.filter((repo) => getRepoExecutionHostId(repo) === initialRepoHost) + : eligible + }, [allRepos, initialRepoHost]) // Derive the pick so it follows updated listings and disappears when its host stops listing it. const selectedRepo = useMemo( () => refreshMobileNewWorkspaceDialogSelectedRepo(repos, pickedRepo), @@ -59,7 +69,26 @@ export function useNewWorkspaceRepositories(args: { ) useEffect(() => { - if (!visible || !lastVisitedRepo.loaded || selectedRepo || repos.length === 0) { + if (!visible || selectedRepo || !initialRepoId) { + return + } + // Waits for its host's listing: a same-id repo on another host is a different repo. + const initial = repos.find( + (repo) => repo.id === initialRepoId && getRepoExecutionHostId(repo) === initialRepoHost + ) + if (initial) { + setSelectedRepo(initial) + } + }, [initialRepoHost, initialRepoId, repos, selectedRepo, visible]) + + useEffect(() => { + if ( + !visible || + initialRepoId || + !lastVisitedRepo.loaded || + selectedRepo || + repos.length === 0 + ) { return } const preferredRepoId = resolveNewWorkspaceDialogRepoId({ @@ -70,7 +99,7 @@ export function useNewWorkspaceRepositories(args: { if (preferredRepo) { setSelectedRepo(preferredRepo) } - }, [lastVisitedRepo.loaded, lastVisitedRepo.repoId, repos, selectedRepo, visible]) + }, [initialRepoId, lastVisitedRepo.loaded, lastVisitedRepo.repoId, repos, selectedRepo, visible]) useEffect(() => { if (!visible || !client) { diff --git a/mobile/src/dictation/dictation-reply-schema.ts b/mobile/src/dictation/dictation-reply-schema.ts index 23a738977ac..9d2bd752fcc 100644 --- a/mobile/src/dictation/dictation-reply-schema.ts +++ b/mobile/src/dictation/dictation-reply-schema.ts @@ -37,6 +37,8 @@ export const dictationSetupSchema = z.looseObject({ dictationHoldToRecord: salvagedOptional('dictationHoldToRecord', z.boolean()), // Absent from older hosts, which remove no fillers either; the phone then keeps them on, the host default. removeFillerWords: salvagedOptional('removeFillerWords', z.boolean()), + // Absent from older hosts, which stop after a minute; the shared reader maps absent and unknown to that. + stopAfterSilenceSeconds: salvagedOptional('stopAfterSilenceSeconds', z.number().nullable()), // Absent from older hosts, which spell nothing; malformed entries are dropped. dictationTerms: salvagedOptional( 'dictationTerms', diff --git a/mobile/src/dictation/mobile-dictation-host-context.ts b/mobile/src/dictation/mobile-dictation-host-context.ts index 9f4d3c23798..f9acb271e93 100644 --- a/mobile/src/dictation/mobile-dictation-host-context.ts +++ b/mobile/src/dictation/mobile-dictation-host-context.ts @@ -4,6 +4,7 @@ import type { RpcClient } from '../transport/rpc/rpc-client-contract' import type { MobileDictationAwayTarget } from './mobile-dictation-away-insert' import type { MobileDictationLiveText } from './use-mobile-dictation-announcements' import type { DictationTerm } from '../../../src/shared/dictation-dictionary' +import type { StopAfterSilenceSeconds } from '../../../src/shared/dictation-silence-stop' export type MobileDictationHostToast = { message: string; open?: () => void } @@ -21,6 +22,7 @@ export type MobileDictationOwner = { // The target tab's pane key, for a screen still in the stack to switch back to it. readonly paneKey: string | undefined readonly dictationMode: string | undefined + readonly silenceSeconds: StopAfterSilenceSeconds readonly removeFillerWords: boolean // The computer's terms for this worktree, for words the phone recognizes itself. readonly dictationTerms: readonly DictationTerm[] | undefined diff --git a/mobile/src/dictation/mobile-dictation-host.tsx b/mobile/src/dictation/mobile-dictation-host.tsx index b2276df26aa..37daa11a247 100644 --- a/mobile/src/dictation/mobile-dictation-host.tsx +++ b/mobile/src/dictation/mobile-dictation-host.tsx @@ -7,6 +7,7 @@ import { useClipboardWriter } from '../platform/clipboard' import { dictationFailureMessage, isDictationSetupRequiredError } from './mobile-dictation-setup' import { useMobileDictationHaptics } from './use-mobile-dictation-haptics' import { useMobileDictationSilenceStop } from './use-mobile-dictation-silence-stop' +import { DEFAULT_STOP_AFTER_SILENCE_SECONDS } from '../../../src/shared/dictation-silence-stop' import { insertMobileDictationAway } from './mobile-dictation-away-insert' import { nativeChatDictationCopy } from './mobile-session-native-chat-dictation-copy' import { dictationAwayCopy } from './mobile-dictation-away-copy' @@ -145,7 +146,14 @@ export function MobileDictationHostProvider({ children }: { children: ReactNode onAudioLimitReached: () => say(nativeChatDictationCopy.stoppedAtCloudLimit()) }) const stop = useMobileDictationHaptics(dictation) - useMobileDictationSilenceStop(dictation, owner?.dictationMode, stop, (message) => say(message)) + useMobileDictationSilenceStop( + dictation, + owner?.dictationMode, + // Off is null, so only a missing owner takes the default. + owner ? owner.silenceSeconds : DEFAULT_STOP_AFTER_SILENCE_SECONDS, + stop, + (message) => say(message) + ) // Screens subscribe to the live dictation; the host's context only changes when its owner or pill does. const liveRef = useRef(dictation) diff --git a/mobile/src/dictation/mobile-session-native-chat-dictation-copy.ts b/mobile/src/dictation/mobile-session-native-chat-dictation-copy.ts index f7ea2f1ee2e..74babf880fa 100644 --- a/mobile/src/dictation/mobile-session-native-chat-dictation-copy.ts +++ b/mobile/src/dictation/mobile-session-native-chat-dictation-copy.ts @@ -14,9 +14,10 @@ export const nativeChatDictationCopy = { 'session.useNativeChatDictation.stoppedAtCloudLimit', 'Dictation stopped at the 10-minute cloud limit.' ), - stoppedAfterSilence: () => + stoppedAfterSilence: (seconds: number) => translate( - 'session.useNativeChatDictation.stoppedAfterSilence', - 'Stopped after a minute of silence' + 'session.useNativeChatDictation.stoppedAfterSilenceSeconds', + 'Stopped after {{seconds}} seconds of silence', + { seconds } ) } diff --git a/mobile/src/dictation/use-mobile-dictation-silence-stop.ts b/mobile/src/dictation/use-mobile-dictation-silence-stop.ts index 11cc537bccc..e9a6baf5a31 100644 --- a/mobile/src/dictation/use-mobile-dictation-silence-stop.ts +++ b/mobile/src/dictation/use-mobile-dictation-silence-stop.ts @@ -1,5 +1,8 @@ import { useEffect, useEffectEvent } from 'react' -import { watchDictationSilence } from '../../../src/shared/dictation-silence-stop' +import { + watchDictationSilence, + type StopAfterSilenceSeconds +} from '../../../src/shared/dictation-silence-stop' import type { UseMobileDictationResult } from '../hooks/mobile-dictation-session-state' import { nativeChatDictationCopy } from './mobile-session-native-chat-dictation-copy' @@ -7,20 +10,23 @@ import { nativeChatDictationCopy } from './mobile-session-native-chat-dictation- export function useMobileDictationSilenceStop( dictation: Pick, dictationMode: string | undefined, + silenceSeconds: StopAfterSilenceSeconds, stop: () => void, showToast: (message: string) => void ): void { const { meter } = dictation - const watching = dictation.isRecording && dictationMode !== 'hold' + const watching = dictation.isRecording && dictationMode !== 'hold' && silenceSeconds !== null const stopForSilence = useEffectEvent(() => { - showToast(nativeChatDictationCopy.stoppedAfterSilence()) + showToast(nativeChatDictationCopy.stoppedAfterSilence(silenceSeconds ?? 0)) stop() }) useEffect(() => { - if (!watching) { + if (!watching || silenceSeconds === null) { return } - return watchDictationSilence(meter.lastSpeechAt, Date.now, () => stopForSilence()) - }, [meter, watching]) + return watchDictationSilence(meter.lastSpeechAt, Date.now, silenceSeconds * 1000, () => + stopForSilence() + ) + }, [meter, watching, silenceSeconds]) } diff --git a/mobile/src/files/attachments/use-mobile-session-image-attachments.ts b/mobile/src/files/attachments/use-mobile-session-image-attachments.ts index b4ccc6417d4..00af1d341b1 100644 --- a/mobile/src/files/attachments/use-mobile-session-image-attachments.ts +++ b/mobile/src/files/attachments/use-mobile-session-image-attachments.ts @@ -4,8 +4,8 @@ import type { MobileImageSource } from '../../platform/media-picker-contract' import type { MobileNativeChatSendIntent, MobileNativeChatSendOutcome -} from '../../session/native-chat/mobile-native-chat-send' -import type { StructuredMobileSendAttachment } from '../../session/use-mobile-structured-send-with-outcome' +} from '../../session/native-chat/composer/mobile-native-chat-send' +import type { StructuredMobileSendAttachment } from '../../session/native-chat/composer/use-mobile-structured-send-with-outcome' import { useMobileImageAttachment } from './use-mobile-image-attachment' import { useMobileNativeChatImageAttachments, diff --git a/mobile/src/home/MobileHomeNeedsYou.tsx b/mobile/src/home/MobileHomeActiveAgents.tsx similarity index 74% rename from mobile/src/home/MobileHomeNeedsYou.tsx rename to mobile/src/home/MobileHomeActiveAgents.tsx index e31ca0db5c1..4db194940c0 100644 --- a/mobile/src/home/MobileHomeNeedsYou.tsx +++ b/mobile/src/home/MobileHomeActiveAgents.tsx @@ -7,10 +7,10 @@ import { areStructurallyEqual } from '../worktree/structural-equality' import { MobileHomeSectionHeading } from './MobileHomeSectionHeading' // Enough to act on without pushing Desktops off the first screen; the Agents tab has the rest. -const NEEDS_YOU_ROWS_SHOWN = 3 +const ACTIVE_ROWS_SHOWN = 3 -/** Feed's short list of agents waiting on the user; hidden when none are. */ -export const MobileHomeNeedsYou = memo(function MobileHomeNeedsYou(props: { +/** Feed's short list of agents waiting on the user or working, those waiting first; hidden when none are. */ +export const MobileHomeActiveAgents = memo(function MobileHomeActiveAgents(props: { handlers: AgentListRowHandlers rows: readonly AgentListRow[] hosts: readonly HostProfile[] @@ -24,14 +24,14 @@ export const MobileHomeNeedsYou = memo(function MobileHomeNeedsYou(props: { return ( <> 1} hosts={props.hosts} diff --git a/mobile/src/home/tabs/MobileHomeFeedTab.tsx b/mobile/src/home/tabs/MobileHomeFeedTab.tsx index 68e1d7ad013..e3c9b67cd52 100644 --- a/mobile/src/home/tabs/MobileHomeFeedTab.tsx +++ b/mobile/src/home/tabs/MobileHomeFeedTab.tsx @@ -8,12 +8,12 @@ import type { HostCatalogEntry } from '../../transport/hosts/host-profile' import { MobileHomeAppUpdateCard } from '../MobileHomeAppUpdateCard' import { MobileHomeEmptyState } from '../MobileHomeEmptyState' import { MobileHomeHostList } from '../MobileHomeHostList' -import { MobileHomeNeedsYou } from '../MobileHomeNeedsYou' +import { MobileHomeActiveAgents } from '../MobileHomeActiveAgents' import { MobileHomeTasksSection } from '../MobileHomeTasksSection' import type { MobileHomeData } from '../use-mobile-home-data' import { MobileHomeTabHeader } from './MobileHomeTabHeader' -/** Home's first tab: agents that need you, the desktops, and Tasks. */ +/** Home's first tab: agents that need you or are working, the desktops, and Tasks. */ export function MobileHomeFeedTab(props: { data: MobileHomeData bottomInset: number @@ -42,7 +42,7 @@ export function MobileHomeFeedTab(props: { /> ) } - const needsYou = data.agentsNeedingYou.length > 0 + const hasActiveAgents = data.activeAgents.length > 0 return ( <> {title} @@ -53,8 +53,8 @@ export function MobileHomeFeedTab(props: { isWideLayout && { maxWidth: contentMaxWidth, width: '100%', alignSelf: 'center' } ]} > - selectAgentsNeedingYou(agentList), [agentList]) + const activeAgents = useMemo(() => selectActiveAgents(agentList), [agentList]) const needsYouByHost = useMemo( () => countAgentsNeedingYouByHost(agentsNeedingYou), [agentsNeedingYou] @@ -274,6 +276,7 @@ export function useMobileHomeData() { ...connections, accountsByHost, applyAgentActivity: agentActivity.apply, + activeAgents, agentList, agentsNeedingYou, connectedHosts, diff --git a/mobile/src/i18n/bundled-locale-catalogs.ts b/mobile/src/i18n/bundled-locale-catalogs.ts new file mode 100644 index 00000000000..5883e969ed4 --- /dev/null +++ b/mobile/src/i18n/bundled-locale-catalogs.ts @@ -0,0 +1,23 @@ +import type { SupportedUiLocale } from '../../../src/shared/ui-locale' + +export type LocaleCatalog = Readonly> + +// Literal specifiers: Metro evaluates only the chosen module, and the page build splits each into its own chunk. +const CATALOG_IMPORTS: Record, () => Promise> = { + de: () => import('./locales/de.json').then((module) => module.default), + es: () => import('./locales/es.json').then((module) => module.default), + fr: () => import('./locales/fr.json').then((module) => module.default), + ja: () => import('./locales/ja.json').then((module) => module.default), + ko: () => import('./locales/ko.json').then((module) => module.default), + pt: () => import('./locales/pt.json').then((module) => module.default), + ru: () => import('./locales/ru.json').then((module) => module.default), + tr: () => import('./locales/tr.json').then((module) => module.default), + zh: () => import('./locales/zh.json').then((module) => module.default), + 'zh-Hant': () => import('./locales/zh-Hant.json').then((module) => module.default) +} + +export function importBundledLocaleCatalog( + locale: Exclude +): Promise { + return CATALOG_IMPORTS[locale]() +} diff --git a/mobile/src/i18n/locale-catalog-imports.ts b/mobile/src/i18n/locale-catalog-imports.ts index 664d608019e..d89bb938fea 100644 --- a/mobile/src/i18n/locale-catalog-imports.ts +++ b/mobile/src/i18n/locale-catalog-imports.ts @@ -1,23 +1,9 @@ import type { SupportedUiLocale } from '../../../src/shared/ui-locale' +import type { LocaleCatalog } from './bundled-locale-catalogs' -export type LocaleCatalog = Readonly> +export { importBundledLocaleCatalog as importLocaleCatalog } from './bundled-locale-catalogs' -// Literal specifiers: Metro evaluates only the chosen module, and the page build splits each into its own chunk. -const CATALOG_IMPORTS: Record, () => Promise> = { - de: () => import('./locales/de.json').then((module) => module.default), - es: () => import('./locales/es.json').then((module) => module.default), - fr: () => import('./locales/fr.json').then((module) => module.default), - ja: () => import('./locales/ja.json').then((module) => module.default), - ko: () => import('./locales/ko.json').then((module) => module.default), - pt: () => import('./locales/pt.json').then((module) => module.default), - ru: () => import('./locales/ru.json').then((module) => module.default), - tr: () => import('./locales/tr.json').then((module) => module.default), - zh: () => import('./locales/zh.json').then((module) => module.default), - 'zh-Hant': () => import('./locales/zh-Hant.json').then((module) => module.default) -} - -export function importLocaleCatalog( - locale: Exclude -): Promise { - return CATALOG_IMPORTS[locale]() -} +// Bundled catalogs never change after their import, so none arrives later; the page build's .web.ts does. +export const onLocaleCatalogArrival: ( + listener: (locale: Exclude, catalog: LocaleCatalog) => void +) => () => void = () => () => undefined diff --git a/mobile/src/i18n/locale-catalog-imports.web.ts b/mobile/src/i18n/locale-catalog-imports.web.ts new file mode 100644 index 00000000000..9b3d85fdce2 --- /dev/null +++ b/mobile/src/i18n/locale-catalog-imports.web.ts @@ -0,0 +1,36 @@ +import type { SupportedUiLocale } from '../../../src/shared/ui-locale' +import { importBundledLocaleCatalog, type LocaleCatalog } from './bundled-locale-catalogs' + +// A shell that skips the catalog chunks has page-locale-catalog-source.ts read them from the desktop +// and the device store; other shells import the chunk as before. No transport here, so pages that +// only translate pull in none. +export type { LocaleCatalog } +type CatalogLocale = Exclude +type CatalogLoader = (locale: CatalogLocale) => Promise +type ArrivalListener = (locale: CatalogLocale, catalog: LocaleCatalog) => void + +let loader: CatalogLoader | null = null +const arrivalListeners = new Set() + +export function publishPageLocaleCatalogLoader(next: CatalogLoader): void { + loader = next +} + +// Resolve the catalog or reject so activation falls back to English. +export function importLocaleCatalog(locale: CatalogLocale): Promise { + return loader === null ? importBundledLocaleCatalog(locale) : loader(locale) +} + +// A catalog that arrives after activation settled: a newer copy, or the first one after an offline start. +export function onLocaleCatalogArrival(listener: ArrivalListener): () => void { + arrivalListeners.add(listener) + return () => { + arrivalListeners.delete(listener) + } +} + +export function announceLocaleCatalog(locale: CatalogLocale, catalog: LocaleCatalog): void { + for (const listener of arrivalListeners) { + listener(locale, catalog) + } +} diff --git a/mobile/src/i18n/locales/de.json b/mobile/src/i18n/locales/de.json index 6093f930436..ab13aa29c12 100644 --- a/mobile/src/i18n/locales/de.json +++ b/mobile/src/i18n/locales/de.json @@ -2568,8 +2568,8 @@ "insertFailed": "Diktat konnte nicht eingefügt werden", "insertFailedCopied": "Diktat konnte nicht eingefügt werden und wurde daher in die Zwischenablage kopiert", "inserted": "Diktat eingefügt", - "stoppedAfterSilence": "Nach einer Minute Stille beendet", - "stoppedAtCloudLimit": "Diktat am 10-Minuten-Limit der Cloud gestoppt." + "stoppedAtCloudLimit": "Diktat am 10-Minuten-Limit der Cloud gestoppt.", + "stoppedAfterSilenceSeconds": "Nach {{seconds}} Sekunden Stille gestoppt" }, "useNativeChatStop": { "stopNotSent": "Stoppbefehl nicht gesendet", diff --git a/mobile/src/i18n/locales/en.json b/mobile/src/i18n/locales/en.json index 2b821d27ddd..ab589a20033 100644 --- a/mobile/src/i18n/locales/en.json +++ b/mobile/src/i18n/locales/en.json @@ -661,8 +661,8 @@ "openAccountsHint": "Opens this desktop’s accounts", "emptyTitle": "No usage yet" }, - "needsYou": { - "heading": "Needs you", + "activeAgents": { + "heading": "Active", "seeAll": "See all agents" } }, @@ -1491,6 +1491,11 @@ "offlineAsOfTime": { "yesterday": "yesterday, {{time}}" }, + "newWorkspaceCreateSubmit": { + "uncertainFolderCreate": "This worktree may have been created. Check the folder before creating another.", + "uncertainCreate": "This workspace may have been created. Check your workspaces before creating another.", + "folderCreateBusy": "A worktree in this repository is still being created or checked. It shows in the folder once it lands." + }, "smartRailRow": { "title": "Smart rail", "subtitle": "Shows keys for what your agent is doing" @@ -2401,8 +2406,8 @@ "insertFailedCopied": "Couldn't insert dictation, so it was copied to the clipboard", "insertFailed": "Couldn't insert dictation", "inserted": "Dictation inserted", - "stoppedAfterSilence": "Stopped after a minute of silence", - "stoppedAtCloudLimit": "Dictation stopped at the 10-minute cloud limit." + "stoppedAtCloudLimit": "Dictation stopped at the 10-minute cloud limit.", + "stoppedAfterSilenceSeconds": "Stopped after {{seconds}} seconds of silence" }, "quickCommandLaunch": { "editBeforeRunning": "Edit this quick command before running it", @@ -3678,7 +3683,17 @@ "emptyTitle": "No attached worktrees yet", "emptyCopy": "Worktrees created from this workspace will show up here.", "statusUnavailable": "Unavailable", - "backToFolder": "Back to folder" + "backToFolder": "Back to folder", + "createSection": "Create a worktree", + "createIn": "Create a worktree in {{repo}}", + "created": "Created worktree {{name}} in {{repo}}", + "createdNamed": "Created worktree {{name}}", + "createFailed": "Could not create a worktree in {{repo}}.", + "loadReposRetry": "Load repositories", + "setupChoiceTitle": "Retry without setup?", + "setupChoiceMessage": "Orca couldn't confirm the last create in {{repo}}. Retrying it needs a setup choice; it will be created without running the repository's setup.", + "setupChoiceSkip": "Retry without setup", + "checking": "A worktree from {{repo}} may already have been created. Checking the folder…" }, "hostedReviewCopy": { "updatingBranch": "Updating branch...", diff --git a/mobile/src/i18n/locales/es.json b/mobile/src/i18n/locales/es.json index e898993112e..ad24b5ef7c1 100644 --- a/mobile/src/i18n/locales/es.json +++ b/mobile/src/i18n/locales/es.json @@ -2638,8 +2638,8 @@ "insertFailed": "No se pudo insertar el dictado", "insertFailedCopied": "No se pudo insertar el dictado, así que se copió al portapapeles.", "inserted": "Dictado insertado", - "stoppedAfterSilence": "Se detuvo tras un minuto de silencio", - "stoppedAtCloudLimit": "Dictado detenido al llegar al límite de 10 minutos en la nube." + "stoppedAtCloudLimit": "Dictado detenido al llegar al límite de 10 minutos en la nube.", + "stoppedAfterSilenceSeconds": "Detenido tras {{seconds}} segundos de silencio" }, "useNativeChatStop": { "stopNotSent": "No se envió la orden de detener", diff --git a/mobile/src/i18n/locales/fr.json b/mobile/src/i18n/locales/fr.json index 8d807315fb1..e825464bfe5 100644 --- a/mobile/src/i18n/locales/fr.json +++ b/mobile/src/i18n/locales/fr.json @@ -2638,8 +2638,8 @@ "insertFailed": "Impossible d'insérer la dictée", "insertFailedCopied": "Impossible d'insérer la dictée ; elle a été copiée dans le presse-papiers", "inserted": "Dictée insérée", - "stoppedAfterSilence": "Arrêt après une minute de silence", - "stoppedAtCloudLimit": "Dictée arrêtée à la limite cloud de 10 minutes." + "stoppedAtCloudLimit": "Dictée arrêtée à la limite cloud de 10 minutes.", + "stoppedAfterSilenceSeconds": "Arrêté après {{seconds}} secondes de silence" }, "useNativeChatStop": { "stopNotSent": "Commande d'arrêt non envoyée", diff --git a/mobile/src/i18n/locales/ja.json b/mobile/src/i18n/locales/ja.json index d95daaff72f..85a5d0e8e03 100644 --- a/mobile/src/i18n/locales/ja.json +++ b/mobile/src/i18n/locales/ja.json @@ -2564,8 +2564,8 @@ "insertFailed": "ディクテーションの結果を挿入できませんでした。", "insertFailedCopied": "ディクテーションの結果を挿入できず、クリップボードにコピーしました。", "inserted": "ディクテーションの結果を挿入しました。", - "stoppedAfterSilence": "1分間音声がなかったため停止しました。", - "stoppedAtCloudLimit": "クラウドの10分の上限に達したため、ディクテーションが停止しました。" + "stoppedAtCloudLimit": "クラウドの10分の上限に達したため、ディクテーションが停止しました。", + "stoppedAfterSilenceSeconds": "{{seconds}} 秒間無音だったため停止しました" }, "useNativeChatStop": { "stopNotSent": "停止要求を送信できませんでした。", diff --git a/mobile/src/i18n/locales/ko.json b/mobile/src/i18n/locales/ko.json index 2f8b4179263..b4ccb7ee5d9 100644 --- a/mobile/src/i18n/locales/ko.json +++ b/mobile/src/i18n/locales/ko.json @@ -2564,8 +2564,8 @@ "insertFailed": "받아쓰기 내용을 삽입하지 못했습니다.", "insertFailedCopied": "받아쓰기 내용을 삽입하지 못해 클립보드에 복사했습니다.", "inserted": "받아쓰기 내용 삽입됨", - "stoppedAfterSilence": "1분 동안 말소리가 없어 중지했습니다.", - "stoppedAtCloudLimit": "클라우드 10분 제한에 도달해 받아쓰기가 중지되었습니다." + "stoppedAtCloudLimit": "클라우드 10분 제한에 도달해 받아쓰기가 중지되었습니다.", + "stoppedAfterSilenceSeconds": "{{seconds}}초 동안 조용해서 중지했습니다" }, "useNativeChatStop": { "stopNotSent": "중지 요청 전송 안 됨", diff --git a/mobile/src/i18n/locales/pt.json b/mobile/src/i18n/locales/pt.json index bee99bc37a9..105fd84585f 100644 --- a/mobile/src/i18n/locales/pt.json +++ b/mobile/src/i18n/locales/pt.json @@ -2638,8 +2638,8 @@ "insertFailed": "Não foi possível inserir o ditado", "insertFailedCopied": "Não foi possível inserir o ditado, então ele foi copiado para a área de transferência", "inserted": "Ditado inserido", - "stoppedAfterSilence": "Parou após um minuto de silêncio", - "stoppedAtCloudLimit": "O ditado foi interrompido no limite de 10 minutos da nuvem." + "stoppedAtCloudLimit": "O ditado foi interrompido no limite de 10 minutos da nuvem.", + "stoppedAfterSilenceSeconds": "Parado após {{seconds}} segundos de silêncio" }, "useNativeChatStop": { "stopNotSent": "Comando de parada não enviado", diff --git a/mobile/src/i18n/locales/ru.json b/mobile/src/i18n/locales/ru.json index 8ac3e79c21b..d43bb31d722 100644 --- a/mobile/src/i18n/locales/ru.json +++ b/mobile/src/i18n/locales/ru.json @@ -2708,8 +2708,8 @@ "insertFailed": "Не удалось вставить текст диктовки", "insertFailedCopied": "Не удалось вставить текст диктовки — он скопирован в буфер обмена", "inserted": "Текст диктовки вставлен", - "stoppedAfterSilence": "Остановлено после минуты тишины", - "stoppedAtCloudLimit": "Диктовка остановлена: достигнут 10-минутный облачный лимит." + "stoppedAtCloudLimit": "Диктовка остановлена: достигнут 10-минутный облачный лимит.", + "stoppedAfterSilenceSeconds": "Остановлено после {{seconds}} с тишины" }, "useNativeChatStop": { "stopNotSent": "Команда остановки не отправлена", diff --git a/mobile/src/i18n/locales/tr.json b/mobile/src/i18n/locales/tr.json index bf6323cdbc8..a08a81a9ca4 100644 --- a/mobile/src/i18n/locales/tr.json +++ b/mobile/src/i18n/locales/tr.json @@ -2568,8 +2568,8 @@ "insertFailed": "Dikte metni eklenemedi", "insertFailedCopied": "Dikte metni eklenemediği için panoya kopyalandı", "inserted": "Dikte metni eklendi", - "stoppedAfterSilence": "Bir dakika sessizlikten sonra durduruldu", - "stoppedAtCloudLimit": "Dikte, 10 dakikalık bulut sınırında durduruldu." + "stoppedAtCloudLimit": "Dikte, 10 dakikalık bulut sınırında durduruldu.", + "stoppedAfterSilenceSeconds": "{{seconds}} saniyelik sessizlikten sonra durduruldu" }, "useNativeChatStop": { "stopNotSent": "Durdurma isteği gönderilemedi", diff --git a/mobile/src/i18n/locales/zh-Hant.json b/mobile/src/i18n/locales/zh-Hant.json index 5ae56b6e610..5b00ba4341c 100644 --- a/mobile/src/i18n/locales/zh-Hant.json +++ b/mobile/src/i18n/locales/zh-Hant.json @@ -2564,8 +2564,8 @@ "insertFailed": "無法插入聽寫內容", "insertFailedCopied": "無法插入聽寫內容,已複製到剪貼簿", "inserted": "已插入聽寫內容", - "stoppedAfterSilence": "靜音一分鐘後已停止", - "stoppedAtCloudLimit": "已達 10 分鐘雲端上限。聽寫已停止。" + "stoppedAtCloudLimit": "已達 10 分鐘雲端上限。聽寫已停止。", + "stoppedAfterSilenceSeconds": "靜音 {{seconds}} 秒後已停止" }, "useNativeChatStop": { "stopNotSent": "未送出停止命令", diff --git a/mobile/src/i18n/locales/zh.json b/mobile/src/i18n/locales/zh.json index 04c1c5e2e2c..cfda33b5abd 100644 --- a/mobile/src/i18n/locales/zh.json +++ b/mobile/src/i18n/locales/zh.json @@ -2564,8 +2564,8 @@ "insertFailed": "无法插入听写文本", "insertFailedCopied": "无法插入听写文本,已复制到剪贴板", "inserted": "已插入听写文本", - "stoppedAfterSilence": "静音一分钟后已停止", - "stoppedAtCloudLimit": "已达 10 分钟云端上限。听写已停止。" + "stoppedAtCloudLimit": "已达 10 分钟云端上限。听写已停止。", + "stoppedAfterSilenceSeconds": "静音 {{seconds}} 秒后已停止" }, "useNativeChatStop": { "stopNotSent": "停止指令未发送", diff --git a/mobile/src/i18n/mobile-i18n.test.ts b/mobile/src/i18n/mobile-i18n.test.ts index a2906b02959..08e08089f53 100644 --- a/mobile/src/i18n/mobile-i18n.test.ts +++ b/mobile/src/i18n/mobile-i18n.test.ts @@ -7,7 +7,8 @@ vi.mock('./locale-catalog-imports', () => ({ importLocaleCatalog: (locale: string) => failing.has(locale) ? Promise.reject(new Error('missing chunk')) - : new Promise((resolve) => pending.set(locale, resolve)) + : new Promise((resolve) => pending.set(locale, resolve)), + onLocaleCatalogArrival: () => () => undefined })) const { activateMobileUiLocale, getMobileUiLocale, mobileI18n, translate } = diff --git a/mobile/src/i18n/mobile-i18n.ts b/mobile/src/i18n/mobile-i18n.ts index c3f58905000..d3a5b94be34 100644 --- a/mobile/src/i18n/mobile-i18n.ts +++ b/mobile/src/i18n/mobile-i18n.ts @@ -3,7 +3,7 @@ import { resolvePluralFamilyKey } from '../../../src/shared/i18n-plural-family' import { pseudoLocalizeString } from '../../../src/shared/pseudo-localization' import { DEFAULT_UI_LOCALE, type SupportedUiLocale } from '../../../src/shared/ui-locale' import enRuntimeRequired from './en-runtime-required.json' -import { importLocaleCatalog } from './locale-catalog-imports' +import { importLocaleCatalog, onLocaleCatalogArrival } from './locale-catalog-imports' export type Translate = (key: string, fallback: string, options?: TOptions) => string @@ -83,10 +83,12 @@ export function subscribeMobileUiLanguage(listener: () => void): () => void { } let activationRequest = 0 +let requestedLocale: SupportedUiLocale = DEFAULT_UI_LOCALE // Latest request wins: an older catalog import that settles later must not replace a newer choice. export async function activateMobileUiLocale(locale: SupportedUiLocale): Promise { const request = ++activationRequest + requestedLocale = locale try { if (locale !== 'en' && !mobileI18n.hasResourceBundle(locale, 'translation')) { const catalog = await importLocaleCatalog(locale) @@ -115,6 +117,16 @@ export async function activateMobileUiLocale(locale: SupportedUiLocale): Promise publish() } +// Switch in place, without a reload: a newer copy replaces the shown one, a first copy replaces the English fallback. +// Install it even when another language is up now, so switching back shows the newer copy. +onLocaleCatalogArrival((locale, catalog) => { + mobileI18n.removeResourceBundle(locale, 'translation') + mobileI18n.addResourceBundle(locale, 'translation', catalog, false, true, { skipCopy: true }) + if (locale === requestedLocale) { + void activateMobileUiLocale(locale) + } +}) + // Development-only layout check: accents and pads every string so clipping shows on device. export function setMobilePseudoLocalization(enabled: boolean): void { if (pseudoLocalization !== enabled) { diff --git a/mobile/src/i18n/page-locale-catalog-source.test.ts b/mobile/src/i18n/page-locale-catalog-source.test.ts new file mode 100644 index 00000000000..d69a92dc1b2 --- /dev/null +++ b/mobile/src/i18n/page-locale-catalog-source.test.ts @@ -0,0 +1,218 @@ +import { describe, expect, it, vi } from 'vitest' +import type { ConnectionState } from '../transport/connection/connection-state' +import type { RpcResponse } from '../transport/rpc/rpc-wire-types' +import { + decodeDeviceStoreValue, + encodeDeviceStoreValue +} from '../device-store/device-store-value-codec' +import type { PageDeviceStore } from '../mobile-web-shell/bridge/page-device-store' + +// The page build resolves mobile-i18n's catalog import to the .web module; mirror that here. +vi.mock('./locale-catalog-imports', () => import('./locale-catalog-imports.web')) +// A shell that skipped the catalog chunks: only locales listed here are on disk. +const chunksOnDisk = new Map>() +vi.mock('./bundled-locale-catalogs', () => ({ + importBundledLocaleCatalog: async (locale: string) => { + const catalog = chunksOnDisk.get(locale) + if (!catalog) { + throw new Error('not on disk') + } + return catalog + } +})) + +const OLD_SHA = 'a'.repeat(64) +const NEW_SHA = 'b'.repeat(64) + +type SentRequest = { + method: string + params: unknown + reply: (response: RpcResponse) => void + fail: (error: Error) => void +} + +function fakeClient(initial: ConnectionState) { + let state = initial + let generation = 1 + const listeners = new Set<(next: ConnectionState) => void>() + const sent: SentRequest[] = [] + return { + sent, + getState: () => state, + getGeneration: () => generation, + onStateChange: (listener: (next: ConnectionState) => void) => { + listeners.add(listener) + return () => { + listeners.delete(listener) + } + }, + sendRequest: (method: string, params?: unknown) => + new Promise((reply, fail) => sent.push({ method, params, reply, fail })), + moveTo(next: ConnectionState) { + state = next + for (const listener of listeners) { + listener(next) + } + }, + // The shell swaps in an already-connected replacement, as on a relay-to-LAN move. + cutover() { + generation += 1 + for (const listener of listeners) { + listener('connected') + } + } + } +} + +function fakeStore(rows: Record): PageDeviceStore & { rows: Map } { + const stored = new Map(Object.entries(rows)) + return { + rows: stored, + available: () => true, + read: async (_table, keys) => ({ + status: 'ok', + values: keys.map((key) => stored.get(key) ?? null) + }), + write: async (_table, ops) => { + for (const op of ops) { + if (op.value !== null) { + stored.set(op.key, op.value) + } + } + return { written: true } + } + } +} + +const { startPageLocaleCatalogs } = await import('./page-locale-catalog-source') +const i18n = await import('./mobile-i18n') + +// Module state outlives a test, so each test uses its own locale and publishes its own source. +function openPage(client: ReturnType, store: PageDeviceStore): void { + startPageLocaleCatalogs({ client, store }) +} + +// Microtasks, then one macrotask, which is when the store write runs. +async function settle(): Promise { + for (let turn = 0; turn < 20; turn++) { + await Promise.resolve() + } + await new Promise((resolve) => setTimeout(resolve, 0)) +} + +describe('the page language catalog', () => { + it('opens on the stored copy, then switches in place to the desktop newer one', async () => { + const client = fakeClient('connected') + const store = fakeStore({ + 'i18n-catalog:de': encodeDeviceStoreValue({ + v: 1, + sha256: OLD_SHA, + catalog: { greeting: 'Hallo' } + }) + }) + openPage(client, store) + + await i18n.activateMobileUiLocale('de') + expect(i18n.translate('greeting', 'Hello')).toBe('Hallo') + expect(client.sent.map(({ method, params }) => ({ method, params }))).toEqual([ + { method: 'mobileWeb.bundle.localeCatalog', params: { locale: 'de', knownSha256: OLD_SHA } } + ]) + + client.sent[0].reply({ + id: 'r1', + ok: true, + result: { locale: 'de', sha256: NEW_SHA, catalog: { greeting: 'Servus' } } + }) + await settle() + + expect(i18n.getMobileUiLocale()).toBe('de') + expect(i18n.translate('greeting', 'Hello')).toBe('Servus') + expect(decodeDeviceStoreValue(store.rows.get('i18n-catalog:de') ?? '')).toEqual({ + v: 1, + sha256: NEW_SHA, + catalog: { greeting: 'Servus' } + }) + }) + + it('shows English offline with nothing stored, then the language once the desktop answers', async () => { + vi.spyOn(console, 'warn').mockImplementation(() => {}) + const client = fakeClient('reconnecting') + openPage(client, fakeStore({})) + + await i18n.activateMobileUiLocale('fr') + expect(i18n.getMobileUiLocale()).toBe('en') + expect(i18n.translate('greeting', 'Hello')).toBe('Hello') + expect(client.sent).toHaveLength(0) + + client.moveTo('connected') + await settle() + expect(client.sent.map(({ params }) => params)).toEqual([{ locale: 'fr' }]) + client.sent[0].reply({ + id: 'r1', + ok: true, + result: { locale: 'fr', sha256: NEW_SHA, catalog: { greeting: 'Bonjour' } } + }) + await settle() + + expect(i18n.getMobileUiLocale()).toBe('fr') + expect(i18n.translate('greeting', 'Hello')).toBe('Bonjour') + }) + + it('opens in English when the first request fails on a live link, then switches on the next connection', async () => { + vi.spyOn(console, 'warn').mockImplementation(() => {}) + const client = fakeClient('connected') + openPage(client, fakeStore({})) + + const activation = i18n.activateMobileUiLocale('ja') + await settle() + client.sent[0].fail(new Error('timed out')) + await activation + expect(i18n.getMobileUiLocale()).toBe('en') + + client.moveTo('reconnecting') + client.moveTo('connected') + await settle() + client.sent[1].reply({ + id: 'r2', + ok: true, + result: { locale: 'ja', sha256: NEW_SHA, catalog: { greeting: 'こんにちは' } } + }) + await settle() + + expect(i18n.getMobileUiLocale()).toBe('ja') + expect(i18n.translate('greeting', 'Hello')).toBe('こんにちは') + }) + + it('asks again on the connection a cutover swaps in, without waiting for another reconnect', async () => { + vi.spyOn(console, 'warn').mockImplementation(() => {}) + const client = fakeClient('reconnecting') + openPage(client, fakeStore({})) + + await i18n.activateMobileUiLocale('ko') + client.moveTo('connected') + await settle() + client.cutover() + client.sent[0].fail(new Error('client cut over')) + await settle() + client.sent[1].reply({ + id: 'r2', + ok: true, + result: { locale: 'ko', sha256: NEW_SHA, catalog: { greeting: '안녕하세요' } } + }) + await settle() + + expect(i18n.getMobileUiLocale()).toBe('ko') + expect(i18n.translate('greeting', 'Hello')).toBe('안녕하세요') + }) + + it('imports the chunk an older shell left on disk, with no wait and no request', async () => { + chunksOnDisk.set('es', { greeting: 'Hola' }) + const client = fakeClient('reconnecting') + openPage(client, fakeStore({})) + + await i18n.activateMobileUiLocale('es') + + expect(i18n.translate('greeting', 'Hello')).toBe('Hola') + expect(client.sent).toHaveLength(0) + }) +}) diff --git a/mobile/src/i18n/page-locale-catalog-source.ts b/mobile/src/i18n/page-locale-catalog-source.ts new file mode 100644 index 00000000000..76333fdc22b --- /dev/null +++ b/mobile/src/i18n/page-locale-catalog-source.ts @@ -0,0 +1,265 @@ +import * as z from 'zod' +import type { SupportedUiLocale } from '../../../src/shared/ui-locale' +import { SHA256_PATTERN } from '../../../src/shared/mobile-web-bundle/manifest-contract' +import { + MOBILE_WEB_BUNDLE_LOCALE_CATALOG_METHOD, + MobileWebBundleLocaleCatalogResultSchema +} from '../../../src/shared/mobile-web-bundle/locale-catalog-contract' +import { withTimeoutResult } from '../../../src/shared/promise-timeout-fallback' +import { + decodeDeviceStoreValue, + encodeDeviceStoreValue +} from '../device-store/device-store-value-codec' +import type { BridgeRpcClient } from '../mobile-web-shell/bridge/bridge-rpc-client' +import type { PageDeviceStore } from '../mobile-web-shell/bridge/page-device-store' +import { isMobileMethodUnavailableError } from '../transport/rpc/mobile-method-unavailable' +import { captureRpcOperationSettlement, defineRpcOperation } from '../transport/rpc/rpc-operation' +import { rpcResultVariant } from '../transport/rpc/rpc-operation-result-reader' +import { importBundledLocaleCatalog } from './bundled-locale-catalogs' +import { + announceLocaleCatalog as announce, + publishPageLocaleCatalogLoader, + type LocaleCatalog +} from './locale-catalog-imports.web' + +// The desktop serves the active catalog and the phone keeps a copy per host; only the page entry imports this. +type CatalogLocale = Exclude +type HeldCatalog = { readonly sha256: string; readonly catalog: LocaleCatalog } +type CatalogClient = Pick< + BridgeRpcClient, + 'getState' | 'getGeneration' | 'onStateChange' | 'sendRequest' +> +type CatalogSource = { readonly client: CatalogClient; readonly store: PageDeviceStore } + +const storedCatalogSchema = z.object({ + v: z.literal(1), + sha256: z.string().regex(SHA256_PATTERN), + catalog: z.record(z.string(), z.unknown()) +}) + +const localeCatalogRead = defineRpcOperation({ + name: 'mobileWeb.bundle-locale-catalog', + method: MOBILE_WEB_BUNDLE_LOCALE_CATALOG_METHOD, + acceptance: 'require-result-or-throw', + barrier: 'on-settle', + // Loose like every phone reader, so a host may add fields. + read: rpcResultVariant( + 'mobile-web-bundle-locale-catalog', + MobileWebBundleLocaleCatalogResultSchema.loose() + ) +}) + +const syncing = new Set() +// The stored read plus a relay round trip with the largest catalog fit well inside; past it the page opens in English. +const FIRST_PAINT_CATALOG_WAIT_MS = 3_000 + +const storeKey = (locale: CatalogLocale): string => `i18n-catalog:${locale}` + +async function readStoredCatalog( + store: PageDeviceStore, + locale: CatalogLocale +): Promise { + if (!store.available()) { + return null + } + const read = await store.read('cache', [storeKey(locale)]).catch(() => null) + const raw = read?.status === 'ok' ? read.values[0] : null + if (!raw) { + return null + } + const parsed = storedCatalogSchema.safeParse(decodeDeviceStoreValue(raw)) + return parsed.success ? { sha256: parsed.data.sha256, catalog: parsed.data.catalog } : null +} + +function writeStoredCatalog( + store: PageDeviceStore, + locale: CatalogLocale, + next: HeldCatalog +): void { + if (store.available()) { + const value = encodeDeviceStoreValue({ v: 1, ...next }) + void store.write('cache', [{ key: storeKey(locale), value }]).catch(() => undefined) + } +} + +// A send the host never answered, as opposed to a refusal or an unreadable reply. +class CatalogSendFailed extends Error { + constructor( + message: string, + readonly generation: number | null = null + ) { + super(message) + } +} + +const generationOf = (client: CatalogClient): number | null => client.getGeneration?.() ?? null + +// After a failed send, wait for a reconnect or a cutover to another connection, which is often connected already. +// False once pairing is revoked: that connection never comes back. +function whenConnected(client: CatalogClient, failedGeneration: number | null): Promise { + let reconnected = failedGeneration === null || client.getState() !== 'connected' + const ready = (): boolean => + client.getState() === 'connected' && (reconnected || generationOf(client) !== failedGeneration) + if (ready() || client.getState() === 'auth-failed') { + return Promise.resolve(ready()) + } + return new Promise((resolve) => { + const stop = client.onStateChange((state) => { + reconnected ||= state !== 'connected' + if (ready() || state === 'auth-failed') { + stop() + resolve(ready()) + } + }) + }) +} + +// Rejects when the connection drops first, so a first paint never waits on a reply that can't come. +function beforeConnectionLoss(client: CatalogClient, work: Promise): Promise { + return new Promise((resolve, reject) => { + const stop = client.onStateChange((state) => { + if (state !== 'connected') { + stop() + reject(new CatalogSendFailed('[i18n] connection lost before the catalog arrived')) + } + }) + work.then( + (value) => { + stop() + resolve(value) + }, + (error: unknown) => { + stop() + reject(error) + } + ) + }) +} + +// One request. On an answer the copy becomes the page's and the store's. +async function askHost( + { client, store }: CatalogSource, + locale: CatalogLocale, + known: HeldCatalog | undefined +): Promise { + const generation = generationOf(client) + const settled = await captureRpcOperationSettlement(client, localeCatalogRead, { + locale, + ...(known ? { knownSha256: known.sha256 } : {}) + }) + if (settled.status === 'rejected') { + throw new CatalogSendFailed(`[i18n] the ${locale} catalog request got no answer`, generation) + } + const { outcome } = settled + if (outcome.kind === 'decoded') { + const { sha256, catalog } = outcome.value + // A null catalog only confirms the copy the phone named. + const next = catalog !== null ? { sha256, catalog } : known?.sha256 === sha256 ? known : null + if (next) { + if (next !== known) { + // After the first paint: encoding the copy is main-thread work nothing waits on. + setTimeout(() => { + writeStoredCatalog(store, locale, next) + }, 0) + } + return next + } + } + const refusal = outcome.kind === 'outer-refused' ? outcome.error : undefined + throw new Error( + isMobileMethodUnavailableError(refusal?.code, refusal?.message) + ? '[i18n] this desktop serves no language catalogs' + : `[i18n] the desktop answered no ${locale} catalog` + ) +} + +// Asks until the host answers, resending once per new connection; a refusal ends it. +async function syncFromHost( + current: CatalogSource, + locale: CatalogLocale, + known: HeldCatalog | undefined, + failedGeneration: number | null +): Promise { + for (;;) { + if (!(await whenConnected(current.client, failedGeneration))) { + throw new Error('[i18n] this phone is no longer paired with the desktop') + } + try { + return await askHost(current, locale, known) + } catch (error) { + if (!(error instanceof CatalogSendFailed)) { + throw error + } + failedGeneration = error.generation + } + } +} + +// One sync per locale, announcing a copy other than the one the page already shows. +function syncOnce( + current: CatalogSource, + locale: CatalogLocale, + known: HeldCatalog | undefined, + failedGeneration: number | null = null +): void { + if (syncing.has(locale)) { + return + } + syncing.add(locale) + syncFromHost(current, locale, known, failedGeneration).then( + (next) => { + syncing.delete(locale) + if (next !== known) { + announce(locale, next.catalog) + } + }, + () => { + syncing.delete(locale) + } + ) +} + +// What a first paint may wait for: the stored copy, else one request while connected. +async function firstCatalog(current: CatalogSource, locale: CatalogLocale): Promise { + // Only a locale with no catalog installed is asked for, so nothing is held in memory here. + const known = await readStoredCatalog(current.store, locale) + if (known) { + // Show the stored copy now; a newer one replaces it when the host answers. + syncOnce(current, locale, known) + return known + } + if (current.client.getState() !== 'connected') { + throw new CatalogSendFailed('[i18n] no connection for the catalog yet') + } + return beforeConnectionLoss(current.client, askHost(current, locale, undefined)) +} + +async function loadCatalog(current: CatalogSource, locale: CatalogLocale): Promise { + // A generation an older shell downloaded still holds the chunk: no wait, and this page's own strings. + const bundled = await importBundledLocaleCatalog(locale).catch(() => null) + if (bundled !== null) { + return bundled + } + const first = firstCatalog(current, locale) + const settled = await withTimeoutResult(first, FIRST_PAINT_CATALOG_WAIT_MS) + if (settled.ok) { + return settled.value.catalog + } + // Activation shows English meanwhile; whatever comes later switches the page in place. + first.then( + (late) => { + announce(locale, late.catalog) + }, + (failure: unknown) => { + if (failure instanceof CatalogSendFailed) { + syncOnce(current, locale, undefined, failure.generation) + } + } + ) + throw new Error(`[i18n] no ${locale} catalog for the first paint`) +} + +// Before the first activation, so its catalog comes from the desktop and the store. +export function startPageLocaleCatalogs(current: CatalogSource): void { + publishPageLocaleCatalogLoader((locale) => loadCatalog(current, locale)) +} diff --git a/mobile/src/mobile-web-shell/bridge-host-init.test.ts b/mobile/src/mobile-web-shell/bridge-host-init.test.ts index 0a64fd9585f..a2add44e7ad 100644 --- a/mobile/src/mobile-web-shell/bridge-host-init.test.ts +++ b/mobile/src/mobile-web-shell/bridge-host-init.test.ts @@ -48,6 +48,7 @@ describe('init and state', () => { expect(init.grants.native).toEqual([ BRIDGE_FAULT_GRANT, BRIDGE_RPC_ENVELOPE_GRANT, + 'hostCatalogs', 'navigate', 'storage', 'haptics', diff --git a/mobile/src/mobile-web-shell/bridge-host-native-verbs.test.ts b/mobile/src/mobile-web-shell/bridge-host-native-verbs.test.ts index 87e837fc66b..3a9655cfb7b 100644 --- a/mobile/src/mobile-web-shell/bridge-host-native-verbs.test.ts +++ b/mobile/src/mobile-web-shell/bridge-host-native-verbs.test.ts @@ -205,7 +205,7 @@ describe('grants scoped to the route the page was opened for', () => { const bridge = harness({ routeGrants: navigationOnly, ready: true }) expect(bridge.last()).toMatchObject({ type: 'init', - grants: { native: ['fault', 'rpcEnvelope', 'navigate', 'storage'] } + grants: { native: ['fault', 'rpcEnvelope', 'hostCatalogs', 'navigate', 'storage'] } }) for (const [method, params] of [ ['native.clipboard.read', { mime: 'text' }], diff --git a/mobile/src/mobile-web-shell/bridge-host.ts b/mobile/src/mobile-web-shell/bridge-host.ts index 914b25c9b70..166f3e791d3 100644 --- a/mobile/src/mobile-web-shell/bridge-host.ts +++ b/mobile/src/mobile-web-shell/bridge-host.ts @@ -7,9 +7,8 @@ import { BridgeHostRequests } from './bridge-host-requests' import { BridgeHostSubscriptions } from './bridge-host-subscriptions' import { createBridgeHostStreamFrames } from './bridge-host-stream-frames' import { - BRIDGE_FAULT_GRANT, BRIDGE_PROTOCOL_VERSION, - BRIDGE_RPC_ENVELOPE_GRANT, + BRIDGE_SHELL_GRANTS, readBridgeClientMessage, type BridgeClientMessage } from './bridge/bridge-envelope' @@ -30,11 +29,7 @@ export type { BridgeHost, BridgeHostDiagnostic, BridgeHostOptions } from './brid // Bind the host structurally to one RPC client; the protocol lets pages name no other host. Native origin checks reject expired sessions, and init caps are enforced here. export function createBridgeHost(options: BridgeHostOptions): BridgeHost { const { client, buildId, sessionId, pageRoutes, host } = options - const granted: readonly string[] = [ - BRIDGE_FAULT_GRANT, - BRIDGE_RPC_ENVELOPE_GRANT, - ...options.routeGrants - ] + const granted: readonly string[] = [...BRIDGE_SHELL_GRANTS, ...options.routeGrants] // Validate manifest pairs like the route: a pair refused by the page would invalidate the entire init. const parsedRouteGrants = options.pageRouteGrants === undefined diff --git a/mobile/src/mobile-web-shell/bridge/bridge-envelope.ts b/mobile/src/mobile-web-shell/bridge/bridge-envelope.ts index 8f8e8946fa9..5af16b2a9b3 100644 --- a/mobile/src/mobile-web-shell/bridge/bridge-envelope.ts +++ b/mobile/src/mobile-web-shell/bridge/bridge-envelope.ts @@ -32,10 +32,12 @@ export { BRIDGE_EXTERNAL_LINK_GRANT, BRIDGE_FAULT_GRANT, BRIDGE_FOREGROUND_NUDGE_REASONS, + BRIDGE_HOST_CATALOGS_GRANT, BRIDGE_ID_PATTERN, BRIDGE_NAVIGATE_BACK_NOTIFY, BRIDGE_PROTOCOL_VERSION, - BRIDGE_RPC_ENVELOPE_GRANT + BRIDGE_RPC_ENVELOPE_GRANT, + BRIDGE_SHELL_GRANTS } from './bridge-frame-fields' import { isPageStorageKey, diff --git a/mobile/src/mobile-web-shell/bridge/bridge-frame-fields.ts b/mobile/src/mobile-web-shell/bridge/bridge-frame-fields.ts index 9fea8193746..0a2ce887cd6 100644 --- a/mobile/src/mobile-web-shell/bridge/bridge-frame-fields.ts +++ b/mobile/src/mobile-web-shell/bridge/bridge-frame-fields.ts @@ -25,3 +25,13 @@ export const BRIDGE_EXTERNAL_LINK_GRANT = 'externalLink' // Negotiate rpcEnvelope before relying on extra wire fields; older shells drop unknown fields and could execute without caller-required metadata. export const BRIDGE_RPC_ENVELOPE_GRANT = 'rpcEnvelope' + +// The shell skipped the build's language-catalog chunks, so the page reads its catalog from the desktop. +export const BRIDGE_HOST_CATALOGS_GRANT = 'hostCatalogs' + +// Granted to every page this shell opens, whatever its route declares. +export const BRIDGE_SHELL_GRANTS: readonly string[] = [ + BRIDGE_FAULT_GRANT, + BRIDGE_RPC_ENVELOPE_GRANT, + BRIDGE_HOST_CATALOGS_GRANT +] diff --git a/mobile/src/mobile-web-shell/bridge/bridge-init-frame.ts b/mobile/src/mobile-web-shell/bridge/bridge-init-frame.ts index 2c5208dfe6f..ac4c256e67f 100644 --- a/mobile/src/mobile-web-shell/bridge/bridge-init-frame.ts +++ b/mobile/src/mobile-web-shell/bridge/bridge-init-frame.ts @@ -6,9 +6,8 @@ import { import { BRIDGE_MAX_PENDING_REQUESTS, BRIDGE_MAX_SUBSCRIPTIONS } from './bridge-caps' import { MOBILE_WEB_SHELL_GRANTS } from '../page-route-policy' import { - BRIDGE_FAULT_GRANT, BRIDGE_PROTOCOL_VERSION, - BRIDGE_RPC_ENVELOPE_GRANT, + BRIDGE_SHELL_GRANTS, type BridgeColorScheme, type BridgeConnectionSnapshot, type BridgeHostMessage, @@ -27,8 +26,7 @@ import type { HostStatusReply } from '../../transport/hosts/host-status-reply-sc // Grant the intersection of implemented capabilities and route declarations, plus protocol fault. Use the same resolved list for init and enforcement; new names need no version bump. export const BRIDGE_NATIVE_GRANTS: readonly string[] = [ - BRIDGE_FAULT_GRANT, - BRIDGE_RPC_ENVELOPE_GRANT, + ...BRIDGE_SHELL_GRANTS, ...MOBILE_WEB_SHELL_GRANTS ] diff --git a/mobile/src/mobile-web-shell/generation-manifest-read.ts b/mobile/src/mobile-web-shell/generation-manifest-read.ts index 875cf4966d5..71c6ee09e18 100644 --- a/mobile/src/mobile-web-shell/generation-manifest-read.ts +++ b/mobile/src/mobile-web-shell/generation-manifest-read.ts @@ -1,5 +1,6 @@ import { MobileWebBundleManifestReadSchema, + shellDownloadedAssets, type MobileWebBundleManifestRead } from '../transport/web-bundle/mobile-web-bundle-reply-schemas' import { MANIFEST_FILE_NAME } from './generation-asset-path' @@ -33,12 +34,13 @@ export async function readWaitingStage( } // Deletes are not atomic, so a kill mid-delete can leave the manifest without its assets; only every byte counts as whole. const sizes = new Map() - for (const folder of new Set(manifest.assets.map((asset) => parentOf(asset.path)))) { + const assets = shellDownloadedAssets(manifest) + for (const folder of new Set(assets.map((asset) => parentOf(asset.path)))) { for (const file of await fs.listFiles(folder === '' ? directory : joinUri(directory, folder))) { sizes.set(folder === '' ? file.name : `${folder}/${file.name}`, file.size) } } - const whole = manifest.assets.every((asset) => sizes.get(asset.path) === asset.byteLength) + const whole = assets.every((asset) => sizes.get(asset.path) === asset.byteLength) return whole ? { hostKey, buildId, directory, manifest } : null } diff --git a/mobile/src/mobile-web-shell/generation-staging-assets.ts b/mobile/src/mobile-web-shell/generation-staging-assets.ts index ded1033d931..cd61866c2b4 100644 --- a/mobile/src/mobile-web-shell/generation-staging-assets.ts +++ b/mobile/src/mobile-web-shell/generation-staging-assets.ts @@ -1,10 +1,11 @@ import type { MobileWebBundleFetchResult } from '../transport/web-bundle/mobile-web-bundle-fetch' +import { shellDownloadedAssets } from '../transport/web-bundle/mobile-web-bundle-reply-schemas' import { requireStorablePath } from './generation-asset-path' import { joinUri } from './generation-cache-uri' export function stagingAssetsOf(directory: string, result: MobileWebBundleFetchResult) { const reused = new Set(result.reused) - return result.manifest.assets.map((asset) => ({ + return shellDownloadedAssets(result.manifest).map((asset) => ({ asset, uri: joinUri(directory, requireStorablePath(asset.path)), bytes: reused.has(asset.path) ? null : requireExactBytes(result.assets.get(asset.path), asset) diff --git a/mobile/src/mobile-web-shell/generation-store.test.ts b/mobile/src/mobile-web-shell/generation-store.test.ts index 2a5c4fc70a4..7b5ebd20edf 100644 --- a/mobile/src/mobile-web-shell/generation-store.test.ts +++ b/mobile/src/mobile-web-shell/generation-store.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it } from 'vitest' -import { createGenerationStore, MAX_CACHED_HOSTS } from './generation-store' +import { createGenerationStore } from './generation-store' import { deriveHostCacheKey } from './host-cache-key' import type { MobileWebBundleFetchResult } from '../transport/web-bundle/mobile-web-bundle-fetch' import { computeMobileWebBundleId } from '../../../src/shared/mobile-web-bundle/manifest-contract' @@ -13,7 +13,7 @@ const HOST = deriveHostCacheKey('host-a') function buildResult(options: { buildId?: string - assets?: readonly { path: string; byteLength: number }[] + assets?: readonly { path: string; byteLength: number; kind?: string }[] bytes?: ReadonlyMap }): MobileWebBundleFetchResult { const listed = options.assets ?? [ @@ -24,7 +24,8 @@ function buildResult(options: { path: asset.path, sha256: String(index).repeat(64).slice(0, 64), byteLength: asset.byteLength, - contentType: 'text/html; charset=utf-8' + contentType: 'text/html; charset=utf-8', + ...(asset.kind === undefined ? {} : { kind: asset.kind }) })) const totalBytes = assets.reduce((sum, asset) => sum + asset.byteLength, 0) return { @@ -59,343 +60,6 @@ async function activate( await store.commitGeneration(await store.stageGeneration(hostKey, result)) } -function hostKeys(count: number): string[] { - return Array.from({ length: count }, (_, index) => deriveHostCacheKey(`host-${index}`)) -} - -describe('generation store', () => { - it('refuses an asset that is missing or the wrong length, leaving no generation', async () => { - const fs = createFakeFileSystem() - const store = createGenerationStore({ fileSystem: fs }) - const missing = buildResult({ bytes: new Map([['index.html', new Uint8Array(4)]]) }) - const short = buildResult({ - bytes: new Map([ - ['index.html', new Uint8Array(4)], - ['assets/app.js', new Uint8Array(1)] - ]) - }) - - await expect(store.stageGeneration(HOST, missing)).rejects.toThrow('assets/app.js is absent') - await expect(store.stageGeneration(HOST, short)).rejects.toThrow("not the manifest's 2") - expect(fs.paths()).toEqual([]) - expect(await store.readActiveGeneration(HOST)).toBeNull() - }) - - it('drops the staged tree when a write fails', async () => { - const fs = createFakeFileSystem() - const store = createGenerationStore({ fileSystem: fs }) - fs.failWritesAt(`${HOST}/tmp/${BUILD}/assets/app.js`) - - await expect(store.stageGeneration(HOST, buildResult({}))).rejects.toThrow('disk-full') - - expect(fs.paths().some((path) => path.includes(`tmp/${BUILD}`))).toBe(false) - expect(await store.readActiveGeneration(HOST)).toBeNull() - }) - - it('leaves no generation and no tmp for any host when a download is interrupted', async () => { - const fs = createFakeFileSystem() - const store = createGenerationStore({ fileSystem: fs }) - const other = deriveHostCacheKey('host-b') - // The manifest is written last, so a download cut off mid-stage leaves assets without one. - fs.seed(`${HOST}/tmp/${BUILD}/index.html`, { kind: 'file', bytes: new Uint8Array(4) }) - fs.seed(`${other}/tmp/${BUILD}/index.html`, { kind: 'file', bytes: new Uint8Array(4) }) - - expect(await store.readActiveGeneration(HOST)).toBeNull() - expect(await store.readActiveGeneration(other)).toBeNull() - expect(fs.paths().some((path) => path.includes('/tmp'))).toBe(false) - }) - - it('reads two generations as no activation and drops the host tree', async () => { - const fs = createFakeFileSystem() - const store = createGenerationStore({ fileSystem: fs }) - await activate(store, HOST) - fs.seed(`${HOST}/generations/${'c'.repeat(64)}/manifest.json`, { - kind: 'file', - bytes: new TextEncoder().encode('{}') - }) - - expect(await store.readActiveGeneration(HOST)).toBeNull() - expect(fs.paths().some((path) => path.startsWith(HOST))).toBe(false) - }) - - it('reads an unparseable or mismatched manifest as no activation and drops the host tree', async () => { - for (const body of [ - 'not json', - JSON.stringify({ ...buildResult({}).manifest, buildId: 'd'.repeat(64) }) - ]) { - const fs = createFakeFileSystem() - const store = createGenerationStore({ fileSystem: fs }) - await activate(store, HOST) - fs.seed(`${HOST}/generations/${BUILD}/manifest.json`, { - kind: 'file', - bytes: new TextEncoder().encode(body) - }) - - expect(await store.readActiveGeneration(HOST)).toBeNull() - expect(fs.paths().some((path) => path.startsWith(HOST))).toBe(false) - } - }) - - it('evicts the least recently activated host past the ceiling', async () => { - const fs = createFakeFileSystem() - const store = createGenerationStore({ fileSystem: fs }) - const hosts = hostKeys(MAX_CACHED_HOSTS + 1) - - for (const host of hosts) { - await activate(store, host) - } - - expect(await store.readActiveGeneration(hosts[0])).toBeNull() - expect(fs.paths().some((path) => path.startsWith(hosts[0]))).toBe(false) - for (const host of hosts.slice(1)) { - expect((await store.readActiveGeneration(host))?.buildId).toBe(BUILD) - } - expect(fs.text('hosts.json')).toBe(JSON.stringify(hosts.slice(1))) - }) - - it('evicts a host with no index entry before the least recently activated one', async () => { - const fs = createFakeFileSystem() - const store = createGenerationStore({ fileSystem: fs }) - const [oldest, ...rest] = hostKeys(MAX_CACHED_HOSTS - 1) - const orphan = deriveHostCacheKey('orphan') - for (const host of [oldest, ...rest]) { - await activate(store, host) - } - await activate(store, orphan) - const order = [oldest, ...rest] - fs.seed('hosts.json', { kind: 'file', bytes: new TextEncoder().encode(JSON.stringify(order)) }) - - await activate(store, deriveHostCacheKey('one-too-many')) - - expect(fs.paths().some((path) => path.startsWith(orphan))).toBe(false) - expect((await store.readActiveGeneration(oldest))?.buildId).toBe(BUILD) - }) - - it('never counts or evicts a host that is only mid-download', async () => { - const fs = createFakeFileSystem() - const store = createGenerationStore({ fileSystem: fs }) - const hosts = hostKeys(MAX_CACHED_HOSTS) - const oldest = hosts[0] - const downloading = deriveHostCacheKey('downloading') - for (const host of hosts) { - await activate(store, host) - } - const staged = await store.stageGeneration(downloading, buildResult({})) - - await activate(store, deriveHostCacheKey('one-too-many')) - - // Count activations only; eviction must leave staged downloads intact. - expect(fs.paths().some((path) => path.startsWith(oldest))).toBe(false) - expect(fs.text(`${staged.directory.slice(ROOT.length + 1)}/manifest.json`)).not.toBeNull() - await store.commitGeneration(staged) - expect((await store.readActiveGeneration(downloading))?.buildId).toBe(BUILD) - }) - - it('serializes two stage calls for one host and build', async () => { - const fs = createFakeFileSystem() - const store = createGenerationStore({ fileSystem: fs }) - // Give one build id conflicting asset lists to expose interleaved writes into the same staging directory. - const staging = `${HOST}/tmp/${BUILD}` - const earlier = buildResult({ - buildId: BUILD, - assets: [{ path: 'assets/earlier.js', byteLength: 2 }] - }) - const later = buildResult({ - buildId: BUILD, - assets: [{ path: 'assets/later.js', byteLength: 3 }] - }) - - const [first, second] = await Promise.all([ - store.stageGeneration(HOST, earlier), - store.stageGeneration(HOST, later) - ]) - - expect(first.directory).toBe(second.directory) - expect(fs.writes).toEqual([ - `${staging}/assets/earlier.js`, - `${staging}/manifest.json`, - `${staging}/assets/later.js`, - `${staging}/manifest.json` - ]) - expect(fs.paths().filter((path) => path.startsWith(`${staging}/assets/`))).toEqual([ - `${staging}/assets/later.js` - ]) - }) - - it('refuses a path that escapes the staged tree, and a host key that is not one', async () => { - const fs = createFakeFileSystem() - const store = createGenerationStore({ fileSystem: fs }) - const escapes = [ - '../outside.js', - 'assets/../../outside.js', - '/etc/passwd', - 'assets//app.js', - 'manifest.json', - 'Manifest.JSON' - ] - - for (const path of escapes) { - const result = buildResult({ assets: [{ path, byteLength: 1 }] }) - await expect(store.stageGeneration(HOST, result)).rejects.toThrow('refuses to stage') - } - await expect(store.stageGeneration('host-a', buildResult({}))).rejects.toThrow( - 'not a host cache key' - ) - expect(fs.paths()).toEqual([]) - }) - - it('refuses a rename that did not carry the tree, as Android below API 26 can', async () => { - const fs = createFakeFileSystem() - const store = createGenerationStore({ fileSystem: fs }) - fs.loseContentsOnMove() - - const staged = await store.stageGeneration(HOST, buildResult({})) - await expect(store.commitGeneration(staged)).rejects.toThrow('did not carry its manifest') - - expect(await store.readActiveGeneration(HOST)).toBeNull() - expect(fs.paths().some((path) => path.includes('generations/'))).toBe(false) - }) - - it('keeps the host tree when the manifest read fails, and drops it when it is missing', async () => { - const fs = createFakeFileSystem() - const store = createGenerationStore({ fileSystem: fs }) - const manifest = `${HOST}/generations/${BUILD}/manifest.json` - await activate(store, HOST) - const before = fs.paths().filter((path) => !path.endsWith('/tmp')) - - fs.failReadsAt(manifest) - expect(await store.readActiveGeneration(HOST)).toBeNull() - expect(fs.paths()).toEqual(before) - - fs.failReadsAt(null) - await fs.delete(`${ROOT}/${manifest}`) - expect(await store.readActiveGeneration(HOST)).toBeNull() - expect(fs.paths().some((path) => path.startsWith(HOST))).toBe(false) - }) - - it('replaces an entry named for the build id that is not a readable generation', async () => { - const build = BUILD - // Model a crash between rename and the post-rename manifest check. - for (const seeded of [ - { kind: 'directory' }, - { kind: 'file', bytes: new Uint8Array(1) } - ] as const) { - const fs = createFakeFileSystem() - const store = createGenerationStore({ fileSystem: fs }) - fs.seed(`${HOST}/generations/${build}`, seeded) - - await activate(store, HOST) - - expect((await store.readActiveGeneration(HOST))?.buildId).toBe(build) - expect(fs.text(`${HOST}/generations/${build}/index.html`)).not.toBeNull() - } - }) - - it('refuses a handle whose staged tree is gone without touching the activation', async () => { - const fs = createFakeFileSystem() - const store = createGenerationStore({ fileSystem: fs }) - await activate(store, HOST) - - const staged = await store.stageGeneration(HOST, buildResult(SECOND)) - await store.abortStagedGeneration(staged) - - await expect(store.commitGeneration(staged)).rejects.toThrow('no longer on disk') - expect((await store.readActiveGeneration(HOST))?.buildId).toBe(BUILD) - }) - - it('refuses a staged handle it did not issue', async () => { - const fs = createFakeFileSystem() - const store = createGenerationStore({ fileSystem: fs }) - await activate(store, HOST) - const before = fs.paths() - const forged = { - hostKey: HOST, - buildId: SECOND_BUILD, - directory: `${ROOT}/${HOST}/generations/${BUILD}`, - manifest: buildResult({}).manifest - } - - await expect(store.commitGeneration(forged)).rejects.toThrow('did not issue') - await expect(store.abortStagedGeneration(forged)).rejects.toThrow('did not issue') - expect(fs.paths()).toEqual(before) - expect((await store.readActiveGeneration(HOST))?.buildId).toBe(BUILD) - }) - - it('opens builds kept under the old root without a download once the root moves', async () => { - const fs = createFakeFileSystem() - const legacyRootUri = 'file:///caches/mobile-web' - await activate(createGenerationStore({ fileSystem: { ...fs, rootUri: legacyRootUri } }), HOST) - - const store = createGenerationStore({ fileSystem: fs, legacyRootUri }) - - expect((await store.readActiveGeneration(HOST))?.buildId).toBe(BUILD) - expect(await fs.list(legacyRootUri)).toEqual([]) - }) -}) - -describe('reusable assets for the next download', () => { - const NEXT = buildResult({ - assets: [ - { path: 'index.html', byteLength: 8 }, - { path: 'assets/app-2.js', byteLength: 2 } - ] - }) - const NEXT_BUILD = NEXT.manifest.buildId - const [PAGE, SCRIPT] = NEXT.manifest.assets - const DOWNLOADED = new Map([['index.html', new Uint8Array(8).fill(9)]]) - const LEFT_TO_STAGE = { ...NEXT, assets: DOWNLOADED, reused: ['assets/app-2.js'] } - - it.each([HOST, deriveHostCacheKey('second-host')])( - 'matches cached assets by content for %s', - async (opened) => { - const fs = createFakeFileSystem() - const store = createGenerationStore({ fileSystem: fs }) - expect((await store.openReusableAssets(HOST)).has(SCRIPT!)).toBe(false) - await activate(store, HOST) - - const reusable = await store.openReusableAssets(opened) - - expect(reusable.has(SCRIPT!)).toBe(true) - expect(reusable.has(PAGE!)).toBe(false) - expect(reusable.has({ ...SCRIPT!, sha256: 'f'.repeat(64) })).toBe(false) - expect(await reusable.check(SCRIPT!)).toBe(true) - fs.seed(`${HOST}/generations/${BUILD}/assets/app.js`, { - kind: 'file', - bytes: new Uint8Array(1) - }) - expect(await reusable.check(SCRIPT!)).toBe(false) - } - ) - - it('copies the reused assets beside the downloaded ones and commits the whole build', async () => { - const fs = createFakeFileSystem() - const store = createGenerationStore({ fileSystem: fs }) - await activate(store, HOST) - - await activate(store, HOST, LEFT_TO_STAGE) - - const generation = `${HOST}/generations/${NEXT_BUILD}` - expect(fs.bytes(`${generation}/index.html`)).toEqual(new Uint8Array(8).fill(9)) - expect(fs.bytes(`${generation}/assets/app-2.js`)).toEqual(new Uint8Array(2).fill(7)) - expect((await store.readActiveGeneration(HOST))?.buildId).toBe(NEXT_BUILD) - }) - - it('refuses to stage a reused asset the active generation no longer holds', async () => { - const fs = createFakeFileSystem() - const store = createGenerationStore({ fileSystem: fs }) - await activate(store, HOST) - fs.failReadsAt(`${HOST}/generations/${BUILD}/assets/app.js`) - - await expect(store.stageGeneration(HOST, LEFT_TO_STAGE)).rejects.toThrow('unreadable') - await store.deleteHostCache(HOST) - fs.failReadsAt(null) - await expect(store.stageGeneration(HOST, LEFT_TO_STAGE)).rejects.toThrow( - 'no longer holds the reused asset assets/app-2.js' - ) - expect(fs.paths().some((path) => path.includes(`tmp/${NEXT_BUILD}`))).toBe(false) - }) -}) - // Commit deletes the old build first, so it must not run under a page still loading that build's chunks. describe('an update staged behind a live page', () => { it('stays staged while a page reads the old build, and the next read after it commits', async () => { @@ -413,44 +77,24 @@ describe('an update staged behind a live page', () => { expect(await fs.fileExists(`${ROOT}/${HOST}/generations/${BUILD}/index.html`)).toBe(false) }) - it('lets a page that waited on another page fetch the build itself when that page gives up', async () => { - const store = createGenerationStore({ fileSystem: createFakeFileSystem() }) - const first = await store.claimUpdate(HOST, SECOND_BUILD) - const second = store.claimUpdate(HOST, SECOND_BUILD) - - first?.() - - expect(await second).not.toBeNull() - }) - - it('commits at the next launch when the app ends while the page still reads the old build', async () => { + it('stages a build without its language-catalog chunks and still commits it at the next launch', async () => { const fs = createFakeFileSystem() const first = createGenerationStore({ fileSystem: fs }) await activate(first, HOST) first.holdGeneration(HOST) - first.deferCommit(await first.stageGeneration(HOST, buildResult(SECOND))) + const withCatalog = buildResult({ + assets: [ + { path: 'index.html', byteLength: 8 }, + { path: 'assets/de.js', byteLength: 3, kind: 'catalog' } + ], + bytes: new Map([['index.html', new Uint8Array(8)]]) + }) + first.deferCommit(await first.stageGeneration(HOST, withCatalog)) const relaunched = createGenerationStore({ fileSystem: fs }) - expect((await relaunched.readActiveGeneration(HOST))?.buildId).toBe(SECOND_BUILD) - expect(await fs.fileExists(`${ROOT}/${HOST}/generations/${SECOND_BUILD}/index.html`)).toBe(true) - }) - - it('lets a reader of a host’s build go before a commit or a removal deletes it', async () => { - const fs = createFakeFileSystem() - const onDisk: boolean[] = [] - let reading = BUILD - const store = createGenerationStore({ - fileSystem: fs, - beforeHostFilesDeleted: async (hostKey) => { - onDisk.push(await fs.fileExists(`${ROOT}/${hostKey}/generations/${reading}/manifest.json`)) - } - }) - await activate(store, HOST) - onDisk.length = 0 - await activate(store, HOST, buildResult(SECOND)) - reading = SECOND_BUILD - await store.deleteHostCache(HOST) - expect(onDisk).toEqual([true, true]) + const build = withCatalog.manifest.buildId + expect((await relaunched.readActiveGeneration(HOST))?.buildId).toBe(build) + expect(await fs.fileExists(`${ROOT}/${HOST}/generations/${build}/assets/de.js`)).toBe(false) }) }) diff --git a/mobile/src/mobile-web-shell/mobile-web-shell-session-contract.ts b/mobile/src/mobile-web-shell/mobile-web-shell-session-contract.ts index 1a6f608e8c2..656adbf6b78 100644 --- a/mobile/src/mobile-web-shell/mobile-web-shell-session-contract.ts +++ b/mobile/src/mobile-web-shell/mobile-web-shell-session-contract.ts @@ -25,6 +25,7 @@ export type MobileWebShellGates = { export type MobileWebShellManifestFacts = MobileWebBundleCompatManifest & { readonly buildId: string + // A download with nothing to reuse, in fetch progress's unit (each brotli copy where read, else asset bytes). readonly totalBytes: number readonly totalAssets: number // Older desktops omit routes and serve none. diff --git a/mobile/src/mobile-web-shell/mobile-web-shell-session-effects.ts b/mobile/src/mobile-web-shell/mobile-web-shell-session-effects.ts index c5995d21023..a8d939a15d7 100644 --- a/mobile/src/mobile-web-shell/mobile-web-shell-session-effects.ts +++ b/mobile/src/mobile-web-shell/mobile-web-shell-session-effects.ts @@ -1,8 +1,10 @@ import { fetchMobileWebBundle } from '../transport/web-bundle/mobile-web-bundle-fetch' +import { mobileWebBundleStreamBytes } from '../transport/web-bundle/mobile-web-bundle-window-reader' import { mobileWebBundleManifestRead } from '../transport/web-bundle/mobile-web-bundle-operations' -import type { - MobileWebBundleManifestRead, - MobileWebBundleManifestReply +import { + shellDownloadedAssets, + type MobileWebBundleManifestRead, + type MobileWebBundleManifestReply } from '../transport/web-bundle/mobile-web-bundle-reply-schemas' import type { MobileWebBundleCompatManifest } from '../transport/web-bundle/mobile-web-bundle-compat' import { runRpcOperation } from '../transport/rpc/rpc-operation' @@ -87,8 +89,9 @@ export async function readManifest( manifest: { ...compatOf(manifest), buildId: manifest.buildId, - totalBytes: manifest.totalBytes, - totalAssets: manifest.assets.length, + // What this shell downloads: wire bytes, without the catalog chunks it skips. + totalBytes: mobileWebBundleStreamBytes(opened), + totalAssets: shellDownloadedAssets(manifest).length, routes: manifest.routes } }) diff --git a/mobile/src/mobile-web-shell/removed-host-shell-cache.test.ts b/mobile/src/mobile-web-shell/removed-host-shell-cache.test.ts deleted file mode 100644 index 564fd33101f..00000000000 --- a/mobile/src/mobile-web-shell/removed-host-shell-cache.test.ts +++ /dev/null @@ -1,56 +0,0 @@ -import { beforeEach, describe, expect, it, vi } from 'vitest' - -vi.mock('expo-file-system', () => ({ Directory: class {}, File: class {}, Paths: { cache: '' } })) -vi.mock('./generation-store-file-system', async () => { - const { createFakeGenerationFileSystem } = await import('./generation-file-system-fake') - const fileSystem = createFakeGenerationFileSystem() - return { createExpoGenerationFileSystem: () => fileSystem } -}) - -import { createGenerationStore } from './generation-store' -import { createExpoGenerationFileSystem } from './generation-store-file-system' -import { forgetHostUpdateFailures } from './removed-host-shell-cache' - -function store() { - return createGenerationStore({ fileSystem: createExpoGenerationFileSystem('') }) -} - -async function seed(hostId: string): Promise { - await store().recordUpdateFailure({ - hostId, - at: 1, - reason: 'connection-lost', - hostCode: null, - offeredBuildId: null, - cachedBuildId: null, - outcome: 'opened-cached', - wall: null - }) -} - -describe('forgetHostUpdateFailures', () => { - beforeEach(async () => { - await store().forgetHostUpdateFailures('host-1') - await store().forgetHostUpdateFailures('host-2') - }) - - it("drops the removed host's records and keeps the rest", async () => { - await seed('host-1') - await seed('host-2') - await forgetHostUpdateFailures('host-1') - expect((await store().readUpdateFailures()).map((entry) => entry.hostId)).toEqual(['host-2']) - }) - - it('writes nothing when nothing was recorded', async () => { - const fileSystem = createExpoGenerationFileSystem('') - expect(await fileSystem.readText(`${fileSystem.rootUri}/update-failures.json`)).toBeNull() - const write = vi.spyOn(fileSystem, 'writeText') - try { - await forgetHostUpdateFailures('host-1') - expect(write).not.toHaveBeenCalled() - expect(await fileSystem.readText(`${fileSystem.rootUri}/update-failures.json`)).toBeNull() - } finally { - write.mockRestore() - } - }) -}) diff --git a/mobile/src/mobile-web-shell/use-app-leaves-foreground.ts b/mobile/src/mobile-web-shell/use-app-leaves-foreground.ts index 41306009caa..2a439d8c3fc 100644 --- a/mobile/src/mobile-web-shell/use-app-leaves-foreground.ts +++ b/mobile/src/mobile-web-shell/use-app-leaves-foreground.ts @@ -1,5 +1,5 @@ import { useEffect, useLayoutEffect, useRef } from 'react' -import { AppState } from 'react-native' +import { AppState, Platform } from 'react-native' /** * Calls `onLeave` once each time the app leaves the foreground, before the system can kill it from the app @@ -29,13 +29,17 @@ export function useAppLeavesForeground(onLeave: () => void): void { const change = AppState.addEventListener('change', (next) => next === 'active' ? back() : leave() ) - // Window focus events come from Android only. - const blur = AppState.addEventListener('blur', leave) - const focus = AppState.addEventListener('focus', back) + // Window focus events come from Android only; iOS's RCTAppState rejects the subscription outright + // (a red screen in development), so it is never made there. + const windowFocus = + Platform.OS === 'android' + ? [AppState.addEventListener('blur', leave), AppState.addEventListener('focus', back)] + : [] return () => { change.remove() - blur.remove() - focus.remove() + for (const subscription of windowFocus) { + subscription.remove() + } } }, []) } diff --git a/mobile/src/query/first-paint-query-keys.ts b/mobile/src/query/first-paint-query-keys.ts index 47654004af7..8305d983bb4 100644 --- a/mobile/src/query/first-paint-query-keys.ts +++ b/mobile/src/query/first-paint-query-keys.ts @@ -16,7 +16,7 @@ import { hostProjectSectionsQuery } from '../host-screen/use-host-project-sectio import { sessionTabsFamily, sessionTabsKey } from '../session/tabs/mobile-session-last-tabs' import type { MobileSessionTab } from '../session/tabs/mobile-session-tabs' import { activeSessionTabOf } from '../session/tabs/active-session-tab' -import { storedTabChatTranscriptIdentity } from '../session/native-chat/mobile-native-chat-transcript-store' +import { storedTabChatTranscriptIdentity } from '../session/native-chat/transcript/mobile-native-chat-transcript-store' import { gitStatusQuery } from '../source-control/mobile-git-status-query' import { firstPaintTaskKeys } from '../tasks/task-query-storage' import { hostQueryKey } from './host-query-key' diff --git a/mobile/src/query/page-query-persistence.ts b/mobile/src/query/page-query-persistence.ts index d0dad07998c..0e3eadf7368 100644 --- a/mobile/src/query/page-query-persistence.ts +++ b/mobile/src/query/page-query-persistence.ts @@ -1,6 +1,6 @@ import type { QueryClient } from '@tanstack/react-query' import type { PageDeviceStore } from '../mobile-web-shell/bridge/page-device-store' -import { primeStoredChatTranscripts } from '../session/native-chat/mobile-native-chat-transcript-store' +import { primeStoredChatTranscripts } from '../session/native-chat/transcript/mobile-native-chat-transcript-store' import { firstPaintChatTranscriptIdentity, firstPaintQueryKeys } from './first-paint-query-keys' import { createHostQueryPersistence } from './host-query-persistence' diff --git a/mobile/src/session/MobileNativeChatForkProvider.tsx b/mobile/src/session/MobileNativeChatForkProvider.tsx index 44f80dff88a..6607dae2a36 100644 --- a/mobile/src/session/MobileNativeChatForkProvider.tsx +++ b/mobile/src/session/MobileNativeChatForkProvider.tsx @@ -2,7 +2,7 @@ import { useCallback, useLayoutEffect, useMemo, useRef } from 'react' import { useHostProtocolGates } from '../components/host-protocol-gates-context' import type { TuiAgent } from '../../../src/shared/agent-launch/catalog/tui-agent' import type { StructuredAgentSessionForkSource } from '../../../src/shared/agent-session/structured-agent-session-create' -import { MobileNativeChatForkedFromContext } from './mobile-native-chat-notice-context' +import { MobileNativeChatForkedFromContext } from './native-chat/transcript/mobile-native-chat-notice-context' import { forkMobileStructuredChat } from './mobile-structured-chat-fork' import { MobileNativeChatForkContext, diff --git a/mobile/src/session/__mocks__/mobile-prompt-controller.ts b/mobile/src/session/__mocks__/mobile-prompt-controller.ts index 1e8bd3d9c36..5d374b386be 100644 --- a/mobile/src/session/__mocks__/mobile-prompt-controller.ts +++ b/mobile/src/session/__mocks__/mobile-prompt-controller.ts @@ -2,7 +2,7 @@ import './mobile-prompt-render-mocks' import { createElement } from 'react' import { Pressable } from 'react-native' import type { NativeChatMessage } from '../../../../src/shared/native-chat/native-chat-types' -import type { MobileNativeChatSendOutcome } from '../native-chat/mobile-native-chat-send' +import type { MobileNativeChatSendOutcome } from '../native-chat/composer/mobile-native-chat-send' import type { RpcClient } from '../../transport/rpc/rpc-client-contract' import type { RpcResponse } from '../../transport/rpc/rpc-wire-types' import type { ConnectionState } from '../../transport/connection/connection-state' @@ -55,7 +55,7 @@ vi.mock('../use-mobile-session-view-mode', () => ({ }) })) // The chat's per-connection CI setting read isn't a prompt write; these tests count only those. -vi.mock('../use-mobile-native-chat-ci-result-lines', () => ({ +vi.mock('../native-chat/preferences/use-mobile-native-chat-ci-result-lines', () => ({ useMobileNativeChatCiResultLines: () => false })) vi.mock('../native-chat/use-mobile-native-chat-session-lane', () => ({ diff --git a/mobile/src/session/agent-launch/mobile-existing-agent-launch.ts b/mobile/src/session/agent-launch/mobile-existing-agent-launch.ts index 6b3be4fb6b9..1d2c17eb236 100644 --- a/mobile/src/session/agent-launch/mobile-existing-agent-launch.ts +++ b/mobile/src/session/agent-launch/mobile-existing-agent-launch.ts @@ -22,9 +22,9 @@ import { isAgentLaunchReservationTakenRefusal } from '../../../../src/shared/agent-launch/contracts/agent-launch-replay-refusal' import { sendReplayingAmbiguousDelivery } from '../../tasks/replay-on-ambiguous-delivery' -import { structuredSessionOperationId } from '../structured-session-operation-id' +import { structuredSessionOperationId } from '../native-chat/agent-session/structured-session-operation-id' import { randomV4Uuid } from '../../platform/random-v4-uuid' -import { rememberMobileCreatedStructuredSession } from '../mobile-created-structured-sessions' +import { rememberMobileCreatedStructuredSession } from '../native-chat/agent-session/mobile-created-structured-sessions' // Why: the host waits up to 60s for a terminal agent to become ready before pasting the prompt, // so a prompted launch must outlive that wait or the phone reports a launch that is still running. diff --git a/mobile/src/session/agent-session-write-notice-copy.test.ts b/mobile/src/session/agent-session-write-notice-copy.test.ts deleted file mode 100644 index 5788ba290c2..00000000000 --- a/mobile/src/session/agent-session-write-notice-copy.test.ts +++ /dev/null @@ -1,19 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { agentSessionWriteNoticeParts } from '../../../src/shared/agent-session/failures/agent-session-refusal-notice' -import { agentSessionRefusalFailure } from '../../../src/shared/agent-session/failures/agent-session-write-failure' -import { mobileAgentSessionWriteNoticeText } from './agent-session-write-notice-copy' - -describe('mobileAgentSessionWriteNoticeText', () => { - it('names the attachment an expired refusal lists, as its card labels it', () => { - const failure = agentSessionRefusalFailure({ - code: 'agent_session_operation_invalid', - details: { - reason: 'attachmentExpired', - expiredAttachments: [{ uploadId: 'upload-1', name: 'notes.pdf' }] - } - }) - expect( - mobileAgentSessionWriteNoticeText(agentSessionWriteNoticeParts(failure, 'composer-send')) - ).toBe('notes.pdf expired. Your message was not sent. Remove it and attach it again.') - }) -}) diff --git a/mobile/src/session/mobile-closed-tab-dictation-lifetime.test.tsx b/mobile/src/session/mobile-closed-tab-dictation-lifetime.test.tsx deleted file mode 100644 index f5c97c0cedb..00000000000 --- a/mobile/src/session/mobile-closed-tab-dictation-lifetime.test.tsx +++ /dev/null @@ -1,109 +0,0 @@ -import { createElement, type ReactNode } from 'react' -import { act, create, type ReactTestRenderer } from 'react-test-renderer' -import { afterEach, expect, it, vi } from 'vitest' -import { MobileNativeChatComposer } from './native-chat/composer/MobileNativeChatComposer' -import { captureMobileNativeChatTextDestination } from './native-chat/composer/mobile-native-chat-draft-inputs' -import { - closeMobileNativeChatTabDraft, - readMobileNativeChatDraftEditGeneration, - resetMobileNativeChatDraftStoreForTests, - setMobileNativeChatDraftText -} from './native-chat/composer/mobile-native-chat-draft-store' -import { findByHostType } from '../test-support/react-test-renderer-host-nodes' - -vi.mock('../components/MobileSwitch', () => ({ MobileSwitch: 'Switch' })) -vi.mock('./native-chat/composer/MobileNativeChatContextUsageRing', () => ({ - useMobileNativeChatContextRing: () => ({ barProps: {}, ring: null }) -})) -// BottomDrawer also carries the option pager, which loads Reanimated at import. -vi.mock('react-native-reanimated', async () => - (await import('../test-support/reanimated-pager-stub')).reanimatedPagerStub() -) -vi.mock('react-native', async () => { - const React = await import('react') - return { - ...(await import('../test-support/react-native-motion-stub')).reactNativeMotionStub(), - ActivityIndicator: 'ActivityIndicator', - Image: 'Image', - Keyboard: { dismiss: vi.fn() }, - Platform: { OS: 'ios' }, - Pressable: 'Pressable', - ScrollView: ({ children, ...props }: { children?: ReactNode }) => - React.createElement('ScrollView', props, children), - StyleSheet: { create: (styles: unknown) => styles, hairlineWidth: 1 }, - Text: 'Text', - TextInput: 'TextInput', - View: 'View' - } -}) -vi.mock('lucide-react-native', () => ({ - ArrowUp: 'ArrowUp', - ListEnd: 'ListEnd', - CornerDownRight: 'CornerDownRight', - Check: 'Check', - ChevronDown: 'ChevronDown', - ChevronLeft: 'ChevronLeft', - ChevronRight: 'ChevronRight', - FileText: 'FileText', - Mic: 'Mic', - Package: 'Package', - Plus: 'Plus', - ShieldAlert: 'ShieldAlert', - Square: 'Square', - Terminal: 'Terminal', - X: 'X' -})) -vi.mock('../components/bottom-drawer/mounted-bottom-drawer', () => ({ - MountedBottomDrawer: 'BottomDrawer' -})) -vi.mock('../components/bottom-drawer/bottom-drawer-modal-host-scope', () => ({ - useBottomDrawerModalHost: () => null -})) - -let renderer: ReactTestRenderer | undefined -afterEach(async () => { - await act(async () => renderer?.unmount()) - renderer = undefined - resetMobileNativeChatDraftStoreForTests() -}) - -it.each([false, true])( - 'rejects captured dictation after tab retirement with custom insert=%s', - async (customInsert) => { - const scope = `retired-dictation-${customInsert}` - const insertDictation = vi.fn(() => true) - setMobileNativeChatDraftText(scope, 'old text') - await act(async () => { - renderer = create( - createElement(MobileNativeChatComposer, { - value: 'old text', - draftScopeKey: scope, - insertDictation: customInsert ? insertDictation : undefined, - onChangeText: vi.fn(), - onSend: async () => true, - sendSurfaceId: scope, - getSendCompletionGeneration: () => 0, - getComposerEditGeneration: () => 0 - }) - ) - }) - act(() => findByHostType(renderer!.root, 'TextInput').props.onFocus()) - const insert = captureMobileNativeChatTextDestination()?.insert - if (!insert) { - throw new Error('composer did not register dictation') - } - act(() => { - insert('live dictation') - }) - if (customInsert) { - expect(insertDictation).toHaveBeenCalledOnce() - } else { - expect(readMobileNativeChatDraftEditGeneration(scope)).toBe(2) - } - insertDictation.mockClear() - await act(async () => closeMobileNativeChatTabDraft(scope)) - expect(insert('late dictation')).toBe(false) - expect(insertDictation).not.toHaveBeenCalled() - expect(readMobileNativeChatDraftEditGeneration(scope)).toBe(0) - } -) diff --git a/mobile/src/session/mobile-dictation-session-outcomes.test.tsx b/mobile/src/session/mobile-dictation-session-outcomes.test.tsx index cfbde9cb924..98ea1ae6c0b 100644 --- a/mobile/src/session/mobile-dictation-session-outcomes.test.tsx +++ b/mobile/src/session/mobile-dictation-session-outcomes.test.tsx @@ -4,7 +4,7 @@ import { act } from 'react-test-renderer' import { createWithQueryClient } from '../test-support/query-client-test-renderer' import { beforeEach, describe, expect, it, vi } from 'vitest' import { createFakeRpcClient, type FakeRpcClient } from '../mobile-web-shell/bridge-host-test-fakes' -import type * as NativeChatSendError from './native-chat/use-mobile-native-chat-send-error' +import type * as NativeChatSendError from './native-chat/composer/use-mobile-native-chat-send-error' import type * as NativeChatDraftStore from './native-chat/composer/mobile-native-chat-draft-store' type ChatView = { shown: boolean; scope: string | null } @@ -69,7 +69,7 @@ vi.mock('../platform/clipboard', () => { }) // Stub off-path native chat dependencies to keep Expo out of this mic test. -vi.mock('./native-chat/use-mobile-native-chat-send-error', async (importOriginal) => ({ +vi.mock('./native-chat/composer/use-mobile-native-chat-send-error', async (importOriginal) => ({ ...(await importOriginal()), useMobileNativeChatSendError: () => ({ message: null, @@ -82,7 +82,7 @@ vi.mock('./native-chat/use-mobile-native-chat-send-error', async (importOriginal vi.mock('./native-chat/transcript/use-mobile-native-chat-readability', () => ({ useMobileNativeChatReadability: () => false })) -vi.mock('./native-chat/use-mobile-native-chat-input-lease', () => ({ +vi.mock('./native-chat/composer/use-mobile-native-chat-input-lease', () => ({ useMobileNativeChatInputLease: () => ({ ready: true, readyRef: { current: true }, @@ -297,41 +297,6 @@ describe('a mic tap after the host reported dictation is not set up', () => { }) }) -describe('an audio interruption while recording', () => { - it('finishes the dictation and keeps what was said', async () => { - const rpc = createFakeRpcClient() - await startRecording(rpc) - act(() => seen.audioListeners.get('onAudioInterruption')?.({ data: 'began' })) - const methods = await settle(rpc, 'call me back') - expect(methods).toContain('speech.dictation.finish') - expect(methods).not.toContain('speech.dictation.cancel') - expect(seen.inputs).toEqual(['call me back']) - expect(seen.toasts).toEqual(['Dictation inserted']) - }) -}) - -describe('leaving the session while recording', () => { - it('stops and inserts what was said instead of leaving, and lets the next leave go', async () => { - const rpc = createFakeRpcClient() - const mounted = await startRecording(rpc) - const held: boolean[] = [] - act(() => { - held.push(mounted.current().dictationLeaveHold.hold()) - }) - // Back is released while transcribing, so a swipe can leave too. - expect(mounted.current().dictationLeaveHold.holdsLeave).toBe(false) - act(() => { - held.push(mounted.current().dictationLeaveHold.hold()) - }) - expect(held).toEqual([true, false]) - const methods = await settle(rpc, 'one more thing') - expect(methods.filter((method) => method === 'speech.dictation.finish')).toHaveLength(1) - expect(methods).not.toContain('speech.dictation.cancel') - expect(seen.inputs).toEqual(['one more thing']) - expect(seen.toasts).toEqual(['Dictation inserted']) - }) -}) - describe('a mic tap while the transcript is processing', () => { it('keeps the transcript that comes back', async () => { const rpc = createFakeRpcClient() @@ -367,19 +332,3 @@ describe('a dictation that ends after switching between chat and terminal', () = expect(seen.inputs).toEqual([]) }) }) - -describe('a dictation whose session screen was left', () => { - it('keeps recording, then puts its words in the chat it started in with a toast that opens it', async () => { - seen.chat = { shown: true, scope: 'chat-a' } - const rpc = createFakeRpcClient() - const mounted = await startRecording(rpc) - mounted.leave() - expect(mounted.host().getDictation().isRecording).toBe(true) - expect(mounted.host().pill?.away).toBe(true) - act(() => mounted.host().stop()) - await settle(rpc, 'ship it') - expect(seen.chatWrites).toEqual([['chat-a', 'ship it']]) - expect(mounted.host().pill?.toast?.message).toBe('Inserted in Claude Code') - expect(mounted.host().pill?.toast?.open).toBeTypeOf('function') - }) -}) diff --git a/mobile/src/session/mobile-native-chat-picker-scaling.test.ts b/mobile/src/session/mobile-native-chat-picker-scaling.test.ts deleted file mode 100644 index 8a3adb1e363..00000000000 --- a/mobile/src/session/mobile-native-chat-picker-scaling.test.ts +++ /dev/null @@ -1,86 +0,0 @@ -import { afterEach, expect, it, vi } from 'vitest' -import capture from '../../../src/shared/__fixtures__/omp-native-commands.json' -import * as catalog from '../../../src/shared/native-chat/input/native-chat-slash-commands' -import type { NativeChatPickerItem } from '../../../src/shared/native-chat/input/native-chat-picker-items' -import { deriveComposerAutocomplete } from '../../../src/shared/native-chat/input/native-chat-composer-autocomplete' -import { - mobileComposerCatalog, - boundedMenuItems -} from './native-chat/composer/mobile-native-chat-composer-menu' - -afterEach(() => vi.restoreAllMocks()) - -it('bounds native OMP picker name reads at N/10N while preserving first duplicate descriptions', () => { - const reportedSkills = catalog.sessionReportedSkills - let visits = 0 - vi.spyOn(catalog, 'sessionReportedSkills').mockImplementation((...args) => - reportedSkills(...args).map((skill) => ({ - ...skill, - get name() { - visits += 1 - return skill.name - } - })) - ) - const native = capture.enabled.availableCommands.find((row) => row.name === 'skill:plan')! - for (const surface of ['desktop', 'mobile'] as const) { - const counts = [10, 100].map((size) => { - const reported = [ - ...Array.from({ length: size }, (_, i) => ({ - name: `${native.name}-${i}`, - kind: 'command' as const, - description: i === 0 ? undefined : native.description - })), - { name: `${native.name}-0`, kind: 'command' as const, description: 'Later duplicate' }, - { name: `${native.name}-1`, kind: 'command' as const, description: 'Later duplicate' } - ] - visits = 0 - let rows: NativeChatPickerItem[] - if (surface === 'desktop') { - const picker = deriveComposerAutocomplete( - '/plan', - 5, - catalog.sessionSlashCommandSuggestions('omp', reported), - [], - null, - { status: 'ready', skills: [] }, - null, - catalog.sessionReportedSkills(reported, 'omp') - ) - expect(picker.mode).toBe('slash') - if (picker.mode !== 'slash') { - throw new Error('Missing native picker') - } - rows = picker.items - } else { - const menu = mobileComposerCatalog({ - agent: 'omp', - structured: { reported, conversationCommands: [] } - }) - const picker = deriveComposerAutocomplete( - '/plan', - 5, - menu.commands, - menu.discovery.skills, - menu.profile, - menu.discovery, - null, - menu.sessionSkills - ) - expect(picker.mode).toBe('slash') - rows = picker.mode === 'slash' ? boundedMenuItems(picker.items) : [] - } - const skills = rows.filter((row) => row.kind === 'skill') - expect(skills).toHaveLength(Math.min(size, surface === 'desktop' ? 50 : 10)) - expect(new Set(skills.map((row) => row.token)).size).toBe(skills.length) - expect(skills.find((row) => row.token === '/skill:plan-0')?.description).toBeNull() - expect(skills.find((row) => row.token === '/skill:plan-1')?.description).toBe( - native.description - ) - expect(visits).toBeGreaterThanOrEqual(reported.length) - expect(visits).toBeLessThanOrEqual(10 * reported.length) - return visits - }) - expect(counts[1]).toBeLessThanOrEqual(12 * counts[0]!) - } -}) diff --git a/mobile/src/session/mobile-queued-edit-hook.test-fixture.tsx b/mobile/src/session/mobile-queued-edit-hook.test-fixture.tsx deleted file mode 100644 index fdf2e5e21d0..00000000000 --- a/mobile/src/session/mobile-queued-edit-hook.test-fixture.tsx +++ /dev/null @@ -1,261 +0,0 @@ -import { QueuedMessageUpdateParams } from '../../../src/shared/rpc-contract/structured-agent-session-queued-edit-params' -import { useMobileNativeChatComposerMenu } from './native-chat/composer/use-mobile-native-chat-composer-menu' -import { - resetMobileNativeChatDraftStoreForTests, - useMobileNativeChatDraft -} from './native-chat/composer/mobile-native-chat-draft-store' -import { - updateMobileNativeChatDraftInputs, - resetMobileNativeChatDraftInputsForTests -} from './native-chat/composer/mobile-native-chat-draft-inputs' -import { createElement, type ReactNode } from 'react' -import { act, type ReactTestRenderer } from 'react-test-renderer' -import { createWithQueryClient } from '../test-support/query-client-test-renderer' -import { afterEach, expect, vi } from 'vitest' -import type { - AgentSessionQueuedMessage, - AgentSessionQueuedMessageEditHoldResult -} from '../../../src/shared/agent-session/requests/agent-session-queued-message-wire' -import { agentSessionSendBodyFingerprint } from '../../../src/shared/agent-session/requests/structured-agent-session-send-mutation' -import { queuedMessageWithEdit } from '../../../src/shared/queued-message-edit' -import type { RpcClient } from '../transport/rpc/rpc-client-contract' -import type { RpcResponse } from '../transport/rpc/rpc-wire-types' -import { useMobileStructuredAgentSession } from './use-mobile-structured-agent-session' -import { - CAPABLE, - SESSION_ID, - fieldsOf, - mutationOk, - ok, - snapshotEvent -} from './native-chat/agent-session/use-mobile-structured-agent-session-queued.test-fixture' - -export function withText(body: AgentSessionQueuedMessage['body'], text: string) { - const edited = queuedMessageWithEdit(body, { text }) - if (!edited.ok) { - throw new Error(edited.reason) - } - return edited.body -} - -export function editHoldReply(params: unknown): RpcResponse { - const result: AgentSessionQueuedMessageEditHoldResult = - fieldsOf(params).action === 'release' - ? { status: 'released' } - : { status: 'held', fingerprint: 'fp', leaseDurationMs: 120_000, remainingMs: 120_000 } - return ok(result) -} - -export function readOrHoldReply(method: string, params: unknown): RpcResponse { - return method === 'agentSession.queuedMessageEditHold' - ? editHoldReply(params) - : ok({ models: [], current: {} }) -} - -vi.mock('react-native', async () => ({ - ...(await import('../test-support/react-native-motion-stub')).reactNativeMotionStub(), - Text: 'Text', - View: 'View', - Pressable: 'Pressable', - ScrollView: 'ScrollView', - TextInput: 'TextInput', - ActivityIndicator: 'ActivityIndicator', - Image: 'Image', - Keyboard: { dismiss: vi.fn() }, - Platform: { OS: 'ios' }, - useWindowDimensions: () => ({ fontScale: 1 }), - StyleSheet: { create: (styles: unknown) => styles } -})) -vi.mock('lucide-react-native', () => ({ - FileText: 'FileText', - Package: 'Package', - Terminal: 'Terminal', - ArrowUp: 'ArrowUp', - AtSign: 'AtSign', - AlertCircle: 'AlertCircle', - Image: 'Image', - Paperclip: 'Paperclip', - Check: 'Check', - ChevronDown: 'ChevronDown', - ChevronLeft: 'ChevronLeft', - ChevronRight: 'ChevronRight', - CornerDownRight: 'CornerDownRight', - ListEnd: 'ListEnd', - MoreHorizontal: 'MoreHorizontal', - Mic: 'Mic', - Pencil: 'Pencil', - Play: 'Play', - Plus: 'Plus', - Send: 'Send', - ShieldAlert: 'ShieldAlert', - Square: 'Square', - Trash2: 'Trash2', - X: 'X' -})) -vi.mock('@react-native-async-storage/async-storage', () => ({ - default: { getItem: async () => null, setItem: async () => {}, removeItem: async () => {} } -})) - -export function mobileQueuedEditHarness() { - const state: { - renderer?: ReactTestRenderer - bottomText: string - hook?: ReturnType - menu?: ReturnType - listener?: (data: unknown) => void - } = { bottomText: '' } - const append = vi.fn(() => true) - const error = vi.fn() - const notice = vi.fn() - const resolved = vi.fn() - const sendRequest = vi.fn() - const client: RpcClient = { - sendRequest, - subscribe: (_method, _params, onData) => { - if (_method === 'agentSession.subscribe') { - state.listener = onData - } - return () => {} - }, - updateTerminalSubscriptionViewport: () => {}, - getState: () => 'connected', - getReconnectAttempt: () => 0, - getLastConnectedAt: () => null, - onStateChange: () => () => {}, - notifyForeground: () => {}, - close: () => {} - } - function Harness({ - sessionId = SESSION_ID, - editSupport = true, - enabled = true, - connected = true, - transport = client, - composerScopeKey, - imagesSupport = false, - skillsSupport = false, - agent = 'codex', - renderContent - }: { - sessionId?: string - editSupport?: boolean | null - enabled?: boolean - connected?: boolean - transport?: RpcClient | null - composerScopeKey?: string - imagesSupport?: boolean - skillsSupport?: boolean - agent?: string - renderContent?: (hook: ReturnType) => ReactNode - }): ReactNode { - state.bottomText = useMobileNativeChatDraft('original-bottom') - state.hook = useMobileStructuredAgentSession({ - client: transport, - pairedHostClient: transport, - sessionId, - sourceIdentity: 'host-a', - enabled, - connected, - agent, - hostSupport: - editSupport === null - ? null - : { - ...CAPABLE, - sendSkills: true, - queuedMessages: false, - queuedMessageImageEdit: imagesSupport, - queuedMessageSkillsEdit: skillsSupport, - queuedMessageEdit: editSupport - }, - composerScopeKey, - appendComposerText: append, - onSendError: error, - onQueuedEditNotice: notice, - onActionResolved: resolved - }) - state.menu = useMobileNativeChatComposerMenu({ - value: state.hook.queued.editor?.text ?? '', - onChangeText: (text) => state.hook?.queued.editor?.change(text), - agent, - structuredCatalog: { - reported: [{ name: 'review', kind: 'skill', path: '/B/SKILL.md' }], - conversationCommands: [] - }, - filePaths: [], - focusField: () => {}, - editing: true, - // Mirrors the real composer: the menu hands over its row; the draft keeps name and path. - onPickSkill: ({ token, path }) => { - const key = state.hook?.queued.editor?.scopeKey - if (key && path) { - updateMobileNativeChatDraftInputs(key, (before) => ({ - ...before, - skills: [{ name: token.slice(1), path }] - })) - } - } - }) - return renderContent?.(state.hook) ?? null - } - function requestedFingerprint(message: AgentSessionQueuedMessage) { - const params = sendRequest.mock.calls.findLast( - ([method]) => method === 'agentSession.queuedMessageUpdate' - )?.[1] - const fields = QueuedMessageUpdateParams.parse(params) - const edited = queuedMessageWithEdit(message.body, fields) - if (!edited.ok) { - throw new Error(edited.reason) - } - return agentSessionSendBodyFingerprint(SESSION_ID, edited.body) - } - async function mount( - message: AgentSessionQueuedMessage, - editSupport: boolean | null = true, - agent = 'codex', - sessionId = SESSION_ID - ) { - vi.clearAllMocks() - resetMobileNativeChatDraftInputsForTests() - resetMobileNativeChatDraftStoreForTests() - sendRequest.mockImplementation(async (method, params) => - method === 'agentSession.queuedMessageUpdate' - ? mutationOk({ - status: 'updated', - messageId: message.messageId, - fingerprint: requestedFingerprint(message) - }) - : readOrHoldReply(method, params) - ) - await act(async () => { - state.renderer = createWithQueryClient( - createElement(Harness, { editSupport, agent, sessionId }) - ) - }) - const snapshot = snapshotEvent({ queuedMessages: [message], runningTurn: true }) - act(() => state.listener?.({ ...snapshot, sessionId, page: { ...snapshot.page, sessionId } })) - if (editSupport !== null) { - await act(async () => { - expect(await state.hook!.queued.edit!(message.messageId)).toBe(true) - }) - } - } - afterEach(async () => { - await act(async () => state.renderer?.unmount()) - vi.useRealTimers() - vi.unstubAllGlobals() - }) - - return { - state, - Harness, - mount, - client, - sendRequest, - append, - error, - notice, - resolved, - requestedFingerprint - } -} diff --git a/mobile/src/session/mobile-structured-agent-prompts-free-text.test.ts b/mobile/src/session/mobile-structured-agent-prompts-free-text.test.ts deleted file mode 100644 index 950672cc3c7..00000000000 --- a/mobile/src/session/mobile-structured-agent-prompts-free-text.test.ts +++ /dev/null @@ -1,59 +0,0 @@ -import { describe, expect, it } from 'vitest' -import type { AgentJournalFreeTextInput } from '../../../src/shared/agent-session/journal/agent-session-journal-types' -import { formatQuestionFreeTextAnswer } from './native-chat/input/mobile-native-chat-question' -import { - projectStructuredQuestion, - structuredQuestionResponseTarget, - type StructuredQuestionItem -} from './mobile-structured-agent-prompts' - -function prompt(freeTextInput?: AgentJournalFreeTextInput): StructuredQuestionItem { - return { - itemId: 'item-1', - revision: 3, - sequence: 1, - observedAt: 1, - body: { - kind: 'question', - question: 'Edit the draft', - options: [], - freeTextQuestionId: 'q1', - ...(freeTextInput ? { freeTextInput } : {}), - resolution: { state: 'pending', selectedOptionId: null, resolvedBy: null, resolvedAt: null } - } - } -} - -describe('mobile structured free-text questions', () => { - it('accepts empty and whitespace text only for the matching allowed prompt', () => { - const current = prompt({ allowEmpty: true }) - const projected = projectStructuredQuestion(current)! - for (const answer of ['', ' \n ']) { - const response = formatQuestionFreeTextAnswer(projected, answer) - expect(structuredQuestionResponseTarget(response, current)).toEqual({ - itemId: 'item-1', - expectedRevision: 3, - answer: { questionId: 'q1', optionIds: [], other: answer } - }) - expect(structuredQuestionResponseTarget(response, prompt())).toBeNull() - } - expect( - structuredQuestionResponseTarget(formatQuestionFreeTextAnswer(projected, ''), { - ...current, - revision: 4 - }) - ).toBeNull() - }) - - it('keeps legacy trimming for ordinary free-text answers', () => { - const current = prompt() - const projected = projectStructuredQuestion(current)! - expect( - structuredQuestionResponseTarget( - formatQuestionFreeTextAnswer(projected, ' draft '), - current - ) - ).toMatchObject({ answer: { other: 'draft' } }) - expect(structuredQuestionResponseTarget('', current)).toBeNull() - }) -}) diff --git a/mobile/src/session/mobile-structured-chat-fork.ts b/mobile/src/session/mobile-structured-chat-fork.ts index ff26e8eb7c7..009bde60332 100644 --- a/mobile/src/session/mobile-structured-chat-fork.ts +++ b/mobile/src/session/mobile-structured-chat-fork.ts @@ -7,7 +7,7 @@ import type { StructuredAgentSessionForkSource } from '../../../src/shared/agent-session/structured-agent-session-create' import { AGENT_SESSION_CREATE_TAB_PLACEMENT_RUNTIME_CAPABILITY } from '../../../src/shared/agent-session/agent-session-create-capabilities' -import { createMobileStructuredAgentSession } from './mobile-structured-agent-session-launch' +import { createMobileStructuredAgentSession } from './native-chat/agent-session/mobile-structured-agent-session-launch' import { launchedSelection, withLaunchReply, diff --git a/mobile/src/session/native-chat/MobileNativeChatDiffCard.test.tsx b/mobile/src/session/native-chat/MobileNativeChatDiffCard.test.tsx deleted file mode 100644 index 42da6626f1e..00000000000 --- a/mobile/src/session/native-chat/MobileNativeChatDiffCard.test.tsx +++ /dev/null @@ -1,36 +0,0 @@ -import './transcript/mobile-agent-message-renderer.test-fixture' -import { createElement } from 'react' -import { act, create, type ReactTestRenderer } from 'react-test-renderer' -import { afterEach, expect, it } from 'vitest' -import { findAllByHostType } from '../../test-support/react-test-renderer-host-nodes' -import { Transcript, textIn } from './transcript/mobile-native-chat-turn-diff.test-fixture' - -let renderer: ReactTestRenderer | null = null -afterEach(() => { - act(() => renderer?.unmount()) - renderer = null -}) - -it('shows finished-turn files outside folded work and opens a patch with one tap', () => { - act(() => { - renderer = create(createElement(Transcript, { working: true })) - }) - expect(textIn(renderer!.root)).toContain('greeting.ts') - act(() => { - renderer!.update(createElement(Transcript)) - }) - expect(textIn(renderer!.root)).toContain('greeting.ts') - expect(textIn(renderer!.root)).not.toContain('diagnostic-output') - expect(textIn(renderer!.root)).not.toContain('helloNew()') - const file = findAllByHostType(renderer!.root, 'Pressable').find( - (node) => node.props.accessibilityLabel === '/repo/greeting.ts' - )! - act(() => file.props.onPress()) - expect(textIn(renderer!.root)).toContain('helloNew()') - expect(textIn(renderer!.root)).not.toContain('statusNew()') - act(() => renderer!.unmount()) - act(() => { - renderer = create(createElement(Transcript)) - }) - expect(textIn(renderer!.root)).toContain('status.ts') -}) diff --git a/mobile/src/session/native-chat/MobileNativeChatOverlay.tsx b/mobile/src/session/native-chat/MobileNativeChatOverlay.tsx index 649307a056f..398c127dd31 100644 --- a/mobile/src/session/native-chat/MobileNativeChatOverlay.tsx +++ b/mobile/src/session/native-chat/MobileNativeChatOverlay.tsx @@ -1,4 +1,4 @@ -import { MobileQueuedMessageComposerContext } from '../mobile-queued-message-composer-context' +import { MobileQueuedMessageComposerContext } from './input/mobile-queued-message-composer-context' import { Activity, useCallback, useLayoutEffect, useMemo, useRef, useState } from 'react' import { StyleSheet, View } from 'react-native' import { MobileNativeChatView, type MobileNativeChatInputLockReason } from './MobileNativeChatView' @@ -6,11 +6,11 @@ import { useMobileNativeChatProjection } from './transcript/use-mobile-native-ch import { nativeChatDockedTaskList } from '../../../../src/shared/native-chat/input/native-chat-task-list-state' import type { MobileNativeChatImageAttachments } from './composer/use-mobile-native-chat-image-attachments' import type { MobileNativeChatController } from './mobile-native-chat-controller-contract' -import type { MobileNativeChatStructuredComposer } from './composer/MobileNativeChatComposer' +import type { MobileNativeChatStructuredComposer } from './composer/mobile-native-chat-structured-composer' import { useMobileNativeChatComposerTray } from './composer/use-mobile-native-chat-composer-tray' import { useMobileNativeChatVisualRenderer } from './visual/MobileNativeChatVisual' import { MobileNativeChatVisualContext } from './visual/mobile-native-chat-visual-context' -import { MobileNativeChatRootItemSourceContext } from './mobile-native-chat-item-read' +import { MobileNativeChatRootItemSourceContext } from './transcript/mobile-native-chat-item-read' import { useMobileNativeChatMessageDetail } from './transcript/use-mobile-native-chat-message-detail' import { MobileNativeChatReplyRevealsContext, @@ -19,7 +19,7 @@ import { import { MobileNativeChatRowOverlaysHost } from './transcript/MobileNativeChatRowOverlaysHost' import { nativeChatAskRequiresTerminal } from '../../../../src/shared/native-chat/native-chat-agent-support' import { tuiAgentDisplayName } from '../../../../src/shared/agent-launch/catalog/tui-agent-display-names' -import { MobileNativeChatNoticeContext } from '../mobile-native-chat-notice-context' +import { MobileNativeChatNoticeContext } from './transcript/mobile-native-chat-notice-context' import type { MobileNativeChatImageSource } from './visual/mobile-native-chat-image-preview' import type { MobileNativeChatHostOutage } from './mobile-native-chat-host-outage' import { useMobileNativeChatMarkdownLinks } from './use-mobile-native-chat-markdown-links' diff --git a/mobile/src/session/native-chat/MobileNativeChatView.failure-banner.test.ts b/mobile/src/session/native-chat/MobileNativeChatView.failure-banner.test.ts index 6e7ba0d0431..d2438307f36 100644 --- a/mobile/src/session/native-chat/MobileNativeChatView.failure-banner.test.ts +++ b/mobile/src/session/native-chat/MobileNativeChatView.failure-banner.test.ts @@ -1,14 +1,9 @@ import { describe, expect, it, vi } from 'vitest' import { installChatViewHooks, - assistantTurn, - banners, bannerText, - hostType, - listIds, pressSend, render, - root, update } from './MobileNativeChatView.harness.test-fixture' @@ -51,35 +46,6 @@ vi.mock('./composer/MobileNativeChatComposer', async () => { describe('MobileNativeChatView: send and read failure banners', () => { installChatViewHooks() - it('leaves only the words of a read that failed for good, over a loaded transcript', async () => { - const loaded = [assistantTurn('m1', 'earlier reply')] - const words = 'This chat was saved by a newer Orca. Update Orca to open it.' - const shown = (text: string) => - root().findAll((node) => hostType(node) === 'Text' && node.props.children === text) - const composers = () => root().findAll((node) => hostType(node) === 'Composer') - const lists = () => root().findAll((node) => hostType(node) === 'FlatList') - const failure = { - messages: loaded, - folded: loaded, - status: 'error' as const, - error: words, - canStop: true, - permission: { title: 'Approve?', options: [{ label: 'Allow', send: '1' }] }, - sendErrorMessage: 'Message unconfirmed — check chat before retrying' - } - await render({ ...failure, readFailedFinally: true }) - expect(shown(words)).toHaveLength(1) - expect(composers()).toHaveLength(0) - expect(lists()).toHaveLength(0) - expect(banners()).toHaveLength(0) - expect(root().findAllByProps({ accessibilityLabel: 'Stop the agent' })).toHaveLength(0) - - await update({ ...failure, error: "Orca couldn't open this chat's history right now." }) - expect(listIds()).toEqual(['m1']) - expect(composers()).toHaveLength(1) - expect(banners()).toHaveLength(1) - }) - it('retires the previous banner before sending and preserves the new delivery notice', async () => { const onClearSendError = vi.fn() await render({ @@ -99,6 +65,6 @@ describe('MobileNativeChatView: send and read failure banners', () => { }) }) -vi.mock('../MobileQueuedMessageComposer', () => ({ +vi.mock('./input/MobileQueuedMessageComposer', () => ({ MobileQueuedMessageComposer: 'QueuedMessageComposer' })) diff --git a/mobile/src/session/native-chat/MobileNativeChatView.prompt-presentation.test.ts b/mobile/src/session/native-chat/MobileNativeChatView.prompt-presentation.test.ts deleted file mode 100644 index e905f481014..00000000000 --- a/mobile/src/session/native-chat/MobileNativeChatView.prompt-presentation.test.ts +++ /dev/null @@ -1,188 +0,0 @@ -import './MobileNativeChatView.harness.test-fixture' -import { createElement, type ComponentProps } from 'react' -import { act, create, type ReactTestRenderer } from 'react-test-renderer' -import { Pressable } from 'react-native' -import { afterEach, describe, expect, it, vi } from 'vitest' -import { MobileNativeChatView } from './MobileNativeChatView' -import { useMobileNativeChatPromptPresentation } from './input/use-mobile-native-chat-prompt-presentation' -import type { MobileChatPermission } from './input/mobile-native-chat-permission' -import { setMobileNativeChatDraftText } from './composer/mobile-native-chat-draft-store' -vi.mock('react-native', async () => { - const React = await import('react') - return { - ...(await import('../../test-support/react-native-motion-stub')).reactNativeMotionStub(), - ActivityIndicator: 'ActivityIndicator', - Image: 'Image', - Platform: { OS: 'ios' }, - Keyboard: { dismiss: vi.fn() }, - FlatList: React.forwardRef((props, ref) => { - React.useImperativeHandle(ref, () => ({ scrollToEnd: vi.fn(), scrollToOffset: vi.fn() }), []) - return React.createElement('FlatList', props) - }), - Pressable: 'Pressable', - ScrollView: 'ScrollView', - TextInput: 'TextInput', - StyleSheet: { create: (styles: unknown) => styles, hairlineWidth: 1 }, - Text: 'Text', - View: 'View' - } -}) -vi.mock('react-native-safe-area-context', () => ({ - useSafeAreaInsets: () => ({ top: 0, bottom: 0, left: 0, right: 0 }) -})) -vi.mock('react-native-gesture-handler', () => { - type GestureChain = { - runOnJS: () => GestureChain - onStart: () => GestureChain - onUpdate: () => GestureChain - } - const chain: GestureChain = { runOnJS: () => chain, onStart: () => chain, onUpdate: () => chain } - return { - Gesture: { Simultaneous: () => ({}), Native: () => ({}), Pinch: () => chain }, - GestureDetector: 'GestureDetector', - GestureHandlerRootView: 'GestureHandlerRootView' - } -}) -vi.mock('lucide-react-native', () => - Object.fromEntries( - [ - 'ArrowDown', - 'ArrowUp', - 'ListEnd', - 'CornerDownRight', - 'ChevronDown', - 'ChevronUp', - 'ChevronsDownUp', - 'ChevronsUpDown', - 'ShieldQuestion', - 'ImagePlus', - 'Package', - 'Plus', - 'Mic', - 'Square', - 'X' - ].map((x) => [x, x]) - ) -) -vi.mock('./transcript/MobileNativeChatMessage', () => ({ - MobileNativeChatMessage: 'ChatMessage' -})) -vi.mock('./transcript/MobileNativeChatLiveLine', () => ({ - MobileNativeChatLiveLine: 'LiveStatus' -})) -vi.mock('./input/MobileNativeChatAsk', () => ({ MobileNativeChatAsk: 'ChatAsk' })) -vi.mock('./input/MobileNativeChatQuestion', () => ({ - MobileNativeChatQuestion: 'ChatQuestion' -})) -vi.mock('./input/MobileNativeChatSessionOptionPickers', () => ({ - MobileNativeChatSessionOptionPickers: 'SessionOptions' -})) -vi.mock('./composer/MobileNativeChatComposerMenu', () => ({ - MobileNativeChatComposerSuggestions: 'Suggestions' -})) -vi.mock('../../components/ActionSheetModal', () => ({ ActionSheetModal: 'ActionSheetModal' })) -vi.mock('../../components/MobileMarkdown', () => ({ MobileMarkdown: 'Markdown' })) -let tree: ReactTestRenderer | null = null -setMobileNativeChatDraftText('terminal-1', 'no, do X instead') -const props = { - messages: [], - folded: [], - status: 'ready' as const, - streaming: null, - pending: [], - onSend: vi.fn(async () => true), - sendSurfaceId: 'terminal-1', - getSendCompletionGeneration: () => 0, - getComposerEditGeneration: () => 0, - draftKey: 'terminal-1', - onComposerTextChange: vi.fn() -} -const permission: MobileChatPermission = { - title: 'Claude wants to use Bash', - options: [{ label: 'Deny', send: String.fromCharCode(27) }] -} -type Overrides = Partial> & { - waitStartedAt?: number - sessionKey?: string -} -function Harness(overrides: Overrides) { - const shown = useMobileNativeChatPromptPresentation({ - permission: overrides.permission ?? null, - waitStartedAt: overrides.waitStartedAt ?? 10, - scopeKey: 'tab-1', - sessionKey: overrides.sessionKey ?? 'session-1', - observing: true, - respondPermission: overrides.onRespondPermission ?? (async () => false) - }) - return createElement(MobileNativeChatView, { - ...props, - ...overrides, - permission: shown.permission, - promptKey: shown.occurrenceKey, - onRespondPermission: shown.respondPermission - }) -} -const render = async (overrides: Overrides) => { - await act(async () => { - const element = createElement(Harness, overrides) - if (tree) { - tree.update(element) - } else { - tree = create(element) - } - }) -} -const sendButton = () => tree!.root.findByProps({ accessibilityLabel: 'Send message' }) -const approvalAction = () => - tree!.root.findByProps({ testID: 'native-chat-approval-actions' }).findByType(Pressable) -afterEach(() => { - act(() => tree?.unmount()) - tree = null - vi.unstubAllGlobals() -}) -describe('terminal prompt presentation with the production view, card and composer', () => { - it('a late answer cannot reshow an answered replacement occurrence', async () => { - let finishOld: (accepted: boolean) => void = () => {} - const onRespondPermission = vi - .fn<(send: string) => Promise>() - .mockReturnValueOnce( - new Promise((resolve) => { - finishOld = resolve - }) - ) - .mockResolvedValueOnce(true) - await render({ permission, onRespondPermission }) - act(() => { - void approvalAction().props.onPress() - }) - await render({ permission, onRespondPermission, waitStartedAt: 20 }) - await act(async () => { - await approvalAction().props.onPress() - }) - expect(sendButton().props.disabled).toBe(false) - await act(async () => finishOld(true)) - expect(sendButton().props.disabled).toBe(false) - }) - - it('a late answer cannot dismiss a replacement session', async () => { - let finishOld: (accepted: boolean) => void = () => {} - const onRespondPermission = vi.fn( - () => - new Promise((resolve) => { - finishOld = resolve - }) - ) - await render({ permission, onRespondPermission }) - act(() => { - void approvalAction().props.onPress() - }) - await render({ permission, onRespondPermission, sessionKey: 'session-2' }) - await act(async () => finishOld(true)) - expect(sendButton().props.disabled).toBe(true) - expect(approvalAction().props.disabled).toBe(false) - }) -}) - -vi.mock('../MobileQueuedMessageComposer', () => ({ - MobileQueuedMessageComposer: 'QueuedMessageComposer' -})) diff --git a/mobile/src/session/native-chat/MobileNativeChatView.tsx b/mobile/src/session/native-chat/MobileNativeChatView.tsx index b3eead5e801..5e701c297d3 100644 --- a/mobile/src/session/native-chat/MobileNativeChatView.tsx +++ b/mobile/src/session/native-chat/MobileNativeChatView.tsx @@ -22,19 +22,19 @@ import { useMobileTranslation } from '../../i18n/use-mobile-translation' import { MobileNativeChatInputLockStatus } from './composer/MobileNativeChatInputLockStatus' import { useMobileColorScheme } from '../../theme/use-mobile-color-scheme' import { styles } from './mobile-native-chat-view-styles' -import { MobileNativeChatEmptyStateView } from '../MobileNativeChatEmptyStateView' -import { mobileNativeChatListFooter } from './mobile-native-chat-list-footer' -import { mobileNativeChatListHeader } from './mobile-native-chat-list-header' +import { MobileNativeChatEmptyStateView } from './transcript/MobileNativeChatEmptyStateView' +import { mobileNativeChatListFooter } from './transcript/mobile-native-chat-list-footer' +import { mobileNativeChatListHeader } from './transcript/mobile-native-chat-list-header' import { mobileNativeChatEmptyState, type MobileNativeChatPendingItem -} from './mobile-native-chat-render-data' +} from './transcript/mobile-native-chat-render-data' import { useMobileNativeChatTransientData } from './transcript/use-mobile-native-chat-transient-data' import { useMobileNativeChatRowKeys } from './transcript/mobile-native-chat-row-keys' import { useMobileNativeChatPinchGesture } from './transcript/use-mobile-native-chat-pinch-gesture' import { useMobileNativeChatTailFollow } from './transcript/use-mobile-native-chat-tail-follow' import { useMobileNativeChatTurnDisclosure } from './transcript/use-mobile-native-chat-turn-disclosure' -import { mobileNativeChatComposerPlaceholder } from './use-mobile-native-chat-input-lease' +import { mobileNativeChatComposerPlaceholder } from './composer/use-mobile-native-chat-input-lease' import { MobileNativeChatLiveLine } from './transcript/MobileNativeChatLiveLine' import { MobileNativeChatAwaitingInputRow } from './transcript/MobileNativeChatAwaitingInputRow' import type { NativeChatAwaitingInput } from '../../../../src/shared/native-chat/native-chat-terminal-turn' @@ -43,9 +43,9 @@ import type { PendingNativeChatImage } from './composer/mobile-native-chat-image import type { MobilePastedImages } from './composer/mobile-native-chat-composer-paste' import { MobileNativeChatDraftComposer, - type MobileNativeChatSendProps, - type MobileNativeChatStructuredComposer + type MobileNativeChatSendProps } from './composer/MobileNativeChatComposer' +import type { MobileNativeChatStructuredComposer } from './composer/mobile-native-chat-structured-composer' import { MobileNativeChatPromptCard } from './input/MobileNativeChatPromptCard' import type { MobileNativeChatMicProps } from './composer/MobileNativeChatComposerMic' import { useMobileNativeChatPromptInputOwner } from './input/use-mobile-native-chat-prompt-input-owner' @@ -54,11 +54,11 @@ import { type ComposerTrayProps } from './composer/use-mobile-native-chat-composer-tray' import type { MobileNativeChatSessionOptionPickersProps } from './input/MobileNativeChatSessionOptionPickers' -import { MobileNativeChatScrollRootsBoundary } from '../MobileNativeChatScrollRootsBoundary' +import { MobileNativeChatScrollRootsBoundary } from './transcript/MobileNativeChatScrollRootsBoundary' import { MobileNativeChatRowList } from './transcript/MobileNativeChatRowList' import { useMobileNativeChatRowRenderer } from './transcript/use-mobile-native-chat-row-renderer' -import type { MobileNativeChatStatus } from './use-mobile-native-chat-session' -import type { OlderPagePhase } from '../use-mobile-older-page-loader' +import type { MobileNativeChatStatus } from './mobile-native-chat-session-status' +import type { OlderPagePhase } from './transcript/use-mobile-older-page-loader' import { MobileNativeChatOpenFileContext } from './mobile-native-chat-open-file-context' import { MobileNativeChatLowerRegion } from './MobileNativeChatLowerRegion' import { MobileNativeChatOfflineQueue } from './input/MobileNativeChatOfflineQueue' diff --git a/mobile/src/session/native-chat/MobileNativeChatView.turn-status.test.ts b/mobile/src/session/native-chat/MobileNativeChatView.turn-status.test.ts index 6fa4e9c347b..b8dcf5eda98 100644 --- a/mobile/src/session/native-chat/MobileNativeChatView.turn-status.test.ts +++ b/mobile/src/session/native-chat/MobileNativeChatView.turn-status.test.ts @@ -208,6 +208,6 @@ describe('MobileNativeChatView', () => { }) }) -vi.mock('../MobileQueuedMessageComposer', () => ({ +vi.mock('./input/MobileQueuedMessageComposer', () => ({ MobileQueuedMessageComposer: 'QueuedMessageComposer' })) diff --git a/mobile/src/session/agent-session-failure-copy.ts b/mobile/src/session/native-chat/agent-session/agent-session-failure-copy.ts similarity index 96% rename from mobile/src/session/agent-session-failure-copy.ts rename to mobile/src/session/native-chat/agent-session/agent-session-failure-copy.ts index 541b5a76698..d7779789684 100644 --- a/mobile/src/session/agent-session-failure-copy.ts +++ b/mobile/src/session/native-chat/agent-session/agent-session-failure-copy.ts @@ -2,9 +2,9 @@ import type { AgentSessionFailureCopyId, AgentSessionFailureCopyValues, AgentSessionFailureSay -} from '../../../src/shared/agent-session/failures/agent-session-failure-copy' -import { translate } from '../i18n/mobile-i18n' -import { AGENT_SESSION_FAILURE_COPY } from '../../../src/shared/agent-session/failures/agent-session-failure-copy' +} from '../../../../../src/shared/agent-session/failures/agent-session-failure-copy' +import { translate } from '../../../i18n/mobile-i18n' +import { AGENT_SESSION_FAILURE_COPY } from '../../../../../src/shared/agent-session/failures/agent-session-failure-copy' import { START_FAILURE_COPY } from './agent-session-start-failure-copy' import { SEND_FAILURE_COPY } from './agent-session-send-failure-copy' diff --git a/mobile/src/session/agent-session-send-failure-copy.ts b/mobile/src/session/native-chat/agent-session/agent-session-send-failure-copy.ts similarity index 96% rename from mobile/src/session/agent-session-send-failure-copy.ts rename to mobile/src/session/native-chat/agent-session/agent-session-send-failure-copy.ts index 0a10fcac96f..4efaf079a87 100644 --- a/mobile/src/session/agent-session-send-failure-copy.ts +++ b/mobile/src/session/native-chat/agent-session/agent-session-send-failure-copy.ts @@ -1,9 +1,9 @@ -import { AGENT_SESSION_FAILURE_COPY } from '../../../src/shared/agent-session/failures/agent-session-failure-copy' +import { AGENT_SESSION_FAILURE_COPY } from '../../../../../src/shared/agent-session/failures/agent-session-failure-copy' import type { AgentSessionFailureCopyId, AgentSessionFailureCopyValues -} from '../../../src/shared/agent-session/failures/agent-session-failure-copy' -import { translate } from '../i18n/mobile-i18n' +} from '../../../../../src/shared/agent-session/failures/agent-session-failure-copy' +import { translate } from '../../../i18n/mobile-i18n' export const SEND_FAILURE_COPY = { unconfirmed: (values) => diff --git a/mobile/src/session/agent-session-start-failure-copy.ts b/mobile/src/session/native-chat/agent-session/agent-session-start-failure-copy.ts similarity index 98% rename from mobile/src/session/agent-session-start-failure-copy.ts rename to mobile/src/session/native-chat/agent-session/agent-session-start-failure-copy.ts index 036264d4a0a..924ff47be42 100644 --- a/mobile/src/session/agent-session-start-failure-copy.ts +++ b/mobile/src/session/native-chat/agent-session/agent-session-start-failure-copy.ts @@ -1,8 +1,8 @@ import type { AgentSessionFailureCopyId, AgentSessionFailureCopyValues -} from '../../../src/shared/agent-session/failures/agent-session-failure-copy' -import { translate } from '../i18n/mobile-i18n' +} from '../../../../../src/shared/agent-session/failures/agent-session-failure-copy' +import { translate } from '../../../i18n/mobile-i18n' export const START_FAILURE_COPY = { savedConversationMissing: (values) => diff --git a/mobile/src/session/agent-session-write-notice-copy.ts b/mobile/src/session/native-chat/agent-session/agent-session-write-notice-copy.ts similarity index 96% rename from mobile/src/session/agent-session-write-notice-copy.ts rename to mobile/src/session/native-chat/agent-session/agent-session-write-notice-copy.ts index ffab10462a5..ca95e2529ca 100644 --- a/mobile/src/session/agent-session-write-notice-copy.ts +++ b/mobile/src/session/native-chat/agent-session/agent-session-write-notice-copy.ts @@ -1,10 +1,10 @@ -import { expiredAttachmentsSentence } from '../../../src/shared/agent-session/failures/agent-session-attachment-failure-words' -import { agentSessionFailureSentence } from '../../../src/shared/agent-session/failures/agent-session-failure-words' +import { expiredAttachmentsSentence } from '../../../../../src/shared/agent-session/failures/agent-session-attachment-failure-words' +import { agentSessionFailureSentence } from '../../../../../src/shared/agent-session/failures/agent-session-failure-words' import type { AgentSessionWriteNoticePart, AgentSessionWriteNoticeSentence -} from '../../../src/shared/agent-session/failures/agent-session-write-notice-copy' -import { translate } from '../i18n/mobile-i18n' +} from '../../../../../src/shared/agent-session/failures/agent-session-write-notice-copy' +import { translate } from '../../../i18n/mobile-i18n' import { sayMobileAgentSessionFailure } from './agent-session-failure-copy' const SENTENCES: Record string> = { diff --git a/mobile/src/session/mobile-created-structured-sessions.ts b/mobile/src/session/native-chat/agent-session/mobile-created-structured-sessions.ts similarity index 100% rename from mobile/src/session/mobile-created-structured-sessions.ts rename to mobile/src/session/native-chat/agent-session/mobile-created-structured-sessions.ts diff --git a/mobile/src/session/mobile-structured-agent-session-cancel.ts b/mobile/src/session/native-chat/agent-session/mobile-structured-agent-session-cancel.ts similarity index 89% rename from mobile/src/session/mobile-structured-agent-session-cancel.ts rename to mobile/src/session/native-chat/agent-session/mobile-structured-agent-session-cancel.ts index e7678dfbed5..849b252116f 100644 --- a/mobile/src/session/mobile-structured-agent-session-cancel.ts +++ b/mobile/src/session/native-chat/agent-session/mobile-structured-agent-session-cancel.ts @@ -1,18 +1,18 @@ import { useCallback, useRef } from 'react' import type { StructuredAgentSessionHostSupport } from './mobile-structured-agent-session-host-support' -import type { AgentSessionCancelResult } from '../../../src/shared/agent-session/agent-session-wire' -import type { StructuredAgentSessionState } from '../../../src/shared/agent-session/structured-agent-session-reducer' -import { runningStructuredAgentSessionTurnId } from '../../../src/shared/agent-session/view/structured-agent-session-live-turn' +import type { AgentSessionCancelResult } from '../../../../../src/shared/agent-session/agent-session-wire' +import type { StructuredAgentSessionState } from '../../../../../src/shared/agent-session/structured-agent-session-reducer' +import { runningStructuredAgentSessionTurnId } from '../../../../../src/shared/agent-session/view/structured-agent-session-live-turn' import { joinStructuredAgentSessionStop, structuredAgentSessionStopIsJoinable -} from '../../../src/shared/agent-session/requests/structured-agent-session-stop-join' -import type { RpcClient } from '../transport/rpc/rpc-client-contract' +} from '../../../../../src/shared/agent-session/requests/structured-agent-session-stop-join' +import type { RpcClient } from '../../../transport/rpc/rpc-client-contract' import { requestStructuredAgentSessionMutation, type StructuredAgentSessionMutationCallResult } from './mobile-structured-agent-session-rpc' -import { actionableStructuredPrompts } from './mobile-structured-actionable-prompt' +import { actionableStructuredPrompts } from '../input/mobile-structured-actionable-prompt' type PromptIdentity = { itemId: string; expectedRevision: number } diff --git a/mobile/src/session/mobile-structured-agent-session-contract.ts b/mobile/src/session/native-chat/agent-session/mobile-structured-agent-session-contract.ts similarity index 63% rename from mobile/src/session/mobile-structured-agent-session-contract.ts rename to mobile/src/session/native-chat/agent-session/mobile-structured-agent-session-contract.ts index f3d9f5284fd..f869e25c360 100644 --- a/mobile/src/session/mobile-structured-agent-session-contract.ts +++ b/mobile/src/session/native-chat/agent-session/mobile-structured-agent-session-contract.ts @@ -1,36 +1,36 @@ -import type { AgentSessionSlashCommand } from '../../../src/shared/agent-session/agent-session-wire' -import type { NativeChatSendFollowUp } from '../../../src/shared/native-chat/input/native-chat-follow-up-behavior' -import type { RpcClient } from '../transport/rpc/rpc-client-contract' +import type { AgentSessionSlashCommand } from '../../../../../src/shared/agent-session/agent-session-wire' +import type { NativeChatSendFollowUp } from '../../../../../src/shared/native-chat/input/native-chat-follow-up-behavior' +import type { RpcClient } from '../../../transport/rpc/rpc-client-contract' import type { StructuredAgentSessionHostSupport } from './mobile-structured-agent-session-host-support' import type { MobileNativeChatSendIntent, MobileNativeChatSendOutcome -} from './native-chat/mobile-native-chat-send' -import type { MobileNativeChatVisualSource } from './native-chat/visual/mobile-native-chat-visual-read' -import type { MobileChatPermission } from './native-chat/input/mobile-native-chat-permission' -import type { MobileChatQuestion } from './native-chat/input/mobile-native-chat-question' -import type { MobileNativeChatSession } from './native-chat/use-mobile-native-chat-session' -import type { NativeChatLiveTurnIndicator } from '../../../src/shared/native-chat/transcript/native-chat-turn-status' -import type { NativeChatResolvedPrompt } from '../../../src/shared/native-chat/native-chat-resolution-receipt' -import type { useMobileStructuredAgentOptions } from './use-mobile-structured-agent-options' -import type { useMobileStructuredAgentTurnTiming } from './use-mobile-structured-agent-turn-timing' -import type { StructuredMobileSendAttachment } from './use-mobile-structured-send-with-outcome' +} from '../composer/mobile-native-chat-send' +import type { MobileNativeChatVisualSource } from '../visual/mobile-native-chat-visual-read' +import type { MobileChatPermission } from '../input/mobile-native-chat-permission' +import type { MobileChatQuestion } from '../input/mobile-native-chat-question' +import type { MobileNativeChatSession } from '../use-mobile-native-chat-session' +import type { NativeChatLiveTurnIndicator } from '../../../../../src/shared/native-chat/transcript/native-chat-turn-status' +import type { NativeChatResolvedPrompt } from '../../../../../src/shared/native-chat/native-chat-resolution-receipt' +import type { useMobileStructuredAgentOptions } from '../input/use-mobile-structured-agent-options' +import type { useMobileStructuredAgentTurnTiming } from '../transcript/use-mobile-structured-agent-turn-timing' +import type { StructuredMobileSendAttachment } from '../composer/use-mobile-structured-send-with-outcome' import type { AgentJournalSkillRef, AgentJournalSubmission -} from '../../../src/shared/agent-session/journal/agent-session-journal-types' +} from '../../../../../src/shared/agent-session/journal/agent-session-journal-types' import type { MobileNativeChatCommandRefusalCauses, MobileNativeChatSendErrorReporter -} from './native-chat/use-mobile-native-chat-send-error' -import type { MobileStructuredQueuedMessageControls } from './use-mobile-structured-queued-message-controls' -import type { MobileStructuredBackgroundTasks } from './use-mobile-structured-background-tasks' -import type { NativeChatContextUsageSummary } from '../../../src/shared/native-chat/native-chat-context-usage-summary' -import type { MobileStructuredInterruptedContinue } from './use-mobile-structured-interrupted-continue' -import type { MobileStructuredThreadGoal } from './use-mobile-structured-thread-goal' -import type { MobileStructuredSends } from './use-mobile-structured-sends' -import type { AgentSessionRewindSurface } from '../../../src/shared/agent-session/lifecycle/agent-session-rewind-request' -import type { MobileNativeChatUsageLimit } from './native-chat/use-mobile-native-chat-usage-limit' +} from '../composer/use-mobile-native-chat-send-error' +import type { MobileStructuredQueuedMessageControls } from '../input/use-mobile-structured-queued-message-controls' +import type { MobileStructuredBackgroundTasks } from '../input/use-mobile-structured-background-tasks' +import type { NativeChatContextUsageSummary } from '../../../../../src/shared/native-chat/native-chat-context-usage-summary' +import type { MobileStructuredInterruptedContinue } from '../composer/use-mobile-structured-interrupted-continue' +import type { MobileStructuredThreadGoal } from '../input/use-mobile-structured-thread-goal' +import type { MobileStructuredSends } from '../composer/use-mobile-structured-sends' +import type { AgentSessionRewindSurface } from '../../../../../src/shared/agent-session/lifecycle/agent-session-rewind-request' +import type { MobileNativeChatUsageLimit } from '../use-mobile-native-chat-usage-limit' export type StructuredMobileSession = Omit< ReturnType, diff --git a/mobile/src/session/mobile-structured-agent-session-host-support.ts b/mobile/src/session/native-chat/agent-session/mobile-structured-agent-session-host-support.ts similarity index 90% rename from mobile/src/session/mobile-structured-agent-session-host-support.ts rename to mobile/src/session/native-chat/agent-session/mobile-structured-agent-session-host-support.ts index af40170fc5b..ab43f813b57 100644 --- a/mobile/src/session/mobile-structured-agent-session-host-support.ts +++ b/mobile/src/session/native-chat/agent-session/mobile-structured-agent-session-host-support.ts @@ -2,12 +2,12 @@ import { AGENT_SESSION_COMMANDS_ON_REQUEST_CAPABILITY, AGENT_SESSION_MODEL_EFFORT_DISCOVERY_CAPABILITY, AGENT_SESSION_COHERENT_MODEL_CATALOG_CAPABILITY -} from '../../../src/shared/agent-session/structured-agent-session-surface-capabilities' +} from '../../../../../src/shared/agent-session/structured-agent-session-surface-capabilities' import { AGENT_SESSION_CONVERSATION_STOP_RUNTIME_CAPABILITY, AGENT_SESSION_PROMPT_CANCEL_RUNTIME_CAPABILITY, AGENT_SESSION_REPEATED_STOP_RUNTIME_CAPABILITY -} from '../../../src/shared/agent-session/lifecycle/agent-session-stop-capabilities' +} from '../../../../../src/shared/agent-session/lifecycle/agent-session-stop-capabilities' import { AGENT_SESSION_ITEM_DETAIL_RUNTIME_CAPABILITY, AGENT_SESSION_SEND_RECORDED_RUNTIME_CAPABILITY, @@ -22,21 +22,21 @@ import { AGENT_SESSION_PHONE_REWIND_RUNTIME_CAPABILITY, AGENT_SESSION_PHONE_USAGE_LIMIT_CONTINUE_CANCEL_RUNTIME_CAPABILITY, AGENT_SESSION_QUEUED_MESSAGE_SKILLS_EDIT_RUNTIME_CAPABILITY -} from '../../../src/shared/agent-session/agent-session-runtime-capabilities' -import { AGENT_SESSION_STATUS_FEED_RUNTIME_CAPABILITY } from '../../../src/shared/agent-session/agent-session-attention-capabilities' +} from '../../../../../src/shared/agent-session/agent-session-runtime-capabilities' +import { AGENT_SESSION_STATUS_FEED_RUNTIME_CAPABILITY } from '../../../../../src/shared/agent-session/agent-session-attention-capabilities' import { AGENT_SESSION_SEND_SELECTION_RUNTIME_CAPABILITY, AGENT_SESSION_SEND_OPTIONS_RUNTIME_CAPABILITY, AGENT_SESSION_SEND_SKILLS_RUNTIME_CAPABILITY, AGENT_SESSION_SEND_USAGE_LIMIT_CONTINUATION_RUNTIME_CAPABILITY, AGENT_SESSION_USAGE_LIMIT_AUTO_CONTINUE_RUNTIME_CAPABILITY -} from '../../../src/shared/agent-session/agent-session-create-capabilities' +} from '../../../../../src/shared/agent-session/agent-session-create-capabilities' import { AGENT_SESSION_PERMISSION_MODES_RUNTIME_CAPABILITY, AGENT_SESSION_PERMISSION_OWN_RUNTIME_CAPABILITY -} from '../../../src/shared/agent-session/agent-session-permission-modes-capability' -import { SKILL_DISCOVER_WORKSPACE_CAPABILITY } from '../../../src/shared/skill-install-capability' -import { AGENT_SESSION_PHONE_CONTINUE_INTERRUPTED_RUNTIME_CAPABILITY } from '../../../src/shared/agent-session/agent-session-continue-interrupted-capability' +} from '../../../../../src/shared/agent-session/agent-session-permission-modes-capability' +import { SKILL_DISCOVER_WORKSPACE_CAPABILITY } from '../../../../../src/shared/skill-install-capability' +import { AGENT_SESSION_PHONE_CONTINUE_INTERRUPTED_RUNTIME_CAPABILITY } from '../../../../../src/shared/agent-session/agent-session-continue-interrupted-capability' export type StructuredAgentSessionHostSupport = { commandsOnRequest?: boolean diff --git a/mobile/src/session/mobile-structured-agent-session-launch.test.ts b/mobile/src/session/native-chat/agent-session/mobile-structured-agent-session-launch.test.ts similarity index 95% rename from mobile/src/session/mobile-structured-agent-session-launch.test.ts rename to mobile/src/session/native-chat/agent-session/mobile-structured-agent-session-launch.test.ts index 457d3fb3c2e..13c056860b2 100644 --- a/mobile/src/session/mobile-structured-agent-session-launch.test.ts +++ b/mobile/src/session/native-chat/agent-session/mobile-structured-agent-session-launch.test.ts @@ -1,6 +1,6 @@ import { describe, expect, it, vi } from 'vitest' -import type { RpcClient } from '../transport/rpc/rpc-client-contract' -import { markRpcDeliveryUnknown } from '../transport/rpc/rpc-delivery-ambiguity' +import type { RpcClient } from '../../../transport/rpc/rpc-client-contract' +import { markRpcDeliveryUnknown } from '../../../transport/rpc/rpc-delivery-ambiguity' import { createMobileStructuredAgentSession } from './mobile-structured-agent-session-launch' import './mobile-created-structured-sessions' diff --git a/mobile/src/session/mobile-structured-agent-session-launch.ts b/mobile/src/session/native-chat/agent-session/mobile-structured-agent-session-launch.ts similarity index 88% rename from mobile/src/session/mobile-structured-agent-session-launch.ts rename to mobile/src/session/native-chat/agent-session/mobile-structured-agent-session-launch.ts index d7cb85e2a31..dda006a7c68 100644 --- a/mobile/src/session/mobile-structured-agent-session-launch.ts +++ b/mobile/src/session/native-chat/agent-session/mobile-structured-agent-session-launch.ts @@ -1,30 +1,30 @@ -import { agentSessionForkSourceFailureWords } from '../../../src/shared/agent-session/failures/agent-session-failure-copy' +import { agentSessionForkSourceFailureWords } from '../../../../../src/shared/agent-session/failures/agent-session-failure-copy' import { sayMobileAgentSessionFailure } from './agent-session-failure-copy' -import type { TuiAgent } from '../../../src/shared/agent-launch/catalog/tui-agent' +import type { TuiAgent } from '../../../../../src/shared/agent-launch/catalog/tui-agent' import type { AgentSessionAttachResult, AgentSessionMutationResult -} from '../../../src/shared/agent-session/agent-session-wire' +} from '../../../../../src/shared/agent-session/agent-session-wire' import { isDefinitiveAgentSessionCreateRefusal, isAgentSessionForkSourceAdmissionRefusal, isAgentSessionCreateAdmissionRefusal -} from '../../../src/shared/agent-session/failures/agent-session-definitive-refusal' +} from '../../../../../src/shared/agent-session/failures/agent-session-definitive-refusal' import { createStructuredAgentSessionId, structuredAgentSessionCreateParams, type StructuredAgentSessionCreateParams, type StructuredAgentSessionForkSource -} from '../../../src/shared/agent-session/structured-agent-session-create' -import type { StructuredAgentCreateSupportReply } from '../../../src/shared/agent-session/structured-agent-create-support-reply' -import { TUI_AGENT_DISPLAY_NAMES } from '../../../src/shared/agent-launch/catalog/tui-agent-display-names' -import { hasRuntimeRpcErrorCode } from '../../../src/shared/runtime-rpc-error-code' -import type { RpcClient } from '../transport/rpc/rpc-client-contract' +} from '../../../../../src/shared/agent-session/structured-agent-session-create' +import type { StructuredAgentCreateSupportReply } from '../../../../../src/shared/agent-session/structured-agent-create-support-reply' +import { TUI_AGENT_DISPLAY_NAMES } from '../../../../../src/shared/agent-launch/catalog/tui-agent-display-names' +import { hasRuntimeRpcErrorCode } from '../../../../../src/shared/runtime-rpc-error-code' +import type { RpcClient } from '../../../transport/rpc/rpc-client-contract' import { structuredAgentSessionCreate, structuredAgentSupportProbe -} from './native-chat/agent-session/mobile-structured-create-operations' -import { randomV4Uuid } from '../platform/random-v4-uuid' +} from './mobile-structured-create-operations' +import { randomV4Uuid } from '../../../platform/random-v4-uuid' import { rememberMobileCreatedStructuredSession } from './mobile-created-structured-sessions' // Partial: the reply is read before it is checked. diff --git a/mobile/src/session/mobile-structured-agent-session-rpc.ts b/mobile/src/session/native-chat/agent-session/mobile-structured-agent-session-rpc.ts similarity index 86% rename from mobile/src/session/mobile-structured-agent-session-rpc.ts rename to mobile/src/session/native-chat/agent-session/mobile-structured-agent-session-rpc.ts index 15cd4a7c1bc..e43935f46ac 100644 --- a/mobile/src/session/mobile-structured-agent-session-rpc.ts +++ b/mobile/src/session/native-chat/agent-session/mobile-structured-agent-session-rpc.ts @@ -1,11 +1,11 @@ -import type { AgentSessionMutationResult } from '../../../src/shared/agent-session/agent-session-wire' +import type { AgentSessionMutationResult } from '../../../../../src/shared/agent-session/agent-session-wire' import type { AgentSessionWireRefusalCode, AgentSessionRefusalReference -} from '../../../src/shared/agent-session/failures/agent-session-wire-refusals' -import type { AgentJournalCursor } from '../../../src/shared/agent-session/journal/agent-session-journal-identity' -import { structuredAgentSessionPayloadFingerprint } from '../../../src/shared/agent-session/lifecycle/structured-agent-session-mutation' -import { agentSessionWriteNoticeParts } from '../../../src/shared/agent-session/failures/agent-session-refusal-notice' +} from '../../../../../src/shared/agent-session/failures/agent-session-wire-refusals' +import type { AgentJournalCursor } from '../../../../../src/shared/agent-session/journal/agent-session-journal-identity' +import { structuredAgentSessionPayloadFingerprint } from '../../../../../src/shared/agent-session/lifecycle/structured-agent-session-mutation' +import { agentSessionWriteNoticeParts } from '../../../../../src/shared/agent-session/failures/agent-session-refusal-notice' import { agentSessionRefusalFailure, agentSessionThrownFailure, @@ -13,14 +13,14 @@ import { readAgentSessionErrorRefusal, type AgentSessionWriteFailure, type AgentSessionWriteKind -} from '../../../src/shared/agent-session/failures/agent-session-write-failure' +} from '../../../../../src/shared/agent-session/failures/agent-session-write-failure' import { mobileAgentSessionWriteNoticeText } from './agent-session-write-notice-copy' import { structuredSessionOperationId } from './structured-session-operation-id' -import { isRpcDeliveryUnknown } from '../transport/rpc/rpc-delivery-ambiguity' -import type { RpcClient } from '../transport/rpc/rpc-client-contract' -import '../transport/connection/stable-logical-rpc-client' -import { isLogicalClientCutoverError } from '../transport/connection/logical-client-cutover-error' -import { MOBILE_NATIVE_CHAT_MIN_WRITE_TIMEOUT_MS } from './native-chat/mobile-native-chat-send' +import { isRpcDeliveryUnknown } from '../../../transport/rpc/rpc-delivery-ambiguity' +import type { RpcClient } from '../../../transport/rpc/rpc-client-contract' +import '../../../transport/connection/stable-logical-rpc-client' +import { isLogicalClientCutoverError } from '../../../transport/connection/logical-client-cutover-error' +import { MOBILE_NATIVE_CHAT_MIN_WRITE_TIMEOUT_MS } from '../composer/mobile-native-chat-send' export const STRUCTURED_SEND_TIMEOUT_MS = 15_000 diff --git a/mobile/src/session/mobile-structured-agent-session-send.ts b/mobile/src/session/native-chat/agent-session/mobile-structured-agent-session-send.ts similarity index 74% rename from mobile/src/session/mobile-structured-agent-session-send.ts rename to mobile/src/session/native-chat/agent-session/mobile-structured-agent-session-send.ts index 76fad9815a5..6fd2d8fda9a 100644 --- a/mobile/src/session/mobile-structured-agent-session-send.ts +++ b/mobile/src/session/native-chat/agent-session/mobile-structured-agent-session-send.ts @@ -1,21 +1,21 @@ -import type { AgentSessionSendResult } from '../../../src/shared/agent-session/agent-session-wire' -import type { AgentJournalCursor } from '../../../src/shared/agent-session/journal/agent-session-journal-identity' -import type { AgentJournalSkillRef } from '../../../src/shared/agent-session/journal/agent-session-journal-types' +import type { AgentSessionSendResult } from '../../../../../src/shared/agent-session/agent-session-wire' +import type { AgentJournalCursor } from '../../../../../src/shared/agent-session/journal/agent-session-journal-identity' +import type { AgentJournalSkillRef } from '../../../../../src/shared/agent-session/journal/agent-session-journal-types' import { structuredAgentSessionSendBody, type StructuredAgentSessionAttachment -} from '../../../src/shared/agent-session/requests/structured-agent-session-send-mutation' -import { structuredAgentSessionBlocksTooLarge } from '../../../src/shared/rpc-contract/structured-agent-session-message-params' -import { AGENT_SESSION_MESSAGE_TOO_LARGE_PARTS } from '../../../src/shared/agent-session/failures/agent-session-refusal-notice' +} from '../../../../../src/shared/agent-session/requests/structured-agent-session-send-mutation' +import { structuredAgentSessionBlocksTooLarge } from '../../../../../src/shared/rpc-contract/structured-agent-session-message-params' +import { AGENT_SESSION_MESSAGE_TOO_LARGE_PARTS } from '../../../../../src/shared/agent-session/failures/agent-session-refusal-notice' import { mobileAgentSessionWriteNoticeText } from './agent-session-write-notice-copy' -import type { RpcClient } from '../transport/rpc/rpc-client-contract' -import type { MobileNativeChatSendOutcome } from './native-chat/mobile-native-chat-send' +import type { RpcClient } from '../../../transport/rpc/rpc-client-contract' +import type { MobileNativeChatSendOutcome } from '../composer/mobile-native-chat-send' import { requestStructuredAgentSessionMutation, timeoutForDeadline } from './mobile-structured-agent-session-rpc' -import { mobileStructuredSendDelivery } from './mobile-structured-send-delivery' -import type { MobileNativeChatSendErrorReporter } from './native-chat/use-mobile-native-chat-send-error' +import { mobileStructuredSendDelivery } from '../composer/mobile-structured-send-delivery' +import type { MobileNativeChatSendErrorReporter } from '../composer/use-mobile-native-chat-send-error' export async function sendMobileStructuredAgentSessionMessage(input: { client: RpcClient diff --git a/mobile/src/session/mobile-structured-agent-session-working.ts b/mobile/src/session/native-chat/agent-session/mobile-structured-agent-session-working.ts similarity index 61% rename from mobile/src/session/mobile-structured-agent-session-working.ts rename to mobile/src/session/native-chat/agent-session/mobile-structured-agent-session-working.ts index 1394f856d48..1d4d7986736 100644 --- a/mobile/src/session/mobile-structured-agent-session-working.ts +++ b/mobile/src/session/native-chat/agent-session/mobile-structured-agent-session-working.ts @@ -1,9 +1,9 @@ -import type { StructuredAgentSessionState } from '../../../src/shared/agent-session/structured-agent-session-reducer' +import type { StructuredAgentSessionState } from '../../../../../src/shared/agent-session/structured-agent-session-reducer' import { runningStructuredAgentSessionTurnId, structuredAgentSessionHostSaysWorking -} from '../../../src/shared/agent-session/view/structured-agent-session-live-turn' -import { isStructuredAgentSessionMainAgentWorking } from '../../../src/shared/agent-session/view/structured-agent-session-main-agent-working' +} from '../../../../../src/shared/agent-session/view/structured-agent-session-live-turn' +import { isStructuredAgentSessionMainAgentWorking } from '../../../../../src/shared/agent-session/view/structured-agent-session-main-agent-working' export function mobileStructuredAgentSessionWorking(state: StructuredAgentSessionState): boolean { return structuredAgentSessionHostSaysWorking(state.working, () => diff --git a/mobile/src/session/mobile-structured-host-clock-offset.ts b/mobile/src/session/native-chat/agent-session/mobile-structured-host-clock-offset.ts similarity index 79% rename from mobile/src/session/mobile-structured-host-clock-offset.ts rename to mobile/src/session/native-chat/agent-session/mobile-structured-host-clock-offset.ts index 1a0e9abcf3c..70142d96979 100644 --- a/mobile/src/session/mobile-structured-host-clock-offset.ts +++ b/mobile/src/session/native-chat/agent-session/mobile-structured-host-clock-offset.ts @@ -1,4 +1,4 @@ -import type { StructuredAgentHostClock } from '../../../src/shared/agent-session/structured-agent-session-reducer' +import type { StructuredAgentHostClock } from '../../../../../src/shared/agent-session/structured-agent-session-reducer' // Ignore delivery jitter below the precision of displayed clocks. const OFFSET_GRAIN_MS = 1_000 diff --git a/mobile/src/session/mobile-structured-session-open-message.ts b/mobile/src/session/native-chat/agent-session/mobile-structured-session-open-message.ts similarity index 90% rename from mobile/src/session/mobile-structured-session-open-message.ts rename to mobile/src/session/native-chat/agent-session/mobile-structured-session-open-message.ts index 0557d24bbb6..b70c8f837e8 100644 --- a/mobile/src/session/mobile-structured-session-open-message.ts +++ b/mobile/src/session/native-chat/agent-session/mobile-structured-session-open-message.ts @@ -1,6 +1,6 @@ -import { formatAgentTypeLabel } from '../../../src/shared/agent-status/presentation/agent-type-label' -import type { StructuredSessionOpenFailure } from '../../../src/shared/open-structured-agent-session' -import { translate } from '../i18n/mobile-i18n' +import { formatAgentTypeLabel } from '../../../../../src/shared/agent-status/presentation/agent-type-label' +import type { StructuredSessionOpenFailure } from '../../../../../src/shared/open-structured-agent-session' +import { translate } from '../../../i18n/mobile-i18n' export function mobileStructuredSessionOpenMessage( reason: StructuredSessionOpenFailure['reason'], diff --git a/mobile/src/session/mobile-structured-session-open-rpc.ts b/mobile/src/session/native-chat/agent-session/mobile-structured-session-open-rpc.ts similarity index 88% rename from mobile/src/session/mobile-structured-session-open-rpc.ts rename to mobile/src/session/native-chat/agent-session/mobile-structured-session-open-rpc.ts index b0afd135322..4a6af221381 100644 --- a/mobile/src/session/mobile-structured-session-open-rpc.ts +++ b/mobile/src/session/native-chat/agent-session/mobile-structured-session-open-rpc.ts @@ -1,7 +1,7 @@ import * as z from 'zod' -import { bindDeferredRpcOperation, defineRpcOperation } from '../transport/rpc/rpc-operation' -import { rpcResultVariant } from '../transport/rpc/rpc-operation-result-reader' -import type { RpcMethodName } from '../../../src/shared/rpc-contract/rpc-params-catalog.generated' +import { bindDeferredRpcOperation, defineRpcOperation } from '../../../transport/rpc/rpc-operation' +import { rpcResultVariant } from '../../../transport/rpc/rpc-operation-result-reader' +import type { RpcMethodName } from '../../../../../src/shared/rpc-contract/rpc-params-catalog.generated' function openingRead( method: Method, diff --git a/mobile/src/session/mobile-structured-session-status-feed.test.ts b/mobile/src/session/native-chat/agent-session/mobile-structured-session-status-feed.test.ts similarity index 84% rename from mobile/src/session/mobile-structured-session-status-feed.test.ts rename to mobile/src/session/native-chat/agent-session/mobile-structured-session-status-feed.test.ts index 170c101788f..892df6a0497 100644 --- a/mobile/src/session/mobile-structured-session-status-feed.test.ts +++ b/mobile/src/session/native-chat/agent-session/mobile-structured-session-status-feed.test.ts @@ -1,10 +1,10 @@ import { beforeEach, describe, expect, it, vi } from 'vitest' -import type { AgentSessionStatusSummary } from '../../../src/shared/agent-session/agent-session-wire' -import type { RpcClient } from '../transport/rpc/rpc-client-contract' -import type { ConnectionState } from '../transport/connection/connection-state' -import '../transport/connection/stable-logical-rpc-client' +import type { AgentSessionStatusSummary } from '../../../../../src/shared/agent-session/agent-session-wire' +import type { RpcClient } from '../../../transport/rpc/rpc-client-contract' +import type { ConnectionState } from '../../../transport/connection/connection-state' +import '../../../transport/connection/stable-logical-rpc-client' import { mobileStructuredSessionStatusFeed } from './mobile-structured-session-status-feed' -import { stubRpcClient } from '../transport/rpc/rpc-client-test-stub' +import { stubRpcClient } from '../../../transport/rpc/rpc-client-test-stub' function summary(stopping: boolean): AgentSessionStatusSummary { return { diff --git a/mobile/src/session/mobile-structured-session-status-feed.ts b/mobile/src/session/native-chat/agent-session/mobile-structured-session-status-feed.ts similarity index 91% rename from mobile/src/session/mobile-structured-session-status-feed.ts rename to mobile/src/session/native-chat/agent-session/mobile-structured-session-status-feed.ts index 8617b8afd29..841ef3995af 100644 --- a/mobile/src/session/mobile-structured-session-status-feed.ts +++ b/mobile/src/session/native-chat/agent-session/mobile-structured-session-status-feed.ts @@ -5,14 +5,14 @@ import { foldAgentSessionStatusEvent, revokeAgentSessionStatusLive, type AgentSessionStatusSnapshot -} from '../../../src/shared/agent-session/view/agent-session-status-snapshot-fold' -import type { AgentSessionStatusEvent } from '../../../src/shared/agent-session/agent-session-wire' +} from '../../../../../src/shared/agent-session/view/agent-session-status-snapshot-fold' +import type { AgentSessionStatusEvent } from '../../../../../src/shared/agent-session/agent-session-wire' import { foldAgentSessionConversationNames, type AgentSessionConversationNames -} from '../../../src/shared/agent-session/agent-session-conversation-names' -import { isMobileMethodUnavailableError } from '../transport/rpc/mobile-method-unavailable' -import type { RpcClient } from '../transport/rpc/rpc-client-contract' +} from '../../../../../src/shared/agent-session/agent-session-conversation-names' +import { isMobileMethodUnavailableError } from '../../../transport/rpc/mobile-method-unavailable' +import type { RpcClient } from '../../../transport/rpc/rpc-client-contract' export type MobileStructuredSessionStatusFeed = { subscribe: (listener: () => void) => () => void diff --git a/mobile/src/session/mobile-structured-transcript-subscription.ts b/mobile/src/session/native-chat/agent-session/mobile-structured-transcript-subscription.ts similarity index 83% rename from mobile/src/session/mobile-structured-transcript-subscription.ts rename to mobile/src/session/native-chat/agent-session/mobile-structured-transcript-subscription.ts index 2d07c89e144..24402f13bd0 100644 --- a/mobile/src/session/mobile-structured-transcript-subscription.ts +++ b/mobile/src/session/native-chat/agent-session/mobile-structured-transcript-subscription.ts @@ -1,6 +1,6 @@ -import type { AgentSessionSubscribeEvent } from '../../../src/shared/agent-session/agent-session-wire' -import type { StructuredAgentSessionLiveSubscribe } from '../../../src/shared/agent-session/structured-agent-session-live-read' -import type { RpcClient } from '../transport/rpc/rpc-client-contract' +import type { AgentSessionSubscribeEvent } from '../../../../../src/shared/agent-session/agent-session-wire' +import type { StructuredAgentSessionLiveSubscribe } from '../../../../../src/shared/agent-session/structured-agent-session-live-read' +import type { RpcClient } from '../../../transport/rpc/rpc-client-contract' function isSubscribeEvent(value: unknown): value is AgentSessionSubscribeEvent { if (typeof value !== 'object' || value === null || !('type' in value)) { diff --git a/mobile/src/session/open-mobile-structured-session.ts b/mobile/src/session/native-chat/agent-session/open-mobile-structured-session.ts similarity index 91% rename from mobile/src/session/open-mobile-structured-session.ts rename to mobile/src/session/native-chat/agent-session/open-mobile-structured-session.ts index 346aa09264a..9f37d080a8a 100644 --- a/mobile/src/session/open-mobile-structured-session.ts +++ b/mobile/src/session/native-chat/agent-session/open-mobile-structured-session.ts @@ -4,17 +4,17 @@ import { type StructuredSessionOpenSource, type StructuredSessionOpenTab, type StructuredSessionOpenTarget -} from '../../../src/shared/open-structured-agent-session' -import { isStructuredAgentId } from '../../../src/shared/agent-session/lifecycle/agent-session-provider-handle-encoding' -import { structuredAgentSessionPaneKey } from '../../../src/shared/agent-session/view/structured-agent-session-projection' -import type { RpcClient } from '../transport/rpc/rpc-client-contract' +} from '../../../../../src/shared/open-structured-agent-session' +import { isStructuredAgentId } from '../../../../../src/shared/agent-session/lifecycle/agent-session-provider-handle-encoding' +import { structuredAgentSessionPaneKey } from '../../../../../src/shared/agent-session/view/structured-agent-session-projection' +import type { RpcClient } from '../../../transport/rpc/rpc-client-contract' import { structuredOpenLocation, structuredOpenParty, structuredOpenReveal, structuredOpenTabs } from './mobile-structured-session-open-rpc' -import { sessionTabActivate } from './tabs/mobile-session-tab-write-operations' +import { sessionTabActivate } from '../../tabs/mobile-session-tab-write-operations' /** The workspace client already carries executionHost; a single budget includes connect waits. */ export async function openMobileStructuredSession(args: { diff --git a/mobile/src/session/structured-session-operation-id.ts b/mobile/src/session/native-chat/agent-session/structured-session-operation-id.ts similarity index 69% rename from mobile/src/session/structured-session-operation-id.ts rename to mobile/src/session/native-chat/agent-session/structured-session-operation-id.ts index 434a0f19b5b..80c298a94fb 100644 --- a/mobile/src/session/structured-session-operation-id.ts +++ b/mobile/src/session/native-chat/agent-session/structured-session-operation-id.ts @@ -1,7 +1,7 @@ // Keep id generation dependency-free so create/tasks callers do not pull in the native-chat write graph. -import { createStructuredAgentSessionOperationId } from '../../../src/shared/agent-session/lifecycle/structured-agent-session-mutation' -import { randomV4Uuid } from '../platform/random-v4-uuid' +import { createStructuredAgentSessionOperationId } from '../../../../../src/shared/agent-session/lifecycle/structured-agent-session-mutation' +import { randomV4Uuid } from '../../../platform/random-v4-uuid' export function structuredSessionOperationId(now: number = Date.now()): string { return createStructuredAgentSessionOperationId(randomV4Uuid, now) diff --git a/mobile/src/session/use-mobile-structured-agent-mutation.ts b/mobile/src/session/native-chat/agent-session/use-mobile-structured-agent-mutation.ts similarity index 90% rename from mobile/src/session/use-mobile-structured-agent-mutation.ts rename to mobile/src/session/native-chat/agent-session/use-mobile-structured-agent-mutation.ts index bf684cf71f3..9ccefcba3fd 100644 --- a/mobile/src/session/use-mobile-structured-agent-mutation.ts +++ b/mobile/src/session/native-chat/agent-session/use-mobile-structured-agent-mutation.ts @@ -1,6 +1,6 @@ import { useCallback } from 'react' -import type { StructuredAgentSessionState } from '../../../src/shared/agent-session/structured-agent-session-reducer' -import type { RpcClient } from '../transport/rpc/rpc-client-contract' +import type { StructuredAgentSessionState } from '../../../../../src/shared/agent-session/structured-agent-session-reducer' +import type { RpcClient } from '../../../transport/rpc/rpc-client-contract' import { requestStructuredAgentSessionMutation, type StructuredAgentSessionMutationResult diff --git a/mobile/src/session/use-mobile-structured-agent-rewind.ts b/mobile/src/session/native-chat/agent-session/use-mobile-structured-agent-rewind.ts similarity index 78% rename from mobile/src/session/use-mobile-structured-agent-rewind.ts rename to mobile/src/session/native-chat/agent-session/use-mobile-structured-agent-rewind.ts index 51e9f65a2d1..3200bd020ab 100644 --- a/mobile/src/session/use-mobile-structured-agent-rewind.ts +++ b/mobile/src/session/native-chat/agent-session/use-mobile-structured-agent-rewind.ts @@ -1,24 +1,24 @@ import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react' -import { AGENT_SESSION_CONVERSATION_COMMAND_TIMEOUT_MS } from '../../../src/shared/agent-session/agent-session-conversation-command' -import { AGENT_SESSION_PHONE_REWIND_RUNTIME_CAPABILITY } from '../../../src/shared/agent-session/agent-session-runtime-capabilities' -import type { AgentSessionRewindResult } from '../../../src/shared/agent-session/lifecycle/agent-session-rewind' +import { AGENT_SESSION_CONVERSATION_COMMAND_TIMEOUT_MS } from '../../../../../src/shared/agent-session/agent-session-conversation-command' +import { AGENT_SESSION_PHONE_REWIND_RUNTIME_CAPABILITY } from '../../../../../src/shared/agent-session/agent-session-runtime-capabilities' +import type { AgentSessionRewindResult } from '../../../../../src/shared/agent-session/lifecycle/agent-session-rewind' import { createAgentSessionRewindHook, type AgentSessionRewindInput, type AgentSessionRewindSendOutcome -} from '../../../src/shared/agent-session/lifecycle/agent-session-rewind-request' -import type { StructuredAgentSessionState } from '../../../src/shared/agent-session/structured-agent-session-reducer' -import { actionableStructuredPrompts } from './mobile-structured-actionable-prompt' -import { useRouteRelaysCapability } from '../worktree/workspace-server-context' -import { sayMobileNativeChatRewind } from './native-chat/mobile-native-chat-rewind-copy' -import type { MobileNativeChatSendOutcome } from './native-chat/mobile-native-chat-send' +} from '../../../../../src/shared/agent-session/lifecycle/agent-session-rewind-request' +import type { StructuredAgentSessionState } from '../../../../../src/shared/agent-session/structured-agent-session-reducer' +import { actionableStructuredPrompts } from '../input/mobile-structured-actionable-prompt' +import { useRouteRelaysCapability } from '../../../worktree/workspace-server-context' +import { sayMobileNativeChatRewind } from '../mobile-native-chat-rewind-copy' +import type { MobileNativeChatSendOutcome } from '../composer/mobile-native-chat-send' import { requestStructuredAgentSessionMutation } from './mobile-structured-agent-session-rpc' -import { returnMobileNativeChatMessageToComposer } from './mobile-native-chat-message-hand-back' -import type { useMobileStructuredAgentOptions } from './use-mobile-structured-agent-options' +import { returnMobileNativeChatMessageToComposer } from '../composer/mobile-native-chat-message-hand-back' +import type { useMobileStructuredAgentOptions } from '../input/use-mobile-structured-agent-options' import type { MobileStructuredAgentSessionArgs } from './mobile-structured-agent-session-contract' -import type { MobileStructuredBackgroundTasks } from './use-mobile-structured-background-tasks' -import type { MobileStructuredSendsOut } from './use-mobile-structured-stop-offer' -import { tuiAgentDisplayName } from '../../../src/shared/agent-launch/catalog/tui-agent-display-names' +import type { MobileStructuredBackgroundTasks } from '../input/use-mobile-structured-background-tasks' +import type { MobileStructuredSendsOut } from '../composer/use-mobile-structured-stop-offer' +import { tuiAgentDisplayName } from '../../../../../src/shared/agent-launch/catalog/tui-agent-display-names' const useAgentSessionRewind = createAgentSessionRewindHook( { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState }, diff --git a/mobile/src/session/native-chat/agent-session/use-mobile-structured-agent-session-queued.test-fixture.ts b/mobile/src/session/native-chat/agent-session/use-mobile-structured-agent-session-queued.test-fixture.ts index f4934fb7f57..03221a2d5cf 100644 --- a/mobile/src/session/native-chat/agent-session/use-mobile-structured-agent-session-queued.test-fixture.ts +++ b/mobile/src/session/native-chat/agent-session/use-mobile-structured-agent-session-queued.test-fixture.ts @@ -8,7 +8,7 @@ import type { } from '../../../../../src/shared/agent-session/requests/agent-session-queued-message-wire' import type { AgentSessionSubscribeEvent } from '../../../../../src/shared/agent-session/agent-session-wire' import type { RpcResponse } from '../../../transport/rpc/rpc-wire-types' -import type { StructuredAgentSessionHostSupport } from '../../mobile-structured-agent-session-host-support' +import type { StructuredAgentSessionHostSupport } from './mobile-structured-agent-session-host-support' export const SESSION_ID = 'session-1' diff --git a/mobile/src/session/native-chat/agent-session/use-mobile-structured-agent-session-queued.test.tsx b/mobile/src/session/native-chat/agent-session/use-mobile-structured-agent-session-queued.test.tsx index cae9208f26d..d9e72dd6b4f 100644 --- a/mobile/src/session/native-chat/agent-session/use-mobile-structured-agent-session-queued.test.tsx +++ b/mobile/src/session/native-chat/agent-session/use-mobile-structured-agent-session-queued.test.tsx @@ -7,8 +7,8 @@ import type { AgentSessionSubscribeEvent } from '../../../../../src/shared/agent import type { RpcClient } from '../../../transport/rpc/rpc-client-contract' import type { RpcResponse } from '../../../transport/rpc/rpc-wire-types' import { markRpcDeliveryUnknown } from '../../../transport/rpc/rpc-delivery-ambiguity' -import type { StructuredAgentSessionHostSupport } from '../../mobile-structured-agent-session-host-support' -import { useMobileStructuredAgentSession } from '../../use-mobile-structured-agent-session' +import type { StructuredAgentSessionHostSupport } from './mobile-structured-agent-session-host-support' +import { useMobileStructuredAgentSession } from './use-mobile-structured-agent-session' import type { RpcClientContextValue } from '../../../transport/connection/rpc-client-context-contract' diff --git a/mobile/src/session/native-chat/agent-session/use-mobile-structured-agent-session.clear.test.tsx b/mobile/src/session/native-chat/agent-session/use-mobile-structured-agent-session.clear.test.tsx index ba720a54a09..3c48b99c6fe 100644 --- a/mobile/src/session/native-chat/agent-session/use-mobile-structured-agent-session.clear.test.tsx +++ b/mobile/src/session/native-chat/agent-session/use-mobile-structured-agent-session.clear.test.tsx @@ -6,7 +6,7 @@ import type { AgentSessionSubscribeEvent } from '../../../../../src/shared/agent import { createWithQueryClient } from '../../../test-support/query-client-test-renderer' import type { RpcClient } from '../../../transport/rpc/rpc-client-contract' import type { RpcResponse } from '../../../transport/rpc/rpc-wire-types' -import { useMobileStructuredAgentSession } from '../../use-mobile-structured-agent-session' +import { useMobileStructuredAgentSession } from './use-mobile-structured-agent-session' import { SESSION_ID, mutationOk, @@ -29,25 +29,6 @@ const row = ( observedAt: sequence, body: { kind: 'message', role, blocks: [{ type: 'text', text }] } }) -const divider = (sequence: number): AgentJournalRenderItem => ({ - ...row(sequence, 'assistant', ''), - body: { - kind: 'status', - text: 'Context cleared', - presentation: 'context-cleared', - contextClear: { operationId: `clear-${sequence}`, afterFence: 3, clearedAt: sequence } - } -}) -const dividerLands = (sequence: number): AgentSessionSubscribeEvent => ({ - type: 'batch', - sessionId: SESSION_ID, - batch: { - cursor: { epoch: 'epoch-1', sequence }, - items: [divider(sequence)], - removedItemIds: [], - submissions: [] - } -}) describe('useMobileStructuredAgentSession /clear', () => { let renderer: ReactTestRenderer | null = null @@ -132,22 +113,6 @@ describe('useMobileStructuredAgentSession /clear', () => { } } - it('hides the old transcript from the press until the divider lands', async () => { - const chat = await mount() - expect(chat.shown()).toEqual({ text: ['question', 'reply'], clearing: false }) - - const { outcome } = await chat.sendClear() - expect(chat.shown()).toEqual({ text: [], clearing: true }) - - // The host's reply can reach the phone before the divider it already wrote. - await chat.reply({ command: 'clear', state: 'completed' }) - await expect(outcome).resolves.toBe('accepted') - expect(chat.shown()).toEqual({ text: [], clearing: true }) - - chat.push(dividerLands(3)) - expect(chat.shown()).toEqual({ text: ['Context cleared'], clearing: false }) - }) - it('shows the old transcript again when the host refuses the /clear', async () => { const chat = await mount() const { outcome } = await chat.sendClear() diff --git a/mobile/src/session/native-chat/agent-session/use-mobile-structured-agent-session.interrupted-continue.test.tsx b/mobile/src/session/native-chat/agent-session/use-mobile-structured-agent-session.interrupted-continue.test.tsx index 8030186142d..2778f4aa07a 100644 --- a/mobile/src/session/native-chat/agent-session/use-mobile-structured-agent-session.interrupted-continue.test.tsx +++ b/mobile/src/session/native-chat/agent-session/use-mobile-structured-agent-session.interrupted-continue.test.tsx @@ -7,12 +7,12 @@ import { agentJournalItemKey } from '../../../../../src/shared/agent-session/jou import { AGENT_SESSION_PHONE_CONTINUE_INTERRUPTED_RUNTIME_CAPABILITY } from '../../../../../src/shared/agent-session/agent-session-continue-interrupted-capability' import type { RpcClient } from '../../../transport/rpc/rpc-client-contract' import type { RpcResponse } from '../../../transport/rpc/rpc-wire-types' -import { structuredAgentSessionHostSupport } from '../../mobile-structured-agent-session-host-support' +import { structuredAgentSessionHostSupport } from './mobile-structured-agent-session-host-support' import { snapshotEvent, SESSION_ID } from './use-mobile-structured-agent-session-queued.test-fixture' -import { useMobileStructuredAgentSession } from '../../use-mobile-structured-agent-session' +import { useMobileStructuredAgentSession } from './use-mobile-structured-agent-session' vi.mock('@react-native-async-storage/async-storage', () => ({ default: { getItem: vi.fn(async () => null), setItem: vi.fn(), removeItem: vi.fn() } diff --git a/mobile/src/session/use-mobile-structured-agent-session.test.tsx b/mobile/src/session/native-chat/agent-session/use-mobile-structured-agent-session.test.tsx similarity index 91% rename from mobile/src/session/use-mobile-structured-agent-session.test.tsx rename to mobile/src/session/native-chat/agent-session/use-mobile-structured-agent-session.test.tsx index 327436f803b..73c4f8898d9 100644 --- a/mobile/src/session/use-mobile-structured-agent-session.test.tsx +++ b/mobile/src/session/native-chat/agent-session/use-mobile-structured-agent-session.test.tsx @@ -4,16 +4,16 @@ import { fieldsOf, mutationOk, ok -} from './native-chat/agent-session/use-mobile-structured-agent-session-queued.test-fixture' +} from './use-mobile-structured-agent-session-queued.test-fixture' import { act, type ReactTestRenderer } from 'react-test-renderer' -import { createWithQueryClient } from '../test-support/query-client-test-renderer' +import { createWithQueryClient } from '../../../test-support/query-client-test-renderer' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import type { AgentJournalRenderItem } from '../../../src/shared/agent-session/journal/agent-session-journal-types' +import type { AgentJournalRenderItem } from '../../../../../src/shared/agent-session/journal/agent-session-journal-types' -import type { RpcClient } from '../transport/rpc/rpc-client-contract' -import type { ConnectionState } from '../transport/connection/connection-state' +import type { RpcClient } from '../../../transport/rpc/rpc-client-contract' +import type { ConnectionState } from '../../../transport/connection/connection-state' -import { structuredSendResultFixture } from './structured-agent-send-result.test-fixture' +import { structuredSendResultFixture } from '../../structured-agent-send-result.test-fixture' import { useMobileStructuredAgentSession } from './use-mobile-structured-agent-session' const asyncStorage = vi.hoisted(() => ({ diff --git a/mobile/src/session/use-mobile-structured-agent-session.ts b/mobile/src/session/native-chat/agent-session/use-mobile-structured-agent-session.ts similarity index 79% rename from mobile/src/session/use-mobile-structured-agent-session.ts rename to mobile/src/session/native-chat/agent-session/use-mobile-structured-agent-session.ts index 62c4cd9d9cd..9672b413618 100644 --- a/mobile/src/session/use-mobile-structured-agent-session.ts +++ b/mobile/src/session/native-chat/agent-session/use-mobile-structured-agent-session.ts @@ -1,57 +1,57 @@ -import { asyncQuestionSourceScope as questionSourceScope } from '../../../src/shared/native-chat/input/native-chat-ask' -import { structuredChatTranscriptIdentity } from './native-chat/mobile-native-chat-transcript-store' +import { asyncQuestionSourceScope as questionSourceScope } from '../../../../../src/shared/native-chat/input/native-chat-ask' +import { structuredChatTranscriptIdentity } from '../transcript/mobile-native-chat-transcript-store' import { useMemo, useRef } from 'react' -import { tuiAgentDisplayName } from '../../../src/shared/agent-launch/catalog/tui-agent-display-names' +import { tuiAgentDisplayName } from '../../../../../src/shared/agent-launch/catalog/tui-agent-display-names' import { mobileStructuredAgentSessionWorking } from './mobile-structured-agent-session-working' -import { isFinalAgentSessionReadRefusal } from '../../../src/shared/agent-session/failures/structured-agent-session-read-refusal' +import { isFinalAgentSessionReadRefusal } from '../../../../../src/shared/agent-session/failures/structured-agent-session-read-refusal' import { runningStructuredAgentSessionTurnId, structuredAgentSessionQueueSendsNext -} from '../../../src/shared/agent-session/view/structured-agent-session-live-turn' +} from '../../../../../src/shared/agent-session/view/structured-agent-session-live-turn' import { actionableStructuredApproval, actionableStructuredQuestion -} from './mobile-structured-actionable-prompt' +} from '../input/mobile-structured-actionable-prompt' import { projectStructuredPermission, projectStructuredQuestion -} from './mobile-structured-agent-prompts' +} from '../input/mobile-structured-agent-prompts' import type { MobileStructuredAgentSessionArgs, StructuredMobileSession } from './mobile-structured-agent-session-contract' -import type { MobileNativeChatVisualSource } from './native-chat/visual/mobile-native-chat-visual-read' +import type { MobileNativeChatVisualSource } from '../visual/mobile-native-chat-visual-read' import { useMobileStructuredAgentState } from './use-mobile-structured-agent-state' -import { useMobileStructuredStopPress } from './use-mobile-structured-stop-press' +import { useMobileStructuredStopPress } from '../composer/use-mobile-structured-stop-press' import { useMobileStructuredSessionHostStopping } from './use-mobile-structured-session-host-stopping' -import { useMobileStructuredPromptResponses } from './use-mobile-structured-prompt-responses' -import { useMobileStructuredAgentOptions } from './use-mobile-structured-agent-options' -import { useHostModelCatalogCache } from './mobile-host-model-catalog-query' -import { useMobileStructuredCommandController } from './use-mobile-structured-command-controller' -import { useMobileStructuredSessionOptionStamp } from './use-mobile-structured-session-option-stamp' -import { useMobileStructuredAgentTurnTiming } from './use-mobile-structured-agent-turn-timing' +import { useMobileStructuredPromptResponses } from '../input/use-mobile-structured-prompt-responses' +import { useMobileStructuredAgentOptions } from '../input/use-mobile-structured-agent-options' +import { useHostModelCatalogCache } from '../input/mobile-host-model-catalog-query' +import { useMobileStructuredCommandController } from '../composer/use-mobile-structured-command-controller' +import { useMobileStructuredSessionOptionStamp } from '../input/use-mobile-structured-session-option-stamp' +import { useMobileStructuredAgentTurnTiming } from '../transcript/use-mobile-structured-agent-turn-timing' import { pendingStructuredPromptIdentity, useMobileStructuredRequestCancel } from './mobile-structured-agent-session-cancel' import { useMobileStructuredAgentMutate } from './use-mobile-structured-agent-mutation' -import { useMobileStructuredSendWithOutcome } from './use-mobile-structured-send-with-outcome' -import { useMobileStructuredQueuedMessageControls } from './use-mobile-structured-queued-message-controls' -import { useMobileStructuredBackgroundTasks } from './use-mobile-structured-background-tasks' -import { useMobileStructuredSends } from './use-mobile-structured-sends' -import { useMobileStructuredSendRecorded } from './mobile-structured-send-recorded-read' -import { useMobileNativeChatQueueFollowUps as useQueueFollowUps } from './use-mobile-native-chat-queue-follow-ups' -import { useMobileStructuredStopOffer } from './use-mobile-structured-stop-offer' -import { useMobileStructuredTurnIndicator } from './use-mobile-structured-turn-indicator' -import { useMobileStructuredContextUsage } from './use-mobile-structured-context-usage' -import { useMobileStructuredInterruptedContinue } from './use-mobile-structured-interrupted-continue' +import { useMobileStructuredSendWithOutcome } from '../composer/use-mobile-structured-send-with-outcome' +import { useMobileStructuredQueuedMessageControls } from '../input/use-mobile-structured-queued-message-controls' +import { useMobileStructuredBackgroundTasks } from '../input/use-mobile-structured-background-tasks' +import { useMobileStructuredSends } from '../composer/use-mobile-structured-sends' +import { useMobileStructuredSendRecorded } from '../composer/mobile-structured-send-recorded-read' +import { useMobileNativeChatQueueFollowUps as useQueueFollowUps } from '../preferences/use-mobile-native-chat-queue-follow-ups' +import { useMobileStructuredStopOffer } from '../composer/use-mobile-structured-stop-offer' +import { useMobileStructuredTurnIndicator } from '../transcript/use-mobile-structured-turn-indicator' +import { useMobileStructuredContextUsage } from '../composer/use-mobile-structured-context-usage' +import { useMobileStructuredInterruptedContinue } from '../composer/use-mobile-structured-interrupted-continue' import { useMobileStructuredThreadGoal, useMobileStructuredThreadGoalSend -} from './use-mobile-structured-thread-goal' -import { useMobileStructuredTranscript } from './use-mobile-structured-transcript' +} from '../input/use-mobile-structured-thread-goal' +import { useMobileStructuredTranscript } from '../transcript/use-mobile-structured-transcript' import { useMobileStructuredAgentRewind } from './use-mobile-structured-agent-rewind' -import { useMobileNativeChatUsageLimit } from './native-chat/use-mobile-native-chat-usage-limit' +import { useMobileNativeChatUsageLimit } from '../use-mobile-native-chat-usage-limit' export function useMobileStructuredAgentSession( args: MobileStructuredAgentSessionArgs diff --git a/mobile/src/session/use-mobile-structured-agent-state.ts b/mobile/src/session/native-chat/agent-session/use-mobile-structured-agent-state.ts similarity index 87% rename from mobile/src/session/use-mobile-structured-agent-state.ts rename to mobile/src/session/native-chat/agent-session/use-mobile-structured-agent-state.ts index c2bcae0c88e..7a847917079 100644 --- a/mobile/src/session/use-mobile-structured-agent-state.ts +++ b/mobile/src/session/native-chat/agent-session/use-mobile-structured-agent-state.ts @@ -1,45 +1,48 @@ import { useCallback, useEffect, useLayoutEffect, useRef, useState } from 'react' -import { isRootAgentJournalItem } from '../../../src/shared/agent-session/journal/agent-session-journal-producer' +import { isRootAgentJournalItem } from '../../../../../src/shared/agent-session/journal/agent-session-journal-producer' import type { AgentSessionQueuedMessage, AgentSessionQueuePause -} from '../../../src/shared/agent-session/requests/agent-session-queued-message-wire' +} from '../../../../../src/shared/agent-session/requests/agent-session-queued-message-wire' import { type AgentSessionHistoryResult, AGENT_SESSION_HISTORY_MAX_LIMIT -} from '../../../src/shared/agent-session/agent-session-wire' -import { structuredAgentSessionHolderId } from '../../../src/shared/agent-session/view/structured-agent-session-holder' -import { startStructuredAgentSessionLiveRead } from '../../../src/shared/agent-session/structured-agent-session-live-read' +} from '../../../../../src/shared/agent-session/agent-session-wire' +import { structuredAgentSessionHolderId } from '../../../../../src/shared/agent-session/view/structured-agent-session-holder' +import { startStructuredAgentSessionLiveRead } from '../../../../../src/shared/agent-session/structured-agent-session-live-read' import { type AgentSessionTextAppendCapabilities, agentSessionTextAppendRequest -} from '../../../src/shared/agent-session/agent-session-text-append' -import { isFinalAgentSessionReadRefusal } from '../../../src/shared/agent-session/failures/structured-agent-session-read-refusal' +} from '../../../../../src/shared/agent-session/agent-session-text-append' +import { isFinalAgentSessionReadRefusal } from '../../../../../src/shared/agent-session/failures/structured-agent-session-read-refusal' import { EMPTY_STRUCTURED_AGENT_SESSION, oldestStructuredAgentSessionCursor, type StructuredAgentSessionAction, type StructuredAgentSessionState -} from '../../../src/shared/agent-session/structured-agent-session-reducer' -import { subscribeConnectionRevival } from '../diagnostics/connection/connection-revival-signal' +} from '../../../../../src/shared/agent-session/structured-agent-session-reducer' +import { subscribeConnectionRevival } from '../../../diagnostics/connection/connection-revival-signal' import { readRuntimeStatusProbe, recordRuntimeStatusProbe -} from '../transport/connection/runtime-status-probe' -import { decodeHostStatusReply, readHostStatusReply } from '../query/host-status-query' -import { hostStatusSchema } from '../transport/hosts/host-status-reply-schema' +} from '../../../transport/connection/runtime-status-probe' +import { decodeHostStatusReply, readHostStatusReply } from '../../../query/host-status-query' +import { hostStatusSchema } from '../../../transport/hosts/host-status-reply-schema' import { AGENT_SESSION_TEXT_APPEND_RUNTIME_CAPABILITY, AGENT_SESSION_TOOL_OUTPUT_APPEND_RUNTIME_CAPABILITY -} from '../../../src/shared/agent-session/agent-session-runtime-capabilities' -import type { RpcClient } from '../transport/rpc/rpc-client-contract' +} from '../../../../../src/shared/agent-session/agent-session-runtime-capabilities' +import type { RpcClient } from '../../../transport/rpc/rpc-client-contract' import { agentSessionReadFailureRefusal, agentSessionReadRefusalText, callAgentSession } from './mobile-structured-agent-session-rpc' import { subscribeTranscriptAfterHold } from './mobile-structured-transcript-subscription' -import { useMobileOlderPageLoader, type OlderPagePhase } from './use-mobile-older-page-loader' +import { + useMobileOlderPageLoader, + type OlderPagePhase +} from '../transcript/use-mobile-older-page-loader' import { mobileStructuredAgentSessionWorking } from './mobile-structured-agent-session-working' import { reduceStructuredChatState, @@ -47,8 +50,8 @@ import { storedStructuredSessionState, storedStructuredCopy, unconfirmedStructuredStateSavedAt -} from './native-chat/mobile-native-chat-transcript-writer' -import { useStoredChatTranscript } from './native-chat/use-stored-chat-transcript' +} from '../transcript/mobile-native-chat-transcript-writer' +import { useStoredChatTranscript } from '../transcript/use-stored-chat-transcript' const MAX_RETAINED_SESSION_STATES = 32 diff --git a/mobile/src/session/use-mobile-structured-session-host-stopping.ts b/mobile/src/session/native-chat/agent-session/use-mobile-structured-session-host-stopping.ts similarity index 92% rename from mobile/src/session/use-mobile-structured-session-host-stopping.ts rename to mobile/src/session/native-chat/agent-session/use-mobile-structured-session-host-stopping.ts index a1d3db4174a..866b1873358 100644 --- a/mobile/src/session/use-mobile-structured-session-host-stopping.ts +++ b/mobile/src/session/native-chat/agent-session/use-mobile-structured-session-host-stopping.ts @@ -1,5 +1,5 @@ import { useCallback, useSyncExternalStore } from 'react' -import type { RpcClient } from '../transport/rpc/rpc-client-contract' +import type { RpcClient } from '../../../transport/rpc/rpc-client-contract' import { mobileStructuredSessionStatusFeed } from './mobile-structured-session-status-feed' const noSubscription = (): (() => void) => () => {} diff --git a/mobile/src/session/native-chat/composer/MobileNativeChatComposer.structured.test.ts b/mobile/src/session/native-chat/composer/MobileNativeChatComposer.structured.test.ts index c04552d7585..29fc29234d0 100644 --- a/mobile/src/session/native-chat/composer/MobileNativeChatComposer.structured.test.ts +++ b/mobile/src/session/native-chat/composer/MobileNativeChatComposer.structured.test.ts @@ -7,17 +7,17 @@ import { updateMobileNativeChatDraftInputs } from './mobile-native-chat-draft-inputs' import './use-mobile-native-chat-drafts' -import '../../use-mobile-structured-native-chat-send-bridge' +import './use-mobile-structured-native-chat-send-bridge' import '../mobile-native-chat-scope-key' -import '../../use-mobile-structured-agent-session' +import '../agent-session/use-mobile-structured-agent-session' import '../agent-session/use-mobile-structured-agent-session-queued.test-fixture' import '../../structured-agent-send-result.test-fixture' import { findByHostType } from '../../../test-support/react-test-renderer-host-nodes' -import '../../mobile-structured-agent-session-host-support' +import '../agent-session/mobile-structured-agent-session-host-support' import '../../../../../src/shared/agent-session/agent-session-runtime-capabilities' -import '../../use-mobile-structured-agent-options' -import '../../use-mobile-structured-agent-options.test-fixture' +import '../input/use-mobile-structured-agent-options' +import '../input/use-mobile-structured-agent-options.test-fixture' import { createElement, type ComponentProps } from 'react' diff --git a/mobile/src/session/native-chat/composer/MobileNativeChatComposer.tsx b/mobile/src/session/native-chat/composer/MobileNativeChatComposer.tsx index b58cdede682..07f31ca25c1 100644 --- a/mobile/src/session/native-chat/composer/MobileNativeChatComposer.tsx +++ b/mobile/src/session/native-chat/composer/MobileNativeChatComposer.tsx @@ -39,7 +39,7 @@ import { composerInputStyles as inputStyles } from '../../../components/composer import { MobileNativeChatComposerSendSlot } from './MobileNativeChatComposerSendSlot' import { MobileNativeChatEditActions } from './MobileNativeChatEditActions' import { useMobileNativeChatContextRing } from './MobileNativeChatContextUsageRing' -import type { MobileNativeChatSendIntent } from '../mobile-native-chat-send' +import type { MobileNativeChatSendIntent } from './mobile-native-chat-send' import { MobileNativeChatComposerMic } from './MobileNativeChatComposerMic' import type { MobileNativeChatMicProps } from './MobileNativeChatComposerMic' import { MobileNativeChatDictationLeading } from './MobileNativeChatDictationLeading' @@ -51,8 +51,6 @@ const NO_FILE_PATHS: string[] = [] const NO_ATTACHMENTS: PendingNativeChatImage[] = [] const NO_FILES: PendingNativeChatFile[] = [] -export type { MobileNativeChatStructuredComposer } from './mobile-native-chat-structured-composer' - type Props = MobileNativeChatMicProps & { // Applies dictation's edit to the draft this composer shows; false when it can no longer take it. insertDictation?: (insert: (draft: string) => string) => boolean | void diff --git a/mobile/src/session/native-chat/composer/MobileNativeChatComposerAttachButton.tsx b/mobile/src/session/native-chat/composer/MobileNativeChatComposerAttachButton.tsx index d9760401fca..45d89b53131 100644 --- a/mobile/src/session/native-chat/composer/MobileNativeChatComposerAttachButton.tsx +++ b/mobile/src/session/native-chat/composer/MobileNativeChatComposerAttachButton.tsx @@ -4,7 +4,7 @@ import { Plus } from 'lucide-react-native' import { colors } from '../../../theme/mobile-theme' import { useMobileTranslation } from '../../../i18n/use-mobile-translation' import { ActionSheetModal } from '../../../components/ActionSheetModal' -import { mobileNativeChatAttachActions } from '../mobile-native-chat-attach-actions' +import { mobileNativeChatAttachActions } from './mobile-native-chat-attach-actions' import { COMPOSER_CONTROL_HIT_SLOP, composerInputStyles as inputStyles diff --git a/mobile/src/session/native-chat/composer/MobileNativeChatComposerSendSlot.tsx b/mobile/src/session/native-chat/composer/MobileNativeChatComposerSendSlot.tsx index cc4dd16223b..4651ce6c6d8 100644 --- a/mobile/src/session/native-chat/composer/MobileNativeChatComposerSendSlot.tsx +++ b/mobile/src/session/native-chat/composer/MobileNativeChatComposerSendSlot.tsx @@ -6,7 +6,7 @@ import type { NativeChatSendFollowUp } from '../../../../../src/shared/native-ch import type { SessionOptionDescriptor } from '../../../../../src/shared/native-chat/input/native-chat-session-options' import { MobileNativeChatStopButton } from '../input/MobileNativeChatStopButton' import { MobileNativeChatControlSwap } from '../input/mobile-native-chat-control-swap' -import type { MobileNativeChatSendIntent } from '../mobile-native-chat-send' +import type { MobileNativeChatSendIntent } from './mobile-native-chat-send' import { mobileNativeChatComposerShowsStop } from './mobile-native-chat-composer-layout' import type { MobileNativeChatStructuredComposer } from './mobile-native-chat-structured-composer' import { readMobileNativeChatPickedSkills } from './mobile-native-chat-draft-store' diff --git a/mobile/src/session/native-chat/composer/MobileNativeChatSendButton.tsx b/mobile/src/session/native-chat/composer/MobileNativeChatSendButton.tsx index cde9442e07c..af5a2a79dc9 100644 --- a/mobile/src/session/native-chat/composer/MobileNativeChatSendButton.tsx +++ b/mobile/src/session/native-chat/composer/MobileNativeChatSendButton.tsx @@ -16,7 +16,7 @@ import { useMobileTranslation } from '../../../i18n/use-mobile-translation' import { useKeyboardPersistingTaps } from '../../../platform/keyboard-persisting-taps' import { colors } from '../../../theme/mobile-theme' import { useMobileColorScheme } from '../../../theme/use-mobile-color-scheme' -import type { MobileNativeChatSendIntent } from '../mobile-native-chat-send' +import type { MobileNativeChatSendIntent } from './mobile-native-chat-send' const FOLLOW_UP_ICON = { queue: ListEnd, steer: CornerDownRight } as const diff --git a/mobile/src/session/native-chat/mobile-native-chat-attach-actions.ts b/mobile/src/session/native-chat/composer/mobile-native-chat-attach-actions.ts similarity index 93% rename from mobile/src/session/native-chat/mobile-native-chat-attach-actions.ts rename to mobile/src/session/native-chat/composer/mobile-native-chat-attach-actions.ts index 4b855587cfb..aae916a7d71 100644 --- a/mobile/src/session/native-chat/mobile-native-chat-attach-actions.ts +++ b/mobile/src/session/native-chat/composer/mobile-native-chat-attach-actions.ts @@ -1,6 +1,6 @@ import { AtSign, Image, Package, Paperclip, Terminal } from 'lucide-react-native' -import type { ActionSheetAction } from '../../components/ActionSheetModal' -import { translate } from '../../i18n/mobile-i18n' +import type { ActionSheetAction } from '../../../components/ActionSheetModal' +import { translate } from '../../../i18n/mobile-i18n' // Dismiss the sheet before opening pickers because iOS cannot present them over its Modal. export function mobileNativeChatAttachActions(args: { diff --git a/mobile/src/session/native-chat/composer/mobile-native-chat-composer-menu.ts b/mobile/src/session/native-chat/composer/mobile-native-chat-composer-menu.ts index ecac1d211d2..ea5597fd311 100644 --- a/mobile/src/session/native-chat/composer/mobile-native-chat-composer-menu.ts +++ b/mobile/src/session/native-chat/composer/mobile-native-chat-composer-menu.ts @@ -1,6 +1,7 @@ import type { AgentSessionConversationCommand } from '../../../../../src/shared/agent-session/agent-session-conversation-command' import type { AgentSessionSlashCommand } from '../../../../../src/shared/agent-session/agent-session-wire' import { + getAgentAnsweredNativeChatCommands, getNativeChatAgentProfile, type NativeChatAgentProfile } from '../../../../../src/shared/native-chat/native-chat-agent-profiles' @@ -19,7 +20,6 @@ import type { SlashCommandSuggestion } from '../../../../../src/shared/native-chat/input/native-chat-slash-commands' import { structuredSessionSlashCommands } from '../../../../../src/shared/agent-session/view/structured-agent-session-composer' -import { getMobileNativeChatCommands } from '../mobile-native-chat-send-classification' // Why: the menu is a plain ScrollView right above a streaming transcript, so it mounts a bounded // number of rows; typing narrows the rest. @@ -66,7 +66,7 @@ export function mobileComposerCatalog({ structured.compactInstructions, interactionModeSupported ) - : getMobileNativeChatCommands(agent) + : getAgentAnsweredNativeChatCommands(agent) return { profile: getNativeChatAgentProfile(agent), commands: nativeChatPickerCommands(agent, commands, discovery.skills), diff --git a/mobile/src/session/native-chat/composer/mobile-native-chat-draft-reconcile.ts b/mobile/src/session/native-chat/composer/mobile-native-chat-draft-reconcile.ts index 8ecab906278..5c5a85fad74 100644 --- a/mobile/src/session/native-chat/composer/mobile-native-chat-draft-reconcile.ts +++ b/mobile/src/session/native-chat/composer/mobile-native-chat-draft-reconcile.ts @@ -21,10 +21,6 @@ export type UnconfirmedSend = { deadline: ReturnType | null } -export function normalizedUserText(message: NativeChatMessage): string | null { - return normalizedNativeChatUserMessageText(message) -} - export type PendingImagePreviewEcho = Pick< NativeChatPendingSend, 'id' | 'text' | 'sentAt' | 'afterMessageId' | 'matchingOccurrence' @@ -161,7 +157,7 @@ export function findLandedImagePreviewEchoes( return false } if (targetText) { - const text = normalizedUserText(message) + const text = normalizedNativeChatUserMessageText(message) if (text === null) { return false } @@ -199,7 +195,9 @@ export function findLandedUnconfirmedSends( if (message.role !== 'user') { continue } - const key = isImageSourceUserTurn(message) ? '' : (normalizedUserText(message) ?? '') + const key = isImageSourceUserTurn(message) + ? '' + : (normalizedNativeChatUserMessageText(message) ?? '') const current = userMessagesByText.get(key) ?? [] current.push({ id: message.id, index }) userMessagesByText.set(key, current) diff --git a/mobile/src/session/native-chat/composer/mobile-native-chat-image-send.ts b/mobile/src/session/native-chat/composer/mobile-native-chat-image-send.ts index 130b89692b6..f94eeab180b 100644 --- a/mobile/src/session/native-chat/composer/mobile-native-chat-image-send.ts +++ b/mobile/src/session/native-chat/composer/mobile-native-chat-image-send.ts @@ -5,9 +5,9 @@ import { MOBILE_NATIVE_CHAT_MIN_WRITE_TIMEOUT_MS, openMobileNativeChatSendBudget, readMobileNativeChatInputClear -} from '../mobile-native-chat-send' +} from './mobile-native-chat-send' import { nativeChatTerminalWrite } from '../../../terminal/session/mobile-session-terminal-operations' -import type { MobileNativeChatRpcSender } from '../mobile-native-chat-send' +import type { MobileNativeChatRpcSender } from './mobile-native-chat-send' // Wait for the TUI to register bracketed image attachments before text/Enter arrives. export const MOBILE_NATIVE_CHAT_IMAGE_SETTLE_MS = 300 diff --git a/mobile/src/session/native-chat/composer/mobile-native-chat-in-flight-sends.ts b/mobile/src/session/native-chat/composer/mobile-native-chat-in-flight-sends.ts index 08d94b1b7cc..f4d9d025cf0 100644 --- a/mobile/src/session/native-chat/composer/mobile-native-chat-in-flight-sends.ts +++ b/mobile/src/session/native-chat/composer/mobile-native-chat-in-flight-sends.ts @@ -5,8 +5,8 @@ import { updateMobileNativeChatDraftInputs } from './mobile-native-chat-draft-inputs' import type { PendingNativeChatFile } from './mobile-native-chat-file-attachment' -import type { MobileNativeChatSendOrigin } from '../mobile-native-chat-pending-echo' -import type { MobileNativeChatSendIntent } from '../mobile-native-chat-send' +import type { MobileNativeChatSendOrigin } from '../transcript/mobile-native-chat-pending-echo' +import type { MobileNativeChatSendIntent } from './mobile-native-chat-send' import { saveMobileNativeChatDraft } from './mobile-native-chat-draft-persistence' import type { MobileNativeChatInFlightSend, diff --git a/mobile/src/session/mobile-native-chat-message-hand-back.test.ts b/mobile/src/session/native-chat/composer/mobile-native-chat-message-hand-back.test.ts similarity index 93% rename from mobile/src/session/mobile-native-chat-message-hand-back.test.ts rename to mobile/src/session/native-chat/composer/mobile-native-chat-message-hand-back.test.ts index 697c0dd00af..6d74c9bfa40 100644 --- a/mobile/src/session/mobile-native-chat-message-hand-back.test.ts +++ b/mobile/src/session/native-chat/composer/mobile-native-chat-message-hand-back.test.ts @@ -5,12 +5,12 @@ import { returnMobileNativeChatMessageToComposer } from './mobile-native-chat-me import { readMobileNativeChatDraftInputs, updateMobileNativeChatDraftInputs -} from './native-chat/composer/mobile-native-chat-draft-inputs' +} from './mobile-native-chat-draft-inputs' import { resetMobileNativeChatDraftStoreForTests, setMobileNativeChatDraftText, useMobileNativeChatDraft -} from './native-chat/composer/mobile-native-chat-draft-store' +} from './mobile-native-chat-draft-store' let renderer: ReactTestRenderer | null = null let text = '' diff --git a/mobile/src/session/mobile-native-chat-message-hand-back.ts b/mobile/src/session/native-chat/composer/mobile-native-chat-message-hand-back.ts similarity index 73% rename from mobile/src/session/mobile-native-chat-message-hand-back.ts rename to mobile/src/session/native-chat/composer/mobile-native-chat-message-hand-back.ts index 7391481887f..a3a288a70e7 100644 --- a/mobile/src/session/mobile-native-chat-message-hand-back.ts +++ b/mobile/src/session/native-chat/composer/mobile-native-chat-message-hand-back.ts @@ -1,12 +1,12 @@ -import type { AgentJournalMessageItem } from '../../../src/shared/agent-session/journal/agent-session-journal-types' -import { queuedEditTextForKeptImages } from '../../../src/shared/queued-message-edit' -import { appendReturnedDraftText } from '../../../src/shared/returned-draft-text' -import { mobileDraftImageOfBlock } from './mobile-queued-message-edit-draft' +import type { AgentJournalMessageItem } from '../../../../../src/shared/agent-session/journal/agent-session-journal-types' +import { queuedEditTextForKeptImages } from '../../../../../src/shared/queued-message-edit' +import { appendReturnedDraftText } from '../../../../../src/shared/returned-draft-text' +import { mobileDraftImageOfBlock } from '../input/mobile-queued-message-edit-draft' import { readMobileNativeChatDraftInputs, updateMobileNativeChatDraftInputs -} from './native-chat/composer/mobile-native-chat-draft-inputs' -import { setMobileNativeChatDraftText } from './native-chat/composer/mobile-native-chat-draft-store' +} from './mobile-native-chat-draft-inputs' +import { setMobileNativeChatDraftText } from './mobile-native-chat-draft-store' /** Append a sent message's text and images after what is typed; stable chip ids keep a repeat from doubling them. */ export function returnMobileNativeChatMessageToComposer( diff --git a/mobile/src/session/native-chat/mobile-native-chat-send-classification.ts b/mobile/src/session/native-chat/composer/mobile-native-chat-send-classification.ts similarity index 62% rename from mobile/src/session/native-chat/mobile-native-chat-send-classification.ts rename to mobile/src/session/native-chat/composer/mobile-native-chat-send-classification.ts index 77febaf434c..e228d61446f 100644 --- a/mobile/src/session/native-chat/mobile-native-chat-send-classification.ts +++ b/mobile/src/session/native-chat/composer/mobile-native-chat-send-classification.ts @@ -3,17 +3,13 @@ import { getAgentAnsweredNativeChatCommands, getNativeChatAgentProfile -} from '../../../../src/shared/native-chat/native-chat-agent-profiles' +} from '../../../../../src/shared/native-chat/native-chat-agent-profiles' import { classifyNativeChatSend, - type NativeChatSendClassification, - type SlashCommandSuggestion -} from '../../../../src/shared/native-chat/input/native-chat-slash-commands' + type NativeChatSendClassification +} from '../../../../../src/shared/native-chat/input/native-chat-slash-commands' // Terminal mobile chat lacks desktop-owned command answers and reply rows. -export function getMobileNativeChatCommands(agent: string): readonly SlashCommandSuggestion[] { - return getAgentAnsweredNativeChatCommands(agent) -} export function classifyMobileNativeChatSend( agent: string | null, @@ -26,7 +22,7 @@ export function classifyMobileNativeChatSend( const profile = getNativeChatAgentProfile(agent) return classifyNativeChatSend( text, - getMobileNativeChatCommands(agent), + getAgentAnsweredNativeChatCommands(agent), pickerSkillOriginToken, profile?.skillPrefix ?? null ) diff --git a/mobile/src/session/native-chat/mobile-native-chat-send.ts b/mobile/src/session/native-chat/composer/mobile-native-chat-send.ts similarity index 88% rename from mobile/src/session/native-chat/mobile-native-chat-send.ts rename to mobile/src/session/native-chat/composer/mobile-native-chat-send.ts index c91e15906ee..9c980127a97 100644 --- a/mobile/src/session/native-chat/mobile-native-chat-send.ts +++ b/mobile/src/session/native-chat/composer/mobile-native-chat-send.ts @@ -1,22 +1,22 @@ -import type { RpcClient } from '../../transport/rpc/rpc-client-contract' -import type { PendingNativeChatImage } from './composer/mobile-native-chat-image-attachment' -import type { PendingNativeChatFile } from './composer/mobile-native-chat-file-attachment' -import { isRpcDeliveryUnknown } from '../../transport/rpc/rpc-delivery-ambiguity' -import '../../transport/connection/stable-logical-rpc-client' -import { isLogicalClientCutoverError } from '../../transport/connection/logical-client-cutover-error' +import type { RpcClient } from '../../../transport/rpc/rpc-client-contract' +import type { PendingNativeChatImage } from './mobile-native-chat-image-attachment' +import type { PendingNativeChatFile } from './mobile-native-chat-file-attachment' +import { isRpcDeliveryUnknown } from '../../../transport/rpc/rpc-delivery-ambiguity' +import '../../../transport/connection/stable-logical-rpc-client' +import { isLogicalClientCutoverError } from '../../../transport/connection/logical-client-cutover-error' import { nativeChatTerminalWrite, nativeChatTerminalDraftRead -} from '../../terminal/session/mobile-session-terminal-operations' -import { typeAgentTuiCommand } from '../../../../src/shared/agent-launch/startup/agent-tui-command-typing' -import { readTerminalSendAcknowledgment } from '../../../../src/shared/terminal/pty/lifecycle/terminal-send-acknowledgment' +} from '../../../terminal/session/mobile-session-terminal-operations' +import { typeAgentTuiCommand } from '../../../../../src/shared/agent-launch/startup/agent-tui-command-typing' +import { readTerminalSendAcknowledgment } from '../../../../../src/shared/terminal/pty/lifecycle/terminal-send-acknowledgment' import { AGENT_TUI_CLEAR_MAX_LINES, countAgentTuiInputLines, buildAgentTuiClearInputForText -} from '../../../../src/shared/agent-launch/startup/agent-tui-input-clear' +} from '../../../../../src/shared/agent-launch/startup/agent-tui-input-clear' -import type { AgentJournalSkillRef } from '../../../../src/shared/agent-session/journal/agent-session-journal-types' +import type { AgentJournalSkillRef } from '../../../../../src/shared/agent-session/journal/agent-session-journal-types' export type MobileNativeChatRpcSender = Parameters[0] diff --git a/mobile/src/session/native-chat/mobile-native-chat-stale-input.ts b/mobile/src/session/native-chat/composer/mobile-native-chat-stale-input.ts similarity index 96% rename from mobile/src/session/native-chat/mobile-native-chat-stale-input.ts rename to mobile/src/session/native-chat/composer/mobile-native-chat-stale-input.ts index f0885dd157d..7762f7762ea 100644 --- a/mobile/src/session/native-chat/mobile-native-chat-stale-input.ts +++ b/mobile/src/session/native-chat/composer/mobile-native-chat-stale-input.ts @@ -1,4 +1,4 @@ -import { pasteMobileNativeChatImagePaths } from './composer/mobile-native-chat-image-send' +import { pasteMobileNativeChatImagePaths } from './mobile-native-chat-image-send' import type { MobileNativeChatRpcSender } from './mobile-native-chat-send' // The condition tracked here — a bracketed image paste left sitting on the agent's diff --git a/mobile/src/session/native-chat/composer/mobile-native-chat-structured-composer.ts b/mobile/src/session/native-chat/composer/mobile-native-chat-structured-composer.ts index 5efa1fe1f80..27de249feb3 100644 --- a/mobile/src/session/native-chat/composer/mobile-native-chat-structured-composer.ts +++ b/mobile/src/session/native-chat/composer/mobile-native-chat-structured-composer.ts @@ -1,6 +1,6 @@ import type { MobileComposerStructuredCatalog } from './mobile-native-chat-composer-menu' import type { PendingNativeChatFile } from './mobile-native-chat-file-attachment' -import type { MobileStructuredThreadGoal } from '../../use-mobile-structured-thread-goal' +import type { MobileStructuredThreadGoal } from '../input/use-mobile-structured-thread-goal' export type MobileNativeChatStructuredComposer = { catalog: MobileComposerStructuredCatalog diff --git a/mobile/src/session/native-chat/mobile-native-chat-terminal-write-lock.test.ts b/mobile/src/session/native-chat/composer/mobile-native-chat-terminal-write-lock.test.ts similarity index 100% rename from mobile/src/session/native-chat/mobile-native-chat-terminal-write-lock.test.ts rename to mobile/src/session/native-chat/composer/mobile-native-chat-terminal-write-lock.test.ts diff --git a/mobile/src/session/native-chat/mobile-native-chat-terminal-write-lock.ts b/mobile/src/session/native-chat/composer/mobile-native-chat-terminal-write-lock.ts similarity index 100% rename from mobile/src/session/native-chat/mobile-native-chat-terminal-write-lock.ts rename to mobile/src/session/native-chat/composer/mobile-native-chat-terminal-write-lock.ts diff --git a/mobile/src/session/mobile-structured-composer-command.ts b/mobile/src/session/native-chat/composer/mobile-structured-composer-command.ts similarity index 85% rename from mobile/src/session/mobile-structured-composer-command.ts rename to mobile/src/session/native-chat/composer/mobile-structured-composer-command.ts index 04d80c271fb..55c0ea4432f 100644 --- a/mobile/src/session/mobile-structured-composer-command.ts +++ b/mobile/src/session/native-chat/composer/mobile-structured-composer-command.ts @@ -2,26 +2,26 @@ import { agentSessionConversationCommandFields, type AgentSessionConversationCommand, type AgentSessionConversationCommandResult -} from '../../../src/shared/agent-session/agent-session-conversation-command' -import type { AgentSessionFailureFact } from '../../../src/shared/agent-session/failures/agent-session-failure' +} from '../../../../../src/shared/agent-session/agent-session-conversation-command' +import type { AgentSessionFailureFact } from '../../../../../src/shared/agent-session/failures/agent-session-failure' import { dispatchStructuredAgentSessionComposerCommand, isStructuredAgentSessionHostCommand, type StructuredAgentSessionCommandRefusalCause, type StructuredAgentSessionComposerOptions -} from '../../../src/shared/agent-session/view/structured-agent-session-composer' +} from '../../../../../src/shared/agent-session/view/structured-agent-session-composer' import { conversationCommandReply, heldConversationCommandParts, structuredConversationCommandHold -} from '../../../src/shared/structured-conversation-command-hold' -import { mobileAgentSessionWriteNoticeText } from './agent-session-write-notice-copy' -import type { RpcClient } from '../transport/rpc/rpc-client-contract' -import { translate } from '../i18n/mobile-i18n' -import { sayMobileAgentSessionFailure } from './agent-session-failure-copy' -import type { MobileNativeChatSendOutcome } from './native-chat/mobile-native-chat-send' -import { requestStructuredAgentSessionMutation } from './mobile-structured-agent-session-rpc' -import type { MobileNativeChatSendErrorReporter } from './native-chat/use-mobile-native-chat-send-error' +} from '../../../../../src/shared/structured-conversation-command-hold' +import { mobileAgentSessionWriteNoticeText } from '../agent-session/agent-session-write-notice-copy' +import type { RpcClient } from '../../../transport/rpc/rpc-client-contract' +import { translate } from '../../../i18n/mobile-i18n' +import { sayMobileAgentSessionFailure } from '../agent-session/agent-session-failure-copy' +import type { MobileNativeChatSendOutcome } from './mobile-native-chat-send' +import { requestStructuredAgentSessionMutation } from '../agent-session/mobile-structured-agent-session-rpc' +import type { MobileNativeChatSendErrorReporter } from './use-mobile-native-chat-send-error' /** What the phone shows at keypress that holds a command; `background` also counts the strip mid-turn. */ export type MobileStructuredCommandHolds = Readonly< diff --git a/mobile/src/session/mobile-structured-send-delivery.ts b/mobile/src/session/native-chat/composer/mobile-structured-send-delivery.ts similarity index 77% rename from mobile/src/session/mobile-structured-send-delivery.ts rename to mobile/src/session/native-chat/composer/mobile-structured-send-delivery.ts index d9f3eb2c58f..129006f77ca 100644 --- a/mobile/src/session/mobile-structured-send-delivery.ts +++ b/mobile/src/session/native-chat/composer/mobile-structured-send-delivery.ts @@ -1,9 +1,9 @@ -import type { AgentSessionSendResult } from '../../../src/shared/agent-session/agent-session-wire' -import { agentSessionRefusalOperationState } from '../../../src/shared/agent-session/failures/agent-session-refusal-retry' -import type { MobileNativeChatSendOutcome } from './native-chat/mobile-native-chat-send' -import type { StructuredAgentSessionMutationCallResult } from './mobile-structured-agent-session-rpc' -import { STRUCTURED_AGENT_SESSION_SUBMISSION_MISSING } from '../../../src/shared/agent-session/requests/structured-agent-session-send-evidence' -import { translate } from '../i18n/mobile-i18n' +import type { AgentSessionSendResult } from '../../../../../src/shared/agent-session/agent-session-wire' +import { agentSessionRefusalOperationState } from '../../../../../src/shared/agent-session/failures/agent-session-refusal-retry' +import type { MobileNativeChatSendOutcome } from './mobile-native-chat-send' +import type { StructuredAgentSessionMutationCallResult } from '../agent-session/mobile-structured-agent-session-rpc' +import { STRUCTURED_AGENT_SESSION_SUBMISSION_MISSING } from '../../../../../src/shared/agent-session/requests/structured-agent-session-send-evidence' +import { translate } from '../../../i18n/mobile-i18n' export type MobileStructuredSendDelivery = { outcome: MobileNativeChatSendOutcome diff --git a/mobile/src/session/mobile-structured-send-queue-rule.ts b/mobile/src/session/native-chat/composer/mobile-structured-send-queue-rule.ts similarity index 67% rename from mobile/src/session/mobile-structured-send-queue-rule.ts rename to mobile/src/session/native-chat/composer/mobile-structured-send-queue-rule.ts index 12065e7d0a2..8a5f9dd97c0 100644 --- a/mobile/src/session/mobile-structured-send-queue-rule.ts +++ b/mobile/src/session/native-chat/composer/mobile-structured-send-queue-rule.ts @@ -1,9 +1,9 @@ -import { selectAgentSessionCurrentRequests } from '../../../src/shared/agent-session/requests/agent-session-current-requests' -import type { StructuredAgentSessionState } from '../../../src/shared/agent-session/structured-agent-session-reducer' +import { selectAgentSessionCurrentRequests } from '../../../../../src/shared/agent-session/requests/agent-session-current-requests' +import type { StructuredAgentSessionState } from '../../../../../src/shared/agent-session/structured-agent-session-reducer' import { structuredAgentSessionFollowUpsQueue, structuredAgentSessionQueueEnabled -} from '../../../src/shared/agent-session/view/structured-agent-session-queued-cards' +} from '../../../../../src/shared/agent-session/view/structured-agent-session-queued-cards' /** The desktop's rule: the alternate flips the setting first, then the queue's own rules decide. */ export function mobileStructuredSendQueues( diff --git a/mobile/src/session/mobile-structured-send-recorded-read.ts b/mobile/src/session/native-chat/composer/mobile-structured-send-recorded-read.ts similarity index 85% rename from mobile/src/session/mobile-structured-send-recorded-read.ts rename to mobile/src/session/native-chat/composer/mobile-structured-send-recorded-read.ts index 17e47b2199e..8fec033fadb 100644 --- a/mobile/src/session/mobile-structured-send-recorded-read.ts +++ b/mobile/src/session/native-chat/composer/mobile-structured-send-recorded-read.ts @@ -1,9 +1,9 @@ import { useLayoutEffect, useMemo, useRef } from 'react' import * as z from 'zod' -import { bindDeferredRpcOperation, defineRpcOperation } from '../transport/rpc/rpc-operation' -import { rpcResultVariant } from '../transport/rpc/rpc-operation-result-reader' -import type { RpcClient } from '../transport/rpc/rpc-client-contract' -import type { StructuredAgentSessionHostSupport } from './mobile-structured-agent-session-host-support' +import { bindDeferredRpcOperation, defineRpcOperation } from '../../../transport/rpc/rpc-operation' +import { rpcResultVariant } from '../../../transport/rpc/rpc-operation-result-reader' +import type { RpcClient } from '../../../transport/rpc/rpc-client-contract' +import type { StructuredAgentSessionHostSupport } from '../agent-session/mobile-structured-agent-session-host-support' const sendRecordedRead = bindDeferredRpcOperation( defineRpcOperation({ diff --git a/mobile/src/session/native-chat/unconfirmed-send-deadlines.ts b/mobile/src/session/native-chat/composer/unconfirmed-send-deadlines.ts similarity index 100% rename from mobile/src/session/native-chat/unconfirmed-send-deadlines.ts rename to mobile/src/session/native-chat/composer/unconfirmed-send-deadlines.ts diff --git a/mobile/src/session/native-chat/composer/use-mobile-native-chat-composer-goal-mode.ts b/mobile/src/session/native-chat/composer/use-mobile-native-chat-composer-goal-mode.ts index 91d7ce33131..5c3abd01481 100644 --- a/mobile/src/session/native-chat/composer/use-mobile-native-chat-composer-goal-mode.ts +++ b/mobile/src/session/native-chat/composer/use-mobile-native-chat-composer-goal-mode.ts @@ -3,8 +3,8 @@ import { Goal } from 'lucide-react-native' import type { NativeChatSendFollowUp } from '../../../../../src/shared/native-chat/input/native-chat-follow-up-behavior' import { isBareStructuredAgentSessionGoalCommand } from '../../../../../src/shared/agent-session/view/structured-agent-session-composer' import { useMobileTranslation } from '../../../i18n/use-mobile-translation' -import type { MobileStructuredThreadGoal } from '../../use-mobile-structured-thread-goal' -import type { MobileNativeChatSendIntent } from '../mobile-native-chat-send' +import type { MobileStructuredThreadGoal } from '../input/use-mobile-structured-thread-goal' +import type { MobileNativeChatSendIntent } from './mobile-native-chat-send' import { MobileNativeChatThreadGoalStrip } from '../input/MobileNativeChatThreadGoalStrip' import { MobileNativeChatComposerModeChip } from './MobileNativeChatComposerModeChip' diff --git a/mobile/src/session/native-chat/composer/use-mobile-native-chat-composer-tray.ts b/mobile/src/session/native-chat/composer/use-mobile-native-chat-composer-tray.ts index 2b8005f6de8..4dfbcf863ee 100644 --- a/mobile/src/session/native-chat/composer/use-mobile-native-chat-composer-tray.ts +++ b/mobile/src/session/native-chat/composer/use-mobile-native-chat-composer-tray.ts @@ -8,7 +8,7 @@ import { mobileNativeChatChordHeadId, type MobileNativeChatQueuedMessagesProps } from '../input/MobileNativeChatQueuedMessages' -import type { MobileStructuredBackgroundTasks } from '../../use-mobile-structured-background-tasks' +import type { MobileStructuredBackgroundTasks } from '../input/use-mobile-structured-background-tasks' import { useMobileNativeChatQueuedEditFocus } from '../input/use-mobile-native-chat-queued-edit-focus' import { createMobileQueuedHeadLight } from '../input/mobile-queued-head-light' import { diff --git a/mobile/src/session/native-chat/composer/use-mobile-native-chat-drafts-glued-pending.test.ts b/mobile/src/session/native-chat/composer/use-mobile-native-chat-drafts-glued-pending.test.ts index 09542d51dfb..201a3072094 100644 --- a/mobile/src/session/native-chat/composer/use-mobile-native-chat-drafts-glued-pending.test.ts +++ b/mobile/src/session/native-chat/composer/use-mobile-native-chat-drafts-glued-pending.test.ts @@ -2,7 +2,7 @@ import { createElement } from 'react' import { act, create } from 'react-test-renderer' import { afterEach, describe, expect, it } from 'vitest' import type { NativeChatMessage } from '../../../../../src/shared/native-chat/native-chat-types' -import { buildMobileNativeChatTransientData } from '../mobile-native-chat-render-data' + import { useMobileNativeChatDrafts } from './use-mobile-native-chat-drafts' import { resetMobileNativeChatDraftStoreForTests, @@ -15,10 +15,6 @@ type TestRenderer = { update(element: ReturnType): void } -function userTurn(id: string, text: string, timestamp: number): NativeChatMessage { - return { id, role: 'user', blocks: [{ type: 'text', text }], timestamp, source: 'transcript' } -} - function assistantTurn(id: string, text: string, timestamp: number): NativeChatMessage { return { id, @@ -39,20 +35,6 @@ function imageTurn(id: string, path: string, timestamp: number): NativeChatMessa } } -function renderedPendingTexts( - messages: NativeChatMessage[], - state: DraftState | null -): (string | undefined)[] { - const { data } = buildMobileNativeChatTransientData({ - folded: messages, - streaming: null, - pending: state?.pending ?? [] - }) - return data - .filter((message) => !messages.some((existing) => existing.id === message.id)) - .map((message) => message.blocks.find((block) => block.type === 'text')?.text) -} - describe('useMobileNativeChatDrafts glued pending sends', () => { let renderer: TestRenderer | null = null let state: DraftState | null = null @@ -109,23 +91,6 @@ describe('useMobileNativeChatDrafts glued pending sends', () => { // Between the older history rows and the rows that land after a send, on the host's clock. const SENT_AT = 3000 - function send(text: string): void { - const origin = state?.captureSendOrigin(text, SENT_AT) - if (origin) { - state?.acceptSend(origin, text) - } - } - - function rapidSend(first: string, second: string): void { - act(() => { - send(first) - send(second) - }) - } - - const pendingTexts = (): (string | undefined)[] | undefined => - state?.pending.map((item) => item.text) - // Hydrating rows give no boundary, so these sends match only rows newer than their send time. describe('sends issued while the transcript is still hydrating', () => { // An image retires only by preview binding; excluding its own echo would strand both the photo and later glued sends. @@ -146,18 +111,4 @@ describe('useMobileNativeChatDrafts glued pending sends', () => { }) // Failed-read emptiness is unknown history, not an empty conversation; old rows must not claim sends against it. - describe('sends issued before any read settled', () => { - it('keeps both bubbles when the late read carries only an older glue-alike', async () => { - await mount([], false, false) - rapidSend('fix the', 'bug') - - const olderIdentical = [ - userTurn('m1', 'fix the bug', 1000), - assistantTurn('m2', 'fixed', 1100) - ] - await update(olderIdentical) - expect(pendingTexts()).toEqual(['fix the', 'bug']) - expect(renderedPendingTexts(olderIdentical, state)).toEqual(['fix the', 'bug']) - }) - }) }) diff --git a/mobile/src/session/native-chat/composer/use-mobile-native-chat-drafts.ts b/mobile/src/session/native-chat/composer/use-mobile-native-chat-drafts.ts index 814f11e6d90..456058a6867 100644 --- a/mobile/src/session/native-chat/composer/use-mobile-native-chat-drafts.ts +++ b/mobile/src/session/native-chat/composer/use-mobile-native-chat-drafts.ts @@ -18,7 +18,7 @@ import { normalizeImageTranscriptMessages, normalizeNativeChatUserText as normalizeReconcileText } from '../../../../../src/shared/native-chat/transcript/native-chat-image-transcript-markers' -import { useMobileNativeChatUnconfirmedSends } from '../use-mobile-native-chat-unconfirmed-sends' +import { useMobileNativeChatUnconfirmedSends } from './use-mobile-native-chat-unconfirmed-sends' import { appendMobileNativeChatPending, combineMobileNativeChatPending, @@ -28,7 +28,7 @@ import { visibleMobileNativeChatPending, type MobileNativeChatPendingMessage, type MobileNativeChatSendOrigin -} from '../mobile-native-chat-pending-echo' +} from '../transcript/mobile-native-chat-pending-echo' import { mobileNativeChatScopeKey } from '../mobile-native-chat-scope-key' import { mobileNativeChatDraftDestination } from './mobile-native-chat-draft-inputs' import { useMobileNativeChatLaunchDraftSeed } from './use-mobile-native-chat-launch-draft-seed' diff --git a/mobile/src/session/native-chat/composer/use-mobile-native-chat-image-attachments.test.ts b/mobile/src/session/native-chat/composer/use-mobile-native-chat-image-attachments.test.ts index f9ed1c439a8..c9af74ba808 100644 --- a/mobile/src/session/native-chat/composer/use-mobile-native-chat-image-attachments.test.ts +++ b/mobile/src/session/native-chat/composer/use-mobile-native-chat-image-attachments.test.ts @@ -5,8 +5,8 @@ import '../../../../../src/shared/agent-launch/startup/agent-tui-input-clear' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import type { RpcClient } from '../../../transport/rpc/rpc-client-contract' import type { RpcResponse, RpcSuccess } from '../../../transport/rpc/rpc-wire-types' -import { resetMobileNativeChatStaleInputForTests } from '../mobile-native-chat-stale-input' -import { resetMobileNativeChatTerminalWritesForTests } from '../mobile-native-chat-terminal-write-lock' +import { resetMobileNativeChatStaleInputForTests } from './mobile-native-chat-stale-input' +import { resetMobileNativeChatTerminalWritesForTests } from './mobile-native-chat-terminal-write-lock' import { useMobileNativeChatImageAttachments } from './use-mobile-native-chat-image-attachments' // Stub the media seam so direct Expo imports would expose unsupported Flow syntax and fail the transform. diff --git a/mobile/src/session/native-chat/composer/use-mobile-native-chat-image-attachments.ts b/mobile/src/session/native-chat/composer/use-mobile-native-chat-image-attachments.ts index b3cfdc53aa1..c5533f5492d 100644 --- a/mobile/src/session/native-chat/composer/use-mobile-native-chat-image-attachments.ts +++ b/mobile/src/session/native-chat/composer/use-mobile-native-chat-image-attachments.ts @@ -21,20 +21,20 @@ import { openMobileNativeChatSendBudget, type MobileNativeChatSendIntent, type MobileNativeChatSendOutcome -} from '../mobile-native-chat-send' +} from './mobile-native-chat-send' import { clearMobileNativeChatInputStale, healMobileNativeChatStaleInput, isMobileNativeChatInputStale, markMobileNativeChatInputStale -} from '../mobile-native-chat-stale-input' +} from './mobile-native-chat-stale-input' import { acquireMobileNativeChatTerminalWrite, releaseMobileNativeChatTerminalWrite -} from '../mobile-native-chat-terminal-write-lock' +} from './mobile-native-chat-terminal-write-lock' import { useMobileNativeChatImageUpload } from './use-mobile-native-chat-image-upload' import type { PendingNativeChatFile } from './mobile-native-chat-file-attachment' -import type { StructuredMobileSendAttachment } from '../../use-mobile-structured-send-with-outcome' +import type { StructuredMobileSendAttachment } from './use-mobile-structured-send-with-outcome' type CurrentRef = { readonly current: T } type ShowToast = (message: string, durationMs?: number) => void diff --git a/mobile/src/session/native-chat/use-mobile-native-chat-input-lease.test.ts b/mobile/src/session/native-chat/composer/use-mobile-native-chat-input-lease.test.ts similarity index 57% rename from mobile/src/session/native-chat/use-mobile-native-chat-input-lease.test.ts rename to mobile/src/session/native-chat/composer/use-mobile-native-chat-input-lease.test.ts index 8b99f5736b4..0126af0b4c0 100644 --- a/mobile/src/session/native-chat/use-mobile-native-chat-input-lease.test.ts +++ b/mobile/src/session/native-chat/composer/use-mobile-native-chat-input-lease.test.ts @@ -1,10 +1,7 @@ import { createElement } from 'react' import { act, create, type ReactTestRenderer } from 'react-test-renderer' -import { afterEach, describe, expect, it, vi } from 'vitest' -import { - useMobileNativeChatInputLease, - useSettledMobileNativeChatInputLock -} from './use-mobile-native-chat-input-lease' +import { afterEach, describe, expect, it } from 'vitest' +import { useMobileNativeChatInputLease } from './use-mobile-native-chat-input-lease' type Lease = ReturnType @@ -65,47 +62,3 @@ describe('useMobileNativeChatInputLease', () => { expect(lease?.clear()).toBe(true) }) }) - -describe('useSettledMobileNativeChatInputLock', () => { - let renderer: ReactTestRenderer | null = null - let settled: ReturnType | undefined - - afterEach(() => { - act(() => renderer?.unmount()) - renderer = null - vi.useRealTimers() - }) - - function Harness({ reason }: { reason: 'waiting' | 'disconnected' | null }): null { - settled = useSettledMobileNativeChatInputLock(reason) - return null - } - - it('holds each edge until the lease has stopped flapping', () => { - vi.useFakeTimers() - act(() => { - renderer = create(createElement(Harness, { reason: 'waiting' })) - }) - expect(settled).toBeNull() - act(() => { - vi.advanceTimersByTime(600) - }) - expect(settled).toBe('waiting') - - act(() => renderer?.update(createElement(Harness, { reason: null }))) - act(() => { - vi.advanceTimersByTime(300) - }) - act(() => renderer?.update(createElement(Harness, { reason: 'disconnected' }))) - act(() => { - vi.advanceTimersByTime(600) - }) - expect(settled).toBe('disconnected') - - act(() => renderer?.update(createElement(Harness, { reason: null }))) - act(() => { - vi.advanceTimersByTime(600) - }) - expect(settled).toBeNull() - }) -}) diff --git a/mobile/src/session/native-chat/use-mobile-native-chat-input-lease.ts b/mobile/src/session/native-chat/composer/use-mobile-native-chat-input-lease.ts similarity index 93% rename from mobile/src/session/native-chat/use-mobile-native-chat-input-lease.ts rename to mobile/src/session/native-chat/composer/use-mobile-native-chat-input-lease.ts index 9dd2bd8b078..417500e8ea2 100644 --- a/mobile/src/session/native-chat/use-mobile-native-chat-input-lease.ts +++ b/mobile/src/session/native-chat/composer/use-mobile-native-chat-input-lease.ts @@ -1,7 +1,7 @@ import { useCallback, useEffect, useRef, useState } from 'react' -import { nativeChatTurnStatusCopy } from './native-chat-turn-status-copy' -import { translate, type Translate } from '../../i18n/mobile-i18n' -import type { MobileNativeChatInputLockReason } from './MobileNativeChatView' +import { nativeChatTurnStatusCopy } from '../transcript/native-chat-turn-status-copy' +import { translate, type Translate } from '../../../i18n/mobile-i18n' +import type { MobileNativeChatInputLockReason } from '../MobileNativeChatView' export function useMobileNativeChatInputLease(args: { activeHandle: string | null diff --git a/mobile/src/session/native-chat/composer/use-mobile-native-chat-launch-draft-seed.ts b/mobile/src/session/native-chat/composer/use-mobile-native-chat-launch-draft-seed.ts index acb46ca7679..b5e03cb117e 100644 --- a/mobile/src/session/native-chat/composer/use-mobile-native-chat-launch-draft-seed.ts +++ b/mobile/src/session/native-chat/composer/use-mobile-native-chat-launch-draft-seed.ts @@ -5,7 +5,7 @@ import { nativeChatLaunchDraftTurnBaseline, type NativeChatLaunchDraftTurnBaseline } from '../../../../../src/shared/native-chat/transcript/native-chat-launch-draft-resolution' -import { normalizedUserText } from './mobile-native-chat-draft-reconcile' +import { normalizedNativeChatUserMessageText } from '../../../../../src/shared/native-chat/transcript/native-chat-image-transcript-markers' import { mobileNativeChatLaunchDraftSeeds } from './mobile-native-chat-draft-store' import { mobileNativeChatDraftDestination } from './mobile-native-chat-draft-inputs' @@ -22,7 +22,7 @@ function launchDraftResolved( ): boolean { // Old hosts send no creation time, so any user turn retires the draft. if (createdAt === null) { - return messages.some((message) => normalizedUserText(message) !== null) + return messages.some((message) => normalizedNativeChatUserMessageText(message) !== null) } return launchDraftResolvedByTranscript({ createdAt }, messages, baseline) } diff --git a/mobile/src/session/native-chat/composer/use-mobile-native-chat-offline-sends.test.ts b/mobile/src/session/native-chat/composer/use-mobile-native-chat-offline-sends.test.ts index 72d5595f366..4700cd63d6b 100644 --- a/mobile/src/session/native-chat/composer/use-mobile-native-chat-offline-sends.test.ts +++ b/mobile/src/session/native-chat/composer/use-mobile-native-chat-offline-sends.test.ts @@ -1,7 +1,7 @@ import { createElement } from 'react' import { act, create, type ReactTestRenderer } from 'react-test-renderer' import { afterEach, describe, expect, it, vi } from 'vitest' -import type { MobileNativeChatSendIntent } from '../mobile-native-chat-send' +import type { MobileNativeChatSendIntent } from './mobile-native-chat-send' import type { MobileNativeChatInputLockReason } from '../MobileNativeChatView' import { resetMobileNativeChatDraftStoreForTests } from './mobile-native-chat-draft-store' import { diff --git a/mobile/src/session/native-chat/composer/use-mobile-native-chat-offline-sends.ts b/mobile/src/session/native-chat/composer/use-mobile-native-chat-offline-sends.ts index 21f629a0aec..24ea22aef03 100644 --- a/mobile/src/session/native-chat/composer/use-mobile-native-chat-offline-sends.ts +++ b/mobile/src/session/native-chat/composer/use-mobile-native-chat-offline-sends.ts @@ -1,8 +1,8 @@ import { useCallback, useEffect, useLayoutEffect, useRef, useState } from 'react' import { appendReturnedDraftText } from '../../../../../src/shared/returned-draft-text' -import type { MobileNativeChatSendIntent } from '../mobile-native-chat-send' +import type { MobileNativeChatSendIntent } from './mobile-native-chat-send' import type { MobileNativeChatInputLockReason } from '../MobileNativeChatView' -import { useSettledMobileNativeChatInputLock } from '../use-mobile-native-chat-input-lease' +import { useSettledMobileNativeChatInputLock } from './use-mobile-native-chat-input-lease' import { mobileNativeChatDraftDestination, readMobileNativeChatDraftInputs, diff --git a/mobile/src/session/native-chat/use-mobile-native-chat-send-error.test.ts b/mobile/src/session/native-chat/composer/use-mobile-native-chat-send-error.test.ts similarity index 77% rename from mobile/src/session/native-chat/use-mobile-native-chat-send-error.test.ts rename to mobile/src/session/native-chat/composer/use-mobile-native-chat-send-error.test.ts index d0db1f8c01e..825c6960288 100644 --- a/mobile/src/session/native-chat/use-mobile-native-chat-send-error.test.ts +++ b/mobile/src/session/native-chat/composer/use-mobile-native-chat-send-error.test.ts @@ -100,54 +100,6 @@ describe('useMobileNativeChatSendError', () => { expect(api().message).toBe('Background tasks are still running.') }) - it('holds a failure for four seconds, then drops it', async () => { - await render() - await act(async () => api().show('a')) - expect(api().message).toBe('a') - - await act(async () => { - vi.advanceTimersByTime(3999) - }) - expect(api().message).toBe('a') - await act(async () => { - vi.advanceTimersByTime(1) - }) - expect(api().message).toBeNull() - }) - - it('restarts the hold when a second failure lands mid-hold', async () => { - await render() - await act(async () => api().show('a')) - await act(async () => { - vi.advanceTimersByTime(3000) - }) - await act(async () => api().show('b')) - - await act(async () => { - vi.advanceTimersByTime(3000) - }) - expect(api().message).toBe('b') - - await act(async () => { - vi.advanceTimersByTime(1000) - }) - expect(api().message).toBeNull() - }) - - it('clears immediately and cancels the pending hold', async () => { - await render() - await act(async () => api().show('a')) - await act(async () => api().clear()) - expect(api().message).toBeNull() - - await act(async () => api().show('b')) - await act(async () => api().clear()) - await act(async () => { - vi.advanceTimersByTime(10_000) - }) - expect(api().message).toBeNull() - }) - it('drops a held failure when the scope changes', async () => { await render('terminal-1') await act(async () => api().show('a')) @@ -210,13 +162,4 @@ describe('useMobileNativeChatSendError', () => { expect(showToast).toHaveBeenCalledWith('Delivery unconfirmed', 1600) }) - - it('cancels the pending hold timer on unmount', async () => { - await render() - await act(async () => api().show('a')) - expect(vi.getTimerCount()).toBe(1) - act(() => renderer?.unmount()) - renderer = null - expect(vi.getTimerCount()).toBe(0) - }) }) diff --git a/mobile/src/session/native-chat/use-mobile-native-chat-send-error.ts b/mobile/src/session/native-chat/composer/use-mobile-native-chat-send-error.ts similarity index 97% rename from mobile/src/session/native-chat/use-mobile-native-chat-send-error.ts rename to mobile/src/session/native-chat/composer/use-mobile-native-chat-send-error.ts index db9fc4dab94..fbc0b4ed6f0 100644 --- a/mobile/src/session/native-chat/use-mobile-native-chat-send-error.ts +++ b/mobile/src/session/native-chat/composer/use-mobile-native-chat-send-error.ts @@ -1,5 +1,5 @@ import { useCallback, useEffect, useRef, useState, type MutableRefObject } from 'react' -import type { StructuredAgentSessionCommandRefusalCause } from '../../../../src/shared/agent-session/view/structured-agent-session-composer' +import type { StructuredAgentSessionCommandRefusalCause } from '../../../../../src/shared/agent-session/view/structured-agent-session-composer' // Keep command-refusal causes only while the chat still shows the work that caused them. export type MobileNativeChatSendErrorDetails = { diff --git a/mobile/src/session/native-chat/use-mobile-native-chat-stop.ts b/mobile/src/session/native-chat/composer/use-mobile-native-chat-stop.ts similarity index 88% rename from mobile/src/session/native-chat/use-mobile-native-chat-stop.ts rename to mobile/src/session/native-chat/composer/use-mobile-native-chat-stop.ts index 0adce2c38b9..b6411fd0036 100644 --- a/mobile/src/session/native-chat/use-mobile-native-chat-stop.ts +++ b/mobile/src/session/native-chat/composer/use-mobile-native-chat-stop.ts @@ -1,13 +1,13 @@ import { useCallback, useEffect, useRef, type MutableRefObject } from 'react' -import { translate } from '../../i18n/mobile-i18n' -import type { RpcClient } from '../../transport/rpc/rpc-client-contract' -import { isRpcDeliveryUnknown } from '../../transport/rpc/rpc-delivery-ambiguity' -import '../../transport/connection/stable-logical-rpc-client' -import { isLogicalClientCutoverError } from '../../transport/connection/logical-client-cutover-error' -import { nativeChatTerminalWrite } from '../../terminal/session/mobile-session-terminal-operations' +import { translate } from '../../../i18n/mobile-i18n' +import type { RpcClient } from '../../../transport/rpc/rpc-client-contract' +import { isRpcDeliveryUnknown } from '../../../transport/rpc/rpc-delivery-ambiguity' +import '../../../transport/connection/stable-logical-rpc-client' +import { isLogicalClientCutoverError } from '../../../transport/connection/logical-client-cutover-error' +import { nativeChatTerminalWrite } from '../../../terminal/session/mobile-session-terminal-operations' import { openMobileNativeChatSendBudget } from './mobile-native-chat-send' -import { nativeChatStopSendsSecondEscape } from '../../../../src/shared/native-chat/native-chat-agent-support' -import { NATIVE_CHAT_QUESTION_STEP_MS } from '../../../../src/shared/native-chat/input/native-chat-answer-stepping' +import { nativeChatStopSendsSecondEscape } from '../../../../../src/shared/native-chat/native-chat-agent-support' +import { NATIVE_CHAT_QUESTION_STEP_MS } from '../../../../../src/shared/native-chat/input/native-chat-answer-stepping' // Resolves false only when no Escape could have landed, so the chat may offer Stop again. export function useMobileNativeChatStop(args: { diff --git a/mobile/src/session/native-chat/composer/use-mobile-native-chat-structured-composer.ts b/mobile/src/session/native-chat/composer/use-mobile-native-chat-structured-composer.ts index a0a7b6efb54..80d1e453980 100644 --- a/mobile/src/session/native-chat/composer/use-mobile-native-chat-structured-composer.ts +++ b/mobile/src/session/native-chat/composer/use-mobile-native-chat-structured-composer.ts @@ -1,9 +1,9 @@ import { useMemo } from 'react' import type { AgentSessionConversationCommand } from '../../../../../src/shared/agent-session/agent-session-conversation-command' -import type { MobileNativeChatStructuredComposer } from './MobileNativeChatComposer' +import type { MobileNativeChatStructuredComposer } from './mobile-native-chat-structured-composer' import type { MobileNativeChatFileAttachments } from './use-mobile-native-chat-file-attachments' -import type { useMobileStructuredSessionCommands } from '../../use-mobile-structured-session-commands' -import type { MobileStructuredThreadGoal } from '../../use-mobile-structured-thread-goal' +import type { useMobileStructuredSessionCommands } from './use-mobile-structured-session-commands' +import type { MobileStructuredThreadGoal } from '../input/use-mobile-structured-thread-goal' const NO_COMMANDS: readonly AgentSessionConversationCommand[] = [] diff --git a/mobile/src/session/native-chat/use-mobile-native-chat-unconfirmed-sends.ts b/mobile/src/session/native-chat/composer/use-mobile-native-chat-unconfirmed-sends.ts similarity index 94% rename from mobile/src/session/native-chat/use-mobile-native-chat-unconfirmed-sends.ts rename to mobile/src/session/native-chat/composer/use-mobile-native-chat-unconfirmed-sends.ts index c62e77df380..1adf0877a0b 100644 --- a/mobile/src/session/native-chat/use-mobile-native-chat-unconfirmed-sends.ts +++ b/mobile/src/session/native-chat/composer/use-mobile-native-chat-unconfirmed-sends.ts @@ -1,19 +1,19 @@ // Lost acknowledgements may hide delivered sends: hold them quietly until the transcript confirms them, or hand them back at the deadline. Structured sends own a separate hold. import { useCallback, useEffect, useLayoutEffect, useRef, useState } from 'react' -import type { NativeChatMessage } from '../../../../src/shared/native-chat/native-chat-types' +import type { NativeChatMessage } from '../../../../../src/shared/native-chat/native-chat-types' import { findLandedUnconfirmedSends, type UnconfirmedSend -} from './composer/mobile-native-chat-draft-reconcile' -import { returnMobileNativeChatInFlightSend } from './composer/mobile-native-chat-draft-store' +} from './mobile-native-chat-draft-reconcile' +import { returnMobileNativeChatInFlightSend } from './mobile-native-chat-draft-store' import { claimMobileNativeChatInFlightSends, releaseMobileNativeChatInFlightSends, settleMobileNativeChatInFlightSend, useMobileNativeChatSavedInFlightVersion -} from './composer/mobile-native-chat-in-flight-sends' -import type { MobileNativeChatSendOrigin } from './mobile-native-chat-pending-echo' +} from './mobile-native-chat-in-flight-sends' +import type { MobileNativeChatSendOrigin } from '../transcript/mobile-native-chat-pending-echo' import { createUnconfirmedSendDeadlines } from './unconfirmed-send-deadlines' export const UNCONFIRMED_SEND_MESSAGE = 'Delivery unconfirmed — check chat before retrying' diff --git a/mobile/src/session/native-chat/composer/use-mobile-native-chat-workspace-catalog.ts b/mobile/src/session/native-chat/composer/use-mobile-native-chat-workspace-catalog.ts index 75a0b920379..eb5c6b79b61 100644 --- a/mobile/src/session/native-chat/composer/use-mobile-native-chat-workspace-catalog.ts +++ b/mobile/src/session/native-chat/composer/use-mobile-native-chat-workspace-catalog.ts @@ -1,5 +1,5 @@ import type { RpcClient } from '../../../transport/rpc/rpc-client-contract' -import type { StructuredAgentSessionHostSupport } from '../../mobile-structured-agent-session-host-support' +import type { StructuredAgentSessionHostSupport } from '../agent-session/mobile-structured-agent-session-host-support' import { useMobileNativeChatFileSearch } from './use-mobile-native-chat-file-search' import { useMobileNativeChatSkills } from './use-mobile-native-chat-skills' diff --git a/mobile/src/session/use-mobile-structured-command-controller.ts b/mobile/src/session/native-chat/composer/use-mobile-structured-command-controller.ts similarity index 88% rename from mobile/src/session/use-mobile-structured-command-controller.ts rename to mobile/src/session/native-chat/composer/use-mobile-structured-command-controller.ts index d86f4cdb9f7..2bc205eb14e 100644 --- a/mobile/src/session/use-mobile-structured-command-controller.ts +++ b/mobile/src/session/native-chat/composer/use-mobile-structured-command-controller.ts @@ -1,5 +1,5 @@ import { useMemo } from 'react' -import type { useMobileStructuredAgentOptions } from './use-mobile-structured-agent-options' +import type { useMobileStructuredAgentOptions } from '../input/use-mobile-structured-agent-options' type MobileStructuredAgentOptions = ReturnType diff --git a/mobile/src/session/use-mobile-structured-context-usage.ts b/mobile/src/session/native-chat/composer/use-mobile-structured-context-usage.ts similarity index 64% rename from mobile/src/session/use-mobile-structured-context-usage.ts rename to mobile/src/session/native-chat/composer/use-mobile-structured-context-usage.ts index c381c955bec..1c69e420732 100644 --- a/mobile/src/session/use-mobile-structured-context-usage.ts +++ b/mobile/src/session/native-chat/composer/use-mobile-structured-context-usage.ts @@ -1,11 +1,11 @@ import { useMemo } from 'react' -import type { AgentJournalRenderItem } from '../../../src/shared/agent-session/journal/agent-session-journal-types' -import type { AgentSessionOptionsResult } from '../../../src/shared/agent-session/options/agent-session-options-result' -import { selectStructuredAgentSessionContextUsage } from '../../../src/shared/agent-session/structured-agent-session-context-usage' +import type { AgentJournalRenderItem } from '../../../../../src/shared/agent-session/journal/agent-session-journal-types' +import type { AgentSessionOptionsResult } from '../../../../../src/shared/agent-session/options/agent-session-options-result' +import { selectStructuredAgentSessionContextUsage } from '../../../../../src/shared/agent-session/structured-agent-session-context-usage' import { summarizeContextUsage, type NativeChatContextUsageSummary -} from '../../../src/shared/native-chat/native-chat-context-usage-summary' +} from '../../../../../src/shared/native-chat/native-chat-context-usage-summary' /** The composer ring's readout, from desktop's rule; an older host's missing answer leaves the loaded window's facts. */ export function useMobileStructuredContextUsage( diff --git a/mobile/src/session/use-mobile-structured-interrupted-continue.ts b/mobile/src/session/native-chat/composer/use-mobile-structured-interrupted-continue.ts similarity index 82% rename from mobile/src/session/use-mobile-structured-interrupted-continue.ts rename to mobile/src/session/native-chat/composer/use-mobile-structured-interrupted-continue.ts index 4b0e38729ce..315272016b2 100644 --- a/mobile/src/session/use-mobile-structured-interrupted-continue.ts +++ b/mobile/src/session/native-chat/composer/use-mobile-structured-interrupted-continue.ts @@ -2,20 +2,20 @@ import { useCallback, useMemo, useState } from 'react' import type { AgentJournalRenderItem, AgentJournalSubmission -} from '../../../src/shared/agent-session/journal/agent-session-journal-types' -import { latestNativeChatOrcaStopCut } from '../../../src/shared/native-chat/native-chat-orca-stop-cut' +} from '../../../../../src/shared/agent-session/journal/agent-session-journal-types' +import { latestNativeChatOrcaStopCut } from '../../../../../src/shared/native-chat/native-chat-orca-stop-cut' import { failNativeChatInterruptedContinue, nativeChatInterruptedContinueState, NO_NATIVE_CHAT_INTERRUPTED_CONTINUE_ATTEMPT, nativeChatInterruptedContinueAccepted, type NativeChatInterruptedContinueAttempt -} from '../../../src/shared/native-chat/native-chat-interrupted-continue' -import type { RpcClient } from '../transport/rpc/rpc-client-contract' -import { callAgentSession } from './mobile-structured-agent-session-rpc' -import { useRouteRelaysCapability } from '../worktree/workspace-server-context' -import { AGENT_SESSION_PHONE_CONTINUE_INTERRUPTED_RUNTIME_CAPABILITY } from '../../../src/shared/agent-session/agent-session-continue-interrupted-capability' -import type { StructuredAgentSessionHostSupport } from './mobile-structured-agent-session-host-support' +} from '../../../../../src/shared/native-chat/native-chat-interrupted-continue' +import type { RpcClient } from '../../../transport/rpc/rpc-client-contract' +import { callAgentSession } from '../agent-session/mobile-structured-agent-session-rpc' +import { useRouteRelaysCapability } from '../../../worktree/workspace-server-context' +import { AGENT_SESSION_PHONE_CONTINUE_INTERRUPTED_RUNTIME_CAPABILITY } from '../../../../../src/shared/agent-session/agent-session-continue-interrupted-capability' +import type { StructuredAgentSessionHostSupport } from '../agent-session/mobile-structured-agent-session-host-support' export type MobileStructuredInterruptedContinue = { continueAvailable: boolean diff --git a/mobile/src/session/use-mobile-structured-native-chat-send-bridge.test.ts b/mobile/src/session/native-chat/composer/use-mobile-structured-native-chat-send-bridge.test.ts similarity index 63% rename from mobile/src/session/use-mobile-structured-native-chat-send-bridge.test.ts rename to mobile/src/session/native-chat/composer/use-mobile-structured-native-chat-send-bridge.test.ts index 70cac00aeb4..e7fb01c9d07 100644 --- a/mobile/src/session/use-mobile-structured-native-chat-send-bridge.test.ts +++ b/mobile/src/session/native-chat/composer/use-mobile-structured-native-chat-send-bridge.test.ts @@ -1,17 +1,15 @@ -import { mobileNativeChatDraftDestination } from './native-chat/composer/mobile-native-chat-draft-inputs' +import { mobileNativeChatDraftDestination } from './mobile-native-chat-draft-inputs' import { createElement } from 'react' import { act, create, type ReactTestRenderer } from 'react-test-renderer' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import type { StructuredAgentId } from '../../../src/shared/agent-session/lifecycle/agent-session-provider-handle' -import type { MobileNativeChatSendOrigin } from './native-chat/mobile-native-chat-pending-echo' -import type { MobileNativeChatSendIntent } from './native-chat/mobile-native-chat-send' +import type { StructuredAgentId } from '../../../../../src/shared/agent-session/lifecycle/agent-session-provider-handle' +import type { MobileNativeChatSendOrigin } from '../transcript/mobile-native-chat-pending-echo' + import { useMobileStructuredNativeChatSendBridge } from './use-mobile-structured-native-chat-send-bridge' import { - editMobileNativeChatDraft, recordMobileNativeChatSkillPick, - readMobileNativeChatPickedSkills, resetMobileNativeChatDraftStoreForTests -} from './native-chat/composer/mobile-native-chat-draft-store' +} from './mobile-native-chat-draft-store' const ORIGIN: MobileNativeChatSendOrigin = { draftKey: 'draft', @@ -62,40 +60,6 @@ describe('useMobileStructuredNativeChatSendBridge', () => { resetMobileNativeChatDraftStoreForTests() }) - it('hands back an unconfirmed send with its skills beside newer picks only at the deadline', async () => { - recordMobileNativeChatSkillPick(ORIGIN.draftKey, { - token: '$review', - path: '/skills/review/SKILL.md' - }) - sendStructured.mockImplementation( - async ( - ...args: [unknown, unknown, unknown, unknown, unknown, MobileNativeChatSendIntent] - ) => { - args[5].onCreated?.('lost-id') - editMobileNativeChatDraft(ORIGIN.draftKey, '$newer work') - recordMobileNativeChatSkillPick(ORIGIN.draftKey, { - token: '$newer', - path: '/skills/newer/SKILL.md' - }) - return 'unknown' - } - ) - mount('codex') - - await expect(sendWithOutcome('/review')).resolves.toBe('unknown') - - expect(restoreRejectedDraft).not.toHaveBeenCalled() - expect(onSendError).not.toHaveBeenCalled() - expect(holdUnconfirmed).toHaveBeenCalledWith('lost-id', expect.any(Function)) - act(() => holdUnconfirmed.mock.calls[0]![1]()) - expect(restoreRejectedDraft).toHaveBeenCalledWith(ORIGIN, '/review') - expect(onSendError).toHaveBeenCalledWith('Not confirmed. Restored to the box.') - expect(readMobileNativeChatPickedSkills(ORIGIN.draftKey).map((skill) => skill.name)).toEqual([ - 'newer', - 'review' - ]) - }) - it('puts a host command whose reply was lost back in the box', async () => { sendStructured.mockResolvedValue('unknown') mount('codex') diff --git a/mobile/src/session/use-mobile-structured-native-chat-send-bridge.ts b/mobile/src/session/native-chat/composer/use-mobile-structured-native-chat-send-bridge.ts similarity index 85% rename from mobile/src/session/use-mobile-structured-native-chat-send-bridge.ts rename to mobile/src/session/native-chat/composer/use-mobile-structured-native-chat-send-bridge.ts index 255bb98d849..c1fde649e55 100644 --- a/mobile/src/session/use-mobile-structured-native-chat-send-bridge.ts +++ b/mobile/src/session/native-chat/composer/use-mobile-structured-native-chat-send-bridge.ts @@ -1,26 +1,26 @@ import { useCallback } from 'react' -import type { AgentSessionSlashCommand } from '../../../src/shared/agent-session/agent-session-wire' -import type { StructuredAgentId } from '../../../src/shared/agent-session/lifecycle/agent-session-provider-handle' +import type { AgentSessionSlashCommand } from '../../../../../src/shared/agent-session/agent-session-wire' +import type { StructuredAgentId } from '../../../../../src/shared/agent-session/lifecycle/agent-session-provider-handle' import type { MobileNativeChatSendIntent, MobileNativeChatSendOutcome -} from './native-chat/mobile-native-chat-send' -import type { MobileNativeChatSendOrigin } from './native-chat/mobile-native-chat-pending-echo' +} from './mobile-native-chat-send' +import type { MobileNativeChatSendOrigin } from '../transcript/mobile-native-chat-pending-echo' import type { StructuredMobileSendAttachment } from './use-mobile-structured-send-with-outcome' -import type { AgentJournalSkillRef } from '../../../src/shared/agent-session/journal/agent-session-journal-types' +import type { AgentJournalSkillRef } from '../../../../../src/shared/agent-session/journal/agent-session-journal-types' import { readMobileNativeChatPickedSkills, restoreMobileNativeChatPickedSkills -} from './native-chat/composer/mobile-native-chat-draft-store' +} from './mobile-native-chat-draft-store' import { beginMobileNativeChatInFlightSend, settleMobileNativeChatInFlightSend -} from './native-chat/composer/mobile-native-chat-in-flight-sends' +} from './mobile-native-chat-in-flight-sends' import type { MobileStructuredSends } from './use-mobile-structured-sends' -import { structuredSessionOperationId } from './structured-session-operation-id' -import { isSlashCommandDraft } from '../../../src/shared/native-chat/input/native-chat-slash-commands' -import { UNCONFIRMED_SEND_RESTORED_MESSAGE } from './native-chat/use-mobile-native-chat-unconfirmed-sends' +import { structuredSessionOperationId } from '../agent-session/structured-session-operation-id' +import { isSlashCommandDraft } from '../../../../../src/shared/native-chat/input/native-chat-slash-commands' +import { UNCONFIRMED_SEND_RESTORED_MESSAGE } from './use-mobile-native-chat-unconfirmed-sends' export function useMobileStructuredNativeChatSendBridge(args: { agent: StructuredAgentId | undefined diff --git a/mobile/src/session/use-mobile-structured-send-with-outcome.ts b/mobile/src/session/native-chat/composer/use-mobile-structured-send-with-outcome.ts similarity index 80% rename from mobile/src/session/use-mobile-structured-send-with-outcome.ts rename to mobile/src/session/native-chat/composer/use-mobile-structured-send-with-outcome.ts index be4dd2ea649..5adf512760d 100644 --- a/mobile/src/session/use-mobile-structured-send-with-outcome.ts +++ b/mobile/src/session/native-chat/composer/use-mobile-structured-send-with-outcome.ts @@ -1,46 +1,46 @@ -import { agentSessionInteractionCommand } from '../../../src/shared/agent-session/options/agent-session-interaction-mode' -import { selectAgentSessionCurrentRequests } from '../../../src/shared/agent-session/requests/agent-session-current-requests' +import { agentSessionInteractionCommand } from '../../../../../src/shared/agent-session/options/agent-session-interaction-mode' +import { selectAgentSessionCurrentRequests } from '../../../../../src/shared/agent-session/requests/agent-session-current-requests' import { useCallback } from 'react' -import { runningStructuredAgentSessionTurnId } from '../../../src/shared/agent-session/view/structured-agent-session-live-turn' -import { mobileStructuredAgentSessionWorking } from './mobile-structured-agent-session-working' -import { structuredSessionBackgroundTasksView } from '../../../src/shared/structured-session-background-tasks-view' -import { agentSessionVisibleFailureFacts } from '../../../src/shared/agent-session/failures/agent-session-visible-failures' -import { tuiAgentDisplayName } from '../../../src/shared/agent-launch/catalog/tui-agent-display-names' -import { pendingPromptsAllUnanswerableHere } from '../../../src/shared/agent-session/agent-session-approval-subject' +import { runningStructuredAgentSessionTurnId } from '../../../../../src/shared/agent-session/view/structured-agent-session-live-turn' +import { mobileStructuredAgentSessionWorking } from '../agent-session/mobile-structured-agent-session-working' +import { structuredSessionBackgroundTasksView } from '../../../../../src/shared/structured-session-background-tasks-view' +import { agentSessionVisibleFailureFacts } from '../../../../../src/shared/agent-session/failures/agent-session-visible-failures' +import { tuiAgentDisplayName } from '../../../../../src/shared/agent-launch/catalog/tui-agent-display-names' +import { pendingPromptsAllUnanswerableHere } from '../../../../../src/shared/agent-session/agent-session-approval-subject' import { SkillRefLimitError, structuredAgentSessionSendBody, type StructuredAgentSessionAttachment, type StructuredAgentSessionSendControl -} from '../../../src/shared/agent-session/requests/structured-agent-session-send-mutation' -import type { AgentJournalSkillRef } from '../../../src/shared/agent-session/journal/agent-session-journal-types' -import { MAX_SKILL_REFS } from '../../../src/shared/rpc-contract/structured-agent-session-message-params' +} from '../../../../../src/shared/agent-session/requests/structured-agent-session-send-mutation' +import type { AgentJournalSkillRef } from '../../../../../src/shared/agent-session/journal/agent-session-journal-types' +import { MAX_SKILL_REFS } from '../../../../../src/shared/rpc-contract/structured-agent-session-message-params' import { structuredAgentSessionGoalObjective, type StructuredAgentSessionComposerOptions -} from '../../../src/shared/agent-session/view/structured-agent-session-composer' -import { translate } from '../i18n/mobile-i18n' -import type { AgentSessionSlashCommand } from '../../../src/shared/agent-session/agent-session-wire' -import type { StructuredAgentSessionState } from '../../../src/shared/agent-session/structured-agent-session-reducer' +} from '../../../../../src/shared/agent-session/view/structured-agent-session-composer' +import { translate } from '../../../i18n/mobile-i18n' +import type { AgentSessionSlashCommand } from '../../../../../src/shared/agent-session/agent-session-wire' +import type { StructuredAgentSessionState } from '../../../../../src/shared/agent-session/structured-agent-session-reducer' import { mobileStructuredSendQueues } from './mobile-structured-send-queue-rule' -import type { RpcClient } from '../transport/rpc/rpc-client-contract' +import type { RpcClient } from '../../../transport/rpc/rpc-client-contract' import type { MobileNativeChatSendIntent, MobileNativeChatSendOutcome -} from './native-chat/mobile-native-chat-send' +} from './mobile-native-chat-send' import { dispatchMobileStructuredCommand } from './mobile-structured-composer-command' -import type { MobileNativeChatSendErrorReporter } from './native-chat/use-mobile-native-chat-send-error' -import { sendMobileStructuredAgentSessionMessage } from './mobile-structured-agent-session-send' +import type { MobileNativeChatSendErrorReporter } from './use-mobile-native-chat-send-error' +import { sendMobileStructuredAgentSessionMessage } from '../agent-session/mobile-structured-agent-session-send' import type { MobileStructuredSends } from './use-mobile-structured-sends' import type { MobileStructuredSendsOut } from './use-mobile-structured-stop-offer' -import { structuredSessionOperationId } from './structured-session-operation-id' -import { UNCONFIRMED_SEND_MESSAGE } from './native-chat/use-mobile-native-chat-unconfirmed-sends' -import { timeoutForDeadline } from './mobile-structured-agent-session-rpc' -import { nativeChatTextWithFileReferences } from './native-chat/composer/mobile-native-chat-file-attachment' +import { structuredSessionOperationId } from '../agent-session/structured-session-operation-id' +import { UNCONFIRMED_SEND_MESSAGE } from './use-mobile-native-chat-unconfirmed-sends' +import { timeoutForDeadline } from '../agent-session/mobile-structured-agent-session-rpc' +import { nativeChatTextWithFileReferences } from './mobile-native-chat-file-attachment' import { actionableStructuredApproval, actionableStructuredQuestion -} from './mobile-structured-actionable-prompt' +} from '../input/mobile-structured-actionable-prompt' export type StructuredMobileSendAttachment = | (StructuredAgentSessionAttachment & { kind?: 'image'; id?: string }) diff --git a/mobile/src/session/use-mobile-structured-sends.ts b/mobile/src/session/native-chat/composer/use-mobile-structured-sends.ts similarity index 89% rename from mobile/src/session/use-mobile-structured-sends.ts rename to mobile/src/session/native-chat/composer/use-mobile-structured-sends.ts index 670fc66e312..8764a9b0e3a 100644 --- a/mobile/src/session/use-mobile-structured-sends.ts +++ b/mobile/src/session/native-chat/composer/use-mobile-structured-sends.ts @@ -1,21 +1,21 @@ import { useCallback, useEffect, useLayoutEffect, useRef, useState } from 'react' -import type { AgentJournalCursor } from '../../../src/shared/agent-session/journal/agent-session-journal-identity' -import type { AgentJournalSubmission } from '../../../src/shared/agent-session/journal/agent-session-journal-types' -import { agentJournalSubmissionKey } from '../../../src/shared/agent-session/journal/agent-session-journal-item-key' -import type { StructuredAgentSessionOptimisticMessage } from '../../../src/shared/agent-session/view/structured-agent-session-message-projection' +import type { AgentJournalCursor } from '../../../../../src/shared/agent-session/journal/agent-session-journal-identity' +import type { AgentJournalSubmission } from '../../../../../src/shared/agent-session/journal/agent-session-journal-types' +import { agentJournalSubmissionKey } from '../../../../../src/shared/agent-session/journal/agent-session-journal-item-key' +import type { StructuredAgentSessionOptimisticMessage } from '../../../../../src/shared/agent-session/view/structured-agent-session-message-projection' import { structuredAgentSessionReadCoversSend, structuredAgentSessionSettledSends -} from '../../../src/shared/agent-session/requests/structured-agent-session-send-settlement' -import { mergeSentImagePreviews } from './native-chat/composer/mobile-native-chat-draft-reconcile' -import type { AgentSessionQueuedMessage } from '../../../src/shared/agent-session/requests/agent-session-queued-message-wire' -import type { MobileNativeChatSendErrorReporter } from './native-chat/use-mobile-native-chat-send-error' +} from '../../../../../src/shared/agent-session/requests/structured-agent-session-send-settlement' +import { mergeSentImagePreviews } from './mobile-native-chat-draft-reconcile' +import type { AgentSessionQueuedMessage } from '../../../../../src/shared/agent-session/requests/agent-session-queued-message-wire' +import type { MobileNativeChatSendErrorReporter } from './use-mobile-native-chat-send-error' import { UNCONFIRMED_SEND_MESSAGE, UNCONFIRMED_SEND_RESTORED_MESSAGE -} from './native-chat/use-mobile-native-chat-unconfirmed-sends' -import { createUnconfirmedSendDeadlines } from './native-chat/unconfirmed-send-deadlines' -import { returnMobileNativeChatInFlightSend } from './native-chat/composer/mobile-native-chat-draft-store' +} from './use-mobile-native-chat-unconfirmed-sends' +import { createUnconfirmedSendDeadlines } from './unconfirmed-send-deadlines' +import { returnMobileNativeChatInFlightSend } from './mobile-native-chat-draft-store' import { claimMobileNativeChatInFlightSends, mobileNativeChatInFlightSendIds, @@ -23,7 +23,7 @@ import { releaseMobileNativeChatInFlightSends, settleMobileNativeChatInFlightSend, useMobileNativeChatSavedInFlightVersion -} from './native-chat/composer/mobile-native-chat-in-flight-sends' +} from './mobile-native-chat-in-flight-sends' // Ordinary in-memory input outlives its request; exact host IDs retire it, and a lost reply hands it back at the deadline. type MobileStructuredSend = StructuredAgentSessionOptimisticMessage diff --git a/mobile/src/session/use-mobile-structured-session-commands.ts b/mobile/src/session/native-chat/composer/use-mobile-structured-session-commands.ts similarity index 89% rename from mobile/src/session/use-mobile-structured-session-commands.ts rename to mobile/src/session/native-chat/composer/use-mobile-structured-session-commands.ts index 3c5b002a17e..a86b674b3d7 100644 --- a/mobile/src/session/use-mobile-structured-session-commands.ts +++ b/mobile/src/session/native-chat/composer/use-mobile-structured-session-commands.ts @@ -1,14 +1,14 @@ -import { startAgentSessionCommandMenuQuery } from '../../../src/shared/agent-session/agent-session-command-menu-query' +import { startAgentSessionCommandMenuQuery } from '../../../../../src/shared/agent-session/agent-session-command-menu-query' import { useCallback, useEffect, useMemo, useRef, useState } from 'react' import { useQueryClient } from '@tanstack/react-query' import * as z from 'zod' -import type { AgentSessionSlashCommand } from '../../../src/shared/agent-session/agent-session-wire' -import type { RpcClient } from '../transport/rpc/rpc-client-contract' -import { bindDeferredRpcOperation, defineRpcOperation } from '../transport/rpc/rpc-operation' -import { rpcResultVariant } from '../transport/rpc/rpc-operation-result-reader' -import { defineHostQuery, useHostQuery } from '../query/host-query' -import { hostQueryKey } from '../query/host-query-key' -import { useWorkspaceExecutionHost } from '../navigation/workspace-execution-host' +import type { AgentSessionSlashCommand } from '../../../../../src/shared/agent-session/agent-session-wire' +import type { RpcClient } from '../../../transport/rpc/rpc-client-contract' +import { bindDeferredRpcOperation, defineRpcOperation } from '../../../transport/rpc/rpc-operation' +import { rpcResultVariant } from '../../../transport/rpc/rpc-operation-result-reader' +import { defineHostQuery, useHostQuery } from '../../../query/host-query' +import { hostQueryKey } from '../../../query/host-query-key' +import { useWorkspaceExecutionHost } from '../../../navigation/workspace-execution-host' type Reported = { client: RpcClient diff --git a/mobile/src/session/use-mobile-structured-stop-offer.test.ts b/mobile/src/session/native-chat/composer/use-mobile-structured-stop-offer.test.ts similarity index 100% rename from mobile/src/session/use-mobile-structured-stop-offer.test.ts rename to mobile/src/session/native-chat/composer/use-mobile-structured-stop-offer.test.ts diff --git a/mobile/src/session/use-mobile-structured-stop-offer.ts b/mobile/src/session/native-chat/composer/use-mobile-structured-stop-offer.ts similarity index 94% rename from mobile/src/session/use-mobile-structured-stop-offer.ts rename to mobile/src/session/native-chat/composer/use-mobile-structured-stop-offer.ts index bc0f6261b86..d13e4e32cfe 100644 --- a/mobile/src/session/use-mobile-structured-stop-offer.ts +++ b/mobile/src/session/native-chat/composer/use-mobile-structured-stop-offer.ts @@ -1,5 +1,5 @@ import { useCallback, useMemo, useRef, useState } from 'react' -import { structuredAgentSessionCanStop } from '../../../src/shared/agent-session/view/structured-agent-session-stop-control' +import { structuredAgentSessionCanStop } from '../../../../../src/shared/agent-session/view/structured-agent-session-stop-control' type Send = (...args: Args) => Promise diff --git a/mobile/src/session/use-mobile-structured-stop-press.test.ts b/mobile/src/session/native-chat/composer/use-mobile-structured-stop-press.test.ts similarity index 100% rename from mobile/src/session/use-mobile-structured-stop-press.test.ts rename to mobile/src/session/native-chat/composer/use-mobile-structured-stop-press.test.ts diff --git a/mobile/src/session/use-mobile-structured-stop-press.ts b/mobile/src/session/native-chat/composer/use-mobile-structured-stop-press.ts similarity index 100% rename from mobile/src/session/use-mobile-structured-stop-press.ts rename to mobile/src/session/native-chat/composer/use-mobile-structured-stop-press.ts diff --git a/mobile/src/session/native-chat/input/MobileNativeChatAsk.tsx b/mobile/src/session/native-chat/input/MobileNativeChatAsk.tsx index 5a0ae7676c8..3ec989ff1ee 100644 --- a/mobile/src/session/native-chat/input/MobileNativeChatAsk.tsx +++ b/mobile/src/session/native-chat/input/MobileNativeChatAsk.tsx @@ -22,8 +22,8 @@ import { useMobileColorScheme } from '../../../theme/use-mobile-color-scheme' import type { Translate } from '../../../i18n/mobile-i18n' import { useMobileTranslation } from '../../../i18n/use-mobile-translation' import { MessageBox } from '../../../components/composer-input/MessageBox' -import { MobileNativeChatCardHeaderAction } from '../MobileNativeChatCardHeaderAction' -import { MobileNativeChatQuestionText } from '../MobileNativeChatQuestionText' +import { MobileNativeChatCardHeaderAction } from './MobileNativeChatCardHeaderAction' +import { MobileNativeChatQuestionText } from '../transcript/MobileNativeChatQuestionText' import { useMobileNativeChatAskAutoAdvance } from './use-mobile-native-chat-ask-auto-advance' import { MobileNativeChatAskOptionRow } from './MobileNativeChatAskOptionRow' import { MobileNativeChatOptionPreviewSheet } from './MobileNativeChatOptionPreviewSheet' diff --git a/mobile/src/session/native-chat/input/MobileNativeChatBackgroundTasks.tsx b/mobile/src/session/native-chat/input/MobileNativeChatBackgroundTasks.tsx index 2776c6113d7..d35363724d4 100644 --- a/mobile/src/session/native-chat/input/MobileNativeChatBackgroundTasks.tsx +++ b/mobile/src/session/native-chat/input/MobileNativeChatBackgroundTasks.tsx @@ -18,7 +18,7 @@ import { } from 'lucide-react-native' import type { AgentChildRowModel } from '../../../../../src/shared/agent-status/presentation/agent-child-row-model' import type { AgentSessionBackgroundTask } from '../../../../../src/shared/agent-session/agent-session-background-task-wire' -import { sayMobileBackgroundTask as say } from '../../mobile-background-task-copy' +import { sayMobileBackgroundTask as say } from './mobile-background-task-copy' import { useMobileTranslation } from '../../../i18n/use-mobile-translation' import { backgroundTasksHeaderContent, @@ -38,11 +38,11 @@ import { useNow } from '../../../hooks/use-now' import { colors, radii, spacing, typography } from '../../../theme/mobile-theme' import { themedStyleSheet } from '../../../theme/themed-styles' import { useMobileColorScheme } from '../../../theme/use-mobile-color-scheme' -import type { MobileStructuredBackgroundTasks } from '../../use-mobile-structured-background-tasks' +import type { MobileStructuredBackgroundTasks } from './use-mobile-structured-background-tasks' import { useMobileBackgroundTaskStops, type MobileBackgroundTaskStopping as Stopping -} from '../../use-mobile-background-task-stops' +} from './use-mobile-background-task-stops' import { mobileAgentChildRowName, mobileAgentChildRowText diff --git a/mobile/src/session/native-chat/MobileNativeChatCardHeaderAction.tsx b/mobile/src/session/native-chat/input/MobileNativeChatCardHeaderAction.tsx similarity index 86% rename from mobile/src/session/native-chat/MobileNativeChatCardHeaderAction.tsx rename to mobile/src/session/native-chat/input/MobileNativeChatCardHeaderAction.tsx index 564a5fc6930..6f479175fb6 100644 --- a/mobile/src/session/native-chat/MobileNativeChatCardHeaderAction.tsx +++ b/mobile/src/session/native-chat/input/MobileNativeChatCardHeaderAction.tsx @@ -1,8 +1,8 @@ import { Keyboard, Pressable, StyleSheet } from 'react-native' import { ChevronDown, X } from 'lucide-react-native' -import { colors, pressedStyle } from '../../theme/mobile-theme' -import { useMobileColorScheme } from '../../theme/use-mobile-color-scheme' -import { useMobileTranslation } from '../../i18n/use-mobile-translation' +import { colors, pressedStyle } from '../../../theme/mobile-theme' +import { useMobileColorScheme } from '../../../theme/use-mobile-color-scheme' +import { useMobileTranslation } from '../../../i18n/use-mobile-translation' export function MobileNativeChatCardHeaderAction({ prompt, diff --git a/mobile/src/session/native-chat/input/MobileNativeChatOfflineQueue.tsx b/mobile/src/session/native-chat/input/MobileNativeChatOfflineQueue.tsx index 3a2b2e747c2..0db837cc17a 100644 --- a/mobile/src/session/native-chat/input/MobileNativeChatOfflineQueue.tsx +++ b/mobile/src/session/native-chat/input/MobileNativeChatOfflineQueue.tsx @@ -1,10 +1,10 @@ import { useContext, useMemo } from 'react' import { queuedMessageCardLine } from '../../../../../src/shared/agent-session/view/structured-agent-session-queued-cards' import { useMobileTranslation } from '../../../i18n/use-mobile-translation' -import type { MobileQueuedMessageCard } from '../../mobile-structured-queued-message-cards' +import type { MobileQueuedMessageCard } from './mobile-structured-queued-message-cards' import type { MobileNativeChatOfflineQueue as Queue } from '../composer/use-mobile-native-chat-offline-sends' import { MobileNativeChatQueuedMessages } from './MobileNativeChatQueuedMessages' -import { MobileNativeChatNoticeContext } from '../../mobile-native-chat-notice-context' +import { MobileNativeChatNoticeContext } from '../transcript/mobile-native-chat-notice-context' const PAUSED = { reason: 'failed' } as const diff --git a/mobile/src/session/native-chat/input/MobileNativeChatPermission.tsx b/mobile/src/session/native-chat/input/MobileNativeChatPermission.tsx index 960d7128b3c..f8fffdcc0bd 100644 --- a/mobile/src/session/native-chat/input/MobileNativeChatPermission.tsx +++ b/mobile/src/session/native-chat/input/MobileNativeChatPermission.tsx @@ -3,8 +3,8 @@ import { Pressable, ScrollView, StyleSheet, Text, View } from 'react-native' import { ShieldQuestion } from 'lucide-react-native' import { approvalDetailPreview } from '../../../../../src/shared/agent-session/agent-session-approval-detail-preview' import { approvalBlockedPathToShow } from '../../../../../src/shared/agent-session/agent-session-approval-blocked-path' -import { MobileNativeChatCardHeaderAction } from '../MobileNativeChatCardHeaderAction' -import { MobileNativeChatMarkdown } from '../MobileNativeChatMarkdown' +import { MobileNativeChatCardHeaderAction } from './MobileNativeChatCardHeaderAction' +import { MobileNativeChatMarkdown } from '../transcript/MobileNativeChatMarkdown' import { colors, radii, spacing, typography } from '../../../theme/mobile-theme' import { themedStyleSheet } from '../../../theme/themed-styles' import { useMobileColorScheme } from '../../../theme/use-mobile-color-scheme' diff --git a/mobile/src/session/native-chat/input/MobileNativeChatQuestion.tsx b/mobile/src/session/native-chat/input/MobileNativeChatQuestion.tsx index 8de47622917..43c6bd612b3 100644 --- a/mobile/src/session/native-chat/input/MobileNativeChatQuestion.tsx +++ b/mobile/src/session/native-chat/input/MobileNativeChatQuestion.tsx @@ -1,8 +1,8 @@ import { useMemo, useRef, useState } from 'react' import { Pressable, ScrollView, StyleSheet, Text, View } from 'react-native' import { Check, CircleHelp } from 'lucide-react-native' -import { MobileNativeChatCardHeaderAction } from '../MobileNativeChatCardHeaderAction' -import { MobileNativeChatQuestionText } from '../MobileNativeChatQuestionText' +import { MobileNativeChatCardHeaderAction } from './MobileNativeChatCardHeaderAction' +import { MobileNativeChatQuestionText } from '../transcript/MobileNativeChatQuestionText' import { colors, concentricRadius, radii, spacing, typography } from '../../../theme/mobile-theme' import { themedStyleSheet } from '../../../theme/themed-styles' import { useMobileColorScheme } from '../../../theme/use-mobile-color-scheme' diff --git a/mobile/src/session/native-chat/input/MobileNativeChatQueuedMessages.test.tsx b/mobile/src/session/native-chat/input/MobileNativeChatQueuedMessages.test.tsx index b7cdfdd5a3c..d047b82d231 100644 --- a/mobile/src/session/native-chat/input/MobileNativeChatQueuedMessages.test.tsx +++ b/mobile/src/session/native-chat/input/MobileNativeChatQueuedMessages.test.tsx @@ -1,36 +1,17 @@ // @vitest-environment happy-dom import { activateMobileUiLocale } from '../../../i18n/mobile-i18n' -import { - mobileQueuedMessageCards, - type MobileQueuedMessageCard -} from '../../mobile-structured-queued-message-cards' +import type { MobileQueuedMessageCard } from './mobile-structured-queued-message-cards' import { createElement } from 'react' -import type * as QueuedCardRowModule from '../../MobileQueuedMessageCardRow' -import { MobileNativeChatLowerRegion } from '../MobileNativeChatLowerRegion.web' -import { - useMobileNativeChatLowerGeometry, - useMobileNativeChatLowerRegion -} from '../mobile-native-chat-lower-region-context' +import type * as QueuedCardRowModule from './MobileQueuedMessageCardRow' import { act, create, type ReactTestRenderer } from 'react-test-renderer' import { afterEach, describe, expect, it, vi } from 'vitest' import { MobileNativeChatQueuedMessages } from './MobileNativeChatQueuedMessages' -import { - useMobileNativeChatComposerTray, - type MobileNativeChatComposerTray -} from '../composer/use-mobile-native-chat-composer-tray' -import { useMobileQueuedMessageComposerActions } from '../../use-mobile-queued-message-composer-actions' -import type { MobileStructuredAgentMutate } from '../../use-mobile-structured-agent-mutation' -import type { - AgentSessionQueuedMessage, - AgentSessionQueuedMessageMoveResult -} from '../../../../../src/shared/agent-session/requests/agent-session-queued-message-wire' -import type { StructuredAgentSessionMutationResult } from '../../mobile-structured-agent-session-rpc' const rowRenders = vi.hoisted(() => ({ count: 0 })) -vi.mock('../../MobileQueuedMessageCardRow', async (importOriginal) => { +vi.mock('./MobileQueuedMessageCardRow', async (importOriginal) => { const original = await importOriginal() return { MobileQueuedMessageCardRow: ( @@ -89,7 +70,7 @@ vi.mock('./MobileNativeChatDockedTaskList', () => ({ MobileNativeChatDockedTaskList: 'DockedTaskList' })) -vi.mock('../../MobileQueuedMessageComposer', () => ({ +vi.mock('./MobileQueuedMessageComposer', () => ({ MobileQueuedMessageComposer: 'QueuedMessageComposer' })) @@ -162,82 +143,6 @@ describe('MobileNativeChatQueuedMessages', () => { expect(sheet(mounted).props.visible).toBe(false) }) - it('the empty chord presses only the head card where its own button would, and offers it only while that press would act, across chat switches', async () => { - let tray!: MobileNativeChatComposerTray - function Tray(props: Parameters[0]['queued']) { - tray = useMobileNativeChatComposerTray({ - queued: props, - taskList: null, - backgroundTasks: null - }) - return createElement('View', null, tray.content) - } - const settles: ((accepted: boolean) => void)[] = [] - const onSend = vi.fn(() => new Promise((resolve) => settles.push(resolve))) - const chatA = { sessionKey: 'a', cards: [card({ messageId: 'a1' }), card({ messageId: 'a2' })] } - const chatB = { sessionKey: 'b', cards: [card({ messageId: 'b1' })] } - const show = async ( - chat: typeof chatA, - props: Partial[0]> = {} - ): Promise => { - await act(async () => { - renderer ??= create(createElement('View')) - renderer.update(createElement(Tray, { ...chat, agentWorking: true, onSend, ...props })) - }) - } - const press = (alternateSteers = true) => { - let pressed = false - act(() => { - pressed = tray.steerHead!.run(alternateSteers) - }) - return pressed - } - - await show(chatA) - expect(tray.steerHead!.steers(true)).toBe(true) - expect(press()).toBe(true) - expect(onSend).toHaveBeenLastCalledWith('a1') - // On its way: neither offered nor admitted again, like a second tap. - expect(tray.steerHead!.steers(true)).toBe(false) - expect(press()).toBe(false) - - // Another chat's head is its own; A settling later must not clear B's hold. - await show(chatB) - expect(tray.steerHead!.steers(true)).toBe(true) - expect(press()).toBe(true) - await act(async () => settles[0]!(true)) - expect(tray.steerHead!.steers(true)).toBe(false) - expect(press()).toBe(false) - await act(async () => settles[1]!(true)) - expect(tray.steerHead!.steers(true)).toBe(true) - - // Back to A, whose list remounts: an action started there still holds until it settles. - await show(chatA) - expect(press()).toBe(true) - await show(chatB) - await show(chatA) - expect(tray.steerHead!.steers(true)).toBe(false) - expect(press()).toBe(false) - await act(async () => settles[2]!(true)) - expect(tray.steerHead!.steers(true)).toBe(true) - - // No turn running (the paused queue after Stop): the head card's own Send. - await show(chatA, { agentWorking: false }) - expect(tray.steerHead!.steers(false)).toBe(true) - const refusals: [Partial[0]>, boolean][] = [ - [{}, false], - [{ steerHeld: true }, true], - [{ cards: [card({ messageId: 'a1', command: true }), card({ messageId: 'a2' })] }, true] - ] - for (const [props, alternateSteers] of refusals) { - await show(chatA, props) - expect(tray.steerHead!.steers(alternateSteers)).toBe(false) - const sends = onSend.mock.calls.length - expect(press(alternateSteers)).toBe(false) - expect(onSend).toHaveBeenCalledTimes(sends) - } - }) - it('runs one action per card at a time, however fast its controls are tapped', async () => { let answer: (done: boolean) => void = () => undefined const onSend = vi.fn(() => new Promise((resolve) => (answer = resolve))) @@ -270,71 +175,6 @@ describe('MobileNativeChatQueuedMessages', () => { }) } - it.each([100, 1000])('keeps pending work linear at %i cards', async (size) => { - let counting = false - let reads = 0 - let memberships = 0 - const ids = Array.from({ length: size }, (_, index) => `perf-card-${index}`) - const cards = ids.map((messageId) => - Object.defineProperty(card({ messageId }), 'messageId', { - get: () => { - reads += Number(counting) - return messageId - } - }) - ) - const has = Set.prototype.has - const membership = vi.spyOn(Set.prototype, 'has') - membership.mockImplementation(function (this: Set, key: unknown) { - if (counting && typeof key === 'string' && key.startsWith('perf-card-')) { - memberships++ - } - return has.call(this, key) - }) - const send = Promise.withResolvers() - const clear = Promise.withResolvers() - const onClearAll = vi.fn(() => clear.promise) - const onResume = vi.fn(async () => true) - const onSend = vi.fn(() => send.promise) - const mounted = await mountPaused({ - cards, - pause: { reason: 'stopped' }, - onClearAll, - onResume, - onSend - }) - const labels = ['Delete every queued message', 'Resume sending the queued messages'] - const steer = 'Send this message' - const trigger = async (action: () => void) => { - counting = true - await act(async () => action()) - counting = false - } - // The last card forces the complete conflict scan; admission and settlement each rerender. - await trigger(() => control(mounted, steer, size - 1).props.onPress()) - expect(onSend).toHaveBeenCalledExactlyOnceWith(ids.at(-1)) - expect(control(mounted, labels[0]!).props.disabled).toBe(true) - await trigger(() => send.resolve(false)) - // Same frame, before disabled state renders: the shared admission check refuses the rest. - await trigger(() => { - control(mounted, labels[0]!).props.onPress() - control(mounted, labels[1]!).props.onPress() - control(mounted, steer).props.onPress() - }) - expect(onClearAll).toHaveBeenCalledExactlyOnceWith(ids) - expect([onResume.mock.calls.length, onSend.mock.calls.length]).toEqual([0, 1]) - const greyed = () => [...labels, steer].map((label) => control(mounted, label).props.disabled) - expect(greyed()).toEqual([true, true, true]) - await trigger(() => clear.resolve(false)) - expect(greyed()).toEqual([false, false, false]) - // Four pending/settled renders plus admission: fixed linear budgets, independent of N. - expect(reads).toBeGreaterThanOrEqual(4 * size) - expect(reads).toBeLessThanOrEqual(36 * size) - expect(memberships).toBeGreaterThanOrEqual(size) - expect(memberships).toBeLessThanOrEqual(18 * size) - console.info('queue operation counts', { cards: size, reads, memberships }) - }) - function resumeButton(mounted: ReactTestRenderer) { return control(mounted, 'Resume sending the queued messages') } @@ -355,193 +195,4 @@ describe('MobileNativeChatQueuedMessages', () => { expect(onResume).toHaveBeenCalledTimes(2) }) }) - - it('admits one queue move synchronously, preserves unrelated actions and releases after settlement', async () => { - const messages: AgentSessionQueuedMessage[] = ['a', 'b', 'c', 'd'].map( - (messageId, position) => ({ - messageId, - position, - state: 'waiting', - body: { kind: 'message', role: 'user', blocks: [{ type: 'text', text: messageId }] } - }) - ) - messages[2]!.body.from = { kind: 'agent', senders: [], orchestration: null } - type MoveReply = StructuredAgentSessionMutationResult - const first = Promise.withResolvers() - const second = Promise.withResolvers() - const mutate = vi - .fn<(...args: Parameters) => Promise>() - .mockReturnValueOnce(first.promise) - .mockReturnValueOnce(second.promise) - const send = vi.fn(async () => true) - function Harness({ published = messages }: { published?: AgentSessionQueuedMessage[] }) { - const queue = useMobileQueuedMessageComposerActions({ - messages: published, - sessionId: 's', - sessionKey: 's', - reorderCapable: true, - enabled: true, - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: Vitest erases the generic result signature; this hook only requests queuedMessageMove, and both deferred replies are checked as MoveReply. - mutate: mutate as MobileStructuredAgentMutate, - onSendError: () => {} - }) - return createElement(MobileNativeChatQueuedMessages, { - cards: mobileQueuedMessageCards(queue.messages, []), - onMove: queue.move, - onSend: send - }) - } - await act(async () => { - renderer = create(createElement(Harness)) - }) - const list = () => renderer!.root.find((node) => String(node.type) === 'DragReorderList') - const ids = () => list().props.items.map((entry: MobileQueuedMessageCard) => entry.messageId) - const queuedMove = list().props.onMove - act(() => { - expect(queuedMove({ movedId: 'c', beforeId: 'a' })).toBe(true) - expect(queuedMove({ movedId: 'b', afterId: 'd' })).toBe(false) - }) - expect(mutate).toHaveBeenCalledTimes(1) - expect(ids()).toEqual(['c', 'a', 'b', 'd']) - expect(list().props.canMove).toBeUndefined() - expect(list().props.items[0].from).toBeDefined() - expect( - list().props.items.every((entry: MobileQueuedMessageCard) => - list().props.isMoveDisabled(entry) - ) - ).toBe(true) - const movedRow = list().props.renderRow(list().props.items[0]) - act(() => movedRow.props.onSend()) - expect(send).not.toHaveBeenCalled() - const otherRow = list().props.renderRow(list().props.items[1]) - await act(async () => otherRow.props.onSend()) - expect(send).toHaveBeenCalledExactlyOnceWith('a') - await act(async () => { - first.resolve({ - status: 'accepted', - value: { messageId: 'c', status: 'stale' }, - sameFence: true - }) - await first.promise - }) - expect(ids()).toEqual(['a', 'b', 'c', 'd']) - expect( - list().props.items.every( - (entry: MobileQueuedMessageCard) => !list().props.isMoveDisabled(entry) - ) - ).toBe(true) - act(() => expect(list().props.onMove({ movedId: 'b', afterId: 'd' })).toBe(true)) - // The host republishes the moved order with fresh positions; cards sort by position. - const published = [0, 2, 3, 1].map((index, position) => ({ ...messages[index]!, position })) - await act(async () => renderer!.update(createElement(Harness, { published }))) - expect(ids()).toEqual(['a', 'c', 'd', 'b']) - await act(async () => renderer!.unmount()) - renderer = null - await act(async () => { - second.resolve({ - status: 'accepted', - value: { messageId: 'b', status: 'moved' }, - sameFence: true - }) - await second.promise - }) - expect(mutate).toHaveBeenCalledTimes(2) - }) }) - -for (const population of [10, 100]) { - it(`does no queue population work on geometry-only updates with ${population} cards`, async () => { - const root = document.createElement('div') - root.dataset.testid = 'native-chat-view' - const viewport = document.createElement('div') - const content = document.createElement('div') - root.append(viewport) - viewport.append(content) - document.body.append(root) - let height = 180 - Object.defineProperties(viewport, { - clientHeight: { get: () => height }, - clientWidth: { value: 300 }, - scrollHeight: { value: 300 } - }) - vi.spyOn(root, 'getBoundingClientRect').mockImplementation(() => new DOMRect(0, 0, 300, 500)) - let visits = 0 - let operationRenders = 0 - let observedHeight = 0 - function GeometryConsumer() { - observedHeight = useMobileNativeChatLowerGeometry().viewportHeight - return null - } - function OperationConsumer() { - useMobileNativeChatLowerRegion() - operationRenders++ - return null - } - const cards = Array.from({ length: population }, (_, index) => { - const item = card({ messageId: `queued-${index}` }) - Object.defineProperty(item, 'messageId', { - get: () => { - visits++ - return `queued-${index}` - } - }) - return item - }) - let mounted: ReactTestRenderer | undefined - const paint = () => new Promise((resolve) => requestAnimationFrame(() => resolve())) - const render = (items: MobileQueuedMessageCard[]) => ( - - - - - - ) - try { - await act(async () => { - mounted = create(render(cards), { - createNodeMock: (element) => { - const props = element.props - if ( - typeof props === 'object' && - props !== null && - 'testID' in props && - props.testID === 'native-chat-lower-scroll' - ) { - return { getScrollableNode: () => viewport } - } - return element.type === 'ScrollView' ? { scrollToEnd: () => {} } : content - } - }) - }) - await act(paint) - await act(paint) - expect(observedHeight).toBe(180) - visits = 0 - operationRenders = 0 - rowRenders.count = 0 - await act(async () => { - height = 120 - window.dispatchEvent(new Event('resize')) - await paint() - }) - expect(observedHeight).toBe(120) - expect.soft(operationRenders).toBe(0) - expect.soft(rowRenders.count).toBe(0) - expect.soft(visits).toBe(0) - await act(async () => - mounted!.update( - render([...cards, card({ messageId: 'appended', text: 'A real new message' })]) - ) - ) - expect(rowRenders.count).toBeGreaterThan(0) - expect(visits).toBeGreaterThan(0) - expect( - mounted!.root.findAllByProps({ children: 'A real new message' }).length - ).toBeGreaterThan(0) - } finally { - await act(async () => mounted?.unmount()) - root.remove() - vi.restoreAllMocks() - } - }) -} diff --git a/mobile/src/session/native-chat/input/MobileNativeChatQueuedMessages.tsx b/mobile/src/session/native-chat/input/MobileNativeChatQueuedMessages.tsx index 40d45fd502b..b2a8d678a9e 100644 --- a/mobile/src/session/native-chat/input/MobileNativeChatQueuedMessages.tsx +++ b/mobile/src/session/native-chat/input/MobileNativeChatQueuedMessages.tsx @@ -9,7 +9,7 @@ import { colors } from '../../../theme/mobile-theme' import { useMobileColorScheme } from '../../../theme/use-mobile-color-scheme' import { useMobileTranslation } from '../../../i18n/use-mobile-translation' import { useLargeSystemText } from '../../../theme/use-large-system-text' -import type { MobileQueuedMessageCard } from '../../mobile-structured-queued-message-cards' +import type { MobileQueuedMessageCard } from './mobile-structured-queued-message-cards' import type { MobileQueuedHeadLight } from './mobile-queued-head-light' import { createMobileQueuedCardActionStore, @@ -18,10 +18,10 @@ import { } from './mobile-queued-card-actions' import { headSteerableQueuedMessageCard } from '../../../../../src/shared/agent-session/view/structured-agent-session-queued-cards' import type { AgentSessionQueuePause } from '../../../../../src/shared/agent-session/requests/agent-session-queued-message-wire' -import type { MobileQueuedMessageEdit } from '../../use-mobile-structured-queued-message-controls' -import type { MobileQueuedMessageInlineEditor } from '../../mobile-queued-message-edit-draft' -import { MobileQueuedMessageCardRow } from '../../MobileQueuedMessageCardRow' -import { MobileQueuedMessageScrollList } from '../../MobileQueuedMessageScrollList' +import type { MobileQueuedMessageEdit } from './use-mobile-structured-queued-message-controls' +import type { MobileQueuedMessageInlineEditor } from './mobile-queued-message-edit-draft' +import { MobileQueuedMessageCardRow } from './MobileQueuedMessageCardRow' +import { MobileQueuedMessageScrollList } from './MobileQueuedMessageScrollList' import { queuedMessageStyles as styles } from './mobile-native-chat-queued-message-styles' import { useMobileNativeChatLowerRegion } from '../mobile-native-chat-lower-region-context' diff --git a/mobile/src/session/native-chat/input/MobileNativeChatSessionOptionPickers.test.ts b/mobile/src/session/native-chat/input/MobileNativeChatSessionOptionPickers.test.ts index 676636c583d..dee922e54dd 100644 --- a/mobile/src/session/native-chat/input/MobileNativeChatSessionOptionPickers.test.ts +++ b/mobile/src/session/native-chat/input/MobileNativeChatSessionOptionPickers.test.ts @@ -1,15 +1,3 @@ -import type { AgentSessionOptionsResult } from '../../../../../src/shared/agent-session/options/agent-session-options-result' -import { useMobileNativeChatSessionOptionController } from './use-mobile-native-chat-session-option-controller' -import { - OPTIONS, - BASE, - deferred, - accepted, - optionsClient, - recordingMutate, - mountOptions, - settle -} from '../../use-mobile-structured-agent-options.test-fixture' import { createElement, useState, type ReactNode } from 'react' import { act, type ReactTestRenderer } from 'react-test-renderer' import { createWithQueryClient } from '../../../test-support/query-client-test-renderer' @@ -160,6 +148,31 @@ describe('MobileNativeChatSessionOptionPickers', () => { renderer = null }) + it('toggles a Fast-only Codex speed on the same Fast mode switch as Claude', async () => { + const speed: SessionOptionDescriptor = { + id: 'serviceTier', + label: 'Speed', + kind: { + type: 'select', + currentValue: 'default', + choices: [ + { value: 'default', label: 'Standard' }, + { value: 'priority', label: 'Fast' } + ] + }, + valueSource: 'reported', + transport: 'catalog', + settable: true + } + mount([MODEL_DESCRIPTOR, speed], false, 'model') + const toggle = findAllByHostType(renderer!.root, 'Switch').find( + (node) => node.props.accessibilityLabel === 'Fast mode' + ) + expect(toggle?.props.value).toBe(false) + await act(async () => toggle!.props.onValueChange(true)) + expect(setOption).toHaveBeenCalledWith('serviceTier', 'priority') + }) + it('consumes a refused page without replay, then permits a fresh open and permission pick', async () => { const placeholder: SessionOptionDescriptor = { ...MODEL_DESCRIPTOR, @@ -180,124 +193,6 @@ describe('MobileNativeChatSessionOptionPickers', () => { await act(async () => rowByText('Full access').props.onPress()) expect(setOption).toHaveBeenCalledExactlyOnceWith('permissionMode', 'full-access') }) - - it('picks the shown Codex default during a reply and captures it only for the next message', async () => { - const pending = deferred() - let reads = 0 - const rpc = optionsClient(() => - ++reads === 1 - ? Promise.resolve({ - ...OPTIONS, - listedModelIds: OPTIONS.models.map((row) => row.id), - current: { model: 'gpt-fast', acceptedInputSources: { model: 'saved' }, defaulted: [] } - }) - : pending.promise - ) - const { calls, mutate } = recordingMutate(async () => - accepted({ key: 'effort', value: 'low', options: { effort: 'low' } }, true) - ) - const view = await mountOptions({ ...BASE, client: rpc.client, mutate, sendSelection: true }) - const snapshot = () => [...view.current().optionSnapshot] - try { - const update = mount(snapshot(), true) - const running = view.current().sendSelection() - expect(running).toEqual({ selection: { model: 'gpt-fast' } }) - await act(async () => pill('Model').props.onPress()) - setOption.mockImplementation(view.current().setStructuredOption) - await act(async () => pill('Low').props.onPress()) - await settle() - expect(calls.map((call) => call.fields)).toEqual([{ key: 'effort', value: 'low' }]) - expect(view.current().sendSelection()).toEqual({ - selection: { model: 'gpt-fast', effort: 'low' } - }) - expect(running).toEqual({ selection: { model: 'gpt-fast' } }) - update(true, snapshot()) - await act(async () => pill('Low').props.onPress()) - expect(setOption).toHaveBeenCalledTimes(1) - } finally { - await view.unmount() - } - }) - - it('renders actual settled permission/reset picks without busy state and locks ordinary pending model work', async () => { - const idle = deferred() - let reads = 0 - const rpc = optionsClient(() => - ++reads === 1 - ? Promise.resolve({ ...OPTIONS, current: { ...OPTIONS.current, permissionMode: 'ask' } }) - : idle.promise - ) - const replies = Array.from({ length: 3 }, () => deferred>()) - const { calls, mutate } = recordingMutate((index) => replies[index].promise) - const view = await mountOptions({ ...BASE, client: rpc.client, mutate, permissionOwn: true }) - function ActualPickers() { - const options = view.current() - const { nativeChatSessionOptions } = useMobileNativeChatSessionOptionController({ - client: rpc.client, - activeChatStructured: true, - activeSessionTabId: BASE.sessionId, - agent: 'codex', - dispatchCommand: async () => 'accepted', - hostId: 'phone-picker', - isTabChatView: () => true, - isWorking: true, - reportedModel: null, - structured: { - snapshot: options.optionSnapshot, - pendingId: options.pendingOptionId, - setOption: options.setStructuredOption, - invokeAction: options.invokeStructuredOption - }, - toggleTabChatView: () => {}, - worktreeId: 'workspace-1' - }) - return createElement(MobileNativeChatSessionOptionPickers, { - ...nativeChatSessionOptions!, - presentation: { page: 'model', refocus: false }, - onDrawerOpen: () => {}, - onNavigate: () => {} - }) - } - try { - await act(async () => { - renderer = createWithQueryClient(createElement(ActualPickers)) - }) - for (const [index, value] of ['full-access', 'own'].entries()) { - let pick!: Promise - act(() => { - pick = view.current().setStructuredOption('permissionMode', value) - }) - expect(calls[index]?.fields).toEqual({ key: 'permissionMode', value }) - expect(view.current().pendingOptionId).toBeNull() - await act(async () => renderer!.update(createElement(ActualPickers))) - expect(renderer!.root.findAllByProps({ children: 'Applying…' })).toHaveLength(0) - expect(rowByText('GPT Fast').props.accessibilityState?.disabled).toBe(false) - await act(async () => - replies[index].resolve( - accepted({ key: 'permissionMode', value, options: { permissionMode: value } }, true) - ) - ) - await expect(pick).resolves.toBe(true) - expect(view.current().pendingOptionId).toBeNull() - await act(async () => renderer!.update(createElement(ActualPickers))) - expect(renderer!.root.findAllByProps({ children: 'Applying…' })).toHaveLength(0) - expect(rowByText('GPT Fast').props.accessibilityState?.disabled).toBe(false) - } - act(() => { - void view.current().setStructuredOption('model', 'gpt-fast') - }) - await act(async () => renderer!.update(createElement(ActualPickers))) - expect(rowByText('GPT Live').props.accessibilityState?.disabled).toBe(true) - expect(renderer!.root.findAllByProps({ children: 'Applying…' })).toHaveLength(1) - expect(calls.map((call) => call.fields)).toEqual([ - { key: 'permissionMode', value: 'full-access' }, - { key: 'permissionMode', value: 'own' }, - { key: 'model', value: 'gpt-fast' } - ]) - } finally { - await view.unmount() - } - }) }) const PERMISSION_CHOICES: SessionOptionSelectChoice[] = [ diff --git a/mobile/src/session/native-chat/input/MobileNativeChatSessionOptionPickers.tsx b/mobile/src/session/native-chat/input/MobileNativeChatSessionOptionPickers.tsx index 64360176bd6..973ee4010c1 100644 --- a/mobile/src/session/native-chat/input/MobileNativeChatSessionOptionPickers.tsx +++ b/mobile/src/session/native-chat/input/MobileNativeChatSessionOptionPickers.tsx @@ -36,7 +36,8 @@ import { descriptorRowElements, ModelPill, SessionOptionCaption, - SessionOptionSummaryRow + SessionOptionSummaryRow, + showsSessionOptionAsSwitch } from './MobileNativeChatSessionOptionRows' import { SessionOptionSegments, @@ -383,7 +384,7 @@ function OptionRows({ {descriptors.flatMap((descriptor) => { const isPermission = descriptor === permission const disabled = locked(descriptor) || !descriptor.settable - if (descriptor.kind.type === 'boolean' && !descriptor.action) { + if (showsSessionOptionAsSwitch(descriptor)) { return descriptorRowElements( { descriptor, diff --git a/mobile/src/session/native-chat/input/MobileNativeChatSessionOptionRows.tsx b/mobile/src/session/native-chat/input/MobileNativeChatSessionOptionRows.tsx index e8dfb017a3d..63c69893624 100644 --- a/mobile/src/session/native-chat/input/MobileNativeChatSessionOptionRows.tsx +++ b/mobile/src/session/native-chat/input/MobileNativeChatSessionOptionRows.tsx @@ -17,6 +17,10 @@ import { nativeChatSessionOptionActionLabel, nativeChatSessionOptionLabel } from '../../../../../src/shared/native-chat/input/native-chat-session-option-labels' +import { + loneFastTier, + speedButtonTiers +} from '../../../../../src/shared/native-chat/input/native-chat-session-speed-tiers' import { sayMobileNativeChatSessionOption as say } from './native-chat-session-option-copy' import { MobileSwitch } from '../../../components/MobileSwitch' @@ -131,6 +135,20 @@ type DescriptorRowsProps = { moreChoices?: { shown: boolean; onToggle: () => void } } +/** A Fast-only speed, which toggles on one row like Claude's Fast mode. */ +function fastSpeedSwitch(descriptor: SessionOptionDescriptor) { + const speed = speedButtonTiers(descriptor) + const fast = speed ? loneFastTier(speed.tiers) : undefined + return speed && fast ? { standard: speed.standard, fast } : null +} + +export function showsSessionOptionAsSwitch(descriptor: SessionOptionDescriptor): boolean { + return ( + !descriptor.action && + (descriptor.kind.type === 'boolean' || fastSpeedSwitch(descriptor) !== null) + ) +} + /** One descriptor's rows as an array, so a ListGroup can draw the separators between them. */ export function descriptorRowElements( { @@ -156,8 +174,10 @@ export function descriptorRowElements( ] } // An unknown baseline still renders a switch; the source marker prevents implying the value was confirmed. - if (descriptor.kind.type === 'boolean') { - const label = nativeChatSessionOptionLabel(descriptor, say) + const fastSpeed = fastSpeedSwitch(descriptor) + if (descriptor.kind.type === 'boolean' || fastSpeed) { + const { kind } = descriptor + const label = fastSpeed ? say('fastMode') : nativeChatSessionOptionLabel(descriptor, say) const marker = sessionOptionValueMarker(descriptor) return [ onSetOption(next)} + value={ + kind.type === 'boolean' + ? kind.currentValue + : kind.currentValue === fastSpeed?.fast.value + } + onValueChange={(next) => + onSetOption( + fastSpeed ? (next ? fastSpeed.fast.value : fastSpeed.standard.value) : next + ) + } disabled={locked} /> } diff --git a/mobile/src/session/native-chat/input/MobileNativeChatThreadGoalStrip.tsx b/mobile/src/session/native-chat/input/MobileNativeChatThreadGoalStrip.tsx index 9d73bb6da3f..d1aa5793cd7 100644 --- a/mobile/src/session/native-chat/input/MobileNativeChatThreadGoalStrip.tsx +++ b/mobile/src/session/native-chat/input/MobileNativeChatThreadGoalStrip.tsx @@ -17,7 +17,7 @@ import { themedStyleSheet } from '../../../theme/themed-styles' import { useMobileColorScheme } from '../../../theme/use-mobile-color-scheme' import { COMPOSER_TUCK } from '../composer/mobile-native-chat-composer-styles' import { queuedMessageStyles } from './mobile-native-chat-queued-message-styles' -import type { MobileStructuredThreadGoal } from '../../use-mobile-structured-thread-goal' +import type { MobileStructuredThreadGoal } from './use-mobile-structured-thread-goal' type Translate = ReturnType diff --git a/mobile/src/session/MobileQueuedCardText.tsx b/mobile/src/session/native-chat/input/MobileQueuedCardText.tsx similarity index 85% rename from mobile/src/session/MobileQueuedCardText.tsx rename to mobile/src/session/native-chat/input/MobileQueuedCardText.tsx index c0af69cf12f..d97d8e1beeb 100644 --- a/mobile/src/session/MobileQueuedCardText.tsx +++ b/mobile/src/session/native-chat/input/MobileQueuedCardText.tsx @@ -1,10 +1,10 @@ import { useState } from 'react' import { Pressable, Text, View } from 'react-native' -import { colors, typography, pressedStyle } from '../theme/mobile-theme' -import { themedStyleSheet } from '../theme/themed-styles' -import { useMobileColorScheme } from '../theme/use-mobile-color-scheme' -import { queuedMessageStyles } from './native-chat/input/mobile-native-chat-queued-message-styles' -import { useMobileTranslation } from '../i18n/use-mobile-translation' +import { colors, typography, pressedStyle } from '../../../theme/mobile-theme' +import { themedStyleSheet } from '../../../theme/themed-styles' +import { useMobileColorScheme } from '../../../theme/use-mobile-color-scheme' +import { queuedMessageStyles } from './mobile-native-chat-queued-message-styles' +import { useMobileTranslation } from '../../../i18n/use-mobile-translation' // Expand clipped queued text before Steer/Delete; use the queue’s capped scroller rather than nesting another scroll box. export function MobileQueuedCardText({ diff --git a/mobile/src/session/MobileQueuedMessageCardRow.tsx b/mobile/src/session/native-chat/input/MobileQueuedMessageCardRow.tsx similarity index 91% rename from mobile/src/session/MobileQueuedMessageCardRow.tsx rename to mobile/src/session/native-chat/input/MobileQueuedMessageCardRow.tsx index 66460db018e..d7bb5553a1b 100644 --- a/mobile/src/session/MobileQueuedMessageCardRow.tsx +++ b/mobile/src/session/native-chat/input/MobileQueuedMessageCardRow.tsx @@ -10,19 +10,19 @@ import { Send, Trash2 } from 'lucide-react-native' -import { colors, pressedStyle } from '../theme/mobile-theme' -import { queuedMessageCardSteers } from '../../../src/shared/agent-session/view/structured-agent-session-queued-cards' -import { useMobileColorScheme } from '../theme/use-mobile-color-scheme' +import { colors, pressedStyle } from '../../../theme/mobile-theme' +import { queuedMessageCardSteers } from '../../../../../src/shared/agent-session/view/structured-agent-session-queued-cards' +import { useMobileColorScheme } from '../../../theme/use-mobile-color-scheme' import type { MobileQueuedMessageCard } from './mobile-structured-queued-message-cards' -import type { MobileQueuedMessageInlineEditor } from './use-mobile-structured-queued-edit' +import type { MobileQueuedMessageInlineEditor } from './mobile-queued-message-edit-draft' import { MobileQueuedMessageComposer } from './MobileQueuedMessageComposer' import { MobileQueuedCardText } from './MobileQueuedCardText' -import type { MobileQueuedHeadLight } from './native-chat/input/mobile-queued-head-light' +import type { MobileQueuedHeadLight } from './mobile-queued-head-light' const subscribeNever = () => () => undefined -import { MobileAgentMessageSenders } from './native-chat/transcript/MobileAgentMessageSenders' -import { queuedMessageStyles as styles } from './native-chat/input/mobile-native-chat-queued-message-styles' -import { useMobileTranslation } from '../i18n/use-mobile-translation' +import { MobileAgentMessageSenders } from '../transcript/MobileAgentMessageSenders' +import { queuedMessageStyles as styles } from './mobile-native-chat-queued-message-styles' +import { useMobileTranslation } from '../../../i18n/use-mobile-translation' type QueuedMessageCardRowProps = { dragHandle?: ReactNode diff --git a/mobile/src/session/MobileQueuedMessageComposer.tsx b/mobile/src/session/native-chat/input/MobileQueuedMessageComposer.tsx similarity index 82% rename from mobile/src/session/MobileQueuedMessageComposer.tsx rename to mobile/src/session/native-chat/input/MobileQueuedMessageComposer.tsx index 6ec1670fbff..94bec868eb4 100644 --- a/mobile/src/session/MobileQueuedMessageComposer.tsx +++ b/mobile/src/session/native-chat/input/MobileQueuedMessageComposer.tsx @@ -1,21 +1,21 @@ import { useContext, useEffect, useMemo, useRef } from 'react' import { MobileQueuedMessageComposerContext } from './mobile-queued-message-composer-context' import { Text, type TextInput, View } from 'react-native' -import { MobileNativeChatComposer } from './native-chat/composer/MobileNativeChatComposer' -import type { MobileQueuedMessageInlineEditor } from './use-mobile-structured-queued-edit' -import { useMobileNativeChatFileAttachments } from './native-chat/composer/use-mobile-native-chat-file-attachments' -import { useMobileNativeChatImageUpload } from './native-chat/composer/use-mobile-native-chat-image-upload' +import { MobileNativeChatComposer } from '../composer/MobileNativeChatComposer' +import type { MobileQueuedMessageInlineEditor } from './mobile-queued-message-edit-draft' +import { useMobileNativeChatFileAttachments } from '../composer/use-mobile-native-chat-file-attachments' +import { useMobileNativeChatImageUpload } from '../composer/use-mobile-native-chat-image-upload' import { updateMobileNativeChatDraftInputs, useMobileNativeChatDraftInputs -} from './native-chat/composer/mobile-native-chat-draft-inputs' -import { prepareQueuedMessageEditText } from '../../../src/shared/queued-message-edit-command' -import type { AgentMessageSource } from '../../../src/shared/agent-session/agent-session-message-source' -import { MobileAgentMessageSenders } from './native-chat/transcript/MobileAgentMessageSenders' -import { queuedMessageStyles as styles } from './native-chat/input/mobile-native-chat-queued-message-styles' -import { useMobileColorScheme } from '../theme/use-mobile-color-scheme' -import { createUuidV4 } from '../../../src/shared/uuid-v4' -import { useMobileTranslation } from '../i18n/use-mobile-translation' +} from '../composer/mobile-native-chat-draft-inputs' +import { prepareQueuedMessageEditText } from '../../../../../src/shared/queued-message-edit-command' +import type { AgentMessageSource } from '../../../../../src/shared/agent-session/agent-session-message-source' +import { MobileAgentMessageSenders } from '../transcript/MobileAgentMessageSenders' +import { queuedMessageStyles as styles } from './mobile-native-chat-queued-message-styles' +import { useMobileColorScheme } from '../../../theme/use-mobile-color-scheme' +import { createNonSecureContextUuid as createUuidV4 } from '../../../../../src/shared/non-secure-context-uuid' +import { useMobileTranslation } from '../../../i18n/use-mobile-translation' export function MobileQueuedMessageComposer({ editor, diff --git a/mobile/src/session/MobileQueuedMessageScrollList.tsx b/mobile/src/session/native-chat/input/MobileQueuedMessageScrollList.tsx similarity index 95% rename from mobile/src/session/MobileQueuedMessageScrollList.tsx rename to mobile/src/session/native-chat/input/MobileQueuedMessageScrollList.tsx index fac8c9e1e8f..c7a05ffed9d 100644 --- a/mobile/src/session/MobileQueuedMessageScrollList.tsx +++ b/mobile/src/session/native-chat/input/MobileQueuedMessageScrollList.tsx @@ -6,9 +6,9 @@ import Animated, { type AnimatedRef, type SharedValue } from 'react-native-reanimated' -import { spacing } from '../theme/mobile-theme' -import { MobileEdgeFade } from '../components/MobileEdgeFade' -import { useMobileNativeChatLowerRegion } from './native-chat/mobile-native-chat-lower-region-context' +import { spacing } from '../../../theme/mobile-theme' +import { MobileEdgeFade } from '../../../components/MobileEdgeFade' +import { useMobileNativeChatLowerRegion } from '../mobile-native-chat-lower-region-context' /** Desktop's `max-h-40`: three one-line cards and part of a fourth, whose cut-off edge is the * sign that the list scrolls. */ diff --git a/mobile/src/session/mobile-background-task-copy.ts b/mobile/src/session/native-chat/input/mobile-background-task-copy.ts similarity index 98% rename from mobile/src/session/mobile-background-task-copy.ts rename to mobile/src/session/native-chat/input/mobile-background-task-copy.ts index e204e2e8005..52cd8474413 100644 --- a/mobile/src/session/mobile-background-task-copy.ts +++ b/mobile/src/session/native-chat/input/mobile-background-task-copy.ts @@ -1,8 +1,8 @@ import type { BackgroundTaskCopyId, BackgroundTaskSay -} from '../../../src/shared/background-task-copy' -import { translate } from '../i18n/mobile-i18n' +} from '../../../../../src/shared/background-task-copy' +import { translate } from '../../../i18n/mobile-i18n' export const sayMobileBackgroundTask: BackgroundTaskSay = (id, values) => { const count = values?.count diff --git a/mobile/src/session/mobile-host-model-catalog-query.ts b/mobile/src/session/native-chat/input/mobile-host-model-catalog-query.ts similarity index 82% rename from mobile/src/session/mobile-host-model-catalog-query.ts rename to mobile/src/session/native-chat/input/mobile-host-model-catalog-query.ts index 04e3eb307f4..eb6eb1ff7d1 100644 --- a/mobile/src/session/mobile-host-model-catalog-query.ts +++ b/mobile/src/session/native-chat/input/mobile-host-model-catalog-query.ts @@ -1,18 +1,18 @@ import { useMemo } from 'react' import { useQueryClient } from '@tanstack/react-query' -import type { AgentSessionModelCatalogResult } from '../../../src/shared/agent-session/agent-session-wire' +import type { AgentSessionModelCatalogResult } from '../../../../../src/shared/agent-session/agent-session-wire' import { hostReadsSavedModelCatalogsOnly, selectHostModelCatalogSnapshot, withHostModelCatalogAnswer, type HostModelCatalogSnapshot -} from '../../../src/shared/agent-session/options/host-model-catalog-snapshot-rules' -import { defineHostQuery, useHostQuery } from '../query/host-query' -import { hostQueryKey } from '../query/host-query-key' -import { useWorkspaceExecutionHost } from '../navigation/workspace-execution-host' -import type { RpcClient } from '../transport/rpc/rpc-client-contract' -import { readRuntimeStatusProbe } from '../transport/connection/runtime-status-probe' -import { callAgentSession } from './mobile-structured-agent-session-rpc' +} from '../../../../../src/shared/agent-session/options/host-model-catalog-snapshot-rules' +import { defineHostQuery, useHostQuery } from '../../../query/host-query' +import { hostQueryKey } from '../../../query/host-query-key' +import { useWorkspaceExecutionHost } from '../../../navigation/workspace-execution-host' +import type { RpcClient } from '../../../transport/rpc/rpc-client-contract' +import { readRuntimeStatusProbe } from '../../../transport/connection/runtime-status-probe' +import { callAgentSession } from '../agent-session/mobile-structured-agent-session-rpc' import type { HostModelCatalogCache } from './use-mobile-host-model-catalog-upgrade' // The host's account-level lists per agent, which a chat's first frame shows before its own read answers. diff --git a/mobile/src/session/native-chat/input/mobile-native-chat-permission-send.ts b/mobile/src/session/native-chat/input/mobile-native-chat-permission-send.ts index 8a63b5555c7..f40820cae03 100644 --- a/mobile/src/session/native-chat/input/mobile-native-chat-permission-send.ts +++ b/mobile/src/session/native-chat/input/mobile-native-chat-permission-send.ts @@ -3,11 +3,11 @@ import type { RpcClient } from '../../../transport/rpc/rpc-client-contract' import { sendMobileNativeChatMessageWithOutcome, type MobileNativeChatSendOutcome -} from '../mobile-native-chat-send' +} from '../composer/mobile-native-chat-send' import { acquireMobileNativeChatTerminalWrite, releaseMobileNativeChatTerminalWrite -} from '../mobile-native-chat-terminal-write-lock' +} from '../composer/mobile-native-chat-terminal-write-lock' export function sendMobileNativeChatPermissionResponse(args: { client: RpcClient diff --git a/mobile/src/session/mobile-prompt-controller.test.ts b/mobile/src/session/native-chat/input/mobile-prompt-controller.test.ts similarity index 90% rename from mobile/src/session/mobile-prompt-controller.test.ts rename to mobile/src/session/native-chat/input/mobile-prompt-controller.test.ts index 8b82f60e47a..c863cdd5e25 100644 --- a/mobile/src/session/mobile-prompt-controller.test.ts +++ b/mobile/src/session/native-chat/input/mobile-prompt-controller.test.ts @@ -1,11 +1,11 @@ import { act } from 'react-test-renderer' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import './native-chat/input/mobile-native-chat-prompt-dismissals' -import './mobile-structured-send-delivery' -import './structured-agent-send-result.test-fixture' -import type { RpcResponse } from '../transport/rpc/rpc-wire-types' -import type { RpcClient } from '../transport/rpc/rpc-client-contract' -import type { NativeChatMessage } from '../../../src/shared/native-chat/native-chat-types' +import './mobile-native-chat-prompt-dismissals' +import '../composer/mobile-structured-send-delivery' +import '../../structured-agent-send-result.test-fixture' +import type { RpcResponse } from '../../../transport/rpc/rpc-wire-types' +import type { RpcClient } from '../../../transport/rpc/rpc-client-contract' +import type { NativeChatMessage } from '../../../../../src/shared/native-chat/native-chat-types' import { session, @@ -20,7 +20,7 @@ import { permissionAction, getController, askAnswer -} from './__mocks__/mobile-prompt-controller' +} from '../../__mocks__/mobile-prompt-controller' const client: RpcClient = { sendRequest: vi.fn(), diff --git a/mobile/src/session/mobile-queued-message-composer-context.ts b/mobile/src/session/native-chat/input/mobile-queued-message-composer-context.ts similarity index 80% rename from mobile/src/session/mobile-queued-message-composer-context.ts rename to mobile/src/session/native-chat/input/mobile-queued-message-composer-context.ts index c4e6382b5d6..9bfeea6fd03 100644 --- a/mobile/src/session/mobile-queued-message-composer-context.ts +++ b/mobile/src/session/native-chat/input/mobile-queued-message-composer-context.ts @@ -1,6 +1,6 @@ -import type { NativeChatSkillDiscoverySnapshot } from '../../../src/shared/native-chat/input/native-chat-picker-items' +import type { NativeChatSkillDiscoverySnapshot } from '../../../../../src/shared/native-chat/input/native-chat-picker-items' import { createContext } from 'react' -import type { MobileNativeChatStructuredComposer } from './native-chat/composer/MobileNativeChatComposer' +import type { MobileNativeChatStructuredComposer } from '../composer/mobile-native-chat-structured-composer' export const MobileQueuedMessageComposerContext = createContext<{ agent: string | null diff --git a/mobile/src/session/mobile-queued-message-edit-draft.ts b/mobile/src/session/native-chat/input/mobile-queued-message-edit-draft.ts similarity index 86% rename from mobile/src/session/mobile-queued-message-edit-draft.ts rename to mobile/src/session/native-chat/input/mobile-queued-message-edit-draft.ts index dc794e4dba1..81bf996551b 100644 --- a/mobile/src/session/mobile-queued-message-edit-draft.ts +++ b/mobile/src/session/native-chat/input/mobile-queued-message-edit-draft.ts @@ -1,5 +1,8 @@ -import type { QueuedEditLeaseLoss } from '../../../src/shared/queued-message-edit-lease' -import type { MobileStructuredAgentMutate } from './use-mobile-structured-agent-mutation' +import type { + QueuedEditLease, + QueuedEditLeaseLoss +} from '../../../../../src/shared/queued-message-edit-lease' +import type { MobileStructuredAgentMutate } from '../agent-session/use-mobile-structured-agent-mutation' import type { MobileQueuedMessageCard } from './mobile-structured-queued-message-cards' import { mobileQueuedEditValueKey, @@ -11,23 +14,22 @@ import { closeMobileNativeChatEditInputs, readMobileNativeChatDraftInputs, updateMobileNativeChatDraftInputs -} from './native-chat/composer/mobile-native-chat-draft-inputs' -import type { AgentSessionQueuedMessage } from '../../../src/shared/agent-session/requests/agent-session-queued-message-wire' -import type { AgentJournalSubmission } from '../../../src/shared/agent-session/journal/agent-session-journal-types' -import type { RpcClient } from '../transport/rpc/rpc-client-contract' -import type { MobileQueuedEditLease } from './mobile-queued-message-edit-lease' -import { pickedSkillsInText } from '../../../src/shared/agent-session/requests/structured-agent-session-send-mutation' +} from '../composer/mobile-native-chat-draft-inputs' +import type { AgentSessionQueuedMessage } from '../../../../../src/shared/agent-session/requests/agent-session-queued-message-wire' +import type { AgentJournalSubmission } from '../../../../../src/shared/agent-session/journal/agent-session-journal-types' +import type { RpcClient } from '../../../transport/rpc/rpc-client-contract' +import { pickedSkillsInText } from '../../../../../src/shared/agent-session/requests/structured-agent-session-send-mutation' import { queuedEditKeptImages, queuedEditTextForKeptImages, type QueuedMessageImageBlock -} from '../../../src/shared/queued-message-edit' -import { appendReturnedDraftText } from '../../../src/shared/returned-draft-text' +} from '../../../../../src/shared/queued-message-edit' +import { appendReturnedDraftText } from '../../../../../src/shared/returned-draft-text' import { setMobileNativeChatDraftText, type MobileComposerWriter -} from './native-chat/composer/mobile-native-chat-draft-store' -import { nativeChatTextWithFileReferences } from './native-chat/composer/mobile-native-chat-file-attachment' +} from '../composer/mobile-native-chat-draft-store' +import { nativeChatTextWithFileReferences } from '../composer/mobile-native-chat-file-attachment' export type MobileQueuedMessageInlineEditor = { messageId: string @@ -84,7 +86,7 @@ export type MobileQueuedEditDraft = { attempt?: MobileQueuedEditAttempt closed: boolean pendingClose: boolean - lease: MobileQueuedEditLease + lease: QueuedEditLease } export function closeMobileQueuedEditDraft( diff --git a/mobile/src/session/mobile-queued-message-edit-lease.ts b/mobile/src/session/native-chat/input/mobile-queued-message-edit-lease.ts similarity index 66% rename from mobile/src/session/mobile-queued-message-edit-lease.ts rename to mobile/src/session/native-chat/input/mobile-queued-message-edit-lease.ts index 424f19e43a4..616a64e4c74 100644 --- a/mobile/src/session/mobile-queued-message-edit-lease.ts +++ b/mobile/src/session/native-chat/input/mobile-queued-message-edit-lease.ts @@ -1,12 +1,10 @@ import { startQueuedEditLease, type QueuedEditLeaseLoss -} from '../../../src/shared/queued-message-edit-lease' -import type { RpcClient } from '../transport/rpc/rpc-client-contract' -import { callAgentSession } from './mobile-structured-agent-session-rpc' -import { structuredSessionOperationId } from './structured-session-operation-id' - -export type { QueuedEditLease as MobileQueuedEditLease } from '../../../src/shared/queued-message-edit-lease' +} from '../../../../../src/shared/queued-message-edit-lease' +import type { RpcClient } from '../../../transport/rpc/rpc-client-contract' +import { callAgentSession } from '../agent-session/mobile-structured-agent-session-rpc' +import { structuredSessionOperationId } from '../agent-session/structured-session-operation-id' export function startMobileQueuedEditLease(args: { getClient: () => RpcClient | null diff --git a/mobile/src/session/mobile-queued-message-edit-open.ts b/mobile/src/session/native-chat/input/mobile-queued-message-edit-open.ts similarity index 83% rename from mobile/src/session/mobile-queued-message-edit-open.ts rename to mobile/src/session/native-chat/input/mobile-queued-message-edit-open.ts index cbb6d597434..5a5d550ad2a 100644 --- a/mobile/src/session/mobile-queued-message-edit-open.ts +++ b/mobile/src/session/native-chat/input/mobile-queued-message-edit-open.ts @@ -1,16 +1,16 @@ -import type { QueuedEditLeaseLoss } from '../../../src/shared/queued-message-edit-lease' +import type { QueuedEditLeaseLoss } from '../../../../../src/shared/queued-message-edit-lease' import { queuedMessageEditableText, queuedEditKeptImages -} from '../../../src/shared/queued-message-edit' -import { agentSessionSendBodyFingerprint } from '../../../src/shared/agent-session/requests/structured-agent-session-send-mutation' -import { createUuidV4 } from '../../../src/shared/uuid-v4' +} from '../../../../../src/shared/queued-message-edit' +import { agentSessionSendBodyFingerprint } from '../../../../../src/shared/agent-session/requests/structured-agent-session-send-mutation' +import { createNonSecureContextUuid as createUuidV4 } from '../../../../../src/shared/non-secure-context-uuid' import { startMobileQueuedEditLease } from './mobile-queued-message-edit-lease' import { mobileQueuedEditValueKey } from './mobile-queued-message-edit-value' import { mobileNativeChatDraftDestination, readMobileNativeChatDraftInputs -} from './native-chat/composer/mobile-native-chat-draft-inputs' +} from '../composer/mobile-native-chat-draft-inputs' import { seedMobileQueuedEditInputs, type MobileQueuedEditDraft as Edit, diff --git a/mobile/src/session/mobile-queued-message-edit-outcome.ts b/mobile/src/session/native-chat/input/mobile-queued-message-edit-outcome.ts similarity index 89% rename from mobile/src/session/mobile-queued-message-edit-outcome.ts rename to mobile/src/session/native-chat/input/mobile-queued-message-edit-outcome.ts index ef37efd9d30..13d8ab65330 100644 --- a/mobile/src/session/mobile-queued-message-edit-outcome.ts +++ b/mobile/src/session/native-chat/input/mobile-queued-message-edit-outcome.ts @@ -1,8 +1,8 @@ -import type { AgentSessionQueuedMessageUpdateResult } from '../../../src/shared/agent-session/requests/agent-session-queued-message-wire' -import { agentSessionSendBodyFingerprint } from '../../../src/shared/agent-session/requests/structured-agent-session-send-mutation' +import type { AgentSessionQueuedMessageUpdateResult } from '../../../../../src/shared/agent-session/requests/agent-session-queued-message-wire' +import { agentSessionSendBodyFingerprint } from '../../../../../src/shared/agent-session/requests/structured-agent-session-send-mutation' import type { MobileQueuedEditDraft } from './mobile-queued-message-edit-draft' -import type { StructuredAgentSessionMutationResult } from './mobile-structured-agent-session-rpc' -import { readMobileNativeChatDraftInputs } from './native-chat/composer/mobile-native-chat-draft-inputs' +import type { StructuredAgentSessionMutationResult } from '../agent-session/mobile-structured-agent-session-rpc' +import { readMobileNativeChatDraftInputs } from '../composer/mobile-native-chat-draft-inputs' import { mobileQueuedEditValueKey } from './mobile-queued-message-edit-value' type Outcome = 'close' | 'rebase' | 'gone' | 'changed' | 'refused' | 'stay' diff --git a/mobile/src/session/mobile-queued-message-edit-value.ts b/mobile/src/session/native-chat/input/mobile-queued-message-edit-value.ts similarity index 78% rename from mobile/src/session/mobile-queued-message-edit-value.ts rename to mobile/src/session/native-chat/input/mobile-queued-message-edit-value.ts index 173aacd67b2..ebf12bbbf00 100644 --- a/mobile/src/session/mobile-queued-message-edit-value.ts +++ b/mobile/src/session/native-chat/input/mobile-queued-message-edit-value.ts @@ -1,5 +1,5 @@ -import type { MobileNativeChatDraftInputs } from './native-chat/composer/mobile-native-chat-draft-inputs' -import { pickedSkillsInText } from '../../../src/shared/agent-session/requests/structured-agent-session-send-mutation' +import type { MobileNativeChatDraftInputs } from '../composer/mobile-native-chat-draft-inputs' +import { pickedSkillsInText } from '../../../../../src/shared/agent-session/requests/structured-agent-session-send-mutation' type Image = MobileNativeChatDraftInputs['images'][number] export function sameMobileQueuedEditImage(left: Image, right: Image): boolean { diff --git a/mobile/src/session/mobile-structured-actionable-prompt.ts b/mobile/src/session/native-chat/input/mobile-structured-actionable-prompt.ts similarity index 78% rename from mobile/src/session/mobile-structured-actionable-prompt.ts rename to mobile/src/session/native-chat/input/mobile-structured-actionable-prompt.ts index 71b34891229..1a79e5a192d 100644 --- a/mobile/src/session/mobile-structured-actionable-prompt.ts +++ b/mobile/src/session/native-chat/input/mobile-structured-actionable-prompt.ts @@ -1,5 +1,5 @@ -import { pendingStructuredSessionPrompts } from '../../../src/shared/agent-session/view/structured-agent-session-message-projection' -import type { StructuredAgentSessionState } from '../../../src/shared/agent-session/structured-agent-session-reducer' +import { pendingStructuredSessionPrompts } from '../../../../../src/shared/agent-session/view/structured-agent-session-message-projection' +import type { StructuredAgentSessionState } from '../../../../../src/shared/agent-session/structured-agent-session-reducer' import type { StructuredApprovalItem, StructuredQuestionItem diff --git a/mobile/src/session/mobile-structured-agent-prompts-permission.test.ts b/mobile/src/session/native-chat/input/mobile-structured-agent-prompts-permission.test.ts similarity index 100% rename from mobile/src/session/mobile-structured-agent-prompts-permission.test.ts rename to mobile/src/session/native-chat/input/mobile-structured-agent-prompts-permission.test.ts diff --git a/mobile/src/session/mobile-structured-agent-prompts.ts b/mobile/src/session/native-chat/input/mobile-structured-agent-prompts.ts similarity index 94% rename from mobile/src/session/mobile-structured-agent-prompts.ts rename to mobile/src/session/native-chat/input/mobile-structured-agent-prompts.ts index 93a3bb5d7ed..ace186b66e5 100644 --- a/mobile/src/session/mobile-structured-agent-prompts.ts +++ b/mobile/src/session/native-chat/input/mobile-structured-agent-prompts.ts @@ -1,11 +1,11 @@ -import type { AgentJournalRenderItem } from '../../../src/shared/agent-session/journal/agent-session-journal-types' +import type { AgentJournalRenderItem } from '../../../../../src/shared/agent-session/journal/agent-session-journal-types' import { agentSessionPromptQuestions, type AgentSessionQuestionAnswer -} from '../../../src/shared/agent-session/agent-session-question-answer' -import { chatApprovalFromJournal } from '../../../src/shared/native-chat/input/native-chat-interactive-prompt' -import type { MobileChatPermission } from './native-chat/input/mobile-native-chat-permission' -import type { MobileChatQuestion } from './native-chat/input/mobile-native-chat-question' +} from '../../../../../src/shared/agent-session/agent-session-question-answer' +import { chatApprovalFromJournal } from '../../../../../src/shared/native-chat/input/native-chat-interactive-prompt' +import type { MobileChatPermission } from './mobile-native-chat-permission' +import type { MobileChatQuestion } from './mobile-native-chat-question' export type StructuredApprovalItem = AgentJournalRenderItem & { body: Extract diff --git a/mobile/src/session/mobile-structured-queued-message-cards.ts b/mobile/src/session/native-chat/input/mobile-structured-queued-message-cards.ts similarity index 78% rename from mobile/src/session/mobile-structured-queued-message-cards.ts rename to mobile/src/session/native-chat/input/mobile-structured-queued-message-cards.ts index 42d009d89bd..3730aa220fe 100644 --- a/mobile/src/session/mobile-structured-queued-message-cards.ts +++ b/mobile/src/session/native-chat/input/mobile-structured-queued-message-cards.ts @@ -1,18 +1,18 @@ -import { stripSentImagePromptMarkers } from '../../../src/shared/native-chat/transcript/native-chat-image-transcript-markers' -import type { AgentSessionFailureFact } from '../../../src/shared/agent-session/failures/agent-session-failure' -import { mobileAgentSessionWriteNoticeText } from './agent-session-write-notice-copy' -import type { AgentJournalSubmission } from '../../../src/shared/agent-session/journal/agent-session-journal-types' +import { stripSentImagePromptMarkers } from '../../../../../src/shared/native-chat/transcript/native-chat-image-transcript-markers' +import type { AgentSessionFailureFact } from '../../../../../src/shared/agent-session/failures/agent-session-failure' +import { mobileAgentSessionWriteNoticeText } from '../agent-session/agent-session-write-notice-copy' +import type { AgentJournalSubmission } from '../../../../../src/shared/agent-session/journal/agent-session-journal-types' import { QUEUED_MESSAGE_PAUSED_SEND_FAILED, type AgentSessionQueuedMessage -} from '../../../src/shared/agent-session/requests/agent-session-queued-message-wire' +} from '../../../../../src/shared/agent-session/requests/agent-session-queued-message-wire' import { projectQueuedMessageCards, queuedMessageCardLine, queuedMessageCardNeedsAttention, queuedMessageReturnedNotice, type QueuedMessageCard -} from '../../../src/shared/agent-session/view/structured-agent-session-queued-cards' +} from '../../../../../src/shared/agent-session/view/structured-agent-session-queued-cards' // The shared projection decides each card's hold; this layer words it for the phone. export type MobileQueuedMessageCard = QueuedMessageCard & { diff --git a/mobile/src/session/use-mobile-background-task-stops.ts b/mobile/src/session/native-chat/input/use-mobile-background-task-stops.ts similarity index 97% rename from mobile/src/session/use-mobile-background-task-stops.ts rename to mobile/src/session/native-chat/input/use-mobile-background-task-stops.ts index 7f70d3c67d3..f9031d89e2b 100644 --- a/mobile/src/session/use-mobile-background-task-stops.ts +++ b/mobile/src/session/native-chat/input/use-mobile-background-task-stops.ts @@ -2,7 +2,7 @@ import { useRef, useState } from 'react' import { structuredSessionConfirmedStopsStillListed, structuredSessionListedTaskRun -} from '../../../src/shared/structured-session-background-tasks-view' +} from '../../../../../src/shared/structured-session-background-tasks-view' import type { MobileStructuredBackgroundTasks } from './use-mobile-structured-background-tasks' export type MobileBackgroundTaskStopping = { taskIds: ReadonlySet; all: boolean } diff --git a/mobile/src/session/use-mobile-bridge-chat-prompt-writes.ts b/mobile/src/session/native-chat/input/use-mobile-bridge-chat-prompt-writes.ts similarity index 74% rename from mobile/src/session/use-mobile-bridge-chat-prompt-writes.ts rename to mobile/src/session/native-chat/input/use-mobile-bridge-chat-prompt-writes.ts index 07739f5ef3e..d2d918cc4f8 100644 --- a/mobile/src/session/use-mobile-bridge-chat-prompt-writes.ts +++ b/mobile/src/session/native-chat/input/use-mobile-bridge-chat-prompt-writes.ts @@ -1,10 +1,10 @@ import type { MutableRefObject } from 'react' -import type { RpcClient } from '../transport/rpc/rpc-client-contract' -import { useMobileNativeChatPermissionSend } from './native-chat/input/mobile-native-chat-permission-send' -import { useMobileNativeChatAnswerSend } from './native-chat/input/use-mobile-native-chat-answer-send' -import { useMobileNativeChatCancelAsk } from './native-chat/input/use-mobile-native-chat-cancel-ask' -import { useMobileNativeChatStop } from './native-chat/use-mobile-native-chat-stop' -import type { MobileNativeChatAnswerSend } from './native-chat/input/use-mobile-native-chat-answer-send' +import type { RpcClient } from '../../../transport/rpc/rpc-client-contract' +import { useMobileNativeChatPermissionSend } from './mobile-native-chat-permission-send' +import { useMobileNativeChatAnswerSend } from './use-mobile-native-chat-answer-send' +import { useMobileNativeChatCancelAsk } from './use-mobile-native-chat-cancel-ask' +import { useMobileNativeChatStop } from '../composer/use-mobile-native-chat-stop' +import type { MobileNativeChatAnswerSend } from './use-mobile-native-chat-answer-send' // Share the bridge write gate and cancel pending answer groups before interrupting; structured prompts use RPC instead. export function useMobileBridgeChatPromptWrites(args: { diff --git a/mobile/src/session/use-mobile-host-model-catalog-upgrade.ts b/mobile/src/session/native-chat/input/use-mobile-host-model-catalog-upgrade.ts similarity index 87% rename from mobile/src/session/use-mobile-host-model-catalog-upgrade.ts rename to mobile/src/session/native-chat/input/use-mobile-host-model-catalog-upgrade.ts index abb401f3d43..8075148cddf 100644 --- a/mobile/src/session/use-mobile-host-model-catalog-upgrade.ts +++ b/mobile/src/session/native-chat/input/use-mobile-host-model-catalog-upgrade.ts @@ -1,16 +1,16 @@ import { useCallback, useEffect, useRef, useState, type MutableRefObject } from 'react' -import type { AgentSessionModelCatalogResult } from '../../../src/shared/agent-session/agent-session-wire' -import type { AgentSessionOptionCatalog } from '../../../src/shared/agent-session/options/agent-session-option-catalog-types' -import type { StructuredAgentSessionOptionRecord } from '../../../src/shared/agent-session/options/structured-agent-session-option-state' -import type { StructuredAgentSessionOptionState } from '../../../src/shared/agent-session/options/structured-agent-session-options' -import type { RpcClient } from '../transport/rpc/rpc-client-contract' +import type { AgentSessionModelCatalogResult } from '../../../../../src/shared/agent-session/agent-session-wire' +import type { AgentSessionOptionCatalog } from '../../../../../src/shared/agent-session/options/agent-session-option-catalog-types' +import type { StructuredAgentSessionOptionRecord } from '../../../../../src/shared/agent-session/options/structured-agent-session-option-state' +import type { StructuredAgentSessionOptionState } from '../../../../../src/shared/agent-session/options/structured-agent-session-options' +import type { RpcClient } from '../../../transport/rpc/rpc-client-contract' import { isHostModelListingWaitInFlight, joinHostModelListingWait -} from '../../../src/shared/host-model-listing-waits' -import { callAgentSession } from './mobile-structured-agent-session-rpc' -import { usesModelSpecificAcpEfforts } from '../../../src/shared/agent-session/options/agent-model-catalog-ownership' -import type { HostModelCatalogLaunch } from '../../../src/shared/agent-session/options/host-model-catalog-snapshot-rules' +} from '../../../../../src/shared/host-model-listing-waits' +import { callAgentSession } from '../agent-session/mobile-structured-agent-session-rpc' +import { usesModelSpecificAcpEfforts } from '../../../../../src/shared/agent-session/options/agent-model-catalog-ownership' +import type { HostModelCatalogLaunch } from '../../../../../src/shared/agent-session/options/host-model-catalog-snapshot-rules' /** This world's last host lists for one chat's agent (`useHostModelCatalogCache`). A port, so this hook's * module graph stays free of the query layer for the root-only tests that bundle it. */ diff --git a/mobile/src/session/native-chat/input/use-mobile-native-chat-answer-send.ts b/mobile/src/session/native-chat/input/use-mobile-native-chat-answer-send.ts index b5ba3e86b04..96460626c77 100644 --- a/mobile/src/session/native-chat/input/use-mobile-native-chat-answer-send.ts +++ b/mobile/src/session/native-chat/input/use-mobile-native-chat-answer-send.ts @@ -12,12 +12,12 @@ import { MOBILE_NATIVE_CHAT_QUESTION_STEP_MS } from './mobile-native-chat-answer import { openMobileNativeChatSendBudget, sendMobileNativeChatMessageWithOutcome -} from '../mobile-native-chat-send' -import { healMobileNativeChatStaleInput } from '../mobile-native-chat-stale-input' +} from '../composer/mobile-native-chat-send' +import { healMobileNativeChatStaleInput } from '../composer/mobile-native-chat-stale-input' import { acquireMobileNativeChatTerminalWrite, releaseMobileNativeChatTerminalWrite -} from '../mobile-native-chat-terminal-write-lock' +} from '../composer/mobile-native-chat-terminal-write-lock' import { nativeChatAskRequiresTerminal, resolveNativeChatTranscriptAgent, diff --git a/mobile/src/session/native-chat/input/use-mobile-native-chat-cancel-ask.ts b/mobile/src/session/native-chat/input/use-mobile-native-chat-cancel-ask.ts index ea463e43a4e..64edb4f80de 100644 --- a/mobile/src/session/native-chat/input/use-mobile-native-chat-cancel-ask.ts +++ b/mobile/src/session/native-chat/input/use-mobile-native-chat-cancel-ask.ts @@ -1,7 +1,7 @@ import { useCallback, type MutableRefObject } from 'react' import { nativeChatAskRequiresTerminal } from '../../../../../src/shared/native-chat/native-chat-agent-support' import type { RpcClient } from '../../../transport/rpc/rpc-client-contract' -import { sendMobileNativeChatMessageWithOutcome } from '../mobile-native-chat-send' +import { sendMobileNativeChatMessageWithOutcome } from '../composer/mobile-native-chat-send' export function useMobileNativeChatCancelAsk(args: { client: RpcClient | null diff --git a/mobile/src/session/use-mobile-native-chat-model-discovery.ts b/mobile/src/session/native-chat/input/use-mobile-native-chat-model-discovery.ts similarity index 86% rename from mobile/src/session/use-mobile-native-chat-model-discovery.ts rename to mobile/src/session/native-chat/input/use-mobile-native-chat-model-discovery.ts index 4eb3bd930b6..fbdcb937d30 100644 --- a/mobile/src/session/use-mobile-native-chat-model-discovery.ts +++ b/mobile/src/session/native-chat/input/use-mobile-native-chat-model-discovery.ts @@ -1,12 +1,12 @@ import { useEffect, useState } from 'react' import * as z from 'zod' -import { getAgentSessionOptionCatalog } from '../../../src/shared/agent-session/options/agent-session-option-catalog' -import type { CatalogModel } from '../../../src/shared/agent-session/options/agent-session-option-catalog-types' +import { getAgentSessionOptionCatalog } from '../../../../../src/shared/agent-session/options/agent-session-option-catalog' +import type { CatalogModel } from '../../../../../src/shared/agent-session/options/agent-session-option-catalog-types' import { catalogModelsFromModelDiscovery, mergeDiscoveredCatalogModels -} from '../../../src/shared/native-chat/input/native-chat-discovered-catalog-models' -import { defineRpcOperation, runRpcOperation } from '../transport/rpc/rpc-operation' +} from '../../../../../src/shared/native-chat/input/native-chat-discovered-catalog-models' +import { defineRpcOperation, runRpcOperation } from '../../../transport/rpc/rpc-operation' const discoveredModel = z.object({ id: z.string().min(1), diff --git a/mobile/src/session/native-chat/input/use-mobile-native-chat-prompt-cards.ts b/mobile/src/session/native-chat/input/use-mobile-native-chat-prompt-cards.ts index 77342854952..1a1e15afdb8 100644 --- a/mobile/src/session/native-chat/input/use-mobile-native-chat-prompt-cards.ts +++ b/mobile/src/session/native-chat/input/use-mobile-native-chat-prompt-cards.ts @@ -1,6 +1,6 @@ import type { MobileNativeChatController } from '../mobile-native-chat-controller-contract' -import type { useMobileStructuredAgentSession } from '../../use-mobile-structured-agent-session' -import { useNativeChatAcceptedAction } from '../../use-native-chat-action-outcomes' +import type { useMobileStructuredAgentSession } from '../agent-session/use-mobile-structured-agent-session' +import { useNativeChatAcceptedAction } from './use-native-chat-action-outcomes' import { useMobileNativeChatPromptPresentation } from './use-mobile-native-chat-prompt-presentation' export function useMobileNativeChatPromptCards({ diff --git a/mobile/src/session/use-mobile-native-chat-prompt-controller.ts b/mobile/src/session/native-chat/input/use-mobile-native-chat-prompt-controller.ts similarity index 81% rename from mobile/src/session/use-mobile-native-chat-prompt-controller.ts rename to mobile/src/session/native-chat/input/use-mobile-native-chat-prompt-controller.ts index 27590badf9f..9d4b146565c 100644 --- a/mobile/src/session/use-mobile-native-chat-prompt-controller.ts +++ b/mobile/src/session/native-chat/input/use-mobile-native-chat-prompt-controller.ts @@ -1,14 +1,14 @@ -import { useMobileAsyncQuestionHides } from './native-chat/input/use-mobile-native-chat-prompt-dismiss' -import type { AskPrompt } from '../../../src/shared/native-chat/input/native-chat-ask-types' -import type { AskAnswerSelection } from '../../../src/shared/native-chat/input/native-chat-ask-answer' -import type { AgentStatusEntry } from '../../../src/shared/agent-status/contracts/agent-status-types' -import type { MobileNativeChatController } from './native-chat/mobile-native-chat-controller-contract' +import { useMobileAsyncQuestionHides } from './use-mobile-native-chat-prompt-dismiss' +import type { AskPrompt } from '../../../../../src/shared/native-chat/input/native-chat-ask-types' +import type { AskAnswerSelection } from '../../../../../src/shared/native-chat/input/native-chat-ask-answer' +import type { AgentStatusEntry } from '../../../../../src/shared/agent-status/contracts/agent-status-types' +import type { MobileNativeChatController } from '../mobile-native-chat-controller-contract' import type { useMobileBridgeChatPromptWrites } from './use-mobile-bridge-chat-prompt-writes' -import { useMobileNativeChatAskDismiss } from './native-chat/input/use-mobile-native-chat-ask-dismiss' -import { useMobileNativeChatPromptCards } from './native-chat/input/use-mobile-native-chat-prompt-cards' -import { useMobileNativeChatPrompts } from './native-chat/input/use-mobile-native-chat-prompts' -import type { useMobileNativeChatSession } from './native-chat/use-mobile-native-chat-session' -import type { useMobileStructuredAgentSession } from './use-mobile-structured-agent-session' +import { useMobileNativeChatAskDismiss } from './use-mobile-native-chat-ask-dismiss' +import { useMobileNativeChatPromptCards } from './use-mobile-native-chat-prompt-cards' +import { useMobileNativeChatPrompts } from './use-mobile-native-chat-prompts' +import type { useMobileNativeChatSession } from '../use-mobile-native-chat-session' +import type { useMobileStructuredAgentSession } from '../agent-session/use-mobile-structured-agent-session' import { useNativeChatAcceptedAction } from './use-native-chat-action-outcomes' // Read the chat's ask and permission/question prompts and route their answers to the active lane. diff --git a/mobile/src/session/native-chat/input/use-mobile-native-chat-prompts.ts b/mobile/src/session/native-chat/input/use-mobile-native-chat-prompts.ts index 06d37d90677..309e699626d 100644 --- a/mobile/src/session/native-chat/input/use-mobile-native-chat-prompts.ts +++ b/mobile/src/session/native-chat/input/use-mobile-native-chat-prompts.ts @@ -14,7 +14,7 @@ import type { NativeChatMessage } from '../../../../../src/shared/native-chat/na import { useMobileStructuredAsyncQuestion, type MobileStructuredAskSession -} from '../../use-mobile-structured-async-question' +} from './use-mobile-structured-async-question' export type MobileNativeChatPrompts = { /** A terminal chat's approval; a structured chat's journal prompts are its own cards. */ diff --git a/mobile/src/session/native-chat/input/use-mobile-native-chat-queued-edit-focus.test.tsx b/mobile/src/session/native-chat/input/use-mobile-native-chat-queued-edit-focus.test.tsx deleted file mode 100644 index 2afa78903dc..00000000000 --- a/mobile/src/session/native-chat/input/use-mobile-native-chat-queued-edit-focus.test.tsx +++ /dev/null @@ -1,67 +0,0 @@ -import { createElement } from 'react' -import { act, create, type ReactTestRenderer } from 'react-test-renderer' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { useMobileNativeChatQueuedEditFocus } from './use-mobile-native-chat-queued-edit-focus' -import type { MobileQueuedMessageEdit } from '../../use-mobile-structured-queued-message-controls' - -type Focus = ReturnType - -describe('useMobileNativeChatQueuedEditFocus', () => { - let renderer: ReactTestRenderer | null = null - let latest: Focus | null = null - - function Harness({ onEdit }: { onEdit?: MobileQueuedMessageEdit }): null { - latest = useMobileNativeChatQueuedEditFocus(onEdit) - return null - } - - beforeEach(() => { - vi.stubGlobal('requestAnimationFrame', (callback: FrameRequestCallback) => - setTimeout(() => callback(0), 0) - ) - }) - - afterEach(() => { - act(() => renderer?.unmount()) - renderer = null - latest = null - vi.unstubAllGlobals() - }) - - it('focuses the composer after Edit copies a queued message into it', async () => { - const onEdit = vi.fn(async (_messageId, onCopied) => { - onCopied?.() - return false - }) - await act(async () => { - renderer = create(createElement(Harness, { onEdit })) - }) - const focus = vi.fn() - const inputRef: { current: unknown } = latest!.composerInputRef - inputRef.current = { focus } - let edited: boolean | undefined - await act(async () => { - edited = await latest!.editQueuedMessage!('queued-1') - await new Promise((resolve) => setTimeout(resolve, 0)) - }) - expect(onEdit).toHaveBeenCalledWith('queued-1', expect.any(Function)) - // A failed Delete still leaves the copied text in the composer, so focus regardless. - expect(focus).toHaveBeenCalledTimes(1) - expect(edited).toBe(false) - }) - - it('leaves focus alone when Edit copied nothing', async () => { - const onEdit = vi.fn(async () => false) - await act(async () => { - renderer = create(createElement(Harness, { onEdit })) - }) - const focus = vi.fn() - const inputRef: { current: unknown } = latest!.composerInputRef - inputRef.current = { focus } - await act(async () => { - await latest!.editQueuedMessage!('queued-1') - await new Promise((resolve) => setTimeout(resolve, 0)) - }) - expect(focus).not.toHaveBeenCalled() - }) -}) diff --git a/mobile/src/session/native-chat/input/use-mobile-native-chat-queued-edit-focus.ts b/mobile/src/session/native-chat/input/use-mobile-native-chat-queued-edit-focus.ts index 730c71eeb63..79777e6a83e 100644 --- a/mobile/src/session/native-chat/input/use-mobile-native-chat-queued-edit-focus.ts +++ b/mobile/src/session/native-chat/input/use-mobile-native-chat-queued-edit-focus.ts @@ -1,6 +1,6 @@ import { useMemo, useRef, type RefObject } from 'react' import type { TextInput } from 'react-native' -import type { MobileQueuedMessageEdit } from '../../use-mobile-structured-queued-message-controls' +import type { MobileQueuedMessageEdit } from './use-mobile-structured-queued-message-controls' // Focus after a queued Edit actually copies text; empty copies preserve current focus. export function useMobileNativeChatQueuedEditFocus(onEdit: MobileQueuedMessageEdit | undefined): { diff --git a/mobile/src/session/native-chat/input/use-mobile-native-chat-session-option-controller.ts b/mobile/src/session/native-chat/input/use-mobile-native-chat-session-option-controller.ts index 66d2403ae64..fc87fe07d76 100644 --- a/mobile/src/session/native-chat/input/use-mobile-native-chat-session-option-controller.ts +++ b/mobile/src/session/native-chat/input/use-mobile-native-chat-session-option-controller.ts @@ -1,5 +1,5 @@ import type { RpcClient } from '../../../transport/rpc/rpc-client-contract' -import { useMobileNativeChatModelDiscovery } from '../../use-mobile-native-chat-model-discovery' +import { useMobileNativeChatModelDiscovery } from './use-mobile-native-chat-model-discovery' import { writeMobileNativeChatSessionOptions } from './mobile-native-chat-session-option-persistence' import { getAgentSessionOptionCatalog } from '../../../../../src/shared/agent-session/options/agent-session-option-catalog' import type { AgentSessionOptionCatalog } from '../../../../../src/shared/agent-session/options/agent-session-option-catalog-types' @@ -12,7 +12,7 @@ import type { SessionOptionsSurface } from '../../../../../src/shared/native-chat/input/native-chat-session-options' import { mobileNativeChatScopeKey } from '../mobile-native-chat-scope-key' -import type { MobileNativeChatSendOutcome } from '../mobile-native-chat-send' +import type { MobileNativeChatSendOutcome } from '../composer/mobile-native-chat-send' import type { MobileNativeChatSessionOptionPickersProps } from './MobileNativeChatSessionOptionPickers' import { useMobileNativeChatSessionOptions, diff --git a/mobile/src/session/native-chat/input/use-mobile-native-chat-session-options.test.ts b/mobile/src/session/native-chat/input/use-mobile-native-chat-session-options.test.ts index 6a856612617..5feb142b26d 100644 --- a/mobile/src/session/native-chat/input/use-mobile-native-chat-session-options.test.ts +++ b/mobile/src/session/native-chat/input/use-mobile-native-chat-session-options.test.ts @@ -1,16 +1,8 @@ import { createElement } from 'react' import { act, create, type ReactTestRenderer } from 'react-test-renderer' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import type { MobileNativeChatSendOutcome } from '../mobile-native-chat-send' -import { - applyNativeChatSessionOptionSettingsMutation, - resolveNativeChatSessionOptionDefaults -} from '../../../../../src/shared/native-chat/input/native-chat-session-option-defaults' -import { resolveAgentSessionOptionLaunch } from '../../../../../src/shared/agent-session/options/agent-session-option-launch' -import type { - PersistedNativeChatSessionOptions, - NativeChatSessionOptionSettingsMutation -} from '../../../../../src/shared/native-chat/input/native-chat-session-options' +import type { MobileNativeChatSendOutcome } from '../composer/mobile-native-chat-send' + import { clearMobileSessionOptionRecordsForTests, useMobileNativeChatSessionOptions, @@ -66,55 +58,6 @@ describe('useMobileNativeChatSessionOptions', () => { api = null }) - it.each([ - ['grok', true], - ['grok', false], - ['omp', true], - ['omp', false] - ] as const)( - '%s discovery cached=%s writes only an explicit owning-host pick', - async (agent, cached) => { - let persisted: PersistedNativeChatSessionOptions = { [agent]: { model: 'retired' } } - const writeOwner = vi.fn((mutation: NativeChatSessionOptionSettingsMutation) => { - persisted = applyNativeChatSessionOptionSettingsMutation(persisted, mutation) ?? persisted - }) - const writeOther = vi.fn() - const model = agent === 'grok' ? 'grok-4.7' : 'deepseek/deepseek-v4-pro' - const discoveredModels = [{ id: model, label: model, options: [] }] - mount({ - agent, - scopeKey: 'owner\0worktree\0tab', - reportedModel: 'retired', - modelSwitchCommand: 'orca-model', - writeSettings: writeOwner, - discoveredModels: cached ? discoveredModels : null - }) - if (!cached) { - update({ discoveredModels }) - } - expect(writeOwner).not.toHaveBeenCalled() - expect( - resolveAgentSessionOptionLaunch( - agent, - resolveNativeChatSessionOptionDefaults(persisted, agent) - ).args - ).toContain('retired') - await act(async () => { - expect(await api!.setOption('model', model)).toBe(true) - }) - expect(writeOwner).toHaveBeenCalledOnce() - expect( - resolveAgentSessionOptionLaunch( - agent, - resolveNativeChatSessionOptionDefaults(persisted, agent) - ).args - ).toContain(model) - update({ scopeKey: 'other\0worktree\0tab', writeSettings: writeOther }) - expect(writeOwner).toHaveBeenCalledOnce() - expect(writeOther).not.toHaveBeenCalled() - } - ) - it('starts over when the tab runs another agent and then a fresh session', async () => { mount({ reportedModel: 'claude-sonnet-5' }) await act(async () => { diff --git a/mobile/src/session/native-chat/input/use-mobile-native-chat-session-options.ts b/mobile/src/session/native-chat/input/use-mobile-native-chat-session-options.ts index 0158d5b3fc8..e9f38403cc5 100644 --- a/mobile/src/session/native-chat/input/use-mobile-native-chat-session-options.ts +++ b/mobile/src/session/native-chat/input/use-mobile-native-chat-session-options.ts @@ -19,7 +19,7 @@ import type { SessionOptionDescriptor, SessionOptionValue } from '../../../../../src/shared/native-chat/input/native-chat-session-options' -import type { MobileNativeChatSendOutcome } from '../mobile-native-chat-send' +import type { MobileNativeChatSendOutcome } from '../composer/mobile-native-chat-send' import { createNativeChatPtySessionOptions, type NativeChatPtySessionOptionsSurface diff --git a/mobile/src/session/use-mobile-queued-message-composer-actions.ts b/mobile/src/session/native-chat/input/use-mobile-queued-message-composer-actions.ts similarity index 91% rename from mobile/src/session/use-mobile-queued-message-composer-actions.ts rename to mobile/src/session/native-chat/input/use-mobile-queued-message-composer-actions.ts index ac28c9ed593..482e2cb4b70 100644 --- a/mobile/src/session/use-mobile-queued-message-composer-actions.ts +++ b/mobile/src/session/native-chat/input/use-mobile-queued-message-composer-actions.ts @@ -2,9 +2,9 @@ import { useCallback, useLayoutEffect, useRef, useState } from 'react' import type { AgentSessionQueuedMessage, AgentSessionQueuedMessageMoveResult -} from '../../../src/shared/agent-session/requests/agent-session-queued-message-wire' -import type { DragReorderMove } from '../components/drag-reorder-positions' -import type { MobileStructuredAgentMutate } from './use-mobile-structured-agent-mutation' +} from '../../../../../src/shared/agent-session/requests/agent-session-queued-message-wire' +import type { DragReorderMove } from '../../../components/drag-reorder-positions' +import type { MobileStructuredAgentMutate } from '../agent-session/use-mobile-structured-agent-mutation' type QueuedMessages = readonly AgentSessionQueuedMessage[] | null | undefined diff --git a/mobile/src/session/use-mobile-structured-agent-options.before-attach.test.ts b/mobile/src/session/native-chat/input/use-mobile-structured-agent-options.before-attach.test.ts similarity index 91% rename from mobile/src/session/use-mobile-structured-agent-options.before-attach.test.ts rename to mobile/src/session/native-chat/input/use-mobile-structured-agent-options.before-attach.test.ts index 92b9d7c8fc0..83752c125af 100644 --- a/mobile/src/session/use-mobile-structured-agent-options.before-attach.test.ts +++ b/mobile/src/session/native-chat/input/use-mobile-structured-agent-options.before-attach.test.ts @@ -1,7 +1,7 @@ import { act } from 'react-test-renderer' import { describe, expect, it, vi } from 'vitest' -import type { AgentSessionOptionResult } from '../../../src/shared/agent-session/agent-session-wire' -import type { StructuredAgentSessionMutationResult } from './mobile-structured-agent-session-rpc' +import type { AgentSessionOptionResult } from '../../../../../src/shared/agent-session/agent-session-wire' +import type { StructuredAgentSessionMutationResult } from '../agent-session/mobile-structured-agent-session-rpc' import { OPTIONS, deferred, diff --git a/mobile/src/session/use-mobile-structured-agent-options.chat-return.test.ts b/mobile/src/session/native-chat/input/use-mobile-structured-agent-options.chat-return.test.ts similarity index 96% rename from mobile/src/session/use-mobile-structured-agent-options.chat-return.test.ts rename to mobile/src/session/native-chat/input/use-mobile-structured-agent-options.chat-return.test.ts index 0aa3feb9be5..572915f7b60 100644 --- a/mobile/src/session/use-mobile-structured-agent-options.chat-return.test.ts +++ b/mobile/src/session/native-chat/input/use-mobile-structured-agent-options.chat-return.test.ts @@ -2,7 +2,7 @@ import { act } from 'react-test-renderer' import { expect, it } from 'vitest' -import type { AgentSessionOptionsResult } from '../../../src/shared/agent-session/options/agent-session-options-result' +import type { AgentSessionOptionsResult } from '../../../../../src/shared/agent-session/options/agent-session-options-result' import { BASE, OPTIONS, diff --git a/mobile/src/session/use-mobile-structured-agent-options.test-fixture.ts b/mobile/src/session/native-chat/input/use-mobile-structured-agent-options.test-fixture.ts similarity index 92% rename from mobile/src/session/use-mobile-structured-agent-options.test-fixture.ts rename to mobile/src/session/native-chat/input/use-mobile-structured-agent-options.test-fixture.ts index 936278b71b4..a679f3e3884 100644 --- a/mobile/src/session/use-mobile-structured-agent-options.test-fixture.ts +++ b/mobile/src/session/native-chat/input/use-mobile-structured-agent-options.test-fixture.ts @@ -1,18 +1,18 @@ import { createElement, useLayoutEffect } from 'react' import { act, type ReactTestRenderer } from 'react-test-renderer' -import { createWithQueryClient } from '../test-support/query-client-test-renderer' +import { createWithQueryClient } from '../../../test-support/query-client-test-renderer' import { vi } from 'vitest' import type { AgentSessionModelCatalogResult, AgentSessionOptionResult -} from '../../../src/shared/agent-session/agent-session-wire' -import type { AgentSessionOptionsResult } from '../../../src/shared/agent-session/options/agent-session-options-result' -import type { SessionOptionDescriptor } from '../../../src/shared/native-chat/input/native-chat-session-options' -import type { RpcClient } from '../transport/rpc/rpc-client-contract' +} from '../../../../../src/shared/agent-session/agent-session-wire' +import type { AgentSessionOptionsResult } from '../../../../../src/shared/agent-session/options/agent-session-options-result' +import type { SessionOptionDescriptor } from '../../../../../src/shared/native-chat/input/native-chat-session-options' +import type { RpcClient } from '../../../transport/rpc/rpc-client-contract' import type { StructuredAgentSessionMutate, StructuredAgentSessionMutationResult -} from './mobile-structured-agent-session-rpc' +} from '../agent-session/mobile-structured-agent-session-rpc' import { useMobileStructuredAgentOptions } from './use-mobile-structured-agent-options' const OPTIONS: AgentSessionOptionsResult = { diff --git a/mobile/src/session/use-mobile-structured-agent-options.test.ts b/mobile/src/session/native-chat/input/use-mobile-structured-agent-options.test.ts similarity index 72% rename from mobile/src/session/use-mobile-structured-agent-options.test.ts rename to mobile/src/session/native-chat/input/use-mobile-structured-agent-options.test.ts index 6cc5bdc886b..15196cf15f9 100644 --- a/mobile/src/session/use-mobile-structured-agent-options.test.ts +++ b/mobile/src/session/native-chat/input/use-mobile-structured-agent-options.test.ts @@ -1,16 +1,15 @@ -import { structuredAgentSessionOptionStamp } from '../../../src/shared/agent-session/options/structured-agent-session-option-state' +import { structuredAgentSessionOptionStamp } from '../../../../../src/shared/agent-session/options/structured-agent-session-option-state' import { act } from 'react-test-renderer' import { describe, expect, it, vi } from 'vitest' import type { AgentSessionModelCatalogResult, AgentSessionOptionResult -} from '../../../src/shared/agent-session/agent-session-wire' -import type { AgentSessionOptionsResult } from '../../../src/shared/agent-session/options/agent-session-options-result' -import type { StructuredAgentSessionMutationResult } from './mobile-structured-agent-session-rpc' -import { rememberMobileCreatedStructuredSession } from './mobile-created-structured-sessions' +} from '../../../../../src/shared/agent-session/agent-session-wire' +import type { AgentSessionOptionsResult } from '../../../../../src/shared/agent-session/options/agent-session-options-result' +import type { StructuredAgentSessionMutationResult } from '../agent-session/mobile-structured-agent-session-rpc' +import { rememberMobileCreatedStructuredSession } from '../agent-session/mobile-created-structured-sessions' import { - type Controller, settle, OPTIONS, FAST_OPTIONS, @@ -26,48 +25,6 @@ import { BASE } from './use-mobile-structured-agent-options.test-fixture' -describe('useMobileStructuredAgentOptions generation fencing', () => { - it('drops an options read a later write superseded', async () => { - const stale = deferred() - const first = optionsClient(queuedReads(FAST_OPTIONS)) - // Reconnect replaces the client without staling the retained record; generation must fence its prior read. - let reads = 0 - const reconnected = optionsClient(() => - reads++ === 0 - ? stale.promise - : Promise.resolve({ - ...FAST_OPTIONS, - current: { ...FAST_OPTIONS.current, model: 'gpt-fast' } - }) - ) - const { mutate } = recordingMutate(async () => - accepted({ key: 'model', value: 'gpt-fast', options: { model: 'gpt-fast' } }, true) - ) - const harness = await mountOptions({ ...BASE, client: first.client, mutate }) - - expect(currentValueOf(harness.current().optionSnapshot, 'model')).toBe('gpt-live') - await harness.rerender({ client: reconnected.client }) - expect(reconnected.optionReads()).toBe(1) - - let outcome: boolean | null = null - await act(async () => { - outcome = await harness.current().setStructuredOption('model', 'gpt-fast') - }) - await settle() - expect(outcome).toBe(true) - expect(currentValueOf(harness.current().optionSnapshot, 'model')).toBe('gpt-fast') - - await act(async () => { - stale.resolve({ ...FAST_OPTIONS, conversationCommands: ['compact'] }) - }) - await settle() - - expect(currentValueOf(harness.current().optionSnapshot, 'model')).toBe('gpt-fast') - expect(harness.current().conversationCommands).toEqual([]) - await harness.unmount() - }) -}) - describe('useMobileStructuredAgentOptions images', () => { it('keeps the answer through a pick made during the read', async () => { const stale = deferred() @@ -246,79 +203,6 @@ describe('useMobileStructuredAgentOptions host catalog', () => { }) }) -describe('useMobileStructuredAgentOptions after a lost pick reply', () => { - const tiers = (value: string, label: string) => [{ value, label }] - const answer = (model: string, serviceTier: string): AgentSessionOptionsResult => ({ - models: [ - { - id: 'm1', - label: 'M1', - isDefault: true, - efforts: [], - serviceTiers: tiers('priority', 'Fast') - }, - { id: 'm2', label: 'M2', isDefault: false, efforts: [], serviceTiers: tiers('flex', 'Flex') } - ], - listedModelIds: ['m1', 'm2'], - current: { model, serviceTier, confirmed: ['model'] } - }) - const speed = (controller: Controller) => { - const kind = descriptorFor(controller.optionSnapshot, 'serviceTier')?.kind - return kind?.type === 'select' - ? { value: kind.currentValue, choices: kind.choices.map((choice) => choice.value) } - : null - } - - it('draws the tier the host reconciled to, stays usable through a failed read, and takes the reconnect read', async () => { - const pendingRead = deferred() - const reads = [ - () => Promise.resolve(answer('m1', 'priority')), - () => Promise.reject(new Error('terminal reconciliation offline')), - () => Promise.reject(new Error('status reconciliation offline')), - () => pendingRead.promise, - () => Promise.resolve(answer('m2', 'flex')) - ] - const client = optionsClient(() => - (reads.shift() ?? (() => Promise.resolve(answer('m2', 'flex'))))() - ) - const { mutate } = recordingMutate(async () => ({ status: 'unknown' })) - const harness = await mountOptions({ ...BASE, client: client.client, mutate }) - expect(speed(harness.current())?.value).toBe('priority') - - // The host switched and set Standard, but its reply never arrived. - await act(async () => { - await harness.current().setStructuredOption('model', 'm2') - }) - expect(currentValueOf(harness.current().optionSnapshot, 'model')).toBe('m2') - expect(speed(harness.current())).toEqual({ value: 'default', choices: ['default', 'flex'] }) - expect(harness.current().pendingOptionId).toBeNull() - - expect(client.optionReads()).toBe(2) // The terminal wake consumed its failed query. - // The status-triggered read fails independently: nothing changes. - await harness.rerender({ optionStamp: 'status-1' }) - expect(speed(harness.current())?.value).toBe('default') - - // A read in flight when the user picks Flex answers for the old state and is dropped. - await harness.rerender({ optionStamp: 'status-2' }) - let picked = false - await act(async () => { - picked = await harness.current().setStructuredOption('serviceTier', 'flex') - }) - expect(picked).toBe(true) - await act(async () => pendingRead.resolve(answer('m1', 'priority'))) - await settle() - expect(currentValueOf(harness.current().optionSnapshot, 'model')).toBe('m2') - expect(speed(harness.current())?.value).toBe('flex') - - // Reconnected, the host's answer stands. - await harness.rerender({ optionStamp: 'status-3' }) - expect(currentValueOf(harness.current().optionSnapshot, 'model')).toBe('m2') - expect(speed(harness.current())?.value).toBe('flex') - expect(client.optionReads()).toBe(6) - await harness.unmount() - }) -}) - it('joins the post-receipt menu read with an unchanged phone option stamp', async () => { const initial: AgentSessionOptionsResult = { models: [{ id: 'family', label: 'Family', isDefault: false, efforts: [], effortsKnown: false }], @@ -485,9 +369,9 @@ it('accepts a typed literal at an attached fence while options refresh with no m await view.unmount() }) -import type { PiRefreshFixtureModule } from '../../../src/shared/agent-session/options/structured-agent-session-option-refresh.test-fixture-contract' +import type { PiRefreshFixtureModule } from '../../../../../src/shared/agent-session/options/structured-agent-session-option-refresh.test-fixture-contract' const { piOptionRefreshContract } = await vi.importActual( - '../../../src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-option-refresh.test-fixture' + '../../../../../src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-option-refresh.test-fixture' ) describe('Pi catalog refresh completion', () => { diff --git a/mobile/src/session/use-mobile-structured-agent-options.ts b/mobile/src/session/native-chat/input/use-mobile-structured-agent-options.ts similarity index 87% rename from mobile/src/session/use-mobile-structured-agent-options.ts rename to mobile/src/session/native-chat/input/use-mobile-structured-agent-options.ts index 321ba47ba1a..2fe2c786134 100644 --- a/mobile/src/session/use-mobile-structured-agent-options.ts +++ b/mobile/src/session/native-chat/input/use-mobile-structured-agent-options.ts @@ -1,31 +1,31 @@ -import type { AgentSessionConversationCommand } from '../../../src/shared/agent-session/agent-session-conversation-command' +import type { AgentSessionConversationCommand } from '../../../../../src/shared/agent-session/agent-session-conversation-command' import { useMobileStructuredOptionState } from './use-mobile-structured-option-state' import { useCallback, useLayoutEffect, useMemo, useRef } from 'react' -import { isAgentSessionHandleProvider } from '../../../src/shared/agent-session/lifecycle/agent-session-provider-handle' -import { structuredAgentSessionSeedCatalog } from '../../../src/shared/agent-session/options/structured-agent-session-seed-catalog' +import { isAgentSessionHandleProvider } from '../../../../../src/shared/agent-session/lifecycle/agent-session-provider-handle' +import { structuredAgentSessionSeedCatalog } from '../../../../../src/shared/agent-session/options/structured-agent-session-seed-catalog' import { structuredAgentSessionOptionView, structuredAgentSessionSendSelection, structuredAgentSessionMessageSelection, structuredAgentSessionShownSnapshot -} from '../../../src/shared/agent-session/options/structured-agent-session-option-view' -import { agentChatPermissionModes } from '../../../src/shared/agent-launch/permissions/agent-chat-permission-support' -import { legacyHostPermissionDescriptor } from '../../../src/shared/agent-session/options/structured-agent-session-permission-option' -import type { RpcClient } from '../transport/rpc/rpc-client-contract' -import type { StructuredAgentSessionHostSupport } from './mobile-structured-agent-session-host-support' -import type { MobileStructuredAgentMutate } from './use-mobile-structured-agent-mutation' +} from '../../../../../src/shared/agent-session/options/structured-agent-session-option-view' +import { agentChatPermissionModes } from '../../../../../src/shared/agent-launch/permissions/agent-chat-permission-support' +import { legacyHostPermissionDescriptor } from '../../../../../src/shared/agent-session/options/structured-agent-session-permission-option' +import type { RpcClient } from '../../../transport/rpc/rpc-client-contract' +import type { StructuredAgentSessionHostSupport } from '../agent-session/mobile-structured-agent-session-host-support' +import type { MobileStructuredAgentMutate } from '../agent-session/use-mobile-structured-agent-mutation' import { useMobileStructuredHeldOptionPicks } from './use-mobile-structured-held-option-picks' import { useMobileHostModelCatalogUpgrade, type HostModelCatalogCache } from './use-mobile-host-model-catalog-upgrade' -import { mobileCreatedStructuredSession } from './mobile-created-structured-sessions' +import { mobileCreatedStructuredSession } from '../agent-session/mobile-created-structured-sessions' import { structuredAgentSessionOptionAvailability, createStructuredAgentSessionOptionsWriteOwner -} from '../../../src/shared/agent-session/options/structured-agent-session-options-write-owner' +} from '../../../../../src/shared/agent-session/options/structured-agent-session-options-write-owner' import { useMobileStructuredOptionSurface } from './use-mobile-structured-option-surface' -import { lockedStructuredAgentSessionOptionSnapshot } from '../../../src/shared/agent-session/options/structured-agent-session-option-snapshot' +import { lockedStructuredAgentSessionOptionSnapshot } from '../../../../../src/shared/agent-session/options/structured-agent-session-option-snapshot' const NO_COMMANDS: readonly AgentSessionConversationCommand[] = [] diff --git a/mobile/src/session/use-mobile-structured-async-question.ts b/mobile/src/session/native-chat/input/use-mobile-structured-async-question.ts similarity index 78% rename from mobile/src/session/use-mobile-structured-async-question.ts rename to mobile/src/session/native-chat/input/use-mobile-structured-async-question.ts index 3ce76cd2aba..19f632ed561 100644 --- a/mobile/src/session/use-mobile-structured-async-question.ts +++ b/mobile/src/session/native-chat/input/use-mobile-structured-async-question.ts @@ -2,11 +2,11 @@ import { useCallback } from 'react' import { formatAskAnswer, type AskAnswerSelection -} from '../../../src/shared/native-chat/input/native-chat-ask-answer' -import { nativeChatAnswerSendIntent } from '../../../src/shared/native-chat/input/native-chat-follow-up-behavior' -import type { AskPrompt } from '../../../src/shared/native-chat/input/native-chat-ask-types' -import type { QueuedMessageCard } from '../../../src/shared/agent-session/view/structured-agent-session-queued-cards' -import type { useMobileStructuredAgentSession } from './use-mobile-structured-agent-session' +} from '../../../../../src/shared/native-chat/input/native-chat-ask-answer' +import { nativeChatAnswerSendIntent } from '../../../../../src/shared/native-chat/input/native-chat-follow-up-behavior' +import type { AskPrompt } from '../../../../../src/shared/native-chat/input/native-chat-ask-types' +import type { QueuedMessageCard } from '../../../../../src/shared/agent-session/view/structured-agent-session-queued-cards' +import type { useMobileStructuredAgentSession } from '../agent-session/use-mobile-structured-agent-session' export type MobileStructuredAskSession = Pick< ReturnType, diff --git a/mobile/src/session/use-mobile-structured-background-tasks.ts b/mobile/src/session/native-chat/input/use-mobile-structured-background-tasks.ts similarity index 66% rename from mobile/src/session/use-mobile-structured-background-tasks.ts rename to mobile/src/session/native-chat/input/use-mobile-structured-background-tasks.ts index fa81de570ff..3f30e490e0e 100644 --- a/mobile/src/session/use-mobile-structured-background-tasks.ts +++ b/mobile/src/session/native-chat/input/use-mobile-structured-background-tasks.ts @@ -1,16 +1,16 @@ import { useCallback, useMemo } from 'react' -import type { AgentChildRowContext } from '../../../src/shared/agent-status/presentation/agent-child-row-model' -import type { AgentSessionCancelResult } from '../../../src/shared/agent-session/agent-session-wire' -import { agentChildRowContextForSessionStream } from '../../../src/shared/agent-status/presentation/agent-child-row-stream-context' -import type { StructuredAgentSessionState } from '../../../src/shared/agent-session/structured-agent-session-reducer' +import type { AgentChildRowContext } from '../../../../../src/shared/agent-status/presentation/agent-child-row-model' +import type { AgentSessionCancelResult } from '../../../../../src/shared/agent-session/agent-session-wire' +import { agentChildRowContextForSessionStream } from '../../../../../src/shared/agent-status/presentation/agent-child-row-stream-context' +import type { StructuredAgentSessionState } from '../../../../../src/shared/agent-session/structured-agent-session-reducer' import { structuredSessionBackgroundTasksView, type StructuredSessionBackgroundTasksView -} from '../../../src/shared/structured-session-background-tasks-view' -import { structuredSessionForegroundCommands } from '../../../src/shared/structured-session-foreground-commands' -import type { StructuredAgentSessionMutationResult } from './mobile-structured-agent-session-rpc' -import type { MobileStructuredAgentMutate } from './use-mobile-structured-agent-mutation' -import { mobileStructuredHostClockOffsetMs } from './mobile-structured-host-clock-offset' +} from '../../../../../src/shared/structured-session-background-tasks-view' +import { structuredSessionForegroundCommands } from '../../../../../src/shared/structured-session-foreground-commands' +import type { StructuredAgentSessionMutationResult } from '../agent-session/mobile-structured-agent-session-rpc' +import type { MobileStructuredAgentMutate } from '../agent-session/use-mobile-structured-agent-mutation' +import { mobileStructuredHostClockOffsetMs } from '../agent-session/mobile-structured-host-clock-offset' export type MobileStructuredBackgroundTasks = { // Scope strip expansion and stopping state to the conversation. diff --git a/mobile/src/session/use-mobile-structured-held-option-picks.ts b/mobile/src/session/native-chat/input/use-mobile-structured-held-option-picks.ts similarity index 81% rename from mobile/src/session/use-mobile-structured-held-option-picks.ts rename to mobile/src/session/native-chat/input/use-mobile-structured-held-option-picks.ts index 245fb1c5d08..71ea9355013 100644 --- a/mobile/src/session/use-mobile-structured-held-option-picks.ts +++ b/mobile/src/session/native-chat/input/use-mobile-structured-held-option-picks.ts @@ -1,16 +1,16 @@ import { useEffect, useLayoutEffect, useRef } from 'react' -import type { AgentSessionOptionResult } from '../../../src/shared/agent-session/agent-session-wire' -import { acceptedStructuredSessionSelectionOutcome } from '../../../src/shared/agent-session/options/structured-agent-session-options-write-owner' -import type { StructuredSessionSelectionController } from '../../../src/shared/agent-session/options/structured-agent-session-selection-operations' -import type { SessionOptionDescriptor } from '../../../src/shared/native-chat/input/native-chat-session-options' +import type { AgentSessionOptionResult } from '../../../../../src/shared/agent-session/agent-session-wire' +import { acceptedStructuredSessionSelectionOutcome } from '../../../../../src/shared/agent-session/options/structured-agent-session-options-write-owner' +import type { StructuredSessionSelectionController } from '../../../../../src/shared/agent-session/options/structured-agent-session-selection-operations' +import type { SessionOptionDescriptor } from '../../../../../src/shared/native-chat/input/native-chat-session-options' import { nativeChatModelPillLabel, nativeChatSessionOptionLabel -} from '../../../src/shared/native-chat/input/native-chat-session-option-labels' -import { translate } from '../i18n/mobile-i18n' -import { mobileSessionOptionSummaryValue } from './native-chat/input/mobile-native-chat-session-option-labels' -import { sayMobileNativeChatSessionOption as say } from './native-chat/input/native-chat-session-option-copy' -import type { MobileStructuredAgentMutate } from './use-mobile-structured-agent-mutation' +} from '../../../../../src/shared/native-chat/input/native-chat-session-option-labels' +import { translate } from '../../../i18n/mobile-i18n' +import { mobileSessionOptionSummaryValue } from './mobile-native-chat-session-option-labels' +import { sayMobileNativeChatSessionOption as say } from './native-chat-session-option-copy' +import type { MobileStructuredAgentMutate } from '../agent-session/use-mobile-structured-agent-mutation' function pickLabel(descriptor: SessionOptionDescriptor | undefined): string | null { if (!descriptor) { diff --git a/mobile/src/session/use-mobile-structured-option-state.ts b/mobile/src/session/native-chat/input/use-mobile-structured-option-state.ts similarity index 85% rename from mobile/src/session/use-mobile-structured-option-state.ts rename to mobile/src/session/native-chat/input/use-mobile-structured-option-state.ts index 2be67786423..095dcb90908 100644 --- a/mobile/src/session/use-mobile-structured-option-state.ts +++ b/mobile/src/session/native-chat/input/use-mobile-structured-option-state.ts @@ -1,19 +1,19 @@ import { useCallback, useEffect, useMemo, useRef, useState, useSyncExternalStore } from 'react' -import { mobileStructuredSessionStatusFeed } from './mobile-structured-session-status-feed' -import { projectRuntimePermission } from '../../../src/shared/agent-session/options/structured-agent-session-permission-option' +import { mobileStructuredSessionStatusFeed } from '../agent-session/mobile-structured-session-status-feed' +import { projectRuntimePermission } from '../../../../../src/shared/agent-session/options/structured-agent-session-permission-option' import { useMobileStructuredSelectionController } from './use-mobile-structured-selection-controller' -import type { AgentSessionRewindSupport } from '../../../src/shared/agent-session/lifecycle/agent-session-rewind' -import type { AgentSessionOptionsResult } from '../../../src/shared/agent-session/options/agent-session-options-result' -import { callAgentSession } from './mobile-structured-agent-session-rpc' -import { forgetMobileCreatedStructuredSession } from './mobile-created-structured-sessions' -import { createStructuredAgentSessionOptionsReadOwner } from '../../../src/shared/agent-session/options/structured-agent-session-options-read-owner' -import { BoundedMap } from '../../../src/shared/bounded-map' -import type { RpcClient } from '../transport/rpc/rpc-client-contract' -import type { AgentSessionOptionCatalog } from '../../../src/shared/agent-session/options/agent-session-option-catalog-types' -import { usesInstalledAgentModelCatalog } from '../../../src/shared/agent-session/options/agent-model-catalog-ownership' -import { structuredAgentSessionFirstFrameOptionState } from '../../../src/shared/agent-session/options/structured-agent-session-first-frame' +import type { AgentSessionRewindSupport } from '../../../../../src/shared/agent-session/lifecycle/agent-session-rewind' +import type { AgentSessionOptionsResult } from '../../../../../src/shared/agent-session/options/agent-session-options-result' +import { callAgentSession } from '../agent-session/mobile-structured-agent-session-rpc' +import { forgetMobileCreatedStructuredSession } from '../agent-session/mobile-created-structured-sessions' +import { createStructuredAgentSessionOptionsReadOwner } from '../../../../../src/shared/agent-session/options/structured-agent-session-options-read-owner' +import { BoundedMap } from '../../../../../src/shared/bounded-map' +import type { RpcClient } from '../../../transport/rpc/rpc-client-contract' +import type { AgentSessionOptionCatalog } from '../../../../../src/shared/agent-session/options/agent-session-option-catalog-types' +import { usesInstalledAgentModelCatalog } from '../../../../../src/shared/agent-session/options/agent-model-catalog-ownership' +import { structuredAgentSessionFirstFrameOptionState } from '../../../../../src/shared/agent-session/options/structured-agent-session-first-frame' import type { HostModelCatalogCache } from './use-mobile-host-model-catalog-upgrade' -import { structuredAgentSessionReportsAtFence } from '../../../src/shared/agent-session/options/structured-agent-session-runtime-reports' +import { structuredAgentSessionReportsAtFence } from '../../../../../src/shared/agent-session/options/structured-agent-session-runtime-reports' // Matches the transcripts this view retains per chat. const MAX_RETAINED_CHAT_READERS = 32 diff --git a/mobile/src/session/use-mobile-structured-option-surface.ts b/mobile/src/session/native-chat/input/use-mobile-structured-option-surface.ts similarity index 95% rename from mobile/src/session/use-mobile-structured-option-surface.ts rename to mobile/src/session/native-chat/input/use-mobile-structured-option-surface.ts index d1d96d6d118..4fed7c5eaf8 100644 --- a/mobile/src/session/use-mobile-structured-option-surface.ts +++ b/mobile/src/session/native-chat/input/use-mobile-structured-option-surface.ts @@ -3,7 +3,7 @@ import type { SessionOptionDescriptor, SessionOptionsSurface, SessionOptionValue -} from '../../../src/shared/native-chat/input/native-chat-session-options' +} from '../../../../../src/shared/native-chat/input/native-chat-session-options' export function useMobileStructuredOptionSurface(args: { admits: NonNullable diff --git a/mobile/src/session/use-mobile-structured-prompt-responses.ts b/mobile/src/session/native-chat/input/use-mobile-structured-prompt-responses.ts similarity index 89% rename from mobile/src/session/use-mobile-structured-prompt-responses.ts rename to mobile/src/session/native-chat/input/use-mobile-structured-prompt-responses.ts index cbc0a1d764f..b80ff2ecbae 100644 --- a/mobile/src/session/use-mobile-structured-prompt-responses.ts +++ b/mobile/src/session/native-chat/input/use-mobile-structured-prompt-responses.ts @@ -1,14 +1,14 @@ import { useCallback } from 'react' -import type { AgentSessionPromptResult } from '../../../src/shared/agent-session/agent-session-wire' -import type { AgentJournalQuestionItem } from '../../../src/shared/agent-session/journal/agent-session-journal-types' +import type { AgentSessionPromptResult } from '../../../../../src/shared/agent-session/agent-session-wire' +import type { AgentJournalQuestionItem } from '../../../../../src/shared/agent-session/journal/agent-session-journal-types' import { AGENT_SESSION_RESPONSE_OPTION_ID_MAX_LENGTH, decodeAgentSessionQuestionAnswers, isValidAgentSessionQuestionAnswers, legacyAgentSessionSelectedOptionId, type AgentSessionQuestionAnswer -} from '../../../src/shared/agent-session/agent-session-question-answer' -import type { StructuredAgentSessionState } from '../../../src/shared/agent-session/structured-agent-session-reducer' +} from '../../../../../src/shared/agent-session/agent-session-question-answer' +import type { StructuredAgentSessionState } from '../../../../../src/shared/agent-session/structured-agent-session-reducer' import { actionableStructuredApproval, actionableStructuredQuestion @@ -20,8 +20,8 @@ import { import type { StructuredAgentSessionMutate, StructuredAgentSessionMutationResult -} from './mobile-structured-agent-session-rpc' -import type { MobileChatQuestion } from './native-chat/input/mobile-native-chat-question' +} from '../agent-session/mobile-structured-agent-session-rpc' +import type { MobileChatQuestion } from './mobile-native-chat-question' export function useMobileStructuredPromptResponses(args: { stateRef: { readonly current: StructuredAgentSessionState } diff --git a/mobile/src/session/use-mobile-structured-queued-edit.ts b/mobile/src/session/native-chat/input/use-mobile-structured-queued-edit.ts similarity index 93% rename from mobile/src/session/use-mobile-structured-queued-edit.ts rename to mobile/src/session/native-chat/input/use-mobile-structured-queued-edit.ts index 200a5608cb8..73db331e222 100644 --- a/mobile/src/session/use-mobile-structured-queued-edit.ts +++ b/mobile/src/session/native-chat/input/use-mobile-structured-queued-edit.ts @@ -1,4 +1,4 @@ -import type { QueuedEditLeaseLoss } from '../../../src/shared/queued-message-edit-lease' +import type { QueuedEditLeaseLoss } from '../../../../../src/shared/queued-message-edit-lease' import { createMobileQueuedEdit } from './mobile-queued-message-edit-open' import { useCallback, @@ -9,21 +9,21 @@ import { useRef, useState } from 'react' -import type { AgentSessionQueuedMessageUpdateResult } from '../../../src/shared/agent-session/requests/agent-session-queued-message-wire' -import { agentSessionSendBodyFingerprint } from '../../../src/shared/agent-session/requests/structured-agent-session-send-mutation' -import { queuedMessageWithEdit } from '../../../src/shared/queued-message-edit' +import type { AgentSessionQueuedMessageUpdateResult } from '../../../../../src/shared/agent-session/requests/agent-session-queued-message-wire' +import { agentSessionSendBodyFingerprint } from '../../../../../src/shared/agent-session/requests/structured-agent-session-send-mutation' +import { queuedMessageWithEdit } from '../../../../../src/shared/queued-message-edit' import { mobileQueuedEditValueKey, snapshotMobileQueuedEditInputs } from './mobile-queued-message-edit-value' import { settleMobileQueuedEdit } from './mobile-queued-message-edit-outcome' -import { queuedEditPublicationKey } from '../../../src/shared/queued-message-edit-publication' +import { queuedEditPublicationKey } from '../../../../../src/shared/queued-message-edit-publication' import { startMobileQueuedEditLease } from './mobile-queued-message-edit-lease' import { useMobileNativeChatDraftInputs, readMobileNativeChatDraftInputs, mobileNativeChatDraftDestination -} from './native-chat/composer/mobile-native-chat-draft-inputs' +} from '../composer/mobile-native-chat-draft-inputs' import { closeMobileQueuedEditDraft, mobileQueuedEditSaving, @@ -35,7 +35,6 @@ import { type MobileStructuredQueuedEditArgs, type MobileQueuedMessageInlineEditor } from './mobile-queued-message-edit-draft' -export type { MobileQueuedMessageInlineEditor } from './mobile-queued-message-edit-draft' export function useMobileStructuredQueuedEdit(args: MobileStructuredQueuedEditArgs) { const { sessionKey, sessionId, client, mutate, onSendError, onActionResolved } = args diff --git a/mobile/src/session/use-mobile-structured-queued-message-controls.ts b/mobile/src/session/native-chat/input/use-mobile-structured-queued-message-controls.ts similarity index 87% rename from mobile/src/session/use-mobile-structured-queued-message-controls.ts rename to mobile/src/session/native-chat/input/use-mobile-structured-queued-message-controls.ts index 4013522fce1..e4026afd448 100644 --- a/mobile/src/session/use-mobile-structured-queued-message-controls.ts +++ b/mobile/src/session/native-chat/input/use-mobile-structured-queued-message-controls.ts @@ -1,31 +1,29 @@ -import type { DragReorderMove } from '../components/drag-reorder-positions' +import type { DragReorderMove } from '../../../components/drag-reorder-positions' import { useMobileQueuedMessageComposerActions } from './use-mobile-queued-message-composer-actions' import { useCallback, useMemo } from 'react' -import { useMobileTranslation } from '../i18n/use-mobile-translation' +import { useMobileTranslation } from '../../../i18n/use-mobile-translation' import type { AgentJournalRenderItem, AgentJournalSubmission -} from '../../../src/shared/agent-session/journal/agent-session-journal-types' -import { agentSessionVisibleFailureFacts } from '../../../src/shared/agent-session/failures/agent-session-visible-failures' -import { mapSettledWithConcurrency } from '../../../src/shared/map-with-concurrency' +} from '../../../../../src/shared/agent-session/journal/agent-session-journal-types' +import { agentSessionVisibleFailureFacts } from '../../../../../src/shared/agent-session/failures/agent-session-visible-failures' +import { mapSettledWithConcurrency } from '../../../../../src/shared/map-with-concurrency' import type { AgentSessionQueuedMessage, AgentSessionQueuedMessageDeleteResult, AgentSessionQueuedMessagesResumeResult, AgentSessionQueuePause -} from '../../../src/shared/agent-session/requests/agent-session-queued-message-wire' -import type { AgentSessionSendResult } from '../../../src/shared/agent-session/agent-session-wire' -import { queuedMessagesQueuePause } from '../../../src/shared/agent-session/view/structured-agent-session-queued-cards' +} from '../../../../../src/shared/agent-session/requests/agent-session-queued-message-wire' +import type { AgentSessionSendResult } from '../../../../../src/shared/agent-session/agent-session-wire' +import { queuedMessagesQueuePause } from '../../../../../src/shared/agent-session/view/structured-agent-session-queued-cards' import { mobileQueuedMessageCards, type MobileQueuedMessageCard } from './mobile-structured-queued-message-cards' -import type { MobileStructuredAgentMutate } from './use-mobile-structured-agent-mutation' -import type { RpcClient } from '../transport/rpc/rpc-client-contract' -import { - useMobileStructuredQueuedEdit, - type MobileQueuedMessageInlineEditor -} from './use-mobile-structured-queued-edit' +import type { MobileStructuredAgentMutate } from '../agent-session/use-mobile-structured-agent-mutation' +import type { RpcClient } from '../../../transport/rpc/rpc-client-contract' +import { useMobileStructuredQueuedEdit } from './use-mobile-structured-queued-edit' +import type { MobileQueuedMessageInlineEditor } from './mobile-queued-message-edit-draft' // The host owns queued drafts; render its published cards even when it cannot queue new sends. const CLEAR_DELETE_CONCURRENCY = 8 diff --git a/mobile/src/session/use-mobile-structured-selection-controller.ts b/mobile/src/session/native-chat/input/use-mobile-structured-selection-controller.ts similarity index 85% rename from mobile/src/session/use-mobile-structured-selection-controller.ts rename to mobile/src/session/native-chat/input/use-mobile-structured-selection-controller.ts index f4a53b8aad3..82f26744f1e 100644 --- a/mobile/src/session/use-mobile-structured-selection-controller.ts +++ b/mobile/src/session/native-chat/input/use-mobile-structured-selection-controller.ts @@ -1,7 +1,7 @@ import { useEffect, useMemo, useSyncExternalStore } from 'react' -import { createStructuredSessionSelectionController } from '../../../src/shared/agent-session/options/structured-agent-session-selection-operations' -import { persistMobileStructuredOptionPicks } from './native-chat/input/mobile-native-chat-session-option-persistence' -import type { RpcClient } from '../transport/rpc/rpc-client-contract' +import { createStructuredSessionSelectionController } from '../../../../../src/shared/agent-session/options/structured-agent-session-selection-operations' +import { persistMobileStructuredOptionPicks } from './mobile-native-chat-session-option-persistence' +import type { RpcClient } from '../../../transport/rpc/rpc-client-contract' /** Temporary operations belong to one phone authority, above its queried host answer. */ export function useMobileStructuredSelectionController(args: { diff --git a/mobile/src/session/use-mobile-structured-session-option-stamp.ts b/mobile/src/session/native-chat/input/use-mobile-structured-session-option-stamp.ts similarity index 73% rename from mobile/src/session/use-mobile-structured-session-option-stamp.ts rename to mobile/src/session/native-chat/input/use-mobile-structured-session-option-stamp.ts index 3e64e9e9198..0dec257c4d6 100644 --- a/mobile/src/session/use-mobile-structured-session-option-stamp.ts +++ b/mobile/src/session/native-chat/input/use-mobile-structured-session-option-stamp.ts @@ -1,7 +1,7 @@ import { useCallback, useSyncExternalStore } from 'react' -import type { RpcClient } from '../transport/rpc/rpc-client-contract' -import { structuredAgentSessionOptionStamp } from '../../../src/shared/agent-session/options/structured-agent-session-option-state' -import { mobileStructuredSessionStatusFeed } from './mobile-structured-session-status-feed' +import type { RpcClient } from '../../../transport/rpc/rpc-client-contract' +import { structuredAgentSessionOptionStamp } from '../../../../../src/shared/agent-session/options/structured-agent-session-option-state' +import { mobileStructuredSessionStatusFeed } from '../agent-session/mobile-structured-session-status-feed' const noSubscription = (): (() => void) => () => {} diff --git a/mobile/src/session/use-mobile-structured-thread-goal.ts b/mobile/src/session/native-chat/input/use-mobile-structured-thread-goal.ts similarity index 81% rename from mobile/src/session/use-mobile-structured-thread-goal.ts rename to mobile/src/session/native-chat/input/use-mobile-structured-thread-goal.ts index b273b2d9780..a0145274ad1 100644 --- a/mobile/src/session/use-mobile-structured-thread-goal.ts +++ b/mobile/src/session/native-chat/input/use-mobile-structured-thread-goal.ts @@ -2,23 +2,23 @@ import { useCallback, useLayoutEffect, useMemo, useRef, useState } from 'react' import { AGENT_OWNED_THREAD_GOAL_CLEAR_COMMAND, agentSessionThreadGoalReport -} from '../../../src/shared/agent-session/agent-session-thread-goal-report' +} from '../../../../../src/shared/agent-session/agent-session-thread-goal-report' import type { AgentSessionThreadGoalChange, AgentSessionThreadGoalResult -} from '../../../src/shared/agent-session/agent-session-thread-goal-wire' -import { agentSessionWriteNoticeParts } from '../../../src/shared/agent-session/failures/agent-session-refusal-notice' -import type { AgentJournalThreadGoal } from '../../../src/shared/agent-session/journal/agent-session-journal-types' -import type { AgentSessionOptionsResult } from '../../../src/shared/agent-session/options/agent-session-options-result' -import type { StructuredAgentSessionState } from '../../../src/shared/agent-session/structured-agent-session-reducer' -import type { StructuredAgentSessionComposerOptions } from '../../../src/shared/agent-session/view/structured-agent-session-composer' -import { mobileAgentSessionWriteNoticeText } from './agent-session-write-notice-copy' -import type { MobileStructuredAgentSessionArgs } from './mobile-structured-agent-session-contract' -import { mobileStructuredHostClockOffsetMs } from './mobile-structured-host-clock-offset' -import type { MobileNativeChatSendOutcome } from './native-chat/mobile-native-chat-send' -import type { MobileStructuredAgentMutate } from './use-mobile-structured-agent-mutation' -import { AGENT_SESSION_PHONE_THREAD_GOAL_RUNTIME_CAPABILITY } from '../../../src/shared/agent-session/agent-session-runtime-capabilities' -import { useRouteRelaysCapability } from '../worktree/workspace-server-context' +} from '../../../../../src/shared/agent-session/agent-session-thread-goal-wire' +import { agentSessionWriteNoticeParts } from '../../../../../src/shared/agent-session/failures/agent-session-refusal-notice' +import type { AgentJournalThreadGoal } from '../../../../../src/shared/agent-session/journal/agent-session-journal-types' +import type { AgentSessionOptionsResult } from '../../../../../src/shared/agent-session/options/agent-session-options-result' +import type { StructuredAgentSessionState } from '../../../../../src/shared/agent-session/structured-agent-session-reducer' +import type { StructuredAgentSessionComposerOptions } from '../../../../../src/shared/agent-session/view/structured-agent-session-composer' +import { mobileAgentSessionWriteNoticeText } from '../agent-session/agent-session-write-notice-copy' +import type { MobileStructuredAgentSessionArgs } from '../agent-session/mobile-structured-agent-session-contract' +import { mobileStructuredHostClockOffsetMs } from '../agent-session/mobile-structured-host-clock-offset' +import type { MobileNativeChatSendOutcome } from '../composer/mobile-native-chat-send' +import type { MobileStructuredAgentMutate } from '../agent-session/use-mobile-structured-agent-mutation' +import { AGENT_SESSION_PHONE_THREAD_GOAL_RUNTIME_CAPABILITY } from '../../../../../src/shared/agent-session/agent-session-runtime-capabilities' +import { useRouteRelaysCapability } from '../../../worktree/workspace-server-context' export type MobileStructuredThreadGoal = { /** Scopes the strip's expansion to the conversation. */ diff --git a/mobile/src/session/use-native-chat-action-outcomes.ts b/mobile/src/session/native-chat/input/use-native-chat-action-outcomes.ts similarity index 100% rename from mobile/src/session/use-native-chat-action-outcomes.ts rename to mobile/src/session/native-chat/input/use-native-chat-action-outcomes.ts diff --git a/mobile/src/session/native-chat/mobile-native-chat-controller-contract.ts b/mobile/src/session/native-chat/mobile-native-chat-controller-contract.ts index a1b142c8dda..247fcbc108e 100644 --- a/mobile/src/session/native-chat/mobile-native-chat-controller-contract.ts +++ b/mobile/src/session/native-chat/mobile-native-chat-controller-contract.ts @@ -1,7 +1,7 @@ import type { NativeChatSkillDiscoverySnapshot } from '../../../../src/shared/native-chat/input/native-chat-picker-items' import type { AgentSessionRewindSurface } from '../../../../src/shared/agent-session/lifecycle/agent-session-rewind-request' import type { NativeChatSendFollowUp } from '../../../../src/shared/native-chat/input/native-chat-follow-up-behavior' -import type { StructuredMobileSendAttachment } from '../use-mobile-structured-send-with-outcome' +import type { StructuredMobileSendAttachment } from './composer/use-mobile-structured-send-with-outcome' import type { MobileSessionView } from '../../storage/session-view-preferences' import type { Dispatch, MutableRefObject, SetStateAction } from 'react' import type { @@ -22,18 +22,18 @@ import type { NativeChatResolvedPrompt } from '../../../../src/shared/native-cha import type { MobileNativeChatSendIntent, MobileNativeChatSendOutcome -} from './mobile-native-chat-send' -import type { MobileNativeChatCommandRefusalCauses } from './use-mobile-native-chat-send-error' -import type { MobileStructuredQueuedMessageControls } from '../use-mobile-structured-queued-message-controls' -import type { MobileStructuredThreadGoal } from '../use-mobile-structured-thread-goal' -import type { MobileStructuredBackgroundTasks } from '../use-mobile-structured-background-tasks' -import type { MobileStructuredInterruptedContinue } from '../use-mobile-structured-interrupted-continue' -import type { MobileNativeChatPendingMessage } from './mobile-native-chat-pending-echo' +} from './composer/mobile-native-chat-send' +import type { MobileNativeChatCommandRefusalCauses } from './composer/use-mobile-native-chat-send-error' +import type { MobileStructuredQueuedMessageControls } from './input/use-mobile-structured-queued-message-controls' +import type { MobileStructuredThreadGoal } from './input/use-mobile-structured-thread-goal' +import type { MobileStructuredBackgroundTasks } from './input/use-mobile-structured-background-tasks' +import type { MobileStructuredInterruptedContinue } from './composer/use-mobile-structured-interrupted-continue' +import type { MobileNativeChatPendingMessage } from './transcript/mobile-native-chat-pending-echo' import type { useMobileNativeChatSession } from './use-mobile-native-chat-session' import type { MobileNativeChatSessionOptionPickersProps } from './input/MobileNativeChatSessionOptionPickers' import type { MobileNativeChatVisualSource } from './visual/mobile-native-chat-visual-read' import type { NativeChatContextUsageSummary } from '../../../../src/shared/native-chat/native-chat-context-usage-summary' -import type { useMobileStructuredSessionCommands } from '../use-mobile-structured-session-commands' +import type { useMobileStructuredSessionCommands } from './composer/use-mobile-structured-session-commands' import type { MobileNativeChatUsageLimit } from './use-mobile-native-chat-usage-limit' export type MobileNativeChatController = { diff --git a/mobile/src/session/native-chat/mobile-native-chat-lower-scroll.ts b/mobile/src/session/native-chat/mobile-native-chat-lower-scroll.ts index 6aca979c534..d0194b0689c 100644 --- a/mobile/src/session/native-chat/mobile-native-chat-lower-scroll.ts +++ b/mobile/src/session/native-chat/mobile-native-chat-lower-scroll.ts @@ -1,5 +1,5 @@ -import { createMobileNativeChatReadingHold } from './mobile-native-chat-reading-hold' -import { connectMobileNativeChatScrollGesture } from './mobile-native-chat-scroll-gesture' +import { createMobileNativeChatReadingHold } from './transcript/mobile-native-chat-reading-hold' +import { connectMobileNativeChatScrollGesture } from './transcript/mobile-native-chat-scroll-gesture' import { externalAllowance, composerGroupOf as groupOf, diff --git a/mobile/src/session/native-chat/mobile-native-chat-reading-place.test.tsx b/mobile/src/session/native-chat/mobile-native-chat-reading-place.test.tsx deleted file mode 100644 index 9cd4aa4d9f9..00000000000 --- a/mobile/src/session/native-chat/mobile-native-chat-reading-place.test.tsx +++ /dev/null @@ -1,652 +0,0 @@ -import { - Activity, - createElement as h, - Fragment, - useMemo, - type ReactElement, - type ReactNode -} from 'react' -import { - act, - create, - type ReactTestRenderer, - type ReactTestRendererJSON as Node -} from 'react-test-renderer' -import { afterEach, expect, it, vi } from 'vitest' -import { splitNativeChatBlocks } from '../../../../src/shared/native-chat/tools/native-chat-tool-fold' -import type { - NativeChatBlock, - NativeChatMessage -} from '../../../../src/shared/native-chat/native-chat-types' -import { foldMobileNativeChatMessages } from './mobile-native-chat-render-data' -import { - useMobileNativeChatRowKeys, - type MobileNativeChatRowKeys -} from './transcript/mobile-native-chat-row-keys' -import { mobileNativeChatRowId } from '../mobile-native-chat-reading-place' -import { MobileNativeChatPageList } from './transcript/MobileNativeChatPageList' -import { ToolRun } from './transcript/MobileNativeChatToolRun' -import { useMobileNativeChatTurnDisclosure } from './transcript/use-mobile-native-chat-turn-disclosure' - -const platform = vi.hoisted(() => ({ OS: 'web' })) -const scrollable = vi.hoisted(() => { - const held: { node: unknown } = { node: null } - return held -}) - -vi.mock('react-native', async () => { - const React = await import('react') - class ScrollView extends React.Component<{ children?: ReactNode }> { - scrollToEnd = (): void => {} - scrollTo = (): void => {} - getScrollableNode = (): unknown => scrollable.node - getInnerViewNode = (): object => ({}) - render(): ReactNode { - return React.createElement('div', null, this.props.children) - } - } - const settled = () => ({ start: (): void => {}, stop: (): void => {} }) - return { - Platform: platform, - Text: 'span', - View: 'div', - Pressable: 'button', - ScrollView, - Animated: { - Text: 'span', - Value: class { - setValue(): void {} - }, - loop: (animation: unknown) => animation, - sequence: settled, - timing: settled - }, - StyleSheet: { create: (styles: unknown) => styles, hairlineWidth: 1 }, - useWindowDimensions: () => ({ width: 400, height: 800 }) - } -}) -vi.mock('lucide-react-native', () => { - const icon = () => null - const names = ['Bot', 'Brain', 'Check', 'ChevronRight', 'Circle', 'CircleCheck', 'CircleDot'] - const more = ['Eye', 'FileMinus2', 'FilePen', 'FilePlus2', 'Folder', 'Globe', 'ListChecks'] - const rest = ['MessageSquareMore', 'Pencil', 'Plug', 'Search', 'SquareTerminal', 'Wrench'] - return Object.fromEntries([...names, ...more, ...rest].map((name) => [name, icon])) -}) -vi.mock('./transcript/mobile-native-chat-tool-styles', () => ({ - toolStyles: {}, - toolType: () => ({ row: {}, meta: {}, code: {} }) -})) -vi.mock('../../components/MobileSourceCopyButton', () => ({ MobileSourceCopyButton: () => null })) -vi.mock('../../platform/external-link', () => ({ openExternalLink: vi.fn() })) -vi.mock('../../components/inline-text-selection', () => ({ INLINE_TEXT_SELECTION: false })) - -// The browser's resize step: after layout, before paint. -const observers = new Map<() => void, Set>() -const resized = () => act(() => observers.forEach((_, deliver) => deliver())) -// Only observers watching `target` hear about it, as in the browser. -const resizedOnly = (target: unknown) => - act(() => observers.forEach((targets, deliver) => targets.has(target) && deliver())) -vi.stubGlobal( - 'ResizeObserver', - class { - constructor(private readonly deliver: () => void) { - observers.set(deliver, new Set()) - } - observe(target: unknown): void { - observers.get(this.deliver)?.add(target) - } - unobserve(target: unknown): void { - observers.get(this.deliver)?.delete(target) - } - disconnect(): void { - observers.delete(this.deliver) - } - } -) - -const mountedRenderers = new Set() - -afterEach(() => { - act(() => { - for (const renderer of mountedRenderers) { - renderer.unmount() - } - }) - mountedRenderers.clear() - scrollable.node = null - vi.useRealTimers() - vi.restoreAllMocks() -}) - -const say = (id: string, role: 'user' | 'assistant', text: string): NativeChatMessage => ({ - id, - role, - timestamp: null, - source: 'transcript', - blocks: [{ type: 'text', text }] -}) -const edit = (n: number): NativeChatBlock => { - const lines = (word: string): string => Array.from({ length: 30 }, () => word).join('\n') - const input = { file_path: `f${n}.ts`, old_string: lines('old'), new_string: lines('new') } - return { type: 'tool-call', name: 'Edit', callId: `c${n}`, input } -} -const run = (n: number): NativeChatMessage[] => [ - { ...say(`a${n}`, 'assistant', ''), blocks: [edit(n)] }, - { ...say(`r${n}`, 'user', ''), blocks: [{ type: 'tool-result', callId: `c${n}`, output: 'ok' }] } -] -const chat = [say('u0', 'user', 'first'), say('x0', 'assistant', 'answer'), say('u1', 'user', 'go')] - .concat({ - ...say('a1', 'assistant', 'On it'), - blocks: [{ type: 'text', text: 'On it' }, edit(1)] - }) - .concat(run(1).slice(1), ...Array.from({ length: 39 }, (_, i) => run(i + 2))) - -type Box = { id: string; top: number; bottom: number; end: number; parent: number; rows: boolean } -type Element = { - getAttribute: () => string - getBoundingClientRect: () => { top: number; bottom: number } - querySelectorAll: (selector: string) => Element[] - children: Element[] - nextElementSibling: Element | null -} - -const oldHostTail = (): NativeChatMessage[] => JSON.parse(JSON.stringify(chat)) -const from = (id: string) => oldHostTail().slice(chat.findIndex((m) => m.id === id)) - -// Model end-anchored scrollTop=0 at the tail and negative offsets above; prepending history must not shift the view. -function page(tree: () => Node | Node[] | null) { - const boxes = (): Box[] => { - const out: Box[] = [] - let y = 0 - const walk = (node: Node | string, parent: number): void => { - if (typeof node === 'string' || node.type === 'span') { - y += typeof node === 'string' ? 0 : 20 - return - } - const id = String(node.props.testID ?? '') - const rows = node.props['data-chat-rows'] !== undefined - const at = out.push({ id, top: y, bottom: y, end: 0, parent, rows }) - 1 - node.children?.forEach((child) => walk(child, at)) - out[at] = { ...out[at]!, bottom: y, end: out.length } - } - walk({ type: 'page', props: {}, children: [tree() ?? []].flat() }, -1) - return out - } - const element = (all: Box[], at: number): Element => { - const box = all[at]! - const siblings = (parent: number): Element[] => - all.flatMap((other, i) => (other.parent === parent ? [element(all, i)] : [])) - return { - getAttribute: () => box.id, - getBoundingClientRect: () => ({ - top: box.top - node.viewTop(), - bottom: box.bottom - node.viewTop() - }), - querySelectorAll: (inner: string) => select(all, at + 1, box.end, inner), - get children() { - return siblings(at) - }, - get nextElementSibling() { - const next = all.findIndex((other, i) => i > at && other.parent === box.parent) - return next === -1 ? null : element(all, next) - } - } - } - const select = (all: Box[], from: number, to: number, selector: string): Element[] => { - const prefix = /\^="([^"]+)"/.exec(selector)?.[1] ?? '?' - return all.flatMap((box, at) => - at >= from && at < to && box.id.startsWith(prefix) ? [element(all, at)] : [] - ) - } - let scrollTop = 0 - const listeners = new Map void>() - const node = { - writes: 0, - get scrollTop(): number { - return scrollTop - }, - set scrollTop(value: number) { - node.writes += 1 - scrollTop = value - }, - clientHeight: 200, - get scrollHeight(): number { - return boxes()[0]?.bottom ?? 0 - }, - viewTop: (): number => Math.max(0, node.scrollHeight - node.clientHeight) + node.scrollTop, - showFrom: (y: number): void => { - node.scrollTop = y - Math.max(0, node.scrollHeight - node.clientHeight) - }, - getAttribute: () => null, - getBoundingClientRect: () => ({ top: 0, bottom: node.clientHeight }), - addEventListener: (type: string, listener: () => void): void => { - listeners.set(type, listener) - }, - removeEventListener: (type: string): void => { - listeners.delete(type) - }, - touch: (type: 'touchstart' | 'touchend'): void => listeners.get(type)?.(), - querySelectorAll: (selector: string): Element[] => select(boxes(), 0, Infinity, selector), - querySelector: (): Element | null => { - const all = boxes() - const at = all.findIndex((box) => box.rows) - return at === -1 ? null : element(all, at) - }, - top: (id: string): number => - (boxes().find((box) => box.id === id)?.top ?? Number.NaN) - node.viewTop() - } - return node -} - -function Row({ - message, - rowKey, - joined = 0, - workRun, - joinsWorkRun -}: { - message: NativeChatMessage - rowKey: string - joined?: number - workRun?: readonly NativeChatMessage[] - joinsWorkRun?: boolean -}): ReactElement | null { - if (joinsWorkRun) { - return null - } - const { prose, tools } = splitNativeChatBlocks((workRun ?? [message]).flatMap((m) => m.blocks)) - const words = prose - .map((block, i) => h('span', { key: i }, block.type === 'text' ? block.text : '')) - .concat(Array.from({ length: joined }, (_, i) => h('span', { key: `joined:${i}` }, 'joined'))) - const run = tools.length > 0 && h(ToolRun, { blocks: tools }) - return h('div', { testID: mobileNativeChatRowId(rowKey) }, words, run) -} - -let shownKeys!: MobileNativeChatRowKeys - -function Chat(props: { - messages: NativeChatMessage[] - following: boolean - live: boolean - joined?: number - runs?: boolean - status?: boolean -}): ReactElement { - const folded = useMemo( - () => foldMobileNativeChatMessages(props.messages, 'claude'), - [props.messages] - ) - const turns = useMobileNativeChatTurnDisclosure({ - messages: folded, - enabled: props.runs === true, - isWorking: false, - scopeKey: 'chat' - }) - const keys = useMobileNativeChatRowKeys(folded, props.messages, 'chat', turns.presentation) - shownKeys = keys - return h(MobileNativeChatPageList, { - ref: null, - rows: turns.listMessages, - rowKeys: keys, - runs: turns.presentation.workRuns.heads, - isFollowing: () => props.following, - onEndDistance: () => {}, - renderItem: ({ item, index }) => { - const { workRun, joinsWorkRun } = turns.resolveRow(index, item) - const row = h(Row, { - message: item, - rowKey: keys.keyOf(item), - joined: item === folded.at(-1) ? props.joined : 0, - workRun, - joinsWorkRun - }) - // Turn status draws beside its row, untagged. - return props.status - ? h( - Fragment, - null, - row, - ...Array.from({ length: 5 }, (_, i) => h('span', { key: i }, 'Done')) - ) - : row - }, - layoutKey: 'layout', - contentContainerStyle: null, - header: h('div', { testID: 'header' }, h('span', null, 'Loading')), - footer: props.live ? h('span', null, 'Working') : null, - emptyStateView: null, - onScroll: () => {} - }) -} - -function mount( - messages: NativeChatMessage[], - options: { following: boolean; live: boolean; runs?: boolean; status?: boolean } = { - following: false, - live: false - } -) { - let renderer!: ReactTestRenderer - act(() => { - renderer = create(h('div')) - mountedRenderers.add(renderer) - }) - const scroller = page(() => renderer.toJSON()) - scrollable.node = scroller - let mode: 'visible' | 'hidden' = 'visible' - let last: { messages: NativeChatMessage[]; joined: number } = { messages, joined: 0 } - const show = (next: NativeChatMessage[], joined = 0): number => { - const before = scroller.writes - last = { messages: next, joined } - act(() => renderer.update({h(Chat, { ...options, ...last })})) - return scroller.writes - before - } - // Hide or show the list the way the chat overlay does behind its terminal. - const display = (next: 'visible' | 'hidden') => { - mode = next - show(last.messages, last.joined) - } - vi.useFakeTimers({ now: 10_000, toFake: ['Date', 'setTimeout', 'clearTimeout'] }) - const scrolled = () => - act(() => - renderer.root.find((n) => n.props.onScroll && n.props.scrollEventThrottle).props.onScroll({}) - ) - const rest = () => - act(() => { - vi.advanceTimersByTime(400) - }) - const read = (move: () => void) => { - move() - scrolled() - rest() - } - show(messages) - const find = (id: string) => renderer.root.find((n) => n.props.testID === id) - const press = (id: string) => act(() => find(id).findAllByType('button')[0]!.props.onPress()) - const drawn = (id: string) => renderer.root.findAll((n) => n.props.testID === id).length - const lines = (id: string) => find(id).findAllByType('span').length - const rows = () => - renderer.root - .findAll((n) => n.type === 'div' && String(n.props.testID).startsWith('chat-row:')) - .map((n) => n.props.testID) - return { scroller, show, display, press, drawn, lines, find, rows, scrolled, rest, read } -} - -it('keeps the line a reader was on, its run open, when older messages join the run from an old host', () => { - // Exercise anchoring both inside a run and at Load earlier when older calls absorb the visible orphan result. - for (const atTop of [false, true]) { - const chat0 = mount(from('r31')) - chat0.press(mobileNativeChatRowId('a32')) - chat0.press('chat-member:call:c34') - const opened = chat0.lines('chat-member:call:c34') - chat0.read(() => (chat0.scroller.scrollTop += chat0.scroller.top('chat-member:call:c34'))) - // Old hosts can replay the whole tail as new objects with unchanged ids. - for (const [older, first] of [ - ['r21', 'c32'], - ['u0', 'c22'] - ] as const) { - if (atTop) { - chat0.read(() => chat0.scroller.showFrom(0)) - } - const line = `chat-member:call:${atTop ? first : 'c34'}` - const top = chat0.scroller.top(line) - expect(chat0.show(from(older))).toBeLessThanOrEqual(1) - expect(chat0.scroller.top(line)).toBe(top) - } - - expect(chat0.rows().slice(0, 3)).toEqual(['u0', 'x0', 'u1'].map(mobileNativeChatRowId)) - expect(chat0.lines('chat-member:call:c34')).toBe(opened) - expect(chat0.drawn('chat-member:call:c1')).toBe(1) - expect(shownKeys.current('r21')).toBe('a32') - - chat0.show([...oldHostTail(), say('done', 'assistant', 'Done'), say('ask', 'user', 'next')]) - expect(chat0.drawn(mobileNativeChatRowId('a32'))).toBe(1) - expect(chat0.drawn('chat-member:call:c34')).toBe(1) - } - - // Both collapsed headers and open lines must stay anchored as older calls join above. - const later = Array.from({ length: 10 }, (_, i) => say(`t${i}`, 'user', 'later')) - for (const open of [false, true]) { - const tail = mount([...from('r21'), ...later]) - if (open) { - tail.press(mobileNativeChatRowId('a22')) - tail.read(() => (tail.scroller.scrollTop += tail.scroller.top('chat-member:call:c27') + 40)) - } - const before = tail.scroller.top(mobileNativeChatRowId('t0')) - tail.show([...oldHostTail(), ...later]) - expect(tail.scroller.top(mobileNativeChatRowId('t0'))).toBe(before) - } -}) - -it('holds back a change below a scrolling reader until they rest, then keeps their line', () => { - const rows = Array.from({ length: 12 }, (_, i) => say(`m${i}`, i % 2 ? 'assistant' : 'user', 'x')) - const chat0 = mount(rows) - chat0.scroller.showFrom(40) - chat0.scrolled() - // A correction mid-fling would stop iOS momentum; hold the below-reader reply until rest. - const line = chat0.scroller.top(mobileNativeChatRowId('m4')) - expect(chat0.show([...rows, say('n1', 'assistant', 'reply')])).toBe(0) - expect(chat0.drawn(mobileNativeChatRowId('n1'))).toBe(0) - expect(chat0.scroller.top(mobileNativeChatRowId('m4'))).toBe(line) - chat0.rest() - expect(chat0.drawn(mobileNativeChatRowId('n1'))).toBe(1) - expect(chat0.scroller.top(mobileNativeChatRowId('m4'))).toBe(line) -}) - -it('a parked reader stays parked when React Native Web repeats the scroll event of its own correction', () => { - const rows = Array.from({ length: 12 }, (_, i) => say(`m${i}`, i % 2 ? 'assistant' : 'user', 'x')) - const chat0 = mount(rows) - chat0.read(() => chat0.scroller.showFrom(40)) - const line = chat0.scroller.top(mobileNativeChatRowId('m4')) - const n1 = say('n1', 'assistant', 'reply') - chat0.show([...rows, n1]) - chat0.scrolled() - // React Native Web sends the last scroll event again 100 ms after scrolling stops. - chat0.scrolled() - chat0.show([...rows, n1, say('n2', 'assistant', 'more')]) - expect(chat0.drawn(mobileNativeChatRowId('n2'))).toBe(1) - expect(chat0.scroller.top(mobileNativeChatRowId('m4'))).toBe(line) -}) - -it('releases a held change once a chat hidden mid-touch is shown again and the reader rests', () => { - const rows = Array.from({ length: 12 }, (_, i) => say(`m${i}`, i % 2 ? 'assistant' : 'user', 'x')) - const chat0 = mount(rows) - chat0.scroller.touch('touchstart') - chat0.scroller.showFrom(40) - chat0.scrolled() - chat0.show([...rows, say('n1', 'assistant', 'reply')]) - chat0.display('hidden') - // The hidden list hears no touchend. - chat0.scroller.touch('touchend') - chat0.display('visible') - chat0.rest() - expect(chat0.drawn(mobileNativeChatRowId('n1'))).toBe(1) -}) - -it('keeps a parked reader on their line when the list viewport changes height, as when the composer grows', () => { - const rows = Array.from({ length: 12 }, (_, i) => say(`m${i}`, i % 2 ? 'assistant' : 'user', 'x')) - const chat0 = mount(rows) - chat0.read(() => chat0.scroller.showFrom(40)) - const line = chat0.scroller.top(mobileNativeChatRowId('m4')) - - chat0.scroller.clientHeight = 120 - resizedOnly(chat0.scroller) - - expect(chat0.scroller.top(mobileNativeChatRowId('m4'))).toBe(line) -}) - -it("holds a row's look with its messages: what the chat's state adds lands once the reader rests", () => { - const rows = Array.from({ length: 12 }, (_, i) => say(`m${i}`, i % 2 ? 'assistant' : 'user', 'x')) - const chat0 = mount(rows) - chat0.scroller.showFrom(40) - chat0.scrolled() - const line = chat0.scroller.top(mobileNativeChatRowId('m4')) - expect(chat0.show(rows, 3)).toBe(0) - expect(chat0.lines(mobileNativeChatRowId('m11'))).toBe(1) - expect(chat0.scroller.top(mobileNativeChatRowId('m4'))).toBe(line) - chat0.rest() - expect(chat0.lines(mobileNativeChatRowId('m11'))).toBe(4) - expect(chat0.scroller.top(mobileNativeChatRowId('m4'))).toBe(line) -}) - -it('draws a run once when an older page brings in its start while the reader moves', () => { - const call = (id: string): NativeChatMessage => ({ - ...say(id, 'assistant', ''), - blocks: [{ type: 'tool-call', name: 'Bash', callId: id, input: { command: id } }] - }) - const thought: NativeChatMessage = { ...say('t', 'assistant', 'weighing it'), role: 'reasoning' } - const later = Array.from({ length: 12 }, (_, i) => - say(`m${i}`, i % 2 ? 'assistant' : 'user', 'x') - ) - const chat0 = mount([thought, call('b'), ...later], { following: false, live: false, runs: true }) - chat0.scroller.showFrom(40) - chat0.scrolled() - chat0.show([say('u', 'user', 'go'), call('a'), thought, call('b'), ...later]) - const once = ['u', 'a', 'm0'].map(mobileNativeChatRowId) - expect(chat0.rows().slice(0, 3)).toEqual(once) - expect(chat0.drawn('chat-member:run')).toBe(1) - chat0.rest() - expect(chat0.rows().slice(0, 3)).toEqual(once) - expect(chat0.drawn('chat-member:run')).toBe(1) -}) - -it('draws a bounded tail again once a reader who scrolled back through history returns to it', () => { - // Rows and their status lines are sized so a cut that drops a row's status would draw it back. - const messages = Array.from({ length: 200 }, (_, i) => ({ - ...say(`m${i}`, i % 2 ? 'assistant' : 'user', ''), - blocks: [0, 1].map((line) => ({ type: 'text' as const, text: `message ${i}.${line}` })) - })) - const options = { following: true, live: false, status: true } - const chat0 = mount(messages, options) - const tail = chat0.rows().length - options.following = false - chat0.show(messages) - for (let page = 0; page < 8; page += 1) { - chat0.read(() => chat0.scroller.showFrom(0)) - } - expect(chat0.rows().length).toBeGreaterThan(tail * 2) - - options.following = true - chat0.show(messages) - chat0.read(() => (chat0.scroller.scrollTop = 0)) - expect(chat0.rows().length).toBeLessThanOrEqual(tail) - expect(chat0.rows().at(-1)).toBe(mobileNativeChatRowId('m199')) -}) - -it('holds a row the reader taps open in place, and a reply below waits out a flick', () => { - const later = Array.from({ length: 10 }, (_, i) => say(`t${i}`, 'user', 'later')) - const chat0 = mount([...from('r21'), ...later]) - const header = mobileNativeChatRowId('a22') - chat0.read(() => (chat0.scroller.scrollTop += chat0.scroller.top(header) - 40)) - chat0.scroller.touch('touchstart') - chat0.scroller.touch('touchend') - const before = chat0.scroller.top(header) - chat0.press(header) - resized() - expect(chat0.scroller.top(header)).toBe(before) - - // Touch release can start a fling; it is not evidence the list is at rest. - chat0.scroller.touch('touchstart') - chat0.scroller.scrollTop -= 30 - chat0.scrolled() - chat0.scroller.touch('touchend') - expect(chat0.show([...from('r21'), ...later, say('n1', 'assistant', 'reply')])).toBe(0) - expect(chat0.drawn(mobileNativeChatRowId('n1'))).toBe(0) -}) - -it('at the cap, a trim and an append of equal height hold a parked reader and leave a following one to follow', () => { - const rows = Array.from({ length: 13 }, (_, i) => - say(`m${i}`, i % 2 ? 'assistant' : 'user', `message ${i}`) - ) - for (const options of [ - { following: true, live: false }, - { following: true, live: true }, - { following: false, live: false } - ]) { - const chat0 = mount(rows.slice(0, 12), options) - chat0.read(() => - options.following ? (chat0.scroller.scrollTop = 0) : chat0.scroller.showFrom(50) - ) - const before = { - scrollTop: chat0.scroller.scrollTop, - m4: chat0.scroller.top(mobileNativeChatRowId('m4')) - } - - const writes = chat0.show(rows.slice(1)) - - expect(writes).toBe(options.following ? 0 : 1) - if (options.following) { - expect(chat0.scroller.scrollTop).toBe(before.scrollTop) - } else { - expect(chat0.scroller.top(mobileNativeChatRowId('m4'))).toBe(before.m4) - } - } - - // Sequential and parallel trims split results to opposite sides; orphan results must never inherit a run’s key. - const output = (n: number): NativeChatMessage => ({ - ...say(`o${n}`, 'user', ''), - role: 'tool', - blocks: [{ type: 'tool-result', callId: `c${n}`, output: 'ok' }] - }) - const six = [1, 2, 3, 4, 5, 6] - const calls = (id: string) => - six.map((n) => ({ ...say(`${id}${n}`, 'assistant', ''), blocks: [edit(n)] })) - const outputs = { ...output(1), id: 'U', blocks: six.flatMap((n) => output(n).blocks) } - for (const [source, head, orphan, last, absorbed] of [ - [chat.slice(3, 15), 'a1', 'r1', 11, []], - [calls('p').concat(six.map(output)), 'p1', 'o1', 6, ['o1', 'o2', 'o3', 'o4']], - [calls('q').concat(outputs), 'q1', 'U', 6, ['U']] - ] as const) { - const top = mount([...source, ...rows]) - top.press(mobileNativeChatRowId(head)) - top.read(() => (top.scroller.scrollTop += top.scroller.top('chat-member:call:c6') - 10)) - const trim = (trimmed: number) => { - top.show([...source.slice(trimmed), ...rows, say(`done${trimmed}`, 'assistant', 'Done')]) - const run = top.find(mobileNativeChatRowId(head)) - expect(run.findAll((n) => n.props.testID === 'chat-member:call:c6')).toHaveLength(1) - expect(top.scroller.top('chat-member:call:c6')).toBe(10) - } - trim(1) - expect(top.drawn(mobileNativeChatRowId(orphan))).toBe(1) - trim(2) - trim(4) - top.show([...source, ...rows, say('done4', 'assistant', 'Done')]) - expect(absorbed.map(shownKeys.current)).toEqual(absorbed.map(() => head)) - top.show([...source.slice(last), ...rows, say('done', 'assistant', 'Done')]) - expect(top.drawn(mobileNativeChatRowId(head))).toBe(0) - } - - const reader = mount([...chat.slice(3, 15), ...rows]) - reader.press(mobileNativeChatRowId('a1')) - reader.read(() => (reader.scroller.scrollTop += reader.scroller.top('chat-member:call:c1'))) - const next = reader.scroller.top('chat-member:call:c2') - expect(next).toBeGreaterThan(0) - reader.show([...chat.slice(4, 15), ...rows, say('done', 'assistant', 'Done')]) - expect(reader.scroller.top('chat-member:call:c2')).toBe(next) -}) - -it('a roster keeps its key when the fold moves it, and the rows the reader saw after it stay put', () => { - const sibling = (id: string): NativeChatMessage => ({ - ...say(id, 'user', ''), - role: 'system', - blocks: [ - { type: 'text', text: `Ran subagent ${id}` }, - { type: 'subagent', id: `agent-${id}`, label: id, state: 'completed', groupId: 'turn-1' } - ] - }) - const said = (name: string) => - Array.from({ length: 12 }, (_, i) => say(`${name}${i}`, i % 2 ? 'assistant' : 'user', name)) - const all = [...said('old'), sibling('s1'), ...said('mid'), sibling('s2'), ...said('new')] - const chat0 = mount(all.slice(25)) - const tops = (ids: string[]) => ids.map((id) => chat0.scroller.top(mobileNativeChatRowId(id))) - chat0.read(() => chat0.scroller.showFrom(20)) - const below = tops(['new0', 'new5']) - expect(chat0.show(all)).toBeLessThanOrEqual(1) - expect(tops(['new0', 'new5'])).toEqual(below) - expect(chat0.drawn(mobileNativeChatRowId('s2'))).toBe(1) - chat0.read(() => (chat0.scroller.scrollTop += chat0.scroller.top(mobileNativeChatRowId('s2')))) - const after = tops(['mid0', 'mid5']) - expect(chat0.show(all.slice(13))).toBeLessThanOrEqual(1) - expect(tops(['mid0', 'mid5'])).toEqual(after) - expect(chat0.drawn(mobileNativeChatRowId('s2'))).toBe(1) -}) diff --git a/mobile/src/session/native-chat/mobile-native-chat-send-classification.test.ts b/mobile/src/session/native-chat/mobile-native-chat-send-classification.test.ts deleted file mode 100644 index a916038e77a..00000000000 --- a/mobile/src/session/native-chat/mobile-native-chat-send-classification.test.ts +++ /dev/null @@ -1,52 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { - classifyMobileNativeChatSend, - getMobileNativeChatCommands -} from './mobile-native-chat-send-classification' - -describe('classifyMobileNativeChatSend', () => { - it('recognizes OMP selectors and context commands without claiming generic help', () => { - expect(classifyMobileNativeChatSend('omp', '/switch')).toBe('command') - expect(classifyMobileNativeChatSend('omp', '/compact focus on tests')).toBe('command') - expect(classifyMobileNativeChatSend('omp', '/help')).toBe('unknown-token') - expect(classifyMobileNativeChatSend('omp', '/smol')).toBe('unknown-token') - }) - - it('classifies catalog commands per agent', () => { - expect(classifyMobileNativeChatSend('claude', '/clear')).toBe('command') - expect(classifyMobileNativeChatSend('claude', '/compact')).toBe('command') - expect(classifyMobileNativeChatSend('codex', '/model')).toBe('command') - expect(classifyMobileNativeChatSend('codex', '/permissions')).toBe('command') - }) - - it('treats slash tokens outside the agent catalog as unknown, never chat', () => { - expect(classifyMobileNativeChatSend('claude', '/model sonnet')).toBe('unknown-token') - expect(classifyMobileNativeChatSend('claude', '/cost')).toBe('unknown-token') - expect(classifyMobileNativeChatSend('claude', '/diff')).toBe('unknown-token') - }) - - it('leaves /context off mobile, which has no way to show its answer', () => { - for (const agent of ['openclaude', 'omp']) { - expect(classifyMobileNativeChatSend(agent, '/context')).toBe('unknown-token') - expect(classifyMobileNativeChatSend(agent, '/compact')).toBe('command') - expect(getMobileNativeChatCommands(agent).map(({ name }) => name)).not.toContain('context') - } - }) - - it('keeps prose as chat, including leading-whitespace slash text', () => { - expect(classifyMobileNativeChatSend('claude', 'hello there')).toBe('chat') - expect(classifyMobileNativeChatSend('claude', ' /clear is a command')).toBe('chat') - expect(classifyMobileNativeChatSend('claude', '/usr/bin/python is missing')).toBe( - 'unknown-token' - ) - }) - - it('treats $ tokens as skill grammar only for Codex', () => { - expect(classifyMobileNativeChatSend('codex', '$deploy now')).toBe('unknown-token') - expect(classifyMobileNativeChatSend('claude', '$PATH is empty')).toBe('chat') - }) - - it('defaults to chat when no agent is resolved', () => { - expect(classifyMobileNativeChatSend(null, '/clear')).toBe('chat') - }) -}) diff --git a/mobile/src/session/native-chat/mobile-native-chat-stream-frame.test.ts b/mobile/src/session/native-chat/mobile-native-chat-stream-frame.test.ts deleted file mode 100644 index 29a44951f12..00000000000 --- a/mobile/src/session/native-chat/mobile-native-chat-stream-frame.test.ts +++ /dev/null @@ -1,62 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { - createNativeChatMerger, - replaceList -} from '../../../../src/shared/native-chat/native-chat-merge' -import type { NativeChatMessage } from '../../../../src/shared/native-chat/native-chat-types' -import { applyMobileNativeChatStreamFrame } from './mobile-native-chat-stream-frame' - -function message(id: string): NativeChatMessage { - return { - id, - role: 'assistant', - blocks: [{ type: 'text', text: id }], - timestamp: 0, - source: 'transcript' - } -} - -describe('applyMobileNativeChatStreamFrame', () => { - it('replaces a partially overlapping replay that no longer extends the retained tail', () => { - const merger = createNativeChatMerger() - replaceList(merger, ['old-1', 'shared', 'old-tail'].map(message)) - - // Keep hasMore true so only the contiguity check can reject the interleaved row. - const replay = [message('shared'), message('compacted-summary'), message('old-tail')] - expect( - applyMobileNativeChatStreamFrame({ - merger, - frame: { type: 'snapshot', messages: replay, hasMore: true, beforeOffset: 9 }, - limit: 100, - replaceSnapshot: false - }) - ).toEqual({ - kind: 'messages', - messages: replay, - hasMore: true, - beforeOffset: 9, - windowReplaced: true - }) - }) - - it('replaces retained history when replay metadata says no earlier rows remain', () => { - const merger = createNativeChatMerger() - replaceList(merger, ['removed-1', 'removed-2', 'a', 'b'].map(message)) - - const replay = [message('a'), message('b')] - expect( - applyMobileNativeChatStreamFrame({ - merger, - frame: { type: 'snapshot', messages: replay, hasMore: false, beforeOffset: 0 }, - limit: 100, - replaceSnapshot: false - }) - ).toEqual({ - kind: 'messages', - messages: replay, - hasMore: false, - beforeOffset: 0, - windowReplaced: true - }) - }) -}) diff --git a/mobile/src/session/native-chat/mobile-native-chat-unsent-notices.ts b/mobile/src/session/native-chat/mobile-native-chat-unsent-notices.ts index fb40c24539c..d3416e91524 100644 --- a/mobile/src/session/native-chat/mobile-native-chat-unsent-notices.ts +++ b/mobile/src/session/native-chat/mobile-native-chat-unsent-notices.ts @@ -1,5 +1,5 @@ import { agentJournalSubmissionKey } from '../../../../src/shared/agent-session/journal/agent-session-journal-item-key' -import { mobileAgentSessionWriteNoticeText } from '../agent-session-write-notice-copy' +import { mobileAgentSessionWriteNoticeText } from './agent-session/agent-session-write-notice-copy' import { agentSessionVisibleFailureFacts } from '../../../../src/shared/agent-session/failures/agent-session-visible-failures' import type { NativeChatTurnJournal } from '../../../../src/shared/native-chat/transcript/native-chat-turn-membership' import { dispatchWasWithdrawn } from '../../../../src/shared/agent-session/requests/structured-agent-session-dispatch-rejection' diff --git a/mobile/src/session/mobile-native-chat-host-preference-operations.ts b/mobile/src/session/native-chat/preferences/mobile-native-chat-host-preference-operations.ts similarity index 81% rename from mobile/src/session/mobile-native-chat-host-preference-operations.ts rename to mobile/src/session/native-chat/preferences/mobile-native-chat-host-preference-operations.ts index 459aff6fdc0..d7499d5314b 100644 --- a/mobile/src/session/mobile-native-chat-host-preference-operations.ts +++ b/mobile/src/session/native-chat/preferences/mobile-native-chat-host-preference-operations.ts @@ -1,7 +1,7 @@ -import { bindDeferredRpcOperation, defineRpcOperation } from '../transport/rpc/rpc-operation' -import type { RpcCompatibleReader } from '../transport/rpc/rpc-operation-contract' -import '../../../src/shared/source-control/listing/source-control-group-order' -import { settingsMember, settingsField } from '../settings/mobile-settings-projection' +import { bindDeferredRpcOperation, defineRpcOperation } from '../../../transport/rpc/rpc-operation' +import type { RpcCompatibleReader } from '../../../transport/rpc/rpc-operation-contract' +import '../../../../../src/shared/source-control/listing/source-control-group-order' +import { settingsMember, settingsField } from '../../../settings/mobile-settings-projection' // Missing reports let the caller tell an older host's absence from a reported value. function reportedBooleanSettingReader( diff --git a/mobile/src/session/mobile-native-chat-host-preference.test.tsx b/mobile/src/session/native-chat/preferences/mobile-native-chat-host-preference.test.tsx similarity index 65% rename from mobile/src/session/mobile-native-chat-host-preference.test.tsx rename to mobile/src/session/native-chat/preferences/mobile-native-chat-host-preference.test.tsx index b19ba1fbb4b..83b0adec268 100644 --- a/mobile/src/session/mobile-native-chat-host-preference.test.tsx +++ b/mobile/src/session/native-chat/preferences/mobile-native-chat-host-preference.test.tsx @@ -2,9 +2,9 @@ import { act, create, type ReactTestRenderer } from 'react-test-renderer' import { afterEach, expect, it, vi } from 'vitest' import { useMobileNativeChatQueueFollowUps } from './use-mobile-native-chat-queue-follow-ups' import { useMobileNativeChatCiResultLines } from './use-mobile-native-chat-ci-result-lines' -import type { RpcClient } from '../transport/rpc/rpc-client-contract' -import type { ConnectionState } from '../transport/connection/connection-state' -import type { RpcResponse } from '../transport/rpc/rpc-wire-types' +import type { RpcClient } from '../../../transport/rpc/rpc-client-contract' +import type { ConnectionState } from '../../../transport/connection/connection-state' +import type { RpcResponse } from '../../../transport/rpc/rpc-wire-types' function connection() { let state: ConnectionState = 'connected' @@ -82,71 +82,6 @@ afterEach(() => { renderers.clear() }) -it('re-renders only the consumers of the preference and desktop that changed', async () => { - const a = connection(), - b = connection() - const renders = new Map() - const values = new Map() - const count = (id: string, value: boolean) => { - values.set(id, value) - renders.set(id, (renders.get(id) ?? 0) + 1) - } - function CiLines({ id, client }: { id: string; client: RpcClient }) { - count(id, useMobileNativeChatCiResultLines(client, true)) - return null - } - function FollowUps({ id, client }: { id: string; client: RpcClient }) { - count(id, useMobileNativeChatQueueFollowUps(client, true, id, client, true)) - return null - } - await act(async () => { - renderers.add( - create( - <> - - - - {Array.from({ length: 9 }, (_, index) => ( - - ))} - - ) - ) - }) - await act(async () => {}) - // Ten chats on B share one read and one stream. - expect(b.client.sendRequest).toHaveBeenCalledTimes(1) - expect(b.client.subscribe).toHaveBeenCalledTimes(1) - // B executes the chat and reports CI lines on; A, the paired desktop, hasn't reported. - await act(async () => b.emit({ type: 'nativeChatCiResultLinesChanged', ciResultLines: true })) - expect([values.get('ci-a'), values.get('follow-ups-a'), values.get('ci-b')]).toEqual([ - false, - true, - true - ]) - const settled = new Map(renders) - await act(async () => a.emit({ type: 'nativeChatCiResultLinesChanged', ciResultLines: true })) - expect(values.get('ci-a')).toBe(true) - expect(renders).toEqual(new Map([...settled, ['ci-a', settled.get('ci-a')! + 1]])) - await act(async () => a.emit({ type: 'nativeChatQueueFollowUpsChanged', queueFollowUps: false })) - expect(values.get('follow-ups-a')).toBe(false) - expect(renders).toEqual( - new Map([ - ...settled, - ['ci-a', settled.get('ci-a')! + 1], - ['follow-ups-a', settled.get('follow-ups-a')! + 1] - ]) - ) - const beforeOther = new Map(renders) - await act(async () => b.emit({ type: 'nativeChatCiResultLinesChanged', ciResultLines: false })) - expect(values.get('ci-b')).toBe(false) - expect(renders.get('ci-a')).toBe(beforeOther.get('ci-a')) - expect(renders.get('follow-ups-a')).toBe(beforeOther.get('follow-ups-a')) - // A snapshot-less ready re-reads once for the connection, not once per chat. - await act(async () => b.emit({ type: 'ready', subscriptionId: 'legacy' })) - expect(b.client.sendRequest).toHaveBeenCalledTimes(2) -}) - it('shows CI lines from the last value the paired desktop reported, hidden until it reports one', async () => { const desktop = connection() const values: boolean[] = [] diff --git a/mobile/src/session/mobile-native-chat-host-preference.ts b/mobile/src/session/native-chat/preferences/mobile-native-chat-host-preference.ts similarity index 95% rename from mobile/src/session/mobile-native-chat-host-preference.ts rename to mobile/src/session/native-chat/preferences/mobile-native-chat-host-preference.ts index a25db4207c0..5da3241c9fc 100644 --- a/mobile/src/session/mobile-native-chat-host-preference.ts +++ b/mobile/src/session/native-chat/preferences/mobile-native-chat-host-preference.ts @@ -2,12 +2,12 @@ import { nativeChatCiResultLinesRead, nativeChatQueueFollowUpsRead } from './mobile-native-chat-host-preference-operations' -import type { RpcClient } from '../transport/rpc/rpc-client-contract' +import type { RpcClient } from '../../../transport/rpc/rpc-client-contract' import { subscribeSharedClientEvents, type SharedClientEvent -} from '../transport/connection/shared-client-events' -import { nativeChatQueueFollowUps } from '../../../src/shared/native-chat/input/native-chat-follow-up-behavior' +} from '../../../transport/connection/shared-client-events' +import { nativeChatQueueFollowUps } from '../../../../../src/shared/native-chat/input/native-chat-follow-up-behavior' /** A desktop chat setting the host pushes live: its read, its change event and its ready-snapshot field. */ export type MobileNativeChatHostPreferenceKind = { diff --git a/mobile/src/session/use-mobile-native-chat-ci-result-lines.ts b/mobile/src/session/native-chat/preferences/use-mobile-native-chat-ci-result-lines.ts similarity index 91% rename from mobile/src/session/use-mobile-native-chat-ci-result-lines.ts rename to mobile/src/session/native-chat/preferences/use-mobile-native-chat-ci-result-lines.ts index 8684aa95eb3..7a189a6d890 100644 --- a/mobile/src/session/use-mobile-native-chat-ci-result-lines.ts +++ b/mobile/src/session/native-chat/preferences/use-mobile-native-chat-ci-result-lines.ts @@ -1,5 +1,5 @@ import { useCallback, useSyncExternalStore } from 'react' -import type { RpcClient } from '../transport/rpc/rpc-client-contract' +import type { RpcClient } from '../../../transport/rpc/rpc-client-contract' import { CI_RESULT_LINES_PREFERENCE, mobileNativeChatHostPreference diff --git a/mobile/src/session/use-mobile-native-chat-queue-follow-ups.ts b/mobile/src/session/native-chat/preferences/use-mobile-native-chat-queue-follow-ups.ts similarity index 89% rename from mobile/src/session/use-mobile-native-chat-queue-follow-ups.ts rename to mobile/src/session/native-chat/preferences/use-mobile-native-chat-queue-follow-ups.ts index 882b158db00..201c398ef02 100644 --- a/mobile/src/session/use-mobile-native-chat-queue-follow-ups.ts +++ b/mobile/src/session/native-chat/preferences/use-mobile-native-chat-queue-follow-ups.ts @@ -1,6 +1,6 @@ import { useCallback, useSyncExternalStore } from 'react' -import { nativeChatQueueFollowUps } from '../../../src/shared/native-chat/input/native-chat-follow-up-behavior' -import type { RpcClient } from '../transport/rpc/rpc-client-contract' +import { nativeChatQueueFollowUps } from '../../../../../src/shared/native-chat/input/native-chat-follow-up-behavior' +import type { RpcClient } from '../../../transport/rpc/rpc-client-contract' import { mobileNativeChatHostPreference, QUEUE_FOLLOW_UPS_PREFERENCE diff --git a/mobile/src/session/MobileLinkActionSheet.tsx b/mobile/src/session/native-chat/transcript/MobileLinkActionSheet.tsx similarity index 83% rename from mobile/src/session/MobileLinkActionSheet.tsx rename to mobile/src/session/native-chat/transcript/MobileLinkActionSheet.tsx index 81db7d52d06..6ab27dc905c 100644 --- a/mobile/src/session/MobileLinkActionSheet.tsx +++ b/mobile/src/session/native-chat/transcript/MobileLinkActionSheet.tsx @@ -1,10 +1,10 @@ import { useState } from 'react' import { Copy, ExternalLink, Globe } from 'lucide-react-native' -import { ActionSheetModal, type ActionSheetAction } from '../components/ActionSheetModal' -import { openExternalLink } from '../platform/external-link' -import { useClipboardWriter } from '../platform/clipboard' -import { triggerError, triggerSuccess } from '../platform/haptics' -import { useMobileTranslation } from '../i18n/use-mobile-translation' +import { ActionSheetModal, type ActionSheetAction } from '../../../components/ActionSheetModal' +import { openExternalLink } from '../../../platform/external-link' +import { useClipboardWriter } from '../../../platform/clipboard' +import { triggerError, triggerSuccess } from '../../../platform/haptics' +import { useMobileTranslation } from '../../../i18n/use-mobile-translation' // Choices for a tapped chat link: Orca's browser on the host, the phone's browser, or the clipboard. export function MobileLinkActionSheet(props: { diff --git a/mobile/src/session/native-chat/transcript/MobileNativeChatAgentMessageCard.tsx b/mobile/src/session/native-chat/transcript/MobileNativeChatAgentMessageCard.tsx index f3e0575224e..a7c2b263ac4 100644 --- a/mobile/src/session/native-chat/transcript/MobileNativeChatAgentMessageCard.tsx +++ b/mobile/src/session/native-chat/transcript/MobileNativeChatAgentMessageCard.tsx @@ -11,7 +11,7 @@ import { type AgentMessageHeading } from '../../../../../src/shared/agent-session/agent-message-presentation' import { mobileNativeChatDisplayCopyText } from './mobile-native-chat-display-copy' -import { MobileNativeChatMarkdown } from '../MobileNativeChatMarkdown' +import { MobileNativeChatMarkdown } from './MobileNativeChatMarkdown' import { MobileAgentIcon } from '../../../components/MobileAgentIcon' import { AgentStateDot } from '../../../components/AgentStateDot' import { MobileSourceCopyButton } from '../../../components/MobileSourceCopyButton' diff --git a/mobile/src/session/native-chat/transcript/MobileNativeChatAwaitingInputRow.tsx b/mobile/src/session/native-chat/transcript/MobileNativeChatAwaitingInputRow.tsx index f29c25359ef..9d607c9658b 100644 --- a/mobile/src/session/native-chat/transcript/MobileNativeChatAwaitingInputRow.tsx +++ b/mobile/src/session/native-chat/transcript/MobileNativeChatAwaitingInputRow.tsx @@ -8,7 +8,7 @@ import { colors, spacing, typography } from '../../../theme/mobile-theme' import { themedStyleSheet } from '../../../theme/themed-styles' import { useMobileColorScheme } from '../../../theme/use-mobile-color-scheme' import { scaledType } from './mobile-native-chat-message-styles' -import { MobileNativeChatQuestionText } from '../MobileNativeChatQuestionText' +import { MobileNativeChatQuestionText } from './MobileNativeChatQuestionText' const ICON_SIZE = 15 diff --git a/mobile/src/session/native-chat/transcript/MobileNativeChatBackgroundTaskRun.tsx b/mobile/src/session/native-chat/transcript/MobileNativeChatBackgroundTaskRun.tsx index 029bb7f7076..0e72502a666 100644 --- a/mobile/src/session/native-chat/transcript/MobileNativeChatBackgroundTaskRun.tsx +++ b/mobile/src/session/native-chat/transcript/MobileNativeChatBackgroundTaskRun.tsx @@ -6,7 +6,7 @@ import { INLINE_TEXT_SELECTION } from '../../../components/inline-text-selection import { colors, spacing, typography } from '../../../theme/mobile-theme' import { themedStyleSheet } from '../../../theme/themed-styles' import { useMobileColorScheme } from '../../../theme/use-mobile-color-scheme' -import { sayMobileBackgroundTask } from '../../mobile-background-task-copy' +import { sayMobileBackgroundTask } from '../input/mobile-background-task-copy' import { BackgroundTaskKindIcon } from '../input/MobileNativeChatBackgroundTasks' import { scaledType } from './mobile-native-chat-message-styles' diff --git a/mobile/src/session/native-chat/MobileNativeChatDiffCard.tsx b/mobile/src/session/native-chat/transcript/MobileNativeChatDiffCard.tsx similarity index 85% rename from mobile/src/session/native-chat/MobileNativeChatDiffCard.tsx rename to mobile/src/session/native-chat/transcript/MobileNativeChatDiffCard.tsx index 261373b2835..fa7d1eeecb6 100644 --- a/mobile/src/session/native-chat/MobileNativeChatDiffCard.tsx +++ b/mobile/src/session/native-chat/transcript/MobileNativeChatDiffCard.tsx @@ -1,25 +1,25 @@ import { useMemo } from 'react' import { Pressable, Text, View } from 'react-native' -import { MobileNativeChatOwnedScrollView } from './transcript/MobileNativeChatOwnedScrollView' +import { MobileNativeChatOwnedScrollView } from './MobileNativeChatOwnedScrollView' import { ChevronRight, FileMinus2, FilePen, FilePlus2 } from 'lucide-react-native' -import { nativeChatEditFilePatchText } from '../../../../src/shared/native-chat/tools/native-chat-edit-cards' +import { nativeChatEditFilePatchText } from '../../../../../src/shared/native-chat/tools/native-chat-edit-cards' import { nativeChatEditFileBaseName, nativeChatEditGutterChars, unifiedLineNumber, type NativeChatEditFile, type NativeChatEditLine -} from '../../../../src/shared/native-chat/tools/native-chat-edit-model' -import { nativeChatToolRowVerbCopy } from './transcript/native-chat-tool-row-verb-copy' -import { nativeChatDiffCardCopy } from '../../source-control/review/native-chat-diff-card-copy' -import { useMobileTranslation } from '../../i18n/use-mobile-translation' -import { MobileSourceCopyButton } from '../../components/MobileSourceCopyButton' -import { colors, pressedStyle } from '../../theme/mobile-theme' -import { useMobileColorScheme } from '../../theme/use-mobile-color-scheme' -import { useMobileNativeChatOpenedDetail } from './visual/mobile-native-chat-opened-detail' -import { useMobileNativeChatDisclosure } from './transcript/mobile-native-chat-disclosure-store' -import { toolStyles as styles, toolType } from './transcript/mobile-native-chat-tool-styles' -import { useMobileNativeChatOpenFile } from './mobile-native-chat-open-file-context' +} from '../../../../../src/shared/native-chat/tools/native-chat-edit-model' +import { nativeChatToolRowVerbCopy } from './native-chat-tool-row-verb-copy' +import { nativeChatDiffCardCopy } from '../../../source-control/review/native-chat-diff-card-copy' +import { useMobileTranslation } from '../../../i18n/use-mobile-translation' +import { MobileSourceCopyButton } from '../../../components/MobileSourceCopyButton' +import { colors, pressedStyle } from '../../../theme/mobile-theme' +import { useMobileColorScheme } from '../../../theme/use-mobile-color-scheme' +import { useMobileNativeChatOpenedDetail } from '../visual/mobile-native-chat-opened-detail' +import { useMobileNativeChatDisclosure } from './mobile-native-chat-disclosure-store' +import { toolStyles as styles, toolType } from './mobile-native-chat-tool-styles' +import { useMobileNativeChatOpenFile } from '../mobile-native-chat-open-file-context' function VerbIcon({ kind, size }: { kind: NativeChatEditFile['changeKind']; size: number }) { useMobileColorScheme() diff --git a/mobile/src/session/MobileNativeChatEmptyStateView.tsx b/mobile/src/session/native-chat/transcript/MobileNativeChatEmptyStateView.tsx similarity index 64% rename from mobile/src/session/MobileNativeChatEmptyStateView.tsx rename to mobile/src/session/native-chat/transcript/MobileNativeChatEmptyStateView.tsx index 69e33b7ccad..e58ef3da95d 100644 --- a/mobile/src/session/MobileNativeChatEmptyStateView.tsx +++ b/mobile/src/session/native-chat/transcript/MobileNativeChatEmptyStateView.tsx @@ -1,6 +1,6 @@ import { Text, View } from 'react-native' -import type { NativeChatEmptyStateCopy } from '../../../src/shared/native-chat/native-chat-empty-state' -import { styles } from './native-chat/mobile-native-chat-view-styles' +import type { NativeChatEmptyStateCopy } from '../../../../../src/shared/native-chat/native-chat-empty-state' +import { styles } from '../mobile-native-chat-view-styles' export function MobileNativeChatEmptyStateView({ copy }: { copy: NativeChatEmptyStateCopy }) { return ( diff --git a/mobile/src/session/native-chat/MobileNativeChatFullContent.tsx b/mobile/src/session/native-chat/transcript/MobileNativeChatFullContent.tsx similarity index 87% rename from mobile/src/session/native-chat/MobileNativeChatFullContent.tsx rename to mobile/src/session/native-chat/transcript/MobileNativeChatFullContent.tsx index 537902265eb..aab95c37457 100644 --- a/mobile/src/session/native-chat/MobileNativeChatFullContent.tsx +++ b/mobile/src/session/native-chat/transcript/MobileNativeChatFullContent.tsx @@ -1,27 +1,27 @@ import { useContext, useEffect, useMemo, useState } from 'react' import { Pressable, Text, View, type TextStyle } from 'react-native' -import { truncateToolDetail } from '../../../../src/shared/native-chat/tools/native-chat-tool-summary' +import { truncateToolDetail } from '../../../../../src/shared/native-chat/tools/native-chat-tool-summary' import { isNativeChatToolOutputClipped, nativeChatToolFullPayload, nativeChatToolOutputPartialSizes -} from '../../../../src/shared/native-chat/tools/native-chat-tool-output' +} from '../../../../../src/shared/native-chat/tools/native-chat-tool-output' import type { NativeChatMessage, NativeChatToolResultBlock -} from '../../../../src/shared/native-chat/native-chat-types' -import type { AgentJournalBoundedPayload } from '../../../../src/shared/agent-session/journal/agent-session-journal-types' -import { INLINE_TEXT_SELECTION } from '../../components/inline-text-selection' -import { styles } from './transcript/mobile-native-chat-message-styles' -import { toolStyles } from './transcript/mobile-native-chat-tool-styles' -import { useMobileColorScheme } from '../../theme/use-mobile-color-scheme' -import { useMobileTranslation } from '../../i18n/use-mobile-translation' -import { MobileNativeChatOwnedScrollView } from './transcript/MobileNativeChatOwnedScrollView' +} from '../../../../../src/shared/native-chat/native-chat-types' +import type { AgentJournalBoundedPayload } from '../../../../../src/shared/agent-session/journal/agent-session-journal-types' +import { INLINE_TEXT_SELECTION } from '../../../components/inline-text-selection' +import { styles } from './mobile-native-chat-message-styles' +import { toolStyles } from './mobile-native-chat-tool-styles' +import { useMobileColorScheme } from '../../../theme/use-mobile-color-scheme' +import { useMobileTranslation } from '../../../i18n/use-mobile-translation' +import { MobileNativeChatOwnedScrollView } from './MobileNativeChatOwnedScrollView' import { MobileNativeChatItemSourceContext, readMobileNativeChatItem } from './mobile-native-chat-item-read' -import { pressedStyle } from '../../theme/mobile-theme' +import { pressedStyle } from '../../../theme/mobile-theme' // Keep full-content state per row so live transcript revisions cannot overwrite the reader’s requested expansion. diff --git a/mobile/src/session/native-chat/transcript/MobileNativeChatLiveLine.android.test.ts b/mobile/src/session/native-chat/transcript/MobileNativeChatLiveLine.android.test.ts index 8a7b534e6d5..1a0fcdacd7a 100644 --- a/mobile/src/session/native-chat/transcript/MobileNativeChatLiveLine.android.test.ts +++ b/mobile/src/session/native-chat/transcript/MobileNativeChatLiveLine.android.test.ts @@ -28,7 +28,7 @@ vi.mock('./MobileNativeChatRewindDialog', () => ({ MobileNativeChatRewindDialog: vi.mock('./MobileNativeChatMessageActionsSheet', () => ({ MobileNativeChatMessageActionsSheet: 'MessageActionsSheet' })) -vi.mock('../../MobileLinkActionSheet', () => ({ MobileLinkActionSheet: 'LinkActionSheet' })) +vi.mock('./MobileLinkActionSheet', () => ({ MobileLinkActionSheet: 'LinkActionSheet' })) vi.mock('../visual/MobileNativeChatImageViewer', () => ({ MobileNativeChatImageViewer: 'ImageViewer' })) diff --git a/mobile/src/session/native-chat/transcript/MobileNativeChatLiveLine.tsx b/mobile/src/session/native-chat/transcript/MobileNativeChatLiveLine.tsx index 4b0c5ce1df1..c08be0a7f06 100644 --- a/mobile/src/session/native-chat/transcript/MobileNativeChatLiveLine.tsx +++ b/mobile/src/session/native-chat/transcript/MobileNativeChatLiveLine.tsx @@ -2,7 +2,7 @@ import { useContext } from 'react' import { Pressable, Text, View } from 'react-native' import { ChevronRight } from 'lucide-react-native' import { nativeChatReasoningDisclosureKey } from '../../../../../src/shared/native-chat/transcript/native-chat-reasoning-row' -import { formatMobileNativeChatActiveTurnLabel } from '../native-chat-turn-status-copy' +import { formatMobileNativeChatActiveTurnLabel } from './native-chat-turn-status-copy' import { useMobileTranslation } from '../../../i18n/use-mobile-translation' import { INLINE_TEXT_SELECTION } from '../../../components/inline-text-selection' import { LoadingSpinner } from '../../../components/LoadingSpinner' diff --git a/mobile/src/session/native-chat/MobileNativeChatLongPressContent.tsx b/mobile/src/session/native-chat/transcript/MobileNativeChatLongPressContent.tsx similarity index 100% rename from mobile/src/session/native-chat/MobileNativeChatLongPressContent.tsx rename to mobile/src/session/native-chat/transcript/MobileNativeChatLongPressContent.tsx diff --git a/mobile/src/session/native-chat/MobileNativeChatMarkdown.tsx b/mobile/src/session/native-chat/transcript/MobileNativeChatMarkdown.tsx similarity index 73% rename from mobile/src/session/native-chat/MobileNativeChatMarkdown.tsx rename to mobile/src/session/native-chat/transcript/MobileNativeChatMarkdown.tsx index 399e14a473f..fbd25176b08 100644 --- a/mobile/src/session/native-chat/MobileNativeChatMarkdown.tsx +++ b/mobile/src/session/native-chat/transcript/MobileNativeChatMarkdown.tsx @@ -1,6 +1,6 @@ import type { ComponentProps } from 'react' -import { MobileMarkdown } from '../../components/MobileMarkdown' -import { useMobileNativeChatOpenFile } from './mobile-native-chat-open-file-context' +import { MobileMarkdown } from '../../../components/MobileMarkdown' +import { useMobileNativeChatOpenFile } from '../mobile-native-chat-open-file-context' /** Chat markdown: generic markdown with the chat's file opener, so file paths in any chat text open, * and desktop chat's math delimiters. */ diff --git a/mobile/src/session/native-chat/transcript/MobileNativeChatMessage.status-notices.test.ts b/mobile/src/session/native-chat/transcript/MobileNativeChatMessage.status-notices.test.ts deleted file mode 100644 index 8adab75b691..00000000000 --- a/mobile/src/session/native-chat/transcript/MobileNativeChatMessage.status-notices.test.ts +++ /dev/null @@ -1,282 +0,0 @@ -import { createElement, type ReactNode } from 'react' -import { act, create, type ReactTestRenderer } from 'react-test-renderer' -import { afterEach, describe, expect, it, vi } from 'vitest' -import type { AgentJournalStatusItem } from '../../../../../src/shared/agent-session/journal/agent-session-journal-types' -import { isAdmissibleAgentJournalItemBody } from '../../../../../src/shared/agent-session/journal/agent-session-journal-schemas' -import { projectStructuredItemToNativeChat } from '../../../../../src/shared/agent-session/view/structured-agent-session-projection' -import type { NativeChatMessage } from '../../../../../src/shared/native-chat/native-chat-types' -import { agentSessionFailureFact } from '../../../../../src/shared/agent-session/failures/agent-session-failure' -import { agentSessionFailureWords } from '../../../../../src/shared/agent-session/failures/agent-session-failure-words' -import { colors } from '../../../theme/mobile-theme' -import { activateMobileUiLocale } from '../../../i18n/mobile-i18n' -import { MarkdownLinkHandlerContext } from '../../../components/markdown-link-handler' -import { - MobileNativeChatNoticeContext, - type MobileNativeChatNoticeView -} from '../../mobile-native-chat-notice-context' - -vi.mock('react-native', async () => { - const React = await import('react') - const Text = ({ children, ...props }: { children?: ReactNode }): unknown => - React.createElement('Text', props, children) - return { - ActivityIndicator: 'ActivityIndicator', - Animated: { - Text, - Value: class { - setValue(): void {} - }, - loop: (animation: unknown) => animation, - sequence: () => ({ start: vi.fn(), stop: vi.fn() }), - timing: () => ({ start: vi.fn(), stop: vi.fn() }) - }, - Image: 'Image', - Platform: { OS: 'ios' }, - Pressable: 'Pressable', - ScrollView: ({ children, ...props }: { children?: ReactNode }) => - React.createElement('ScrollView', props, children), - Text, - View: ({ children, ...props }: { children?: ReactNode }) => - React.createElement('View', props, children), - StyleSheet: { create: (styles: unknown) => styles, hairlineWidth: 1 }, - useWindowDimensions: () => ({ width: 400, height: 800 }) - } -}) -vi.mock('expo-clipboard', () => ({ setStringAsync: vi.fn() })) -vi.mock('lucide-react-native', () => ({ - AlertCircle: 'AlertCircle', - AlertTriangle: 'AlertTriangle', - ArrowUp: 'ArrowUp', - Bot: 'Bot', - Brain: 'Brain', - Check: 'Check', - ChevronDown: 'ChevronDown', - ChevronRight: 'ChevronRight', - CircleCheck: 'CircleCheck', - CircleX: 'CircleX', - Copy: 'Copy', - Eye: 'Eye', - FileMinus2: 'FileMinus2', - FilePen: 'FilePen', - FilePlus2: 'FilePlus2', - Folder: 'Folder', - Globe: 'Globe', - Info: 'Info', - ListChecks: 'ListChecks', - MessageSquareMore: 'MessageSquareMore', - Pencil: 'Pencil', - Plug: 'Plug', - Search: 'Search', - SquareChevronRight: 'SquareChevronRight', - SquareTerminal: 'SquareTerminal', - Wrench: 'Wrench' -})) -vi.mock('../../../components/MobileMarkdown', () => ({ MobileMarkdown: 'MobileMarkdown' })) -vi.mock('./MobileNativeChatMessageActionsSheet', () => ({ - MobileNativeChatMessageActionsSheet: 'MessageActionsSheet' -})) - -import { MobileNativeChatMessage } from './MobileNativeChatMessage' - -describe('MobileNativeChatMessage status notices', () => { - let renderer: ReactTestRenderer | null = null - - afterEach(async () => { - act(() => renderer?.unmount()) - renderer = null - await activateMobileUiLocale('en') - }) - - function render(message: NativeChatMessage): ReactTestRenderer { - act(() => { - renderer = create(createElement(MobileNativeChatMessage, { message })) - }) - return renderer! - } - - const statusRow = (body: AgentJournalStatusItem): NativeChatMessage => - projectStructuredItemToNativeChat({ - itemId: 'status', - revision: 1, - sequence: 2, - observedAt: 2, - body - })! - const renderNotice = (body: AgentJournalStatusItem, names: MobileNativeChatNoticeView) => { - act(() => { - renderer = create( - createElement( - MobileNativeChatNoticeContext.Provider, - { value: names }, - createElement(MobileNativeChatMessage, { message: statusRow(body) }) - ) - ) - }) - return renderer!.root.findAll( - (node) => String(node.type) === 'Text' && node.props.selectable === true - )[0]! - } - - it('localizes a canonical failure and discloses its diagnostic only on request', async () => { - await activateMobileUiLocale('fr') - const diagnostic = 'Internal provider diagnostic: modelNotFound' - const notice = renderNotice( - { - kind: 'status', - tone: 'error', - ...agentSessionFailureWords(agentSessionFailureFact('modelUnavailable'), { - agentName: 'Codex', - surface: 'row' - }), - providerFrame: { - provider: 'codex', - kind: 'notification:error', - payload: { - head: diagnostic, - byteLength: diagnostic.length, - digest: 'fixture', - truncated: false - } - } - }, - { hostName: null, agentName: 'Codex' } - ) - expect(String(notice.props.children)).toContain('le modèle sélectionné') - expect(String(notice.props.children)).not.toContain(diagnostic) - const details = () => - renderer!.root.findAll( - (node) => String(node.type) === 'Text' && String(node.props.children).includes(diagnostic) - ) - expect(details()).toHaveLength(0) - const disclosure = renderer!.root.find( - (node) => String(node.type) === 'Pressable' && node.props['aria-expanded'] === false - ) - act(() => disclosure.props.onPress()) - expect(details().length).toBeGreaterThan(0) - act(() => renderer?.unmount()) - const hostAdvice: unknown = { - kind: 'status', - text: 'Custom host advice: use the enterprise model.', - failure: agentSessionFailureFact('modelUnavailable') - } - if (!isAdmissibleAgentJournalItemBody(hostAdvice) || hostAdvice.kind !== 'status') { - throw new Error('Expected host status row') - } - const custom = renderNotice(hostAdvice, { hostName: null, agentName: 'Codex' }) - expect(custom.props.children).toBe('Custom host advice: use the enterprise model.') - }) - - it('links a CI result line to its pull request and commit through the link sheet', () => { - const openLink = vi.fn() - act(() => { - renderer = create( - createElement( - MarkdownLinkHandlerContext.Provider, - { value: openLink }, - createElement(MobileNativeChatMessage, { - message: { - // The journal key percent-encodes the line's client message id. - id: 'orca:pr-event%3Agithub.com%2Facme%2Frepo%233%3A8d5f74b0c1%3A1', - role: 'system', - blocks: [ - { - type: 'text', - text: 'CI failing on repo#3 at 8d5f74b', - presentation: 'pull-request-event', - tone: 'failure' - } - ], - timestamp: 0, - source: 'transcript' - } - }) - ) - ) - }) - const links = renderer!.root.findAll( - (node) => String(node.type) === 'Text' && node.props.accessibilityRole === 'link' - ) - // The whole lead is the PR's target, so a lead the ellipsis cuts still opens it. - expect(links.map((link) => link.props.accessibilityLabel ?? link.props.children)).toEqual([ - 'CI failing on repo#3', - '8d5f74b' - ]) - links.forEach((link) => act(() => link.props.onPress())) - expect(openLink.mock.calls).toEqual([ - ['https://github.com/acme/repo/pull/3'], - ['https://github.com/acme/repo/commit/8d5f74b0c1'] - ]) - }) - - // Protocol-shaped synthetic frames, not a live-provider reproduction. - it.each([ - [ - 'codex', - 'notification:guardianWarning', - 'warning', - 'Codex reported a safety review warning. View details.', - 'Codex a signalé un avertissement de sécurité. Voir les détails.', - colors.statusAmber - ] - ] as const)( - 'discloses the entire available %s notice without tool-output clipping or recovery', - async (provider, kind, tone, heading, french, color) => { - const text = `${'安全 '.repeat(1500)}EXPLANATION_SENTINEL` - const head = `{"partial":"${'é'.repeat(4500)}PAYLOAD_SENTINEL` - const tree = render( - statusRow({ - kind: 'status', - text, - tone, - providerFrame: { - provider, - kind, - payload: { head, byteLength: 99999, digest: 'synthetic', truncated: true } - } - }) - ) - const button = () => - tree.root.find( - (node) => - String(node.type) === 'Pressable' && - node.props.accessibilityLabel?.includes('View details.') - ) - expect(button().props.accessibilityLabel).toBe(heading) - expect(button().props['aria-expanded']).toBe(false) - const detailTexts = () => - tree.root.findAll( - (node) => - String(node.type) === 'Text' && - node.props.selectable === true && - Array.isArray(node.props.children) && - node.props.children.includes(text) - ) - expect(detailTexts()).toHaveLength(0) - act(() => button().props.onPress()) - expect(button().props['aria-expanded']).toBe(true) - const detail = detailTexts()[0] - expect(detail.props.children.join('')).toContain(text) - expect(detail.props.children.join('')).toContain(head) - expect(detail.props.children.join('')).toContain( - 'Provider response truncated (original size: 99999 bytes).' - ) - expect(Object.assign({}, ...detail.props.style)).toMatchObject({ color }) - expect( - tree.root.findAll( - (node) => - String(node.type) === 'Text' && String(node.props.children).includes('Show full output') - ) - ).toHaveLength(0) - await act(() => activateMobileUiLocale('fr')) - const translated = tree.root.find( - (node) => String(node.type) === 'Pressable' && node.props.accessibilityLabel === french - ) - expect(translated.props['aria-expanded']).toBe(true) - expect(detailTexts()[0].props.children.join('')).toContain( - 'Réponse du fournisseur tronquée (taille d’origine : 99999 octets).' - ) - act(() => translated.props.onPress()) - expect(detailTexts()).toHaveLength(0) - } - ) -}) diff --git a/mobile/src/session/native-chat/transcript/MobileNativeChatMessage.tool-result-availability.test.tsx b/mobile/src/session/native-chat/transcript/MobileNativeChatMessage.tool-result-availability.test.tsx index d43988aaf5c..d6b44de0b81 100644 --- a/mobile/src/session/native-chat/transcript/MobileNativeChatMessage.tool-result-availability.test.tsx +++ b/mobile/src/session/native-chat/transcript/MobileNativeChatMessage.tool-result-availability.test.tsx @@ -1,15 +1,7 @@ -import { createElement, Fragment, type ReactNode } from 'react' +import { createElement, type ReactNode } from 'react' import { act, create, type ReactTestInstance, type ReactTestRenderer } from 'react-test-renderer' import { afterEach, describe, expect, it, vi } from 'vitest' import type { NativeChatMessage } from '../../../../../src/shared/native-chat/native-chat-types' -import type { - AgentJournalItemBody, - AgentJournalRenderItem -} from '../../../../../src/shared/agent-session/journal/agent-session-journal-types' - -import { projectStructuredItemsToNativeChat } from '../../../../../src/shared/agent-session/view/structured-agent-session-projection' -import { foldMobileNativeChatMessages } from '../mobile-native-chat-render-data' -import { useMobileNativeChatTurnDisclosure } from './use-mobile-native-chat-turn-disclosure' vi.mock('react-native', async () => { const React = await import('react') @@ -118,21 +110,6 @@ describe('mobile tool result availability', () => { vi.restoreAllMocks() }) - function render(row: NativeChatMessage, openRun = true): ReactTestRenderer { - act(() => { - renderer = create(createElement(MobileNativeChatMessage, { message: row })) - }) - if (openRun) { - press( - renderer!.root.find( - (node) => - String(node.type) === 'Pressable' && node.props.accessibilityLiveRegion === 'polite' - ) - ) - } - return renderer! - } - // The page's window unmounts a row scrolled past; older messages joining its fold change its id. it('keeps what the reader opened in a windowed-out row by its row key', () => { const row = message([ @@ -177,175 +154,4 @@ describe('mobile tool result availability', () => { expect(textIn(renderer!.root)).toContain('first output') expect(textIn(renderer!.root)).not.toContain('second output') }) - - it('gives a named completion to its own call past silent calls, not to the first', () => { - const calls: NativeChatMessage['blocks'] = Array.from({ length: 18 }, (_, index) => ({ - type: 'tool-call', - callId: `call-${index}`, - name: 'Bash', - input: { command: `command ${index}` } - })) - const raw = message([ - ...calls, - { type: 'tool-result', callId: 'call-17', output: 'late named output' } - ]) - const [row] = foldMobileNativeChatMessages([raw], 'claude') - const tree = render(row!) - expect(toolLines(tree.root)).toHaveLength(18) - expect(textIn(tree.root)).not.toContain('late named output') - press(button(tree.root, 'command 17')) - expect(textIn(tree.root)).toContain('late named output') - press(button(tree.root, 'command 17')) - expect(button(tree.root, 'command 0').props.disabled).toBe(true) - }) - - it.each([true, false])( - 'draws derived outputs ahead of a prompt queued while stopping (host scopes: %s)', - (hasScopes) => { - function item( - itemId: string, - sequence: number, - body: AgentJournalItemBody - ): AgentJournalRenderItem { - return { - itemId, - sequence, - body, - revision: 1, - observedAt: sequence, - ...(hasScopes - ? { - turnScope: - sequence <= 2 - ? { kind: 'thread' as const } - : { kind: 'turn' as const, turnItemId: 'turn' } - } - : {}) - } - } - const items = [ - item('prompt', 1, { - kind: 'message', - role: 'user', - blocks: [{ type: 'text', text: 'question' }] - }), - item('turn', 2, { kind: 'turn', turnId: 'turn', userItemId: 'prompt', state: 'running' }), - item('working-call', 3, { - kind: 'tool-call', - callId: 'working', - name: 'Bash', - input: 'still working', - state: 'running' - }), - item('queued', 4, { - kind: 'message', - role: 'user', - blocks: [{ type: 'text', text: 'queued question' }] - }), - item('source', 5, { - kind: 'message', - role: 'assistant', - blocks: [ - { type: 'text', text: 'source context' }, - { type: 'tool-result', callId: 'unavailable-a', output: 'output one\nfull one' }, - { type: 'tool-result', callId: 'unavailable-b', output: 'output two\nfull two' } - ] - }) - ] - let drawn: NativeChatMessage[] = [] - let waiting: string[] = [] - let live: string[] = [] - function Phone({ journal }: { journal: AgentJournalRenderItem[] }): React.JSX.Element { - const raw = projectStructuredItemsToNativeChat(journal).map((row) => - row.id === 'queued' ? { ...row, queued: true as const } : row - ) - const rows = foldMobileNativeChatMessages(raw, 'claude') - const disclosure = useMobileNativeChatTurnDisclosure({ - messages: rows, - enabled: true, - isWorking: true, - stopping: true, - turnJournal: { items: journal, submissions: [] }, - scopeKey: 'remote-host\0folder\0tab' - }) - drawn = Array.from(disclosure.listMessages) - waiting = disclosure.waitingRows.map((row) => row.item.id) - live = drawn.flatMap((row, index) => - disclosure.resolveRow(index, row).activeTurnIsWorking ? [row.id] : [] - ) - return createElement( - Fragment, - null, - ...drawn.map((row, index) => - createElement(MobileNativeChatMessage, { - key: row.id, - message: row, - ...disclosure.resolveRow(index, row), - structuredActivityUi: true - }) - ) - ) - } - act(() => { - renderer = create(createElement(Phone, { journal: items })) - }) - const tree = renderer! - const headers = () => - tree.root.findAll( - (node) => - String(node.type) === 'Pressable' && node.props.accessibilityLiveRegion === 'polite' - ) - for (let index = 0; index < headers().length; index += 1) { - press(headers()[index]!) - } - for (let index = 0; index < toolLines(tree.root).length; index += 1) { - press(toolLines(tree.root)[index]!) - } - const orphan = drawn.find((row) => row.role === 'tool')! - expect(orphan.id).not.toBe('source') - expect(orphan.journalPosition).toEqual({ sequence: 5, index: 0 }) - expect(drawn.map((row) => row.id)).toEqual(['prompt', 'working-call', 'source', orphan.id]) - expect(waiting).toEqual(['queued']) - expect(live).toContain(orphan.id) - expect(toolLines(tree.root)).toHaveLength(3) - expect(textIn(tree.root)).toContain('output one\nfull one') - expect(textIn(tree.root)).toContain('output two\nfull two') - const firstOutput = button(tree.root, 'output one') - act(() => tree.update(createElement(Phone, { journal: structuredClone(items) }))) - expect(drawn.find((row) => row.role === 'tool')?.id).toBe(orphan.id) - expect(waiting).toEqual(['queued']) - expect(button(tree.root, 'output one')).toBe(firstOutput) - expect(foldMobileNativeChatMessages(drawn, 'claude')).toEqual(drawn) - } - ) - - it('keeps duplicate-ID rows independently open as results and later rows arrive', () => { - const initial = message([ - { type: 'tool-call', callId: 'duplicate', name: 'Bash', input: 'first input' }, - { type: 'tool-call', callId: 'duplicate', name: 'Bash', input: 'second input' }, - { type: 'tool-result', callId: 'duplicate', output: 'first output' } - ]) - const tree = render(initial) - const first = button(tree.root, 'first input') - const second = button(tree.root, 'second input') - press(first) - expect(textIn(tree.root)).toContain('first output') - const updated = message([ - { type: 'tool-call', callId: 'duplicate', name: 'Bash', input: 'changed first input' }, - { type: 'tool-call', callId: 'duplicate', name: 'Bash', input: 'changed second input' }, - { type: 'tool-result', callId: 'duplicate', output: 'first output' }, - { type: 'tool-result', callId: 'duplicate', output: 'second output' }, - { type: 'tool-call', callId: 'later', name: 'Bash', input: 'later input' } - ]) - act(() => tree.update(createElement(MobileNativeChatMessage, { message: updated }))) - expect(button(tree.root, 'changed first input')).toBe(first) - expect(button(tree.root, 'changed second input')).toBe(second) - expect(textIn(tree.root)).toContain('first output') - expect(textIn(tree.root)).not.toContain('second output') - press(second) - expect(textIn(tree.root)).toContain('second output') - press(first) - expect(textIn(tree.root)).not.toContain('first output') - expect(textIn(tree.root)).toContain('second output') - }) }) diff --git a/mobile/src/session/native-chat/transcript/MobileNativeChatMessage.tsx b/mobile/src/session/native-chat/transcript/MobileNativeChatMessage.tsx index 57100b34894..ab29aada0df 100644 --- a/mobile/src/session/native-chat/transcript/MobileNativeChatMessage.tsx +++ b/mobile/src/session/native-chat/transcript/MobileNativeChatMessage.tsx @@ -1,7 +1,7 @@ import { memo, useCallback, useContext, useLayoutEffect, useMemo, useRef } from 'react' import { Text, View } from 'react-native' import { INLINE_TEXT_SELECTION } from '../../../components/inline-text-selection' -import { MobileNativeChatLongPressContent as Content } from '../MobileNativeChatLongPressContent' +import { MobileNativeChatLongPressContent as Content } from './MobileNativeChatLongPressContent' import { splitNativeChatBlocks } from '../../../../../src/shared/native-chat/tools/native-chat-tool-fold' import { nativeChatToolRunViewedImages } from '../../../../../src/shared/native-chat/tools/native-chat-tool-viewed-images' import { selectActiveToolCall } from '../../../../../src/shared/native-chat/tools/native-chat-tool-activity' @@ -15,7 +15,7 @@ import { MobileNativeChatGroupedThought, MobileNativeChatReasoningRow } from './MobileNativeChatReasoningRow' -import { mobileNativeChatRowId } from '../../mobile-native-chat-reading-place' +import { mobileNativeChatRowId } from './mobile-native-chat-reading-place' import { nativeChatWorkRunEntries } from '../../../../../src/shared/native-chat/native-chat-work-run' import { nativeChatReasoningDisclosureKey } from '../../../../../src/shared/native-chat/transcript/native-chat-reasoning-row' import { MobileNativeChatTurnStatus } from './MobileNativeChatTurnStatus' @@ -27,7 +27,7 @@ import { MobileNativeChatUserMessageFold } from './MobileNativeChatUserMessageFo import { TextAttachmentActions } from './MobileNativeChatTextAttachmentActions' import { MobileNativeChatMessageMeta } from './MobileNativeChatMessageMeta' import { MobileNativeChatAwaitingInputRow } from './MobileNativeChatAwaitingInputRow' -import { MobileNativeChatResolutionReceipt } from '../MobileNativeChatResolutionReceipt' +import { MobileNativeChatResolutionReceipt } from './MobileNativeChatResolutionReceipt' import { nativeChatAskRunBlocks, nativeChatAskRunSubject @@ -41,7 +41,7 @@ import type { NativeChatTurnStatus } from '../../../../../src/shared/native-chat import { styles } from './mobile-native-chat-message-styles' import { MobileNativeChatAgentMessageCard } from './MobileNativeChatAgentMessageCard' import { MobileNativeChatVisualContext } from '../visual/mobile-native-chat-visual-context' -import { useMobileNativeChatFullMessage } from '../MobileNativeChatFullContent' +import { useMobileNativeChatFullMessage } from './MobileNativeChatFullContent' import { useMobileColorScheme } from '../../../theme/use-mobile-color-scheme' import { useMobileTranslation } from '../../../i18n/use-mobile-translation' import { MobileNativeChatPacedProse } from './MobileNativeChatPacedProse' diff --git a/mobile/src/session/native-chat/transcript/MobileNativeChatNoticeRow.tsx b/mobile/src/session/native-chat/transcript/MobileNativeChatNoticeRow.tsx index 3d4631781cd..c1b8600e34d 100644 --- a/mobile/src/session/native-chat/transcript/MobileNativeChatNoticeRow.tsx +++ b/mobile/src/session/native-chat/transcript/MobileNativeChatNoticeRow.tsx @@ -27,8 +27,8 @@ import { MobileNativeChatForkedFromContext, MobileNativeChatNoticeContext, type MobileNativeChatNoticeView -} from '../../mobile-native-chat-notice-context' -import { MobileNativeChatMarkdown } from '../MobileNativeChatMarkdown' +} from './mobile-native-chat-notice-context' +import { MobileNativeChatMarkdown } from './MobileNativeChatMarkdown' import { INLINE_TEXT_SELECTION } from '../../../components/inline-text-selection' import { colors, radii, spacing, typography } from '../../../theme/mobile-theme' import { themedStyleSheet } from '../../../theme/themed-styles' @@ -36,7 +36,7 @@ import { useMobileColorScheme } from '../../../theme/use-mobile-color-scheme' import { nativeChatHostStatusCopy, nativeChatNoticeCopy } from './native-chat-notice-copy' import { nativeChatOrcaStopSay } from './native-chat-orca-stop-copy' import { nativeChatUsageLimitText } from './native-chat-usage-limit-copy' -import { sayMobileAgentSessionFailure } from '../../agent-session-failure-copy' +import { sayMobileAgentSessionFailure } from '../agent-session/agent-session-failure-copy' import type { Translate } from '../../../i18n/mobile-i18n' import { useMobileTranslation } from '../../../i18n/use-mobile-translation' import { NATIVE_CHAT_STOPPED_BEFORE_START_PRESENTATION } from '../../../../../src/shared/native-chat/native-chat-stopped-before-start' diff --git a/mobile/src/session/native-chat/transcript/MobileNativeChatPageList.tsx b/mobile/src/session/native-chat/transcript/MobileNativeChatPageList.tsx index bc8f623b1cb..3ab666638f9 100644 --- a/mobile/src/session/native-chat/transcript/MobileNativeChatPageList.tsx +++ b/mobile/src/session/native-chat/transcript/MobileNativeChatPageList.tsx @@ -27,14 +27,14 @@ import { mobileNativeChatRowBoxProps, type MobileNativeChatReadingUnit, type MobileNativeChatScrollNode -} from '../../mobile-native-chat-reading-place' +} from './mobile-native-chat-reading-place' import type { MobileNativeChatListHandle } from './use-mobile-native-chat-tail-follow' import type { MobileNativeChatScrollRoots } from './mobile-native-chat-scroll-roots' -import { scrollWritesStopMomentum } from '../../mobile-native-chat-scroll-motion' +import { scrollWritesStopMomentum } from './mobile-native-chat-scroll-motion' import { createMobileNativeChatGrowthHold, MobileNativeChatGrowthHoldContext -} from '../../mobile-native-chat-growth-hold' +} from './mobile-native-chat-growth-hold' const FIRST_ROWS = 24 const DRAW_BATCH = 12 diff --git a/mobile/src/session/native-chat/transcript/MobileNativeChatProse.tsx b/mobile/src/session/native-chat/transcript/MobileNativeChatProse.tsx index 69dc694ba84..f1df5cb06c7 100644 --- a/mobile/src/session/native-chat/transcript/MobileNativeChatProse.tsx +++ b/mobile/src/session/native-chat/transcript/MobileNativeChatProse.tsx @@ -1,7 +1,7 @@ import { useCallback, useContext, useEffect, useState } from 'react' import { Image, Pressable, Text, View } from 'react-native' import { INLINE_TEXT_SELECTION } from '../../../components/inline-text-selection' -import { MobileNativeChatMarkdown } from '../MobileNativeChatMarkdown' +import { MobileNativeChatMarkdown } from './MobileNativeChatMarkdown' import { isImageRefBlock, isTextBlock, diff --git a/mobile/src/session/native-chat/MobileNativeChatQuestionText.tsx b/mobile/src/session/native-chat/transcript/MobileNativeChatQuestionText.tsx similarity index 88% rename from mobile/src/session/native-chat/MobileNativeChatQuestionText.tsx rename to mobile/src/session/native-chat/transcript/MobileNativeChatQuestionText.tsx index ff0069026fb..ccd2cb29a48 100644 --- a/mobile/src/session/native-chat/MobileNativeChatQuestionText.tsx +++ b/mobile/src/session/native-chat/transcript/MobileNativeChatQuestionText.tsx @@ -1,7 +1,7 @@ import type { ComponentProps } from 'react' import { View, type StyleProp, type ViewStyle } from 'react-native' -import { styles as markdownStyles } from '../../components/mobile-markdown-styles' -import { typography } from '../../theme/mobile-theme' +import { styles as markdownStyles } from '../../../components/mobile-markdown-styles' +import { typography } from '../../../theme/mobile-theme' import { MobileNativeChatMarkdown } from './MobileNativeChatMarkdown' type Props = Pick< diff --git a/mobile/src/session/native-chat/transcript/MobileNativeChatReasoningRow.tsx b/mobile/src/session/native-chat/transcript/MobileNativeChatReasoningRow.tsx index d07ead88bed..acda77606de 100644 --- a/mobile/src/session/native-chat/transcript/MobileNativeChatReasoningRow.tsx +++ b/mobile/src/session/native-chat/transcript/MobileNativeChatReasoningRow.tsx @@ -1,4 +1,4 @@ -import { mobileNativeChatMemberId } from '../../mobile-native-chat-reading-place' +import { mobileNativeChatMemberId } from './mobile-native-chat-reading-place' import { useState } from 'react' import { Pressable, Text, View } from 'react-native' import { MobileNativeChatOwnedScrollView } from './MobileNativeChatOwnedScrollView' @@ -10,11 +10,11 @@ import { } from '../../../../../src/shared/native-chat/transcript/native-chat-reasoning-row' import type { NativeChatMessage } from '../../../../../src/shared/native-chat/native-chat-types' import { deriveNativeChatRowContent } from '../../../../../src/shared/native-chat/transcript/native-chat-row-content' -import { useMobileNativeChatFullMessage } from '../MobileNativeChatFullContent' -import { MobileNativeChatMarkdown } from '../MobileNativeChatMarkdown' +import { useMobileNativeChatFullMessage } from './MobileNativeChatFullContent' +import { MobileNativeChatMarkdown } from './MobileNativeChatMarkdown' import { colors } from '../../../theme/mobile-theme' import { useMobileColorScheme } from '../../../theme/use-mobile-color-scheme' -import { MobileNativeChatLongPressContent } from '../MobileNativeChatLongPressContent' +import { MobileNativeChatLongPressContent } from './MobileNativeChatLongPressContent' import { CHAT_PROSE_SCALE, styles } from './mobile-native-chat-message-styles' /** A grouped thought keeps its own source recovery when its original transcript row is hidden. */ diff --git a/mobile/src/session/native-chat/MobileNativeChatResolutionReceipt.tsx b/mobile/src/session/native-chat/transcript/MobileNativeChatResolutionReceipt.tsx similarity index 82% rename from mobile/src/session/native-chat/MobileNativeChatResolutionReceipt.tsx rename to mobile/src/session/native-chat/transcript/MobileNativeChatResolutionReceipt.tsx index 5aaab6a6ce0..4f026ad8cfc 100644 --- a/mobile/src/session/native-chat/MobileNativeChatResolutionReceipt.tsx +++ b/mobile/src/session/native-chat/transcript/MobileNativeChatResolutionReceipt.tsx @@ -5,17 +5,17 @@ import { nativeChatReceiptDevice, nativeChatReceiptSubject, type NativeChatResolvedPrompt -} from '../../../../src/shared/native-chat/native-chat-resolution-receipt' -import { nativeChatReceiptCopy } from '../native-chat-receipt-copy' -import { useMobileTranslation } from '../../i18n/use-mobile-translation' -import { INLINE_TEXT_SELECTION } from '../../components/inline-text-selection' -import { colors, spacing, typography } from '../../theme/mobile-theme' -import { MobileNativeChatAwaitingInputRow } from './transcript/MobileNativeChatAwaitingInputRow' +} from '../../../../../src/shared/native-chat/native-chat-resolution-receipt' +import { nativeChatReceiptCopy } from './native-chat-receipt-copy' +import { useMobileTranslation } from '../../../i18n/use-mobile-translation' +import { INLINE_TEXT_SELECTION } from '../../../components/inline-text-selection' +import { colors, spacing, typography } from '../../../theme/mobile-theme' +import { MobileNativeChatAwaitingInputRow } from './MobileNativeChatAwaitingInputRow' import { MobileNativeChatQuestionText } from './MobileNativeChatQuestionText' -import { scaledType } from './transcript/mobile-native-chat-message-styles' -import { MobileNativeChatMessageTime } from './transcript/MobileNativeChatMessageTime' -import { themedStyleSheet } from '../../theme/themed-styles' -import { useMobileColorScheme } from '../../theme/use-mobile-color-scheme' +import { scaledType } from './mobile-native-chat-message-styles' +import { MobileNativeChatMessageTime } from './MobileNativeChatMessageTime' +import { themedStyleSheet } from '../../../theme/themed-styles' +import { useMobileColorScheme } from '../../../theme/use-mobile-color-scheme' export function MobileNativeChatResolutionReceipt({ body, diff --git a/mobile/src/session/native-chat/transcript/MobileNativeChatRowItemSource.tsx b/mobile/src/session/native-chat/transcript/MobileNativeChatRowItemSource.tsx index fbe0ff64203..2aca8478910 100644 --- a/mobile/src/session/native-chat/transcript/MobileNativeChatRowItemSource.tsx +++ b/mobile/src/session/native-chat/transcript/MobileNativeChatRowItemSource.tsx @@ -7,7 +7,7 @@ import { memo, useContext, useMemo, type ComponentProps } from 'react' import { MobileNativeChatItemSourceContext, MobileNativeChatRootItemSourceContext -} from '../mobile-native-chat-item-read' +} from './mobile-native-chat-item-read' import { MobileNativeChatMessage } from './MobileNativeChatMessage' import { resolveMobileNativeChatRowProps, diff --git a/mobile/src/session/native-chat/transcript/MobileNativeChatRowOverlaysHost.test.tsx b/mobile/src/session/native-chat/transcript/MobileNativeChatRowOverlaysHost.test.tsx index b103c43ec36..c6a5a70f8f6 100644 --- a/mobile/src/session/native-chat/transcript/MobileNativeChatRowOverlaysHost.test.tsx +++ b/mobile/src/session/native-chat/transcript/MobileNativeChatRowOverlaysHost.test.tsx @@ -29,7 +29,7 @@ vi.mock('./MobileNativeChatRewindDialog', () => ({ MobileNativeChatRewindDialog: vi.mock('./MobileNativeChatMessageActionsSheet', () => ({ MobileNativeChatMessageActionsSheet: 'MessageActionsSheet' })) -vi.mock('../../MobileLinkActionSheet', () => ({ MobileLinkActionSheet: 'LinkActionSheet' })) +vi.mock('./MobileLinkActionSheet', () => ({ MobileLinkActionSheet: 'LinkActionSheet' })) vi.mock('../visual/MobileImageViewerActions', () => ({ MobileImageViewerActions: 'ImageViewerActions' })) diff --git a/mobile/src/session/native-chat/transcript/MobileNativeChatRowOverlaysHost.tsx b/mobile/src/session/native-chat/transcript/MobileNativeChatRowOverlaysHost.tsx index 04c59b46132..49f233a0224 100644 --- a/mobile/src/session/native-chat/transcript/MobileNativeChatRowOverlaysHost.tsx +++ b/mobile/src/session/native-chat/transcript/MobileNativeChatRowOverlaysHost.tsx @@ -5,7 +5,7 @@ import { triggerMediumImpact } from '../../../platform/haptics' import { MobileNativeChatImageViewer } from '../visual/MobileNativeChatImageViewer' import { MobileImageViewerActions } from '../visual/MobileImageViewerActions' import { MobileNativeChatMessageActionsSheet } from './MobileNativeChatMessageActionsSheet' -import { MobileLinkActionSheet } from '../../MobileLinkActionSheet' +import { MobileLinkActionSheet } from './MobileLinkActionSheet' import { MarkdownLinkHandlerContext } from '../../../components/markdown-link-handler' import { MobileNativeChatRowOverlaysContext, diff --git a/mobile/src/session/MobileNativeChatScrollRootsBoundary.tsx b/mobile/src/session/native-chat/transcript/MobileNativeChatScrollRootsBoundary.tsx similarity index 86% rename from mobile/src/session/MobileNativeChatScrollRootsBoundary.tsx rename to mobile/src/session/native-chat/transcript/MobileNativeChatScrollRootsBoundary.tsx index 3c75a385228..9dc4cf30b88 100644 --- a/mobile/src/session/MobileNativeChatScrollRootsBoundary.tsx +++ b/mobile/src/session/native-chat/transcript/MobileNativeChatScrollRootsBoundary.tsx @@ -1,7 +1,7 @@ import { Component } from 'react' import { Platform } from 'react-native' -import type { MobileNativeChatRowKeys } from './native-chat/transcript/mobile-native-chat-row-keys' -import type { MobileNativeChatScrollRoots } from './native-chat/transcript/mobile-native-chat-scroll-roots' +import type { MobileNativeChatRowKeys } from './mobile-native-chat-row-keys' +import type { MobileNativeChatScrollRoots } from './mobile-native-chat-scroll-roots' type Props = { children?: React.ReactNode diff --git a/mobile/src/session/native-chat/transcript/MobileNativeChatToolLine.tsx b/mobile/src/session/native-chat/transcript/MobileNativeChatToolLine.tsx index 39558247e75..53e3f3e2650 100644 --- a/mobile/src/session/native-chat/transcript/MobileNativeChatToolLine.tsx +++ b/mobile/src/session/native-chat/transcript/MobileNativeChatToolLine.tsx @@ -26,7 +26,7 @@ import { colors, pressedStyle } from '../../../theme/mobile-theme' import { useMobileColorScheme } from '../../../theme/use-mobile-color-scheme' import { highlightMobileCode } from '../../../files/session-documents/mobile-file-syntax' import { MobileNativeChatToolGlyph } from './MobileNativeChatToolIcon' -import { MobileNativeChatToolOutput } from '../MobileNativeChatFullContent' +import { MobileNativeChatToolOutput } from './MobileNativeChatFullContent' import { useMobileNativeChatOpenedDetail } from '../visual/mobile-native-chat-opened-detail' import { useMobileNativeChatDisclosure } from './mobile-native-chat-disclosure-store' import { toolStyles as styles, toolType } from './mobile-native-chat-tool-styles' diff --git a/mobile/src/session/native-chat/transcript/MobileNativeChatToolRun.tsx b/mobile/src/session/native-chat/transcript/MobileNativeChatToolRun.tsx index 852d0421203..2833156b26b 100644 --- a/mobile/src/session/native-chat/transcript/MobileNativeChatToolRun.tsx +++ b/mobile/src/session/native-chat/transcript/MobileNativeChatToolRun.tsx @@ -33,7 +33,7 @@ import { colors, pressedStyle } from '../../../theme/mobile-theme' import { useMobileColorScheme } from '../../../theme/use-mobile-color-scheme' import { MobileNativeChatToolGlyph } from './MobileNativeChatToolIcon' import { MobileNativeChatToolLine } from './MobileNativeChatToolLine' -import { MobileNativeChatDiffCard } from '../MobileNativeChatDiffCard' +import { MobileNativeChatDiffCard } from './MobileNativeChatDiffCard' import { MobileNativeChatTaskList } from '../input/MobileNativeChatTaskList' import { MobileNativeChatOpenedDetailContext } from '../visual/mobile-native-chat-opened-detail' import { @@ -42,7 +42,7 @@ import { useMobileNativeChatDisclosure } from './mobile-native-chat-disclosure-store' import { toolStyles as styles, toolType } from './mobile-native-chat-tool-styles' -import { mobileNativeChatMemberId } from '../../mobile-native-chat-reading-place' +import { mobileNativeChatMemberId } from './mobile-native-chat-reading-place' import { MobileNativeChatOwnedScrollView } from './MobileNativeChatOwnedScrollView' import type { MobileNativeChatToolRunAsides, diff --git a/mobile/src/session/native-chat/transcript/MobileNativeChatTurnDiffRollup.tsx b/mobile/src/session/native-chat/transcript/MobileNativeChatTurnDiffRollup.tsx index cf68fbc59a4..7ab1d87549a 100644 --- a/mobile/src/session/native-chat/transcript/MobileNativeChatTurnDiffRollup.tsx +++ b/mobile/src/session/native-chat/transcript/MobileNativeChatTurnDiffRollup.tsx @@ -6,7 +6,7 @@ import { type NativeChatTurnDiff, type NativeChatTurnDiffFile } from '../../../../../src/shared/native-chat/tools/native-chat-turn-diffs' -import { MobileNativeChatDiffCard } from '../MobileNativeChatDiffCard' +import { MobileNativeChatDiffCard } from './MobileNativeChatDiffCard' import { useMobileNativeChatDisclosure } from './mobile-native-chat-disclosure-store' import { useMobileTranslation } from '../../../i18n/use-mobile-translation' import { useMobileColorScheme } from '../../../theme/use-mobile-color-scheme' diff --git a/mobile/src/session/native-chat/transcript/MobileNativeChatTurnStatus.tsx b/mobile/src/session/native-chat/transcript/MobileNativeChatTurnStatus.tsx index c3066449b9e..0a10c804d48 100644 --- a/mobile/src/session/native-chat/transcript/MobileNativeChatTurnStatus.tsx +++ b/mobile/src/session/native-chat/transcript/MobileNativeChatTurnStatus.tsx @@ -5,7 +5,7 @@ import { nativeChatElapsedSeconds } from '../../../../../src/shared/native-chat/ import { formatMobileNativeChatTurnStatusLabel, nativeChatTurnStatusCopy -} from '../native-chat-turn-status-copy' +} from './native-chat-turn-status-copy' import { useMobileTranslation } from '../../../i18n/use-mobile-translation' import type { AgentTurnOutcome } from '../../../../../src/shared/agent-status/lifecycle/agent-turn-outcome' import { colors, spacing, typography } from '../../../theme/mobile-theme' diff --git a/mobile/src/session/native-chat/transcript/MobileNativeChatUsageLimitStatus.tsx b/mobile/src/session/native-chat/transcript/MobileNativeChatUsageLimitStatus.tsx index 32644911373..2aabf7eee08 100644 --- a/mobile/src/session/native-chat/transcript/MobileNativeChatUsageLimitStatus.tsx +++ b/mobile/src/session/native-chat/transcript/MobileNativeChatUsageLimitStatus.tsx @@ -11,7 +11,7 @@ import { INLINE_TEXT_SELECTION } from '../../../components/inline-text-selection import { MobileNativeChatNoticePill } from './MobileNativeChatNoticePill' import { scaledType } from './mobile-native-chat-message-styles' import { nativeChatUsageLimitStatusText } from './native-chat-usage-limit-copy' -import { MobileNativeChatNoticeContext } from '../../mobile-native-chat-notice-context' +import { MobileNativeChatNoticeContext } from './mobile-native-chat-notice-context' /** True from the reset on; re-renders once when it passes. */ function useResetPassed(resetsAt: number | undefined): boolean { diff --git a/mobile/src/session/native-chat/transcript/MobileNativeChatUserMessageFold.tsx b/mobile/src/session/native-chat/transcript/MobileNativeChatUserMessageFold.tsx index 77030a4d412..9a757b6741d 100644 --- a/mobile/src/session/native-chat/transcript/MobileNativeChatUserMessageFold.tsx +++ b/mobile/src/session/native-chat/transcript/MobileNativeChatUserMessageFold.tsx @@ -9,7 +9,7 @@ import { colors, spacing, typography, pressedStyle } from '../../../theme/mobile import { themedStyleSheet } from '../../../theme/themed-styles' import { useMobileColorScheme } from '../../../theme/use-mobile-color-scheme' import { CHAT_PROSE_SCALE } from './mobile-native-chat-message-styles' -import type { useMobileNativeChatFullMessage } from '../MobileNativeChatFullContent' +import type { useMobileNativeChatFullMessage } from './MobileNativeChatFullContent' import { useMobileTranslation } from '../../../i18n/use-mobile-translation' const FOLDED_HEIGHT = diff --git a/mobile/src/session/mobile-native-chat-growth-hold.ts b/mobile/src/session/native-chat/transcript/mobile-native-chat-growth-hold.ts similarity index 100% rename from mobile/src/session/mobile-native-chat-growth-hold.ts rename to mobile/src/session/native-chat/transcript/mobile-native-chat-growth-hold.ts diff --git a/mobile/src/session/native-chat/mobile-native-chat-item-read.ts b/mobile/src/session/native-chat/transcript/mobile-native-chat-item-read.ts similarity index 77% rename from mobile/src/session/native-chat/mobile-native-chat-item-read.ts rename to mobile/src/session/native-chat/transcript/mobile-native-chat-item-read.ts index c1dd1209ce7..ac6557bf371 100644 --- a/mobile/src/session/native-chat/mobile-native-chat-item-read.ts +++ b/mobile/src/session/native-chat/transcript/mobile-native-chat-item-read.ts @@ -1,11 +1,11 @@ import { createContext, type ContextType } from 'react' import * as z from 'zod' -import { isAdmissibleAgentJournalRenderItem } from '../../../../src/shared/agent-session/journal/agent-session-journal-schemas' -import type { AgentJournalRenderItem } from '../../../../src/shared/agent-session/journal/agent-session-journal-types' -import { bindDeferredRpcOperation, defineRpcOperation } from '../../transport/rpc/rpc-operation' -import { rpcResultVariant } from '../../transport/rpc/rpc-operation-result-reader' -import type { MobileNativeChatVisualSource } from './visual/mobile-native-chat-visual-read' -import type { MobileNativeChatMessageDetail } from './transcript/use-mobile-native-chat-message-detail' +import { isAdmissibleAgentJournalRenderItem } from '../../../../../src/shared/agent-session/journal/agent-session-journal-schemas' +import type { AgentJournalRenderItem } from '../../../../../src/shared/agent-session/journal/agent-session-journal-types' +import { bindDeferredRpcOperation, defineRpcOperation } from '../../../transport/rpc/rpc-operation' +import { rpcResultVariant } from '../../../transport/rpc/rpc-operation-result-reader' +import type { MobileNativeChatVisualSource } from '../visual/mobile-native-chat-visual-read' +import type { MobileNativeChatMessageDetail } from './use-mobile-native-chat-message-detail' const itemReplySchema = z.object({ item: z.custom(isAdmissibleAgentJournalRenderItem).nullable() diff --git a/mobile/src/session/native-chat/mobile-native-chat-list-footer.tsx b/mobile/src/session/native-chat/transcript/mobile-native-chat-list-footer.tsx similarity index 85% rename from mobile/src/session/native-chat/mobile-native-chat-list-footer.tsx rename to mobile/src/session/native-chat/transcript/mobile-native-chat-list-footer.tsx index ccfd71a9f9d..5435ee5257e 100644 --- a/mobile/src/session/native-chat/mobile-native-chat-list-footer.tsx +++ b/mobile/src/session/native-chat/transcript/mobile-native-chat-list-footer.tsx @@ -1,5 +1,5 @@ import { Fragment, type ReactElement } from 'react' -import type { NativeChatMessage } from '../../../../src/shared/native-chat/native-chat-types' +import type { NativeChatMessage } from '../../../../../src/shared/native-chat/native-chat-types' type MobileNativeChatListRow = { item: NativeChatMessage; index: number } diff --git a/mobile/src/session/native-chat/mobile-native-chat-list-header.tsx b/mobile/src/session/native-chat/transcript/mobile-native-chat-list-header.tsx similarity index 93% rename from mobile/src/session/native-chat/mobile-native-chat-list-header.tsx rename to mobile/src/session/native-chat/transcript/mobile-native-chat-list-header.tsx index eca153e8ecf..b65201a55d9 100644 --- a/mobile/src/session/native-chat/mobile-native-chat-list-header.tsx +++ b/mobile/src/session/native-chat/transcript/mobile-native-chat-list-header.tsx @@ -1,8 +1,8 @@ import { useEffect, useState, type ReactElement, type ReactNode } from 'react' import { ActivityIndicator, Animated, Easing, Platform, Pressable, Text, View } from 'react-native' -import { colors } from '../../theme/mobile-theme' -import { styles } from './mobile-native-chat-view-styles' -import type { OlderPagePhase } from '../use-mobile-older-page-loader' +import { colors } from '../../../theme/mobile-theme' +import { styles } from '../mobile-native-chat-view-styles' +import type { OlderPagePhase } from './use-mobile-older-page-loader' const LOAD_EARLIER_FAILED = "Couldn't load earlier messages" const LOAD_EARLIER_RETRY = 'Try Again' diff --git a/mobile/src/session/mobile-native-chat-notice-context.ts b/mobile/src/session/native-chat/transcript/mobile-native-chat-notice-context.ts similarity index 84% rename from mobile/src/session/mobile-native-chat-notice-context.ts rename to mobile/src/session/native-chat/transcript/mobile-native-chat-notice-context.ts index bcf6ab8ab79..24c84092a51 100644 --- a/mobile/src/session/mobile-native-chat-notice-context.ts +++ b/mobile/src/session/native-chat/transcript/mobile-native-chat-notice-context.ts @@ -1,6 +1,6 @@ import { createContext } from 'react' -import type { MobileStructuredInterruptedContinue } from './use-mobile-structured-interrupted-continue' -import type { MobileNativeChatUsageLimit } from './native-chat/use-mobile-native-chat-usage-limit' +import type { MobileStructuredInterruptedContinue } from '../composer/use-mobile-structured-interrupted-continue' +import type { MobileNativeChatUsageLimit } from '../use-mobile-native-chat-usage-limit' /** What a notice row needs: the Orca host behind the chat (null when unnamed), the agent, and Continue for an Orca-stopped turn. */ export type MobileNativeChatNoticeView = { diff --git a/mobile/src/session/native-chat/mobile-native-chat-pending-echo.ts b/mobile/src/session/native-chat/transcript/mobile-native-chat-pending-echo.ts similarity index 91% rename from mobile/src/session/native-chat/mobile-native-chat-pending-echo.ts rename to mobile/src/session/native-chat/transcript/mobile-native-chat-pending-echo.ts index 642696fbac1..00ef55a7594 100644 --- a/mobile/src/session/native-chat/mobile-native-chat-pending-echo.ts +++ b/mobile/src/session/native-chat/transcript/mobile-native-chat-pending-echo.ts @@ -1,15 +1,15 @@ -import type { NativeChatMessage } from '../../../../src/shared/native-chat/native-chat-types' -import type { MobileNativeChatDraftDestination } from './composer/mobile-native-chat-draft-inputs' +import type { NativeChatMessage } from '../../../../../src/shared/native-chat/native-chat-types' +import type { MobileNativeChatDraftDestination } from '../composer/mobile-native-chat-draft-inputs' import { assignNativeChatPendingOccurrence, nativeChatPendingContentKey -} from '../../../../src/shared/native-chat/transcript/native-chat-pending-occurrence' +} from '../../../../../src/shared/native-chat/transcript/native-chat-pending-occurrence' import { NATIVE_CHAT_PENDING_SEND_LIMIT, prunePendingSends, visibleNativeChatPendingSends, type NativeChatPendingSend -} from '../../../../src/shared/native-chat/transcript/native-chat-pending-sends' +} from '../../../../../src/shared/native-chat/transcript/native-chat-pending-sends' export type MobileNativeChatPendingMessage = NativeChatPendingSend & { // Phone-local preview URIs; these echoes retire only once their preview binds to a transcript row. diff --git a/mobile/src/session/native-chat/transcript/mobile-native-chat-projection-sources.ts b/mobile/src/session/native-chat/transcript/mobile-native-chat-projection-sources.ts index d0e4be11ea1..48f57f9bf12 100644 --- a/mobile/src/session/native-chat/transcript/mobile-native-chat-projection-sources.ts +++ b/mobile/src/session/native-chat/transcript/mobile-native-chat-projection-sources.ts @@ -7,7 +7,7 @@ import { nativeChatCommandOutputParentId, surfaceNativeChatCommandOutputs } from '../../../../../src/shared/native-chat/tools/native-chat-command-output' -import { isMobileNativeChatSource } from '../mobile-native-chat-render-data' +import { isMobileNativeChatSource } from './mobile-native-chat-render-data' export type MobileNativeChatProjectionSource = { raw: NativeChatMessage diff --git a/mobile/src/session/native-chat/transcript/mobile-native-chat-projection-tail.ts b/mobile/src/session/native-chat/transcript/mobile-native-chat-projection-tail.ts index adc0bc0f0df..dd964726853 100644 --- a/mobile/src/session/native-chat/transcript/mobile-native-chat-projection-tail.ts +++ b/mobile/src/session/native-chat/transcript/mobile-native-chat-projection-tail.ts @@ -19,7 +19,7 @@ import { groupNativeChatFoldUnitMembers, type NativeChatFoldUnit as Unit } from '../../../../../src/shared/native-chat/transcript/native-chat-fold-units' -import { finishMobileNativeChatMessages } from '../mobile-native-chat-render-data' +import { finishMobileNativeChatMessages } from './mobile-native-chat-render-data' // A tail harness row that is its own image unit and no roster member leaves every earlier unit as it was. function staysInTail(harness: NativeChatMessage): boolean { diff --git a/mobile/src/session/native-chat/transcript/mobile-native-chat-projection.ts b/mobile/src/session/native-chat/transcript/mobile-native-chat-projection.ts index e7b598ab6c2..af6785bfc4d 100644 --- a/mobile/src/session/native-chat/transcript/mobile-native-chat-projection.ts +++ b/mobile/src/session/native-chat/transcript/mobile-native-chat-projection.ts @@ -12,7 +12,7 @@ import { import { finishMobileNativeChatMessages, foldMobileNativeChatMessages -} from '../mobile-native-chat-render-data' +} from './mobile-native-chat-render-data' import { prepareMobileNativeChatSources, type MobileNativeChatProjectionSource diff --git a/mobile/src/session/native-chat/mobile-native-chat-reading-hold.ts b/mobile/src/session/native-chat/transcript/mobile-native-chat-reading-hold.ts similarity index 97% rename from mobile/src/session/native-chat/mobile-native-chat-reading-hold.ts rename to mobile/src/session/native-chat/transcript/mobile-native-chat-reading-hold.ts index 9f741f237b5..e865435de65 100644 --- a/mobile/src/session/native-chat/mobile-native-chat-reading-hold.ts +++ b/mobile/src/session/native-chat/transcript/mobile-native-chat-reading-hold.ts @@ -1,4 +1,4 @@ -import { visible } from './mobile-native-chat-lower-geometry' +import { visible } from '../mobile-native-chat-lower-geometry' export function createMobileNativeChatReadingHold(viewport: HTMLElement, content: HTMLElement) { let hold: { element: HTMLElement; offset: number } | null = null diff --git a/mobile/src/session/mobile-native-chat-reading-place.ts b/mobile/src/session/native-chat/transcript/mobile-native-chat-reading-place.ts similarity index 96% rename from mobile/src/session/mobile-native-chat-reading-place.ts rename to mobile/src/session/native-chat/transcript/mobile-native-chat-reading-place.ts index 14e486b65a5..705e2fad33c 100644 --- a/mobile/src/session/mobile-native-chat-reading-place.ts +++ b/mobile/src/session/native-chat/transcript/mobile-native-chat-reading-place.ts @@ -1,9 +1,9 @@ -import type { MobileNativeChatRowKeys } from './native-chat/transcript/mobile-native-chat-row-keys' +import type { MobileNativeChatRowKeys } from './mobile-native-chat-row-keys' import { mobileNativeChatReadingParts, mobileNativeChatScrollRootKey -} from './native-chat/transcript/mobile-native-chat-scroll-root-handle' -import type { MobileNativeChatScrollRoots } from './native-chat/transcript/mobile-native-chat-scroll-roots' +} from './mobile-native-chat-scroll-root-handle' +import type { MobileNativeChatScrollRoots } from './mobile-native-chat-scroll-roots' type Box = { top: number; bottom: number } diff --git a/mobile/src/session/native-chat/mobile-native-chat-render-data.ts b/mobile/src/session/native-chat/transcript/mobile-native-chat-render-data.ts similarity index 77% rename from mobile/src/session/native-chat/mobile-native-chat-render-data.ts rename to mobile/src/session/native-chat/transcript/mobile-native-chat-render-data.ts index 9065b441ab8..bd71aadc79d 100644 --- a/mobile/src/session/native-chat/mobile-native-chat-render-data.ts +++ b/mobile/src/session/native-chat/transcript/mobile-native-chat-render-data.ts @@ -1,25 +1,25 @@ -import { formatAgentTypeLabel } from '../../../../src/shared/agent-status/presentation/agent-type-label' -import { describeLoadError } from '../../components/load-error-description' -import type { NativeChatEmptyStateCopy } from '../../../../src/shared/native-chat/native-chat-empty-state' -import { isRootAgentJournalItem } from '../../../../src/shared/agent-session/journal/agent-session-journal-producer' -import { stripNoiseMessages } from '../../../../src/shared/native-chat/native-chat-noise' -import { nativeChatStreamingMessage } from '../../../../src/shared/native-chat/native-chat-streaming' -import { isWordlessProviderFrameMessage } from '../../../../src/shared/native-chat/native-chat-provider-frame-summary' +import { formatAgentTypeLabel } from '../../../../../src/shared/agent-status/presentation/agent-type-label' +import { describeLoadError } from '../../../components/load-error-description' +import type { NativeChatEmptyStateCopy } from '../../../../../src/shared/native-chat/native-chat-empty-state' +import { isRootAgentJournalItem } from '../../../../../src/shared/agent-session/journal/agent-session-journal-producer' +import { stripNoiseMessages } from '../../../../../src/shared/native-chat/native-chat-noise' +import { nativeChatStreamingMessage } from '../../../../../src/shared/native-chat/native-chat-streaming' +import { isWordlessProviderFrameMessage } from '../../../../../src/shared/native-chat/native-chat-provider-frame-summary' import { foldToolMessages, isUndrawnProviderFrameMessage -} from '../../../../src/shared/native-chat/tools/native-chat-tool-fold' -import { projectNativeChatTaskListFrames } from '../../../../src/shared/native-chat/input/native-chat-task-list-frames' -import { foldSubagentItems } from '../../../../src/shared/native-chat/transcript/native-chat-subagent-items' -import { prepareNativeChatMessages } from '../../../../src/shared/native-chat/transcript/native-chat-message-preparation' +} from '../../../../../src/shared/native-chat/tools/native-chat-tool-fold' +import { projectNativeChatTaskListFrames } from '../../../../../src/shared/native-chat/input/native-chat-task-list-frames' +import { foldSubagentItems } from '../../../../../src/shared/native-chat/transcript/native-chat-subagent-items' +import { prepareNativeChatMessages } from '../../../../../src/shared/native-chat/transcript/native-chat-message-preparation' import { isImageRefBlock, type NativeChatMessage -} from '../../../../src/shared/native-chat/native-chat-types' -import type { AgentType } from '../../../../src/shared/agent-status/contracts/agent-status-types' -import type { MobileNativeChatStatus } from './mobile-native-chat-session-status' -import { orderNativeChatDisplayMessages } from '../../../../src/shared/native-chat/transcript/native-chat-message-order' -import { translate } from '../../i18n/mobile-i18n' +} from '../../../../../src/shared/native-chat/native-chat-types' +import type { AgentType } from '../../../../../src/shared/agent-status/contracts/agent-status-types' +import type { MobileNativeChatStatus } from '../mobile-native-chat-session-status' +import { orderNativeChatDisplayMessages } from '../../../../../src/shared/native-chat/transcript/native-chat-message-order' +import { translate } from '../../../i18n/mobile-i18n' function mobileNativeChatEmptyStateCopy( kind: 'notFound' | 'empty' | 'error', diff --git a/mobile/src/session/native-chat/transcript/mobile-native-chat-row-keys.ts b/mobile/src/session/native-chat/transcript/mobile-native-chat-row-keys.ts index 04edddf3975..f9ed5e011dd 100644 --- a/mobile/src/session/native-chat/transcript/mobile-native-chat-row-keys.ts +++ b/mobile/src/session/native-chat/transcript/mobile-native-chat-row-keys.ts @@ -5,7 +5,7 @@ import { updateMobileNativeChatRunDescriptors, type MobileNativeChatRunHistory, type MobileNativeChatRunPresentation -} from '../mobile-native-chat-run-descriptors' +} from './mobile-native-chat-run-descriptors' import { isSubagentGroupBlock, isToolResultBlock, diff --git a/mobile/src/session/native-chat/mobile-native-chat-run-descriptors.ts b/mobile/src/session/native-chat/transcript/mobile-native-chat-run-descriptors.ts similarity index 86% rename from mobile/src/session/native-chat/mobile-native-chat-run-descriptors.ts rename to mobile/src/session/native-chat/transcript/mobile-native-chat-run-descriptors.ts index 002948aceb0..9eff1ad301e 100644 --- a/mobile/src/session/native-chat/mobile-native-chat-run-descriptors.ts +++ b/mobile/src/session/native-chat/transcript/mobile-native-chat-run-descriptors.ts @@ -1,10 +1,10 @@ -import type { NativeChatMessage } from '../../../../src/shared/native-chat/native-chat-types' -import type { NativeChatResolvedPrompt } from '../../../../src/shared/native-chat/native-chat-resolution-receipt' -import { splitNativeChatBlocks } from '../../../../src/shared/native-chat/tools/native-chat-tool-fold' -import { nativeChatWorkRunEntries } from '../../../../src/shared/native-chat/native-chat-work-run' -import { nativeChatAskRunBlocks } from '../../../../src/shared/native-chat/input/native-chat-ask-row' -import type { MobileNativeChatWorkRuns } from './transcript/use-mobile-native-chat-transcript-rows' -import type { MobileNativeChatRowSources } from './transcript/mobile-native-chat-row-keys' +import type { NativeChatMessage } from '../../../../../src/shared/native-chat/native-chat-types' +import type { NativeChatResolvedPrompt } from '../../../../../src/shared/native-chat/native-chat-resolution-receipt' +import { splitNativeChatBlocks } from '../../../../../src/shared/native-chat/tools/native-chat-tool-fold' +import { nativeChatWorkRunEntries } from '../../../../../src/shared/native-chat/native-chat-work-run' +import { nativeChatAskRunBlocks } from '../../../../../src/shared/native-chat/input/native-chat-ask-row' +import type { MobileNativeChatWorkRuns } from './use-mobile-native-chat-transcript-rows' +import type { MobileNativeChatRowSources } from './mobile-native-chat-row-keys' export type MobileNativeChatRunPresentation = { rows: readonly NativeChatMessage[] diff --git a/mobile/src/session/mobile-native-chat-scroll-anchoring.ts b/mobile/src/session/native-chat/transcript/mobile-native-chat-scroll-anchoring.ts similarity index 100% rename from mobile/src/session/mobile-native-chat-scroll-anchoring.ts rename to mobile/src/session/native-chat/transcript/mobile-native-chat-scroll-anchoring.ts diff --git a/mobile/src/session/native-chat/mobile-native-chat-scroll-gesture.ts b/mobile/src/session/native-chat/transcript/mobile-native-chat-scroll-gesture.ts similarity index 100% rename from mobile/src/session/native-chat/mobile-native-chat-scroll-gesture.ts rename to mobile/src/session/native-chat/transcript/mobile-native-chat-scroll-gesture.ts diff --git a/mobile/src/session/mobile-native-chat-scroll-motion.ts b/mobile/src/session/native-chat/transcript/mobile-native-chat-scroll-motion.ts similarity index 100% rename from mobile/src/session/mobile-native-chat-scroll-motion.ts rename to mobile/src/session/native-chat/transcript/mobile-native-chat-scroll-motion.ts diff --git a/mobile/src/session/native-chat/transcript/mobile-native-chat-scroll-ownership.test.tsx b/mobile/src/session/native-chat/transcript/mobile-native-chat-scroll-ownership.test.tsx index bae41606a45..f2796e90993 100644 --- a/mobile/src/session/native-chat/transcript/mobile-native-chat-scroll-ownership.test.tsx +++ b/mobile/src/session/native-chat/transcript/mobile-native-chat-scroll-ownership.test.tsx @@ -1,479 +1,6 @@ // @vitest-environment happy-dom -import { - act, - createElement as h, - Fragment, - startTransition, - Suspense, - useLayoutEffect, - useMemo, - type ReactNode -} from 'react' -import { createRoot, type Root } from 'react-dom/client' -import { afterEach, expect, it, vi } from 'vitest' -import type { NativeChatMessage } from '../../../../../src/shared/native-chat/native-chat-types' -import { foldToolMessages } from '../../../../../src/shared/native-chat/tools/native-chat-tool-fold' -import { MobileNativeChatMessage } from './MobileNativeChatMessage' -import { MobileNativeChatScrollRootsBoundary } from '../../MobileNativeChatScrollRootsBoundary' -import { MobileNativeChatScrollMotion } from '../../mobile-native-chat-scroll-motion' -import { - mobileNativeChatScrollFrame, - mobileNativeChatScrollRootKey, - mobileNativeChatReadingParts, - mobileNativeChatVisible -} from './mobile-native-chat-scroll-root-handle' +import { expect, it } from 'vitest' import { MobileNativeChatScrollRoots } from './mobile-native-chat-scroll-roots' -import { - MobileNativeChatDisclosureContext, - useMobileNativeChatDisclosures, - type MobileNativeChatDisclosureStore -} from './mobile-native-chat-disclosure-store' -import { useMobileNativeChatRowKeys } from './mobile-native-chat-row-keys' -import { useMobileNativeChatTurnDisclosure } from './use-mobile-native-chat-turn-disclosure' - -vi.mock('react-native', async () => { - const React = await import('react') - const View = (p: { - children?: ReactNode - testID?: string - onPress?: () => void - accessibilityLiveRegion?: string - }) => - React.createElement( - 'div', - { 'data-testid': p.testID, onClick: p.onPress, 'data-live': p.accessibilityLiveRegion }, - p.children - ) - const ScrollView = React.forwardRef((p: { children?: ReactNode }, ref) => { - const node = React.useRef(null) - React.useImperativeHandle(ref, () => ({ - getScrollableNode: () => node.current, - getInnerViewNode: () => node.current?.firstElementChild - })) - return React.createElement( - 'div', - { ref: node, className: 'viewport' }, - React.createElement('div', null, p.children) - ) - }) - const animation = () => ({ start() {}, stop() {} }) - return { - AppState: { currentState: 'active', addEventListener: () => ({ remove: () => {} }) }, - View, - Text: View, - Pressable: View, - ScrollView, - Image: View, - Platform: { OS: 'web' }, - StyleSheet: { create: (s: unknown) => s, hairlineWidth: 1 }, - useWindowDimensions: () => ({ width: 400, height: 800 }), - Animated: { - Text: View, - Value: class { - setValue() {} - }, - loop: animation, - sequence: animation, - timing: animation - } - } -}) -vi.mock('lucide-react-native', () => - Object.fromEntries( - 'ArrowUp Bot Brain Check ChevronDown ChevronRight Copy Eye FileMinus2 FilePen FilePlus2 Folder Globe ListChecks MessageSquareMore Pencil Plug Search SquareChevronRight SquareTerminal Wrench Circle CircleCheck CircleDot' - .split(' ') - .map((key) => [key, () => null]) - ) -) -vi.mock('../../../components/MobileMarkdown', () => ({ MobileMarkdown: () => null })) -vi.mock('../../../components/MobileSourceCopyButton', () => ({ - MobileSourceCopyButton: () => null -})) -vi.mock('../../../platform/external-link', () => ({ openExternalLink: vi.fn() })) -vi.mock('../../../components/inline-text-selection', () => ({ INLINE_TEXT_SELECTION: false })) - -let renderer: Root | undefined -let container: HTMLDivElement -let page: HTMLElement -let frameShift = 0 -let roots: MobileNativeChatScrollRoots -let owners: (string | undefined)[] -let projected: (string | undefined)[] -let store: MobileNativeChatDisclosureStore -const abandoned = new Promise(() => {}) -const msg = ( - id: string, - blocks: NativeChatMessage['blocks'], - role: NativeChatMessage['role'] = 'assistant' -): NativeChatMessage => ({ id, blocks, role, timestamp: null, source: 'transcript' }) -const a = msg( - 'a', - Array.from({ length: 6 }, (_, i) => ({ - type: 'tool-call', - callId: `c${i}`, - name: 'Bash', - input: { command: `command ${i} ${'argument '.repeat(20)}` } - })) -) -const thought = msg('r', [{ type: 'text', text: 'reason' }], 'reasoning') -const user = msg('u', [{ type: 'text', text: 'go' }], 'user') -const b = msg('b', [{ type: 'tool-call', callId: 'b', name: 'Bash', input: { command: 'b' } }]) -function reader(node: Element, top: number) { - node.dispatchEvent(new Event('touchstart')) - node.scrollTop = top - node.dispatchEvent(new Event('scroll')) - node.dispatchEvent(new Event('touchend')) -} -function members(root: Element): Element[] { - return Array.from(root.querySelectorAll('[data-testid^="chat-member:"]')).filter( - (node) => !mobileNativeChatScrollFrame(node, root) - ) -} -function rect(node: Element): DOMRect { - const viewport = node.closest('[data-chat-scroll-root]') - let top = 0 - let height = 1000 - if (node === page) { - return DOMRect.fromRect({ y: 100, height: 200, width: 400 }) - } - if (viewport === node) { - const parent = node.parentElement?.closest('[data-chat-scroll-root]') - top = parent - ? rect(node.parentElement!.closest('[data-testid^="chat-member:"]') ?? parent).top + 20 - : 40 + frameShift - page.scrollTop - height = 160 - } else if (viewport) { - const member = node.closest('[data-testid^="chat-member:"]') - top = - rect(viewport).top + - Math.max(0, members(viewport).indexOf(member ?? node)) * 60 - - viewport.scrollTop - height = 60 - } else if (node.closest('[data-live], [data-testid="chat-row:u"]')) { - top = -page.scrollTop - height = 20 - } else { - top = -page.scrollTop - } - return DOMRect.fromRect({ y: top, height, width: 400 }) -} -function Shift({ value }: { value: number }): null { - useLayoutEffect(() => { - frameShift = value - }, [value]) - return null -} -function Chat({ - rows, - open = true, - shown = true, - scope = 'chat', - shift = 0, - suspend = false, - structured = true, - working = false -}: { - rows: NativeChatMessage[] - open?: boolean - shown?: boolean - scope?: string - shift?: number - suspend?: boolean - structured?: boolean - working?: boolean -}) { - const current = useMobileNativeChatDisclosures(scope) - const disclosures = useMemo( - () => - open - ? { - ...current, - read: (key: string) => - current.read(key) ?? (/^(run|line|diff):/.test(key) ? true : undefined) - } - : current, - [current, open] - ) - const drawn = useMemo(() => (structured ? rows : foldToolMessages(rows)), [rows, structured]) - const turns = useMobileNativeChatTurnDisclosure({ - messages: drawn, - enabled: structured, - isWorking: working, - scopeKey: scope - }) - const keys = useMobileNativeChatRowKeys(drawn, rows, scope, turns.presentation) - useLayoutEffect(() => { - store = current - roots = current.roots - owners = drawn.map((row) => keys.runOwners.get(row.id)) - }) - if (suspend) { - projected = drawn.map((row) => keys.runOwners.get(row.id)) - throw abandoned - } - return h( - MobileNativeChatDisclosureContext.Provider, - { value: disclosures }, - h( - MobileNativeChatScrollRootsBoundary, - { - rowKeys: keys, - roots: current.roots, - runPlacements: keys.runPlacements, - layoutKey: '1' - }, - h(Shift, { value: shift }), - h( - Fragment, - { key: scope }, - shown && - drawn.map((message, i) => - h(MobileNativeChatMessage, { - key: keys.keyOf(message), - message, - rowKey: keys.keyOf(message), - ...turns.resolveRow(i, message), - ...(open ? { foldedAway: false } : {}), - runOwner: keys.runOwners.get(message.id), - structuredActivityUi: structured - }) - ) - ) - ) - ) -} -function mount(structured = true) { - vi.useFakeTimers() - vi.stubGlobal('IS_REACT_ACT_ENVIRONMENT', true) - vi.stubGlobal('navigator', { userAgent: 'AppleWebKit Safari' }) - container = document.createElement('div') - page = document.createElement('main') - page.style.overflowY = 'auto' - document.body.append(page) - page.append(container) - vi.spyOn(Element.prototype, 'getBoundingClientRect').mockImplementation(function (this: Element) { - return rect(this) - }) - vi.spyOn(HTMLElement.prototype, 'clientHeight', 'get').mockReturnValue(160) - vi.spyOn(Element.prototype, 'scrollHeight', 'get').mockImplementation(function (this: Element) { - return this.getAttribute('data-short') - ? 80 - : members(this).length * 60 + - 400 + - this.querySelectorAll('.viewport').length * 60 + - Number(this.getAttribute('data-growth') ?? 0) - }) - renderer = createRoot(container) - return (rows: NativeChatMessage[], rest: Partial[0]> = {}) => { - const render = () => - renderer!.render(h(Suspense, { fallback: null }, h(Chat, { rows, structured, ...rest }))) - act(() => (rest.suspend ? startTransition(render) : render())) - act(() => vi.advanceTimersByTime(20)) - } -} -afterEach(() => { - act(() => renderer?.unmount()) - page?.remove() - renderer = undefined - frameShift = 0 - vi.useRealTimers() - vi.restoreAllMocks() - vi.unstubAllGlobals() -}) - -it('keeps real structured runs and nested offsets under their own viewport across reheading', () => { - const draw = mount() - draw([user, a]) - const owner = owners[1] - const run = container.querySelector('[data-chat-scroll-root]') - if (!(run instanceof HTMLElement)) { - throw new Error('missing run viewport') - } - const detail = run.querySelector('[data-chat-scroll-root]') - if (!(detail instanceof HTMLElement)) { - throw new Error('missing command viewport') - } - const row = run.closest('[data-testid^="chat-row:"]')! - reader(run, 100) - reader(detail, 35) - act(() => vi.advanceTimersByTime(160)) - roots.restoreAll() - const clipped = run.querySelector('[data-testid="chat-member:call:c0"]')! - expect(mobileNativeChatVisible(clipped, page)).toBe(false) - expect(mobileNativeChatReadingParts(row)).toContain(run) - expect(mobileNativeChatReadingParts(row)).not.toContain(clipped) - const anchor = run.querySelector('[data-testid="chat-member:call:c3"]')! - const offset = rect(anchor).top - rect(run).top - draw([user, thought, a], { shift: 80 }) - expect(owners[1]).toBe(owner) - const restored = container.querySelector('[data-chat-scroll-root]')! - expect( - rect(restored.querySelector('[data-testid="chat-member:call:c3"]')!).top - rect(restored).top - ).toBe(offset) - expect(restored.querySelector('[data-chat-scroll-root]')?.scrollTop).toBe(35) - const top = restored.scrollTop - draw([user, thought, a], { shown: false, shift: 80 }) - draw([user, thought, a], { shift: 80 }) - expect(container.querySelector('[data-chat-scroll-root]')?.scrollTop).toBe(top) - const observer = { observe: vi.fn(), unobserve: vi.fn(), disconnect: vi.fn() } - roots.observeWith(observer) - expect(observer.observe).toHaveBeenCalledWith(container.querySelector('[data-chat-scroll-root]')) - const late = document.createElement('div') - const content = document.createElement('div') - late.append(content) - container.append(late) - late.setAttribute('data-short', 'yes') - store.runScroll.set('late', { top: 37, followsEnd: false, member: 'missing', offset: 10 }) - const stop = roots.register('late', late, content, 'late', 'late', false) - expect(late.scrollHeight).toBeLessThan(late.clientHeight) - expect(observer.observe).toHaveBeenCalledWith(content) - roots.capture(new Set(), false) - expect(store.runScroll.get('late')?.top).toBe(37) - late.removeAttribute('data-short') - roots.restoreAll() - expect(late.scrollTop).toBe(37) - expect(store.runScroll.get('late')?.member).toBeUndefined() - const removed = vi.spyOn(late, 'removeEventListener') - const replacement = document.createElement('div') - late.replaceChildren(replacement) - const replaced = roots.register('late', late, replacement, 'late', 'late', false) - observer.unobserve.mockClear() - stop() - expect(roots.frame('late')).toBe(late) - expect(observer.unobserve.mock.calls.some(([node]) => node === late)).toBe(false) - expect(observer.unobserve.mock.calls.some(([node]) => node === replacement)).toBe(false) - late.remove() - roots.restoreAll() - replaced() - expect(roots.frame('late')).toBeUndefined() - expect(observer.unobserve.mock.calls.some(([node]) => node === content)).toBe(true) - expect(removed).toHaveBeenCalledWith('scroll', expect.any(Function)) -}) - -it.each([true, false])( - 'issues fresh displayed owners through split and merge instead of reviving retired choices (structured=%s)', - (structured) => { - const draw = mount(structured) - draw([user, a, b], { working: true }) - const original = owners[1] - const oldKey = `run:${original}` - act(() => store.write(oldKey, false)) - store.runScroll.set(oldKey, { top: 111, followsEnd: false }) - const splitRows = [ - user, - a, - msg('break', [{ type: 'text', text: 'answer' }], structured ? 'assistant' : 'user'), - b - ] - const registry = roots - draw(splitRows, { suspend: true, working: true }) - expect(projected[1]).not.toBe(original) - expect(owners[1]).toBe(original) - expect(roots).toBe(registry) - expect(store.runScroll.get(oldKey)?.top).toBe(111) - const tentative = [...projected] - draw(splitRows, { working: true }) - const split = [owners[1], owners[3]] - expect(new Set([original, ...split]).size).toBe(3) - expect(owners).toEqual(tentative) - const reused = roots.frame(`run:${split[0]}`)! - reader(reused, 40) - draw([user, a, b]) - expect([original, ...split]).not.toContain(owners[1]) - expect(store.read(oldKey)).toBe(false) - expect(store.runScroll.get(oldKey)?.top).toBe(111) - expect(roots.frame(`run:${owners[1]}`)).toBe(reused) - expect(reused.scrollTop).toBe(40) - expect(store.runScroll.get(`run:${owners[1]}`)?.followsEnd).toBe(false) - } -) - -it('releases on close/scope change, and separates work-follow from reader chaining', async () => { - const draw = mount() - draw([user, a]) - const run = container.querySelector('[data-chat-scroll-root]')! - const detail = run.querySelector('[data-chat-scroll-root]')! - vi.stubGlobal('navigator', { userAgent: 'AppleWebKit Chrome' }) - const pageMotion = new MobileNativeChatScrollMotion() - const detach = pageMotion.attach(page) - pageMotion.reconciled(100, 1000) - reader(run, 100) - reader(detail, 35) - await vi.advanceTimersByTimeAsync(160) - reader(run, run.scrollHeight - run.clientHeight - 20) - await vi.advanceTimersByTimeAsync(160) - const parked = run.scrollTop - run.setAttribute('data-growth', '60') - roots.restoreAll() - expect(run.scrollTop).toBe(parked) - draw([user, a, b]) - expect(run.scrollTop).toBe(run.scrollHeight - run.clientHeight) - run.dispatchEvent(new Event('scroll')) - await vi.advanceTimersByTimeAsync(160) - expect(pageMotion.scrolled(100, 1000, () => false).by).toBe('none') - run.dispatchEvent(new WheelEvent('wheel', { deltaY: -10, bubbles: true })) - expect(pageMotion.scrolled(90, 1000, () => false).by).toBe('reader') - pageMotion.release() - act(() => container.querySelector('[data-live]')!.click()) - expect(run.hasAttribute('data-chat-scroll-root')).toBe(false) - draw([user, a], { scope: 'intermediate' }) - draw([user, a], { scope: 'other' }) - vi.stubGlobal('navigator', { userAgent: 'AppleWebKit Safari' }) - draw([user, a], { scope: 'live', open: false, working: true }) - act(() => container.querySelector('[data-live]')!.click()) - const key = `run:${owners[1]}` - const live = roots.frame(key)! - const end = live.scrollTop - expect(end).toBe(live.scrollHeight - live.clientHeight) - reader(live, end - 100) - draw([user, a], { scope: 'live', open: false, working: true, shift: 40 }) - expect(roots.frame(key)).toBe(live) - expect(live.scrollTop).toBe(end - 100) - expect(store.runScroll.get(key)?.followsEnd).toBe(false) - reader(live, live.scrollHeight - live.clientHeight - 20) - await vi.advanceTimersByTimeAsync(160) - draw([user, a, b], { scope: 'live', open: false, working: true, shift: 40 }) - expect(live.scrollTop).toBe(live.scrollHeight - live.clientHeight) - draw([user, a, b], { scope: 'live', open: false, working: true, shown: false, shift: 40 }) - store.runScroll.set(key, { top: 37, followsEnd: false }) - draw([user, a, b], { scope: 'live', open: false, working: true, shift: 40 }) - expect(roots.frame(key)?.scrollTop).toBe(37) - detach() - pageMotion.release() -}) - -it('keeps the actual changed task checklist through eviction, isolated by chat', () => { - const draw = mount() - const tasks = msg( - 'tasks', - [false, true].map((done) => ({ - type: 'tool-call', - callId: String(done), - name: 'TodoWrite', - input: { - todos: [ - { content: 'Remember', status: done ? 'completed' : 'pending', activeForm: 'Remembering' } - ] - } - })) - ) - draw([user, tasks]) - const count = () => container.textContent?.match(/Remember/g)?.length ?? 0 - const before = count() - const disclosure = Array.from(container.querySelectorAll('div')).findLast( - (node) => node.textContent === 'Full task list' - ) - if (!disclosure) { - throw new Error('missing changed-task disclosure') - } - act(() => disclosure.click()) - expect(count()).toBe(before + 1) - draw([user, tasks], { shown: false }) - draw([user, tasks]) - expect(count()).toBe(before + 1) - draw([user, tasks], { scope: 'different' }) - expect(count()).toBe(before) -}) it("forgets a closed tool line's nested command and output positions, not its neighbours'", () => { const at = { top: 30, followsEnd: false } @@ -485,86 +12,3 @@ it("forgets a closed tool line's nested command and output positions, not its ne new MobileNativeChatScrollRoots(memory, 10).forget('line:a') expect([...memory.keys()]).toEqual(['run:o', 'run:o/line:ab:command', 'diff:src/line:a.ts']) }) - -it.each([10, 100])( - 'bounds expanded notice scroll work and releases collapsed/unmounted roots (%i notices)', - (count) => { - const draw = mount() - const notices = Array.from({ length: count }, (_, i) => - msg( - `notice:${i}`, - [ - { - type: 'text', - text: `Diagnostic ${i}`, - tone: i % 2 === 0 ? 'warning' : 'error', - providerFrame: { - provider: i % 2 === 0 ? 'codex' : 'claude', - kind: - i % 2 === 0 ? 'notification:guardianWarning' : 'message:system:permission_denied', - payload: { head: '{}', byteLength: 2, digest: 'synthetic', truncated: false } - } - } - ], - 'system' - ) - ) - const register = vi.spyOn(MobileNativeChatScrollRoots.prototype, 'register') - draw(notices) - expect(register).not.toHaveBeenCalled() - const observer = { observe: vi.fn(), unobserve: vi.fn(), disconnect: vi.fn() } - roots.observeWith(observer) - const toggles = Array.from(container.querySelectorAll('div')).filter( - (node) => node.childElementCount === 0 && node.textContent?.includes('View details.') - ) - expect(toggles).toHaveLength(count) - act(() => toggles.forEach((toggle) => toggle.click())) - expect(register).toHaveBeenCalledTimes(count) - expect(observer.observe).toHaveBeenCalledTimes(2 * count) - const viewports = Array.from(container.querySelectorAll('[data-chat-scroll-root]')) - expect(viewports).toHaveLength(count) - const ids = viewports.map((node) => mobileNativeChatScrollRootKey(node)!) - expect(new Set(ids).size).toBe(count) - draw([...notices]) - viewports.forEach((node) => reader(node, 35)) - act(() => vi.advanceTimersByTime(160)) - - const memoryWrites = vi.spyOn(store.runScroll, 'set') - const queries = vi.spyOn(Element.prototype, 'querySelectorAll') - const geometry = vi.spyOn(Element.prototype, 'getBoundingClientRect') - const capture = vi.spyOn(roots, 'capture') - const restore = vi.spyOn(roots, 'restoreAll') - register.mockClear() - draw([...notices]) - expect(capture).toHaveBeenCalledOnce() - expect(restore).toHaveBeenCalledOnce() - expect(memoryWrites).toHaveBeenCalledTimes(2 * count) - expect(queries.mock.calls.length).toBeLessThanOrEqual(12 * count) - expect(geometry.mock.calls.length).toBeLessThanOrEqual(8 * count) - expect(register.mock.calls.length).toBeLessThanOrEqual(count) - expect(observer.observe).toHaveBeenCalledTimes(2 * count) - expect(viewports.map((node) => node.scrollTop)).toEqual(Array(count).fill(35)) - - act(() => toggles.slice(0, count / 2).forEach((toggle) => toggle.click())) - expect(observer.unobserve).toHaveBeenCalledTimes(count) - ids.forEach((id, i) => expect(roots.frame(id)).toBe(i < count / 2 ? undefined : viewports[i])) - draw(notices, { shown: false }) - expect(observer.unobserve).toHaveBeenCalledTimes(2 * count) - for (const node of viewports) { - expect(node.hasAttribute('data-chat-scroll-root')).toBe(false) - expect(mobileNativeChatScrollRootKey(node)).toBeUndefined() - expect(observer.unobserve).toHaveBeenCalledWith(node) - expect(observer.unobserve).toHaveBeenCalledWith(node.firstElementChild) - } - ids.forEach((id) => expect(roots.frame(id)).toBeUndefined()) - memoryWrites.mockClear() - queries.mockClear() - geometry.mockClear() - roots.capture(new Set(), false) - roots.restoreAll() - viewports.forEach((node) => reader(node, 50)) - expect(memoryWrites).not.toHaveBeenCalled() - expect(queries).not.toHaveBeenCalled() - expect(geometry).not.toHaveBeenCalled() - } -) diff --git a/mobile/src/session/native-chat/transcript/mobile-native-chat-scroll-root-handle.ts b/mobile/src/session/native-chat/transcript/mobile-native-chat-scroll-root-handle.ts index 4ee32f3c66b..14b3901af0e 100644 --- a/mobile/src/session/native-chat/transcript/mobile-native-chat-scroll-root-handle.ts +++ b/mobile/src/session/native-chat/transcript/mobile-native-chat-scroll-root-handle.ts @@ -1,5 +1,5 @@ -import type { MobileNativeChatScrollMotion } from '../../mobile-native-chat-scroll-motion' -import type { MobileNativeChatScrollAnchoring } from '../../mobile-native-chat-scroll-anchoring' +import type { MobileNativeChatScrollMotion } from './mobile-native-chat-scroll-motion' +import type { MobileNativeChatScrollAnchoring } from './mobile-native-chat-scroll-anchoring' export type MobileNativeChatRootPosition = { top: number diff --git a/mobile/src/session/native-chat/transcript/mobile-native-chat-scroll-roots.ts b/mobile/src/session/native-chat/transcript/mobile-native-chat-scroll-roots.ts index 7d612ef882a..1d46dcb42a5 100644 --- a/mobile/src/session/native-chat/transcript/mobile-native-chat-scroll-roots.ts +++ b/mobile/src/session/native-chat/transcript/mobile-native-chat-scroll-roots.ts @@ -1,8 +1,5 @@ -import { - MobileNativeChatScrollMotion, - scrollKeepsPlace -} from '../../mobile-native-chat-scroll-motion' -import { MobileNativeChatScrollAnchoring } from '../../mobile-native-chat-scroll-anchoring' +import { MobileNativeChatScrollMotion, scrollKeepsPlace } from './mobile-native-chat-scroll-motion' +import { MobileNativeChatScrollAnchoring } from './mobile-native-chat-scroll-anchoring' import { mobileNativeChatScrollRootAttribute as ROOT, mobileNativeChatScrollRootOwners as owners, diff --git a/mobile/src/session/native-chat/transcript/mobile-native-chat-send-text-owner.ts b/mobile/src/session/native-chat/transcript/mobile-native-chat-send-text-owner.ts index 997c1a11062..a075b12f3ed 100644 --- a/mobile/src/session/native-chat/transcript/mobile-native-chat-send-text-owner.ts +++ b/mobile/src/session/native-chat/transcript/mobile-native-chat-send-text-owner.ts @@ -1,5 +1,5 @@ -import type { MobileNativeChatSendIntent } from '../mobile-native-chat-send' -import type { MobileNativeChatSendOrigin } from '../mobile-native-chat-pending-echo' +import type { MobileNativeChatSendIntent } from '../composer/mobile-native-chat-send' +import type { MobileNativeChatSendOrigin } from './mobile-native-chat-pending-echo' type Restore = ( origin: MobileNativeChatSendOrigin, diff --git a/mobile/src/session/native-chat/mobile-native-chat-stream-frame.ts b/mobile/src/session/native-chat/transcript/mobile-native-chat-stream-frame.ts similarity index 91% rename from mobile/src/session/native-chat/mobile-native-chat-stream-frame.ts rename to mobile/src/session/native-chat/transcript/mobile-native-chat-stream-frame.ts index b80ec6ce347..bc38755de03 100644 --- a/mobile/src/session/native-chat/mobile-native-chat-stream-frame.ts +++ b/mobile/src/session/native-chat/transcript/mobile-native-chat-stream-frame.ts @@ -1,8 +1,8 @@ -import { applyAppend, replaceList } from '../../../../src/shared/native-chat/native-chat-merge' -import { translate } from '../../i18n/mobile-i18n' -import type { NativeChatMerger } from '../../../../src/shared/native-chat/native-chat-merge' -import type { NativeChatMessage } from '../../../../src/shared/native-chat/native-chat-types' -import type { NativeChatTranscriptFrame } from '../../../../src/shared/native-chat/native-chat-transcript-frames' +import { applyAppend, replaceList } from '../../../../../src/shared/native-chat/native-chat-merge' +import { translate } from '../../../i18n/mobile-i18n' +import type { NativeChatMerger } from '../../../../../src/shared/native-chat/native-chat-merge' +import type { NativeChatMessage } from '../../../../../src/shared/native-chat/native-chat-types' +import type { NativeChatTranscriptFrame } from '../../../../../src/shared/native-chat/native-chat-transcript-frames' type SnapshotFrame = Extract diff --git a/mobile/src/session/native-chat/mobile-native-chat-transcript-cache.ts b/mobile/src/session/native-chat/transcript/mobile-native-chat-transcript-cache.ts similarity index 85% rename from mobile/src/session/native-chat/mobile-native-chat-transcript-cache.ts rename to mobile/src/session/native-chat/transcript/mobile-native-chat-transcript-cache.ts index 7ea01a40f66..6a913f955b1 100644 --- a/mobile/src/session/native-chat/mobile-native-chat-transcript-cache.ts +++ b/mobile/src/session/native-chat/transcript/mobile-native-chat-transcript-cache.ts @@ -1,6 +1,6 @@ -import { setBoundedScopeCacheEntry } from '../../../../src/shared/native-chat/native-chat-scope-cache' -import type { NativeChatMessage } from '../../../../src/shared/native-chat/native-chat-types' -import type { NativeChatResumePoint } from '../../../../src/shared/rpc-contract/native-chat-params' +import { setBoundedScopeCacheEntry } from '../../../../../src/shared/native-chat/native-chat-scope-cache' +import type { NativeChatMessage } from '../../../../../src/shared/native-chat/native-chat-types' +import type { NativeChatResumePoint } from '../../../../../src/shared/rpc-contract/native-chat-params' import { peekStoredChatTranscript } from './mobile-native-chat-transcript-store' const MAX_CACHED_TRANSCRIPTS = 8 diff --git a/mobile/src/session/native-chat/mobile-native-chat-transcript-encode.ts b/mobile/src/session/native-chat/transcript/mobile-native-chat-transcript-encode.ts similarity index 93% rename from mobile/src/session/native-chat/mobile-native-chat-transcript-encode.ts rename to mobile/src/session/native-chat/transcript/mobile-native-chat-transcript-encode.ts index daeeb767d09..779de03d547 100644 --- a/mobile/src/session/native-chat/mobile-native-chat-transcript-encode.ts +++ b/mobile/src/session/native-chat/transcript/mobile-native-chat-transcript-encode.ts @@ -2,10 +2,10 @@ import { Gzip, strToU8 } from 'fflate' import { trimRetainedItems, mergeSubmissions -} from '../../../../src/shared/agent-session/view/structured-agent-session-item-retention' -import { agentSessionHasOlderTranscript } from '../../../../src/shared/agent-session/agent-session-context-clear' -import { DEVICE_STORE_MAX_VALUE_LENGTH } from '../../device-store/device-store-value-codec' -import { encodeBase64Bytes } from '../../transport/encryption/base64-byte-codec' +} from '../../../../../src/shared/agent-session/view/structured-agent-session-item-retention' +import { agentSessionHasOlderTranscript } from '../../../../../src/shared/agent-session/agent-session-context-clear' +import { DEVICE_STORE_MAX_VALUE_LENGTH } from '../../../device-store/device-store-value-codec' +import { encodeBase64Bytes } from '../../../transport/encryption/base64-byte-codec' import { STORED_TRANSCRIPT_VERSION, type StoredChatTranscript, diff --git a/mobile/src/session/native-chat/mobile-native-chat-transcript-store.ts b/mobile/src/session/native-chat/transcript/mobile-native-chat-transcript-store.ts similarity index 89% rename from mobile/src/session/native-chat/mobile-native-chat-transcript-store.ts rename to mobile/src/session/native-chat/transcript/mobile-native-chat-transcript-store.ts index b3c59746c44..fb091e1f10a 100644 --- a/mobile/src/session/native-chat/mobile-native-chat-transcript-store.ts +++ b/mobile/src/session/native-chat/transcript/mobile-native-chat-transcript-store.ts @@ -1,12 +1,15 @@ import { sha256 } from '@noble/hashes/sha256' import { bytesToHex } from '@noble/hashes/utils' -import { setBoundedScopeCacheEntry } from '../../../../src/shared/native-chat/native-chat-scope-cache' -import type { NativeChatMessage } from '../../../../src/shared/native-chat/native-chat-types' -import { encodeNativeChatTranscriptIdentity } from '../../../../src/shared/native-chat/transcript/native-chat-transcript-retention' -import type { StructuredAgentSessionState } from '../../../../src/shared/agent-session/structured-agent-session-reducer' -import { decodeDeviceStoreValue } from '../../device-store/device-store-value-codec' -import { readPageDeviceStore } from '../../mobile-web-shell/bridge/page-device-store' -import { resolveMobileNativeChat, type MobileNativeChatTab } from './mobile-native-chat-eligibility' +import { setBoundedScopeCacheEntry } from '../../../../../src/shared/native-chat/native-chat-scope-cache' +import type { NativeChatMessage } from '../../../../../src/shared/native-chat/native-chat-types' +import { encodeNativeChatTranscriptIdentity } from '../../../../../src/shared/native-chat/transcript/native-chat-transcript-retention' +import type { StructuredAgentSessionState } from '../../../../../src/shared/agent-session/structured-agent-session-reducer' +import { decodeDeviceStoreValue } from '../../../device-store/device-store-value-codec' +import { readPageDeviceStore } from '../../../mobile-web-shell/bridge/page-device-store' +import { + resolveMobileNativeChat, + type MobileNativeChatTab +} from '../mobile-native-chat-eligibility' // Bump when a stored shape changes: other versions read as a miss. export const STORED_TRANSCRIPT_VERSION = 1 diff --git a/mobile/src/session/native-chat/mobile-native-chat-transcript-writer.ts b/mobile/src/session/native-chat/transcript/mobile-native-chat-transcript-writer.ts similarity index 95% rename from mobile/src/session/native-chat/mobile-native-chat-transcript-writer.ts rename to mobile/src/session/native-chat/transcript/mobile-native-chat-transcript-writer.ts index a500287955f..630532cc6f3 100644 --- a/mobile/src/session/native-chat/mobile-native-chat-transcript-writer.ts +++ b/mobile/src/session/native-chat/transcript/mobile-native-chat-transcript-writer.ts @@ -1,16 +1,16 @@ -import type { NativeChatMessage } from '../../../../src/shared/native-chat/native-chat-types' -import { onPageAppInactive } from '../../mobile-web-shell/bridge/bridge-app-inactive' +import type { NativeChatMessage } from '../../../../../src/shared/native-chat/native-chat-types' +import { onPageAppInactive } from '../../../mobile-web-shell/bridge/bridge-app-inactive' import { EMPTY_STRUCTURED_AGENT_SESSION, reduceStructuredAgentSession, type StructuredAgentSessionAction, type StructuredAgentSessionState -} from '../../../../src/shared/agent-session/structured-agent-session-reducer' +} from '../../../../../src/shared/agent-session/structured-agent-session-reducer' import { MAX_RETAINED_ITEMS, MAX_RETAINED_OWN_ITEMS -} from '../../../../src/shared/agent-session/view/structured-agent-session-item-retention' -import { readPageDeviceStore } from '../../mobile-web-shell/bridge/page-device-store' +} from '../../../../../src/shared/agent-session/view/structured-agent-session-item-retention' +import { readPageDeviceStore } from '../../../mobile-web-shell/bridge/page-device-store' import { chatTranscriptStoreKey, peekStoredChatTranscript, diff --git a/mobile/src/session/native-chat-receipt-copy.ts b/mobile/src/session/native-chat/transcript/native-chat-receipt-copy.ts similarity index 89% rename from mobile/src/session/native-chat-receipt-copy.ts rename to mobile/src/session/native-chat/transcript/native-chat-receipt-copy.ts index 63093240a36..4dba5e0df58 100644 --- a/mobile/src/session/native-chat-receipt-copy.ts +++ b/mobile/src/session/native-chat/transcript/native-chat-receipt-copy.ts @@ -1,4 +1,4 @@ -import type { Translate } from '../i18n/mobile-i18n' +import type { Translate } from '../../../i18n/mobile-i18n' export function nativeChatReceiptCopy(t: Translate, device?: string) { return { diff --git a/mobile/src/session/native-chat/native-chat-turn-status-copy.ts b/mobile/src/session/native-chat/transcript/native-chat-turn-status-copy.ts similarity index 94% rename from mobile/src/session/native-chat/native-chat-turn-status-copy.ts rename to mobile/src/session/native-chat/transcript/native-chat-turn-status-copy.ts index 4f30ef74bab..27b4d095a10 100644 --- a/mobile/src/session/native-chat/native-chat-turn-status-copy.ts +++ b/mobile/src/session/native-chat/transcript/native-chat-turn-status-copy.ts @@ -1,8 +1,8 @@ -import type { Translate } from '../../i18n/mobile-i18n' +import type { Translate } from '../../../i18n/mobile-i18n' import { describeNativeChatActiveTurnLabel, describeNativeChatTurnStatus -} from '../../../../src/shared/native-chat/transcript/native-chat-turn-status' +} from '../../../../../src/shared/native-chat/transcript/native-chat-turn-status' export function formatMobileNativeChatDuration(seconds: number, t: Translate): string { const totalSeconds = Number.isFinite(seconds) ? Math.max(0, Math.floor(seconds)) : 0 diff --git a/mobile/src/session/native-chat/transcript/use-mobile-native-chat-message-detail.ts b/mobile/src/session/native-chat/transcript/use-mobile-native-chat-message-detail.ts index 12fcaca7552..a3fb9ec98f9 100644 --- a/mobile/src/session/native-chat/transcript/use-mobile-native-chat-message-detail.ts +++ b/mobile/src/session/native-chat/transcript/use-mobile-native-chat-message-detail.ts @@ -4,7 +4,7 @@ import { type NativeChatMessage } from '../../../../../src/shared/native-chat/native-chat-types' import { projectStructuredItemToNativeChat } from '../../../../../src/shared/agent-session/view/structured-agent-session-projection' -import { readMobileNativeChatItem } from '../mobile-native-chat-item-read' +import { readMobileNativeChatItem } from './mobile-native-chat-item-read' import type { MobileNativeChatVisualSource } from '../visual/mobile-native-chat-visual-read' export type MobileNativeChatMessageDetail = { diff --git a/mobile/src/session/native-chat/transcript/use-mobile-native-chat-message-send.ts b/mobile/src/session/native-chat/transcript/use-mobile-native-chat-message-send.ts index 0740f24ceec..c3c2803f169 100644 --- a/mobile/src/session/native-chat/transcript/use-mobile-native-chat-message-send.ts +++ b/mobile/src/session/native-chat/transcript/use-mobile-native-chat-message-send.ts @@ -8,11 +8,11 @@ import { typeMobileNativeChatCommandWithOutcome, type MobileNativeChatSendIntent, type MobileNativeChatSendOutcome -} from '../mobile-native-chat-send' +} from '../composer/mobile-native-chat-send' import type { CatalogCommandDelivery } from '../../../../../src/shared/agent-session/options/agent-session-option-catalog-types' import { isSlashCommandDraft } from '../../../../../src/shared/native-chat/input/native-chat-slash-commands' -import { healMobileNativeChatStaleInput } from '../mobile-native-chat-stale-input' -import { classifyMobileNativeChatSend } from '../mobile-native-chat-send-classification' +import { healMobileNativeChatStaleInput } from '../composer/mobile-native-chat-stale-input' +import { classifyMobileNativeChatSend } from '../composer/mobile-native-chat-send-classification' import { readMobileNativeChatSkillOrigin } from '../composer/mobile-native-chat-draft-store' import { nativeChatSendTextOwner } from './mobile-native-chat-send-text-owner' import { @@ -22,12 +22,12 @@ import { import { acquireMobileNativeChatTerminalWrite, releaseMobileNativeChatTerminalWrite -} from '../mobile-native-chat-terminal-write-lock' -import type { MobileNativeChatSendOrigin } from '../mobile-native-chat-pending-echo' +} from '../composer/mobile-native-chat-terminal-write-lock' +import type { MobileNativeChatSendOrigin } from './mobile-native-chat-pending-echo' import { UNCONFIRMED_SEND_MESSAGE, UNCONFIRMED_SEND_RESTORED_MESSAGE -} from '../use-mobile-native-chat-unconfirmed-sends' +} from '../composer/use-mobile-native-chat-unconfirmed-sends' import type { MobileNativeChatLaunchDraftSeed } from '../composer/use-mobile-native-chat-launch-draft-seed' import { buildNativeChatPasteBytes } from '../../../../../src/shared/native-chat/input/native-chat-paste-bytes' diff --git a/mobile/src/session/native-chat/transcript/use-mobile-native-chat-paced-text.ts b/mobile/src/session/native-chat/transcript/use-mobile-native-chat-paced-text.ts index b6067a1d7f7..e20e514a785 100644 --- a/mobile/src/session/native-chat/transcript/use-mobile-native-chat-paced-text.ts +++ b/mobile/src/session/native-chat/transcript/use-mobile-native-chat-paced-text.ts @@ -13,7 +13,7 @@ import { type NativeChatTextRevealFrames } from '../../../../../src/shared/native-chat/transcript/native-chat-text-reveal' import { MobileNativeChatReplyRevealsContext } from './mobile-native-chat-reply-reveals' -import { MobileNativeChatGrowthHoldContext } from '../../mobile-native-chat-growth-hold' +import { MobileNativeChatGrowthHoldContext } from './mobile-native-chat-growth-hold' /** Phones spread each arrival over less time than desktop, so new words show sooner. */ const REVEAL_MS = 180 diff --git a/mobile/src/session/use-mobile-native-chat-terminal-turn.ts b/mobile/src/session/native-chat/transcript/use-mobile-native-chat-terminal-turn.ts similarity index 86% rename from mobile/src/session/use-mobile-native-chat-terminal-turn.ts rename to mobile/src/session/native-chat/transcript/use-mobile-native-chat-terminal-turn.ts index 73f07177b30..2fda3b75901 100644 --- a/mobile/src/session/use-mobile-native-chat-terminal-turn.ts +++ b/mobile/src/session/native-chat/transcript/use-mobile-native-chat-terminal-turn.ts @@ -1,13 +1,13 @@ import { useCallback, useMemo, useState } from 'react' -import type { AgentStatusEntry } from '../../../src/shared/agent-status/contracts/agent-status-types' -import type { NativeChatMessage } from '../../../src/shared/native-chat/native-chat-types' -import type { NativeChatSettledTurns } from '../../../src/shared/native-chat/transcript/native-chat-turn-status' +import type { AgentStatusEntry } from '../../../../../src/shared/agent-status/contracts/agent-status-types' +import type { NativeChatMessage } from '../../../../../src/shared/native-chat/native-chat-types' +import type { NativeChatSettledTurns } from '../../../../../src/shared/native-chat/transcript/native-chat-turn-status' import { mergeNativeChatLiveSession, nativeChatHookHasWorkingSubagents, resolveNativeChatHookState -} from '../../../src/shared/native-chat/native-chat-live-status' -import { shouldClearNativeChatWorkingSuppression } from '../../../src/shared/native-chat/native-chat-working-suppression' +} from '../../../../../src/shared/native-chat/native-chat-live-status' +import { shouldClearNativeChatWorkingSuppression } from '../../../../../src/shared/native-chat/native-chat-working-suppression' import { nativeChatHookLatestTurnWorkedSeconds, nativeChatHookTurnStartedAt, @@ -16,16 +16,16 @@ import { nativeChatTranscriptSettledTurns, resolveNativeChatTerminalTurn, type NativeChatTerminalTurn -} from '../../../src/shared/native-chat/native-chat-terminal-turn' -import { deriveNativeChatStreamingText } from '../../../src/shared/native-chat/native-chat-streaming' +} from '../../../../../src/shared/native-chat/native-chat-terminal-turn' +import { deriveNativeChatStreamingText } from '../../../../../src/shared/native-chat/native-chat-streaming' import { useThrottledLatestValue } from './use-throttled-latest-value' -import type { MobileNativeChatSession } from './native-chat/use-mobile-native-chat-session' -import type { MobileNativeChatResolution } from './native-chat/mobile-native-chat-eligibility' +import type { MobileNativeChatSession } from '../use-mobile-native-chat-session' +import type { MobileNativeChatResolution } from '../mobile-native-chat-eligibility' import { pendingSendsAsMessages, type NativeChatPendingSend -} from '../../../src/shared/native-chat/transcript/native-chat-pending-sends' +} from '../../../../../src/shared/native-chat/transcript/native-chat-pending-sends' const NO_MESSAGES: NativeChatMessage[] = [] diff --git a/mobile/src/session/native-chat/transcript/use-mobile-native-chat-transient-data.ts b/mobile/src/session/native-chat/transcript/use-mobile-native-chat-transient-data.ts index a99c895969f..359db10fe05 100644 --- a/mobile/src/session/native-chat/transcript/use-mobile-native-chat-transient-data.ts +++ b/mobile/src/session/native-chat/transcript/use-mobile-native-chat-transient-data.ts @@ -2,7 +2,7 @@ import { useState } from 'react' import { buildMobileNativeChatTransientData, type MobileNativeChatPendingItem -} from '../mobile-native-chat-render-data' +} from './mobile-native-chat-render-data' import type { NativeChatMessage } from '../../../../../src/shared/native-chat/native-chat-types' import { orderNativeChatDisplayMessages } from '../../../../../src/shared/native-chat/transcript/native-chat-message-order' diff --git a/mobile/src/session/native-chat/transcript/use-mobile-native-chat-turn-disclosure.ts b/mobile/src/session/native-chat/transcript/use-mobile-native-chat-turn-disclosure.ts index 2ca97644e53..097d5428f36 100644 --- a/mobile/src/session/native-chat/transcript/use-mobile-native-chat-turn-disclosure.ts +++ b/mobile/src/session/native-chat/transcript/use-mobile-native-chat-turn-disclosure.ts @@ -23,7 +23,7 @@ import { nativeChatMessagesWaitingBehindLiveTurn } from '../../../../../src/shar import { NATIVE_CHAT_STREAMING_ID } from '../../../../../src/shared/native-chat/native-chat-streaming' import type { NativeChatResolvedPrompt } from '../../../../../src/shared/native-chat/native-chat-resolution-receipt' import { useMobileNativeChatTranscriptRows } from './use-mobile-native-chat-transcript-rows' -import type { MobileNativeChatRunPresentation } from '../mobile-native-chat-run-descriptors' +import type { MobileNativeChatRunPresentation } from './mobile-native-chat-run-descriptors' import { nativeChatRowsInDrawOrder, nativeChatTurnBarRows diff --git a/mobile/src/session/use-mobile-older-page-loader.ts b/mobile/src/session/native-chat/transcript/use-mobile-older-page-loader.ts similarity index 96% rename from mobile/src/session/use-mobile-older-page-loader.ts rename to mobile/src/session/native-chat/transcript/use-mobile-older-page-loader.ts index 7ac4a25ab1b..41c0615413b 100644 --- a/mobile/src/session/use-mobile-older-page-loader.ts +++ b/mobile/src/session/native-chat/transcript/use-mobile-older-page-loader.ts @@ -1,5 +1,5 @@ import { useCallback, useRef, useState } from 'react' -import { RPC_REQUEST_MIN_ACK_MS } from '../transport/rpc/rpc-request-budget' +import { RPC_REQUEST_MIN_ACK_MS } from '../../../transport/rpc/rpc-request-budget' /** One tap's whole wait, connect included, shared by every page it reads. */ export const OLDER_PAGE_BUDGET_MS = 15_000 diff --git a/mobile/src/session/native-chat/transcript/use-mobile-structured-agent-turn-timing.test.tsx b/mobile/src/session/native-chat/transcript/use-mobile-structured-agent-turn-timing.test.tsx new file mode 100644 index 00000000000..5e024daf652 --- /dev/null +++ b/mobile/src/session/native-chat/transcript/use-mobile-structured-agent-turn-timing.test.tsx @@ -0,0 +1,80 @@ +import { createElement } from 'react' +import { act, create, type ReactTestRenderer } from 'react-test-renderer' +import { afterEach, describe, expect, it, vi } from 'vitest' +import type { + AgentJournalRenderItem, + AgentJournalSubmission, + AgentJournalTurnLifecycle +} from '../../../../../src/shared/agent-session/journal/agent-session-journal-types' +import { agentJournalTurnBody } from '../../../../../src/shared/agent-session/lifecycle/agent-session-turn-record' +import { useMobileStructuredAgentTurnTiming } from './use-mobile-structured-agent-turn-timing' + +// Skew the host clock by an hour so unconverted timestamp leakage is obvious. +const HOST_START = 3_600_000_000 +const CLIENT_NOW = 12_345_000 + +function user(itemId: string, sequence: number): AgentJournalRenderItem { + return { + itemId, + revision: 0, + sequence, + observedAt: HOST_START + sequence, + body: { kind: 'message', role: 'user', blocks: [{ type: 'text', text: itemId }] } + } +} + +function lifecycle( + turnId: string, + sequence: number, + turn: Omit, + observedAt: number +): AgentJournalRenderItem { + return { + itemId: `lifecycle-${turnId}`, + revision: 1, + sequence, + observedAt, + body: agentJournalTurnBody({ turnId, ...turn }) + } +} + +type Timing = ReturnType +const NO_SUBMISSIONS: readonly AgentJournalSubmission[] = [] + +describe('useMobileStructuredAgentTurnTiming', () => { + let renderer: ReactTestRenderer | null = null + let timing: Timing | null = null + + function Harness({ + items, + submissions = NO_SUBMISSIONS, + turnId, + hostClock + }: { + items: readonly AgentJournalRenderItem[] + submissions?: readonly AgentJournalSubmission[] + turnId: string | null + hostClock?: { hostNow: number; receivedAt: number } + }): null { + timing = useMobileStructuredAgentTurnTiming({ items, submissions, hostClock }, turnId) + return null + } + + afterEach(() => { + act(() => renderer?.unmount()) + renderer = null + timing = null + vi.useRealTimers() + }) + + it('leaves the anchor null when an older host records no start', () => { + vi.useFakeTimers() + vi.setSystemTime(CLIENT_NOW) + const items = [user('u1', 1), lifecycle('t1', 2, { state: 'running' }, HOST_START)] + act(() => { + renderer = create(createElement(Harness, { items, turnId: 't1' })) + }) + expect(timing?.workingStartedAt).toBeNull() + expect(timing?.settledTurns.size).toBe(0) + }) +}) diff --git a/mobile/src/session/use-mobile-structured-agent-turn-timing.ts b/mobile/src/session/native-chat/transcript/use-mobile-structured-agent-turn-timing.ts similarity index 67% rename from mobile/src/session/use-mobile-structured-agent-turn-timing.ts rename to mobile/src/session/native-chat/transcript/use-mobile-structured-agent-turn-timing.ts index 1dddcdde3b5..e010ef7b5ca 100644 --- a/mobile/src/session/use-mobile-structured-agent-turn-timing.ts +++ b/mobile/src/session/native-chat/transcript/use-mobile-structured-agent-turn-timing.ts @@ -2,16 +2,16 @@ import { useMemo, useState } from 'react' import type { AgentJournalRenderItem, AgentJournalSubmission -} from '../../../src/shared/agent-session/journal/agent-session-journal-types' -import type { NativeChatSettledTurns } from '../../../src/shared/native-chat/transcript/native-chat-turn-status' -import type { AgentSessionLatestTurn } from '../../../src/shared/agent-session/agent-session-wire' -import type { NativeChatTurnJournal } from '../../../src/shared/native-chat/transcript/native-chat-turn-membership' -import type { StructuredAgentHostClock } from '../../../src/shared/agent-session/structured-agent-session-reducer' -import { selectStructuredAgentTurnBars } from '../../../src/shared/agent-session/view/structured-agent-session-turn-timing' +} from '../../../../../src/shared/agent-session/journal/agent-session-journal-types' +import type { NativeChatSettledTurns } from '../../../../../src/shared/native-chat/transcript/native-chat-turn-status' +import type { AgentSessionLatestTurn } from '../../../../../src/shared/agent-session/agent-session-wire' +import type { NativeChatTurnJournal } from '../../../../../src/shared/native-chat/transcript/native-chat-turn-membership' +import type { StructuredAgentHostClock } from '../../../../../src/shared/agent-session/structured-agent-session-reducer' +import { selectStructuredAgentTurnBars } from '../../../../../src/shared/agent-session/view/structured-agent-session-turn-timing' import { stepStructuredAgentTurnClock, type StructuredAgentTurnClockLatch -} from '../../../src/shared/structured-agent-turn-clock-anchor' +} from '../../../../../src/shared/structured-agent-turn-clock-anchor' // Use journal durations and latch the host-to-phone start conversion once per turn so counters remain skew-free. export function useMobileStructuredAgentTurnTiming( diff --git a/mobile/src/session/use-mobile-structured-transcript.ts b/mobile/src/session/native-chat/transcript/use-mobile-structured-transcript.ts similarity index 76% rename from mobile/src/session/use-mobile-structured-transcript.ts rename to mobile/src/session/native-chat/transcript/use-mobile-structured-transcript.ts index 4d1e1745023..8023c0336f5 100644 --- a/mobile/src/session/use-mobile-structured-transcript.ts +++ b/mobile/src/session/native-chat/transcript/use-mobile-structured-transcript.ts @@ -3,15 +3,15 @@ import { agentSessionContextClearOutstanding, agentSessionTranscriptRows, latestAgentSessionContextClearSequence -} from '../../../src/shared/agent-session/agent-session-context-clear' -import type { StructuredAgentSessionState } from '../../../src/shared/agent-session/structured-agent-session-reducer' -import type { StructuredAgentSessionOptimisticMessage } from '../../../src/shared/agent-session/view/structured-agent-session-message-projection' -import { createStructuredAgentSessionMessageProjection } from '../../../src/shared/agent-session/view/structured-agent-session-message-stream' -import { tuiAgentDisplayName } from '../../../src/shared/agent-launch/catalog/tui-agent-display-names' -import { withNativeChatCutTurnNotices } from '../../../src/shared/native-chat/transcript/native-chat-cut-turn-notice' -import { omitNativeChatThreadGoalRows } from '../../../src/shared/native-chat/transcript/native-chat-thread-goal-rows' -import { createStructuredQuestionProjection } from '../../../src/shared/structured-agent-question-projection' -import { projectStructuredAgentStartItem } from '../../../src/shared/structured-agent-start-projection' +} from '../../../../../src/shared/agent-session/agent-session-context-clear' +import type { StructuredAgentSessionState } from '../../../../../src/shared/agent-session/structured-agent-session-reducer' +import type { StructuredAgentSessionOptimisticMessage } from '../../../../../src/shared/agent-session/view/structured-agent-session-message-projection' +import { createStructuredAgentSessionMessageProjection } from '../../../../../src/shared/agent-session/view/structured-agent-session-message-stream' +import { tuiAgentDisplayName } from '../../../../../src/shared/agent-launch/catalog/tui-agent-display-names' +import { withNativeChatCutTurnNotices } from '../../../../../src/shared/native-chat/transcript/native-chat-cut-turn-notice' +import { omitNativeChatThreadGoalRows } from '../../../../../src/shared/native-chat/transcript/native-chat-thread-goal-rows' +import { createStructuredQuestionProjection } from '../../../../../src/shared/structured-agent-question-projection' +import { projectStructuredAgentStartItem } from '../../../../../src/shared/structured-agent-start-projection' const mobileStructuredTranscript = createStructuredQuestionProjection( projectStructuredAgentStartItem diff --git a/mobile/src/session/use-mobile-structured-turn-indicator.ts b/mobile/src/session/native-chat/transcript/use-mobile-structured-turn-indicator.ts similarity index 73% rename from mobile/src/session/use-mobile-structured-turn-indicator.ts rename to mobile/src/session/native-chat/transcript/use-mobile-structured-turn-indicator.ts index 6274d7c509c..73be344024e 100644 --- a/mobile/src/session/use-mobile-structured-turn-indicator.ts +++ b/mobile/src/session/native-chat/transcript/use-mobile-structured-turn-indicator.ts @@ -1,14 +1,14 @@ import { useMemo } from 'react' -import type { StructuredAgentSessionState } from '../../../src/shared/agent-session/structured-agent-session-reducer' -import type { NativeChatLiveTurnIndicator } from '../../../src/shared/native-chat/transcript/native-chat-turn-status' -import { isStructuredAgentSessionThinking } from '../../../src/shared/agent-session/view/structured-agent-session-live-turn' -import { selectStructuredAgentTurnActivity } from '../../../src/shared/native-chat/transcript/native-chat-turn-activity' -import { agentStopDisplayStatus } from '../../../src/shared/agent-status/lifecycle/agent-stop-display-status' -import { mobileStructuredSendQueues } from './mobile-structured-send-queue-rule' +import type { StructuredAgentSessionState } from '../../../../../src/shared/agent-session/structured-agent-session-reducer' +import type { NativeChatLiveTurnIndicator } from '../../../../../src/shared/native-chat/transcript/native-chat-turn-status' +import { isStructuredAgentSessionThinking } from '../../../../../src/shared/agent-session/view/structured-agent-session-live-turn' +import { selectStructuredAgentTurnActivity } from '../../../../../src/shared/native-chat/transcript/native-chat-turn-activity' +import { agentStopDisplayStatus } from '../../../../../src/shared/agent-status/lifecycle/agent-stop-display-status' +import { mobileStructuredSendQueues } from '../composer/mobile-structured-send-queue-rule' import { nativeChatSendFollowUp, type NativeChatSendFollowUp -} from '../../../src/shared/native-chat/input/native-chat-follow-up-behavior' +} from '../../../../../src/shared/native-chat/input/native-chat-follow-up-behavior' export function useMobileStructuredTurnIndicator(input: { state: StructuredAgentSessionState diff --git a/mobile/src/session/native-chat/use-stored-chat-transcript.ts b/mobile/src/session/native-chat/transcript/use-stored-chat-transcript.ts similarity index 100% rename from mobile/src/session/native-chat/use-stored-chat-transcript.ts rename to mobile/src/session/native-chat/transcript/use-stored-chat-transcript.ts diff --git a/mobile/src/session/use-throttled-latest-value.ts b/mobile/src/session/native-chat/transcript/use-throttled-latest-value.ts similarity index 100% rename from mobile/src/session/use-throttled-latest-value.ts rename to mobile/src/session/native-chat/transcript/use-throttled-latest-value.ts diff --git a/mobile/src/session/native-chat/use-mobile-native-chat-controller.ts b/mobile/src/session/native-chat/use-mobile-native-chat-controller.ts index ec49ba67457..b90f76fb88f 100644 --- a/mobile/src/session/native-chat/use-mobile-native-chat-controller.ts +++ b/mobile/src/session/native-chat/use-mobile-native-chat-controller.ts @@ -3,21 +3,21 @@ import { useCallback, useLayoutEffect, useMemo, useRef, type MutableRefObject } import type { RpcClient } from '../../transport/rpc/rpc-client-contract' import type { ConnectionState } from '../../transport/connection/connection-state' import type { MobileNativeChatTab } from './mobile-native-chat-eligibility' -import type { StructuredAgentSessionHostSupport } from '../mobile-structured-agent-session-host-support' +import type { StructuredAgentSessionHostSupport } from './agent-session/mobile-structured-agent-session-host-support' import { useMobileNativeChatDrafts } from './composer/use-mobile-native-chat-drafts' import { useMobileNativeChatWorkspaceCatalog } from './composer/use-mobile-native-chat-workspace-catalog' import { useMobileNativeChatMessageSend } from './transcript/use-mobile-native-chat-message-send' import { useMobileNativeChatSessionOptionController } from './input/use-mobile-native-chat-session-option-controller' import { useMobileNativeChatSessionLane } from './use-mobile-native-chat-session-lane' -import { useMobileStructuredNativeChatSendBridge } from '../use-mobile-structured-native-chat-send-bridge' -import { useMobileNativeChatTerminalTurn } from '../use-mobile-native-chat-terminal-turn' +import { useMobileStructuredNativeChatSendBridge } from './composer/use-mobile-structured-native-chat-send-bridge' +import { useMobileNativeChatTerminalTurn } from './transcript/use-mobile-native-chat-terminal-turn' import type { MobileNativeChatController } from './mobile-native-chat-controller-contract' -import { useMobileBridgeChatPromptWrites } from '../use-mobile-bridge-chat-prompt-writes' +import { useMobileBridgeChatPromptWrites } from './input/use-mobile-bridge-chat-prompt-writes' import { useMobileNativeChatActiveResolution } from './use-mobile-native-chat-active-resolution' -import { useMobileNativeChatPromptController } from '../use-mobile-native-chat-prompt-controller' +import { useMobileNativeChatPromptController } from './input/use-mobile-native-chat-prompt-controller' import { nativeChatPendingSendPlacement } from '../../../../src/shared/native-chat/transcript/native-chat-pending-sends' import { mobileNativeChatScopeKey } from './mobile-native-chat-scope-key' -import { useMobileNativeChatCiResultLines } from '../use-mobile-native-chat-ci-result-lines' +import { useMobileNativeChatCiResultLines } from './preferences/use-mobile-native-chat-ci-result-lines' export function useMobileNativeChatController(args: { client: RpcClient | null diff --git a/mobile/src/session/native-chat/use-mobile-native-chat-session-lane.ts b/mobile/src/session/native-chat/use-mobile-native-chat-session-lane.ts index d61614a79a7..0ce1245b017 100644 --- a/mobile/src/session/native-chat/use-mobile-native-chat-session-lane.ts +++ b/mobile/src/session/native-chat/use-mobile-native-chat-session-lane.ts @@ -1,13 +1,13 @@ import { useCallback } from 'react' import type { MobileComposerWriter } from './composer/mobile-native-chat-draft-store' import type { RpcClient } from '../../transport/rpc/rpc-client-contract' -import type { StructuredAgentSessionHostSupport } from '../mobile-structured-agent-session-host-support' +import type { StructuredAgentSessionHostSupport } from './agent-session/mobile-structured-agent-session-host-support' import type { ConnectionState } from '../../transport/connection/connection-state' import { useMobileNativeChatSession } from './use-mobile-native-chat-session' -import { useMobileStructuredAgentSession } from '../use-mobile-structured-agent-session' -import { useMobileStructuredSessionCommands } from '../use-mobile-structured-session-commands' +import { useMobileStructuredAgentSession } from './agent-session/use-mobile-structured-agent-session' +import { useMobileStructuredSessionCommands } from './composer/use-mobile-structured-session-commands' import type { MobileNativeChatResolution } from './mobile-native-chat-eligibility' -import type { MobileNativeChatSendErrorReporter } from './use-mobile-native-chat-send-error' +import type { MobileNativeChatSendErrorReporter } from './composer/use-mobile-native-chat-send-error' // Run both hooks in fixed order and starve the inactive lane’s identity so flips preserve cached transcripts. export function useMobileNativeChatSessionLane({ diff --git a/mobile/src/session/native-chat/use-mobile-native-chat-session.test.ts b/mobile/src/session/native-chat/use-mobile-native-chat-session.test.ts index 8d9f0705af2..5a5db4d94a0 100644 --- a/mobile/src/session/native-chat/use-mobile-native-chat-session.test.ts +++ b/mobile/src/session/native-chat/use-mobile-native-chat-session.test.ts @@ -5,8 +5,8 @@ import type { NativeChatMessage } from '../../../../src/shared/native-chat/nativ import type { RpcClient } from '../../transport/rpc/rpc-client-contract' import { stubRpcClient } from '../../transport/rpc/rpc-client-test-stub' import { publishPageDeviceStore } from '../../mobile-web-shell/bridge/page-device-store' -import { mobileNativeChatTranscriptCache } from './mobile-native-chat-transcript-cache' -import { encodeStoredChatTranscript } from './mobile-native-chat-transcript-encode' +import { mobileNativeChatTranscriptCache } from './transcript/mobile-native-chat-transcript-cache' +import { encodeStoredChatTranscript } from './transcript/mobile-native-chat-transcript-encode' import { useMobileNativeChatSession, type MobileNativeChatSession @@ -164,62 +164,6 @@ describe('useMobileNativeChatSession', () => { expect(state?.messages.at(-1)?.id).toBe('live-1') }) - it('keeps the rows it shows when a replay window has moved past them', async () => { - const sendRequest = vi.fn(() => new Promise(() => {})) - const window = Array.from({ length: 40 }, (_unused, index) => message(`win-${index}`)) - const subscribe: RpcClient['subscribe'] = vi.fn((_method, _params, onData) => { - emit = onData - onData({ type: 'snapshot', messages: window, hasMore: false, beforeOffset: 0 }) - return () => {} - }) - await mount({ sendRequest, subscribe } as unknown as RpcClient) - - await act(async () => - emit({ - type: 'snapshot', - messages: [...window.slice(1), message('live-1')], - hasMore: true, - beforeOffset: 10 - }) - ) - - expect(state?.messages.map((entry) => entry.id)).toEqual([ - ...window.map((entry) => entry.id), - 'live-1' - ]) - expect(state?.hasMore).toBe(false) - }) - - it('drops paged rows that an authoritative replay says were removed', async () => { - const sendRequest = vi.fn().mockResolvedValue({ - ok: true, - result: { - messages: Array.from({ length: 60 }, (_unused, index) => message(`paged-${index}`)), - hasMore: false, - beforeOffset: 40 - } - }) - const window = Array.from({ length: 40 }, (_unused, index) => message(`win-${index}`)) - const subscribe: RpcClient['subscribe'] = vi.fn((_method, _params, onData) => { - emit = onData - onData({ type: 'snapshot', messages: window, hasMore: true, beforeOffset: 100 }) - return () => {} - }) - await mount({ sendRequest, subscribe } as unknown as RpcClient) - await act(async () => { - state?.loadEarlier() - await Promise.resolve() - }) - expect(state?.messages).toHaveLength(100) - - await act(async () => - emit({ type: 'snapshot', messages: window, hasMore: false, beforeOffset: 0 }) - ) - - expect(state?.messages).toEqual(window) - expect(state?.hasMore).toBe(false) - }) - it('fences an in-flight older page when a merging replay re-cuts the byte cursor', async () => { let resolveEarlier: (response: unknown) => void = () => {} const sendRequest = vi.fn( @@ -272,35 +216,6 @@ describe('useMobileNativeChatSession', () => { expect(state?.messages.map((entry) => entry.id)).toEqual(['early-b', 'base-c']) }) - - it('keeps every row it shows while live output outgrows the first window', async () => { - let resolvePage: (response: unknown) => void = () => {} - const sendRequest = vi - .fn() - .mockImplementationOnce(() => new Promise((resolve) => (resolvePage = resolve))) - .mockImplementation(() => new Promise(() => {})) - const window = Array.from({ length: 40 }, (_unused, index) => message(`window-${index}`)) - const subscribe: RpcClient['subscribe'] = vi.fn((_method, _params, onData) => { - emit = onData - onData({ type: 'snapshot', messages: window, hasMore: true, beforeOffset: 100 }) - return () => {} - }) - await mount({ sendRequest, subscribe } as unknown as RpcClient) - const shown = window.map((entry) => entry.id) - - act(() => state?.loadEarlier()) - await act(async () => emit({ type: 'appended', messages: [message('live-1')] })) - expect(state?.messages.map((entry) => entry.id)).toEqual([...shown, 'live-1']) - - await act(async () => { - resolvePage({ - ok: true, - result: { messages: [message('older-page')], hasMore: true, beforeOffset: 50 } - }) - await Promise.resolve() - }) - expect(state?.messages.map((entry) => entry.id)).toEqual(['older-page', ...shown, 'live-1']) - }) }) describe('useMobileNativeChatSession transcriptLoading', () => { diff --git a/mobile/src/session/native-chat/use-mobile-native-chat-session.ts b/mobile/src/session/native-chat/use-mobile-native-chat-session.ts index 978f859a8f3..0e2d53c95b5 100644 --- a/mobile/src/session/native-chat/use-mobile-native-chat-session.ts +++ b/mobile/src/session/native-chat/use-mobile-native-chat-session.ts @@ -15,21 +15,23 @@ import { nativeChatSessionPageRead } from './agent-session/mobile-native-chat-pa import { applyMobileNativeChatStreamFrame, type MobileNativeChatStreamFrame -} from './mobile-native-chat-stream-frame' +} from './transcript/mobile-native-chat-stream-frame' import { randomV4Uuid } from '../../platform/random-v4-uuid' -import { useMobileOlderPageLoader, type OlderPagePhase } from '../use-mobile-older-page-loader' +import { + useMobileOlderPageLoader, + type OlderPagePhase +} from './transcript/use-mobile-older-page-loader' import { cacheMobileNativeChatTranscript, heldMobileNativeChatTranscript, mobileNativeChatResumePoint, mobileNativeChatTranscriptCache -} from './mobile-native-chat-transcript-cache' -import { terminalChatTranscriptIdentity } from './mobile-native-chat-transcript-store' -import { noteChatTranscript } from './mobile-native-chat-transcript-writer' -import { useStoredChatTranscript } from './use-stored-chat-transcript' +} from './transcript/mobile-native-chat-transcript-cache' +import { terminalChatTranscriptIdentity } from './transcript/mobile-native-chat-transcript-store' +import { noteChatTranscript } from './transcript/mobile-native-chat-transcript-writer' +import { useStoredChatTranscript } from './transcript/use-stored-chat-transcript' import type { MobileNativeChatStatus } from './mobile-native-chat-session-status' -export type { MobileNativeChatStatus } from './mobile-native-chat-session-status' export type MobileNativeChatSession = { messages: NativeChatMessage[] diff --git a/mobile/src/session/native-chat/use-mobile-native-chat-usage-limit.ts b/mobile/src/session/native-chat/use-mobile-native-chat-usage-limit.ts index 400253d479b..443fbf12000 100644 --- a/mobile/src/session/native-chat/use-mobile-native-chat-usage-limit.ts +++ b/mobile/src/session/native-chat/use-mobile-native-chat-usage-limit.ts @@ -14,12 +14,12 @@ import type { } from '../../../../src/shared/agent-session/journal/agent-session-journal-types' import type { AgentSessionOptionsResult } from '../../../../src/shared/agent-session/options/agent-session-options-result' import type { AgentJournalCursor } from '../../../../src/shared/agent-session/journal/agent-session-journal-identity' -import { mobileStructuredSessionStatusFeed } from '../mobile-structured-session-status-feed' -import { callAgentSession } from '../mobile-structured-agent-session-rpc' +import { mobileStructuredSessionStatusFeed } from './agent-session/mobile-structured-session-status-feed' +import { callAgentSession } from './agent-session/mobile-structured-agent-session-rpc' import type { MobileStructuredAgentSessionArgs, StructuredMobileSession -} from '../mobile-structured-agent-session-contract' +} from './agent-session/mobile-structured-agent-session-contract' /** The usage-limit row the person can act on: the latest cut while nothing is running or sending. */ export type MobileNativeChatUsageLimit = { diff --git a/mobile/src/session/structured-create-wire-types.test.ts b/mobile/src/session/structured-create-wire-types.test.ts deleted file mode 100644 index 14813467cb6..00000000000 --- a/mobile/src/session/structured-create-wire-types.test.ts +++ /dev/null @@ -1,51 +0,0 @@ -import { describe, expect, expectTypeOf, it } from 'vitest' -import type { z } from 'zod' -import { - structuredAgentSessionCreateParams, - type StructuredAgentSessionFirstMessage -} from '../../../src/shared/agent-session/structured-agent-session-create' -import { CreateIntentParams } from '../../../src/shared/rpc-contract/structured-agent-session-params' - -describe('the shared create builder used by mobile', () => { - it('remains assignable to the strict create request without an opening message', () => { - const params = structuredAgentSessionCreateParams({ - sessionId: 'codex_11111111_2222_3333_4444_555555555555', - worktree: 'id:workspace-1', - agent: 'codex', - randomUuid: () => '11111111-2222-3333-4444-555555555555' - }) - expectTypeOf(params).toExtend>() - expect(CreateIntentParams.safeParse(params).success).toBe(true) - expect(params).not.toHaveProperty('firstMessage') - }) - - it('accepts only user-authored opening messages at the type and wire boundaries', () => { - const firstMessage: StructuredAgentSessionFirstMessage = { - clientMessageId: 'opening-message', - body: { kind: 'message', role: 'user', blocks: [{ type: 'text', text: 'hello' }] } - } - const params = structuredAgentSessionCreateParams({ - sessionId: 'codex_11111111_2222_3333_4444_555555555555', - worktree: 'id:workspace-1', - agent: 'codex', - firstMessage, - randomUuid: () => '11111111-2222-3333-4444-555555555555' - }) - expect(params.firstMessage).toEqual(firstMessage) - expect(CreateIntentParams.safeParse(params).success).toBe(true) - - type AssistantBody = { - kind: 'message' - role: 'assistant' - blocks: { type: 'text'; text: string }[] - } - expectTypeOf().not.toExtend() - expectTypeOf().toEqualTypeOf<'user'>() - expect( - CreateIntentParams.shape.firstMessage.safeParse({ - clientMessageId: 'opening-message', - body: { kind: 'message', role: 'assistant', blocks: [{ type: 'text', text: 'forged' }] } - }).success - ).toBe(false) - }) -}) diff --git a/mobile/src/session/tabs/use-mobile-session-tab-reconciliation.ts b/mobile/src/session/tabs/use-mobile-session-tab-reconciliation.ts index 58fa5c9e731..5d3e7d7d66b 100644 --- a/mobile/src/session/tabs/use-mobile-session-tab-reconciliation.ts +++ b/mobile/src/session/tabs/use-mobile-session-tab-reconciliation.ts @@ -6,7 +6,7 @@ import { MOBILE_AI_VAULT_CAPABILITY } from '../../agent-history/agent-history-ca import '../../../../src/shared/protocol-version' import { TERMINAL_QUERY_REPLY_INPUT_RUNTIME_CAPABILITY } from '../../../../src/shared/terminal/runtime-policy/terminal-runtime-capabilities' import { PROGRAM_STATUS_RUNTIME_CAPABILITY } from '../../../../src/shared/program-status/protocol' -import { structuredAgentSessionHostSupport } from '../mobile-structured-agent-session-host-support' +import { structuredAgentSessionHostSupport } from '../native-chat/agent-session/mobile-structured-agent-session-host-support' import { runAcceptedMobileSessionTabsEffects } from './mobile-session-tabs-accepted-effects' import type { SessionTabsStreamSource } from './mobile-session-tabs-stream-health' import { useMobileSessionTabsFetchReporting } from './use-mobile-session-tabs-fetch-reporting' diff --git a/mobile/src/session/use-mobile-agent-message-navigation.ts b/mobile/src/session/use-mobile-agent-message-navigation.ts index d054bb3a7a7..fc4916220ae 100644 --- a/mobile/src/session/use-mobile-agent-message-navigation.ts +++ b/mobile/src/session/use-mobile-agent-message-navigation.ts @@ -7,8 +7,8 @@ import { type StructuredSessionOpenFailure } from '../../../src/shared/open-structured-agent-session' import type { RpcClient } from '../transport/rpc/rpc-client-contract' -import { mobileStructuredSessionOpenMessage } from './mobile-structured-session-open-message' -import { openMobileStructuredSession } from './open-mobile-structured-session' +import { mobileStructuredSessionOpenMessage } from './native-chat/agent-session/mobile-structured-session-open-message' +import { openMobileStructuredSession } from './native-chat/agent-session/open-mobile-structured-session' import { openMobileAgentMessageTerminal } from '../terminal/session/mobile-agent-message-terminal' import type { MobileSessionKeyboardStateModel } from '../terminal/session/use-mobile-session-keyboard-state' diff --git a/mobile/src/session/use-mobile-send-completion-generation.test.ts b/mobile/src/session/use-mobile-send-completion-generation.test.ts deleted file mode 100644 index 0776ca717c6..00000000000 --- a/mobile/src/session/use-mobile-send-completion-generation.test.ts +++ /dev/null @@ -1,78 +0,0 @@ -import { createElement, Suspense } from 'react' -import { act, create, type ReactTestRenderer } from 'react-test-renderer' -import { describe, expect, it, vi } from 'vitest' -import { useMobileSendCompletionGeneration } from './use-mobile-send-completion-generation' - -let focusCleanup: (() => void) | undefined - -vi.mock('expo-router', () => ({ - useFocusEffect: (effect: () => void | (() => void)) => { - focusCleanup = effect() ?? undefined - } -})) - -describe('mobile send completion generation', () => { - it('invalidates completions on a surface change and retained-route blur', () => { - const onBlur = vi.fn() - let getGeneration: (() => number) | null = null - let renderer: ReactTestRenderer - - function Harness({ surfaceKey }: { surfaceKey: string }): null { - getGeneration = useMobileSendCompletionGeneration({ onBlur, surfaceKey }) - return null - } - - act(() => { - renderer = create(createElement(Harness, { surfaceKey: 'tab-a' })) - }) - const initialGeneration = getGeneration!() - act(() => { - renderer.update(createElement(Harness, { surfaceKey: 'tab-b' })) - }) - expect(getGeneration!()).toBeGreaterThan(initialGeneration) - - const surfaceGeneration = getGeneration!() - act(() => focusCleanup?.()) - expect(getGeneration!()).toBeGreaterThan(surfaceGeneration) - expect(onBlur).toHaveBeenCalledTimes(1) - - act(() => renderer.unmount()) - }) - - it('does not invalidate the committed surface during a suspended render', () => { - const never = new Promise(() => undefined) - let getGeneration: (() => number) | null = null - let renderer: ReactTestRenderer - - function Harness({ surfaceKey, suspend }: { surfaceKey: string; suspend: boolean }): null { - getGeneration = useMobileSendCompletionGeneration({ onBlur: vi.fn(), surfaceKey }) - if (suspend) { - throw never - } - return null - } - - act(() => { - renderer = create( - createElement( - Suspense, - { fallback: null }, - createElement(Harness, { surfaceKey: 'tab-a', suspend: false }) - ) - ) - }) - const committedGeneration = getGeneration!() - act(() => { - renderer.update( - createElement( - Suspense, - { fallback: null }, - createElement(Harness, { surfaceKey: 'tab-b', suspend: true }) - ) - ) - }) - - expect(getGeneration!()).toBe(committedGeneration) - act(() => renderer.unmount()) - }) -}) diff --git a/mobile/src/session/use-mobile-session-dictation-setup.ts b/mobile/src/session/use-mobile-session-dictation-setup.ts index a1c46e002b8..0a6ee25c923 100644 --- a/mobile/src/session/use-mobile-session-dictation-setup.ts +++ b/mobile/src/session/use-mobile-session-dictation-setup.ts @@ -9,6 +9,11 @@ import { } from '../dictation/mobile-dictation-setup' import type { MobileSessionFeedbackCapabilitiesModel } from './use-mobile-session-feedback-capabilities' import type { DictationTerm } from '../../../src/shared/dictation-dictionary' +import { + DEFAULT_STOP_AFTER_SILENCE_SECONDS, + stopAfterSilenceSeconds, + type StopAfterSilenceSeconds +} from '../../../src/shared/dictation-silence-stop' // The computer's dictation settings as this session reads them: mic shown, mode, filler switch, and whether setup is needed first. export function useMobileSessionDictationSetup(scope: MobileSessionFeedbackCapabilitiesModel) { @@ -19,6 +24,9 @@ export function useMobileSessionDictationSetup(scope: MobileSessionFeedbackCapab // The host's filler switch and this worktree's terms, kept from its last setup read; fillers on until one says otherwise. const [removeFillerWords, setRemoveFillerWords] = useState(true) const [dictationTerms, setDictationTerms] = useState(undefined) + const [silenceSeconds, setSilenceSeconds] = useState( + DEFAULT_STOP_AFTER_SILENCE_SECONDS + ) // Only a host setup read sets this; while false, the host's start refusal decides (older hosts, first tap before the read). const dictationNeedsSetupRef = useRef(false) @@ -35,6 +43,7 @@ export function useMobileSessionDictationSetup(scope: MobileSessionFeedbackCapab setDictationMode(setup.dictationMode) setRemoveFillerWords(setup.removeFillerWords !== false) setDictationTerms(setup.dictationTerms) + setSilenceSeconds(stopAfterSilenceSeconds(setup)) setDictationEnabled(!dictationMicHidden(setup)) dictationNeedsSetupRef.current = dictationNeedsSetup(setup) } @@ -70,6 +79,7 @@ export function useMobileSessionDictationSetup(scope: MobileSessionFeedbackCapab phoneDictation, removeFillerWords, dictationTerms, + silenceSeconds, dictationNeedsSetupRef, closeDictationSetup, refreshDictationMode diff --git a/mobile/src/session/use-mobile-session-dictation.ts b/mobile/src/session/use-mobile-session-dictation.ts index 32159402a3c..4bbdfad37d7 100644 --- a/mobile/src/session/use-mobile-session-dictation.ts +++ b/mobile/src/session/use-mobile-session-dictation.ts @@ -196,6 +196,7 @@ export function useMobileSessionDictation( phoneDictation, removeFillerWords, dictationTerms, + silenceSeconds, dictationNeedsSetupRef, closeDictationSetup, refreshDictationMode @@ -245,6 +246,7 @@ export function useMobileSessionDictation( executionHost ), dictationMode: scope.dictationMode, + silenceSeconds, removeFillerWords, dictationTerms, worktreeId, @@ -266,6 +268,7 @@ export function useMobileSessionDictation( phoneDictation.readyRef, removeFillerWords, dictationTerms, + silenceSeconds, scope.dictationMode, sessionKey, setShowDictationSetup, diff --git a/mobile/src/session/use-mobile-session-feedback-capabilities.ts b/mobile/src/session/use-mobile-session-feedback-capabilities.ts index 7ccc7863841..d7861707160 100644 --- a/mobile/src/session/use-mobile-session-feedback-capabilities.ts +++ b/mobile/src/session/use-mobile-session-feedback-capabilities.ts @@ -3,7 +3,7 @@ import { Animated, Easing, Platform } from 'react-native' import { translate } from '../i18n/mobile-i18n' import { reconcileMobileSessionCreateWarningState } from './tabs/mobile-session-create-warning-state' import type { MobileSessionTerminalRuntimeModel } from '../terminal/session/use-mobile-session-terminal-runtime' -import type { StructuredAgentSessionHostSupport } from './mobile-structured-agent-session-host-support' +import type { StructuredAgentSessionHostSupport } from './native-chat/agent-session/mobile-structured-agent-session-host-support' // A strong ease-out both ways; the presentation turns this fade into a short rise. const TOAST_EASING = Easing.bezier(0.23, 1, 0.32, 1) diff --git a/mobile/src/session/use-mobile-session-native-chat-dictation.ts b/mobile/src/session/use-mobile-session-native-chat-dictation.ts index d339e2a6c63..4bf5a7279b9 100644 --- a/mobile/src/session/use-mobile-session-native-chat-dictation.ts +++ b/mobile/src/session/use-mobile-session-native-chat-dictation.ts @@ -2,8 +2,8 @@ import { useEffect } from 'react' import { useMobileSessionDictation } from './use-mobile-session-dictation' import { useMobileNativeChatController } from './native-chat/use-mobile-native-chat-controller' import { useMobileNativeChatReadability } from './native-chat/transcript/use-mobile-native-chat-readability' -import { useMobileNativeChatInputLease } from './native-chat/use-mobile-native-chat-input-lease' -import { useMobileNativeChatSendError } from './native-chat/use-mobile-native-chat-send-error' +import { useMobileNativeChatInputLease } from './native-chat/composer/use-mobile-native-chat-input-lease' +import { useMobileNativeChatSendError } from './native-chat/composer/use-mobile-native-chat-send-error' import { mobileNativeChatScopeKey } from './native-chat/mobile-native-chat-scope-key' import { mobileNativeChatOverlayInputLockReason } from './native-chat/mobile-native-chat-overlay-lock-reason' import { useMobileSendCompletionGeneration } from './use-mobile-send-completion-generation' diff --git a/mobile/src/session/use-mobile-session-stored-chat-tab.ts b/mobile/src/session/use-mobile-session-stored-chat-tab.ts index 6a88579b9a2..1c17a2c0a94 100644 --- a/mobile/src/session/use-mobile-session-stored-chat-tab.ts +++ b/mobile/src/session/use-mobile-session-stored-chat-tab.ts @@ -7,7 +7,7 @@ import { peekStoredChatTranscript, readStoredChatTranscript, storedTabChatTranscriptIdentity -} from './native-chat/mobile-native-chat-transcript-store' +} from './native-chat/transcript/mobile-native-chat-transcript-store' import type { MobileSessionKeyboardStateModel } from '../terminal/session/use-mobile-session-keyboard-state' /** diff --git a/mobile/src/session/use-mobile-structured-agent-turn-timing.test.tsx b/mobile/src/session/use-mobile-structured-agent-turn-timing.test.tsx deleted file mode 100644 index c1b7ea7c7e3..00000000000 --- a/mobile/src/session/use-mobile-structured-agent-turn-timing.test.tsx +++ /dev/null @@ -1,160 +0,0 @@ -import { createElement } from 'react' -import { act, create, type ReactTestRenderer } from 'react-test-renderer' -import { afterEach, describe, expect, it, vi } from 'vitest' -import type { - AgentJournalRenderItem, - AgentJournalSubmission, - AgentJournalTurnLifecycle -} from '../../../src/shared/agent-session/journal/agent-session-journal-types' -import { agentJournalTurnBody } from '../../../src/shared/agent-session/lifecycle/agent-session-turn-record' -import { useMobileStructuredAgentTurnTiming } from './use-mobile-structured-agent-turn-timing' - -// Skew the host clock by an hour so unconverted timestamp leakage is obvious. -const HOST_START = 3_600_000_000 -const CLIENT_NOW = 12_345_000 - -function user(itemId: string, sequence: number): AgentJournalRenderItem { - return { - itemId, - revision: 0, - sequence, - observedAt: HOST_START + sequence, - body: { kind: 'message', role: 'user', blocks: [{ type: 'text', text: itemId }] } - } -} - -function lifecycle( - turnId: string, - sequence: number, - turn: Omit, - observedAt: number -): AgentJournalRenderItem { - return { - itemId: `lifecycle-${turnId}`, - revision: 1, - sequence, - observedAt, - body: agentJournalTurnBody({ turnId, ...turn }) - } -} - -type Timing = ReturnType -const NO_SUBMISSIONS: readonly AgentJournalSubmission[] = [] - -const SUBMISSIONS: AgentJournalSubmission[] = [ - { - clientMessageId: 'first', - fence: 1, - payloadFingerprint: 'fp', - dispatchState: 'accepted', - providerItemId: 'codex:thread:t1:0', - reason: null, - submittedAt: 1, - resolvedAt: 2 - } -] - -describe('useMobileStructuredAgentTurnTiming', () => { - let renderer: ReactTestRenderer | null = null - let timing: Timing | null = null - - function Harness({ - items, - submissions = NO_SUBMISSIONS, - turnId, - hostClock - }: { - items: readonly AgentJournalRenderItem[] - submissions?: readonly AgentJournalSubmission[] - turnId: string | null - hostClock?: { hostNow: number; receivedAt: number } - }): null { - timing = useMobileStructuredAgentTurnTiming({ items, submissions, hostClock }, turnId) - return null - } - - afterEach(() => { - act(() => renderer?.unmount()) - renderer = null - timing = null - vi.useRealTimers() - }) - - it('hands settled host durations through and anchors the live counter locally, once per turn', () => { - vi.useFakeTimers() - vi.setSystemTime(CLIENT_NOW) - const items = [ - user('orca:first', 1), - lifecycle( - 't1', - 2, - { - state: 'interrupted', - startedAt: HOST_START, - completedAt: HOST_START + 61_000, - userItemId: 'codex:thread:t1:0' - }, - HOST_START + 5 - ), - user('u2', 3), - lifecycle( - 't2', - 4, - { state: 'running', startedAt: HOST_START + 100_000 }, - HOST_START + 102_500 - ) - ] - const submissions = SUBMISSIONS - act(() => { - renderer = create(createElement(Harness, { items, submissions, turnId: 't2' })) - }) - expect(timing?.workingStartedAt).toBe(CLIENT_NOW - 2_500) - expect([...timing!.settledTurns]).toEqual([ - ['orca:first', { startedAt: HOST_START, workedSeconds: 61, verdict: 'interruption' }], - ['u2', null] - ]) - - vi.setSystemTime(CLIENT_NOW + 30_000) - act(() => - renderer?.update(createElement(Harness, { items: [...items], submissions, turnId: 't2' })) - ) - expect(timing?.workingStartedAt).toBe(CLIENT_NOW - 2_500) - - act(() => renderer?.update(createElement(Harness, { items, turnId: null }))) - expect(timing?.workingStartedAt).toBeNull() - - // Convert host age through elapsed receipt time rather than either clock’s absolute timestamp. - vi.setSystemTime(CLIENT_NOW + 60_000) - const next = [ - ...items, - user('u3', 5), - lifecycle( - 't3', - 6, - { state: 'running', startedAt: HOST_START + 150_000 }, - HOST_START + 150_100 - ) - ] - act(() => - renderer?.update( - createElement(Harness, { - items: next, - turnId: 't3', - hostClock: { hostNow: HOST_START + 185_000, receivedAt: CLIENT_NOW + 55_000 } - }) - ) - ) - expect(timing?.workingStartedAt).toBe(CLIENT_NOW + 60_000 - 40_000) - }) - - it('leaves the anchor null when an older host records no start', () => { - vi.useFakeTimers() - vi.setSystemTime(CLIENT_NOW) - const items = [user('u1', 1), lifecycle('t1', 2, { state: 'running' }, HOST_START)] - act(() => { - renderer = create(createElement(Harness, { items, turnId: 't1' })) - }) - expect(timing?.workingStartedAt).toBeNull() - expect(timing?.settledTurns.size).toBe(0) - }) -}) diff --git a/mobile/src/session/use-mobile-structured-session-opening.ts b/mobile/src/session/use-mobile-structured-session-opening.ts index e7932042c0d..d3f03a6e134 100644 --- a/mobile/src/session/use-mobile-structured-session-opening.ts +++ b/mobile/src/session/use-mobile-structured-session-opening.ts @@ -5,9 +5,9 @@ import { useWorkspaceRouteHandoff } from '../navigation/workspace-route-handoff' import { openMobileStructuredSession, mobileStructuredSessionHref -} from './open-mobile-structured-session' +} from './native-chat/agent-session/open-mobile-structured-session' import type { StructuredSessionOpenSource } from '../../../src/shared/open-structured-agent-session' -import { mobileStructuredSessionOpenMessage } from './mobile-structured-session-open-message' +import { mobileStructuredSessionOpenMessage } from './native-chat/agent-session/mobile-structured-session-open-message' import { isStructuredAgentId } from '../../../src/shared/agent-session/lifecycle/agent-session-provider-handle-encoding' import type { MobileSessionTab } from './tabs/mobile-session-tabs' import type { useMobileSessionTabSwitching } from './tabs/use-mobile-session-tab-switching' diff --git a/mobile/src/session/use-throttled-latest-value.test.ts b/mobile/src/session/use-throttled-latest-value.test.ts deleted file mode 100644 index b439f394d77..00000000000 --- a/mobile/src/session/use-throttled-latest-value.test.ts +++ /dev/null @@ -1,63 +0,0 @@ -import { createElement } from 'react' -import { act, create, type ReactTestRenderer } from 'react-test-renderer' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { useThrottledLatestValue } from './use-throttled-latest-value' - -describe('useThrottledLatestValue', () => { - let renderer: ReactTestRenderer | null = null - let latest: string | undefined - - function Harness({ value }: { value: string | undefined }): null { - latest = useThrottledLatestValue(value, 50) - return null - } - - function render(value: string | undefined): void { - act(() => { - renderer = create(createElement(Harness, { value })) - }) - } - - function update(value: string | undefined): void { - act(() => renderer?.update(createElement(Harness, { value }))) - } - - beforeEach(() => { - vi.useFakeTimers() - latest = undefined - }) - - afterEach(() => { - act(() => renderer?.unmount()) - renderer = null - vi.useRealTimers() - }) - - it('emits the first frame immediately', () => { - render('a') - expect(latest).toBe('a') - }) - - it('holds rapid updates but eventually emits the latest value', () => { - render('a') - update('ab') - update('abc') - expect(latest).toBe('a') - act(() => { - vi.advanceTimersByTime(50) - }) - expect(latest).toBe('abc') - }) - - it('clears immediately and drops the trailing emit when the value goes undefined', () => { - render('a') - update('ab') - expect(latest).toBe('a') - update(undefined) - expect(latest).toBeUndefined() - act(() => { - vi.advanceTimersByTime(50) - }) - expect(latest).toBeUndefined() - }) -}) diff --git a/mobile/src/source-control/MobileSourceControlRoutePanel.tsx b/mobile/src/source-control/MobileSourceControlRoutePanel.tsx index f82fd2915e9..a6096584cee 100644 --- a/mobile/src/source-control/MobileSourceControlRoutePanel.tsx +++ b/mobile/src/source-control/MobileSourceControlRoutePanel.tsx @@ -10,6 +10,8 @@ export function MobileSourceControlRoutePanel(props: MobileSourceControlPanelPro if (parseWorkspaceKey(props.worktreeId)?.type === 'folder') { return ( void> + onCreate: (repo: Repo, target: FolderRepoTarget, client: RpcClient, name: string) => void + bottomInset: number +} + +/** A folder with no attached worktrees: desktop's copy, then one create card per repository. */ +export function MobileFolderEmptyState(props: Props) { + const { hostId, folder, desktopCapabilities, folderHostCapabilities, observing, refreshers } = + props + const t = useMobileTranslation() + const { client: desktopClient, state } = useHostClient(hostId) + // A relayed server's folder is created on that server, through the desktop. + const routeHost = workspaceRouteExecutionHost(desktopClient, desktopCapabilities, folder.hostId) + const server = routeHost?.startsWith('runtime:') ? routeHost : undefined + // Only exact-name creates land as named; a server's rows also need a desktop new enough to relay its folder lineage. + const canCreate = + state === 'connected' && + routeHost !== null && + folderHostCapabilities.includes(WORKTREE_CREATE_EXACT_NAME_RUNTIME_CAPABILITY) && + (!server || desktopCapabilities.includes(WORKTREE_CREATE_EXACT_NAME_RUNTIME_CAPABILITY)) + const createClient = useMemo( + () => + desktopClient && server + ? scopeRpcClientToExecutionHost(desktopClient, server) + : desktopClient, + [desktopClient, server] + ) + const catalog = useHostQuery( + server ? serverFolderSourceCatalogQuery : folderSourceCatalogQuery, + { hostId, client: canCreate ? createClient : null }, + { exec: server ?? 'local' }, + NO_INPUT, + { enabled: canCreate, subscribed: observing } + ) + const refetchCatalog = catalog.refetch + useEffect(() => { + if (!canCreate) { + return + } + const refresh = () => void refetchCatalog() + refreshers.add(refresh) + return () => { + refreshers.delete(refresh) + } + }, [canCreate, refetchCatalog, refreshers]) + const repos = useMemo( + () => + canCreate + ? selectFolderSourceRepos(catalog.data, projectGroupIdFromRepoId(folder.repoId)) + : [], + [canCreate, catalog.data, folder.repoId] + ) + const name = folder.displayName.trim() + const catalogFailed = canCreate && catalog.data === undefined && catalog.error !== null + + return ( + + void refetchCatalog() + } + : null + } + bottomInset={props.bottomInset} + > + {repos.length > 0 && createClient && name ? ( + + + + {repos.map((repo) => { + const target: FolderRepoTarget = { + hostId, + executionHost: server, + folderWorktreeId: folder.worktreeId, + repoId: repo.id + } + return ( + props.onCreate(repo, target, createClient, name)} + /> + ) + })} + + + ) : null} + + + ) +} + +function FolderRepoCreateCard(props: { + target: FolderRepoTarget + repo: Repo + onPress: () => void +}) { + const t = useMobileTranslation() + const busy = useSyncExternalStore(subscribeFolderRepoCreates, () => + isFolderRepoCreateBusy(props.target) + ) + return ( + + } + accessory={ + busy ? ( + + ) : ( + + ) + } + busy={busy} + onPress={props.onPress} + accessibilityRole="button" + accessibilityLabel={t('sourceControl.folder.createIn', 'Create a worktree in {{repo}}', { + repo: props.repo.displayName + })} + /> + + ) +} + +const styles = themedStyleSheet(() => ({ + scroll: { flexGrow: 1 }, + cards: { gap: spacing.sm } +})) diff --git a/mobile/src/source-control/folder/MobileFolderSourceControlPanel.test.tsx b/mobile/src/source-control/folder/MobileFolderSourceControlPanel.test.tsx new file mode 100644 index 00000000000..102d52bad8b --- /dev/null +++ b/mobile/src/source-control/folder/MobileFolderSourceControlPanel.test.tsx @@ -0,0 +1,126 @@ +import { createElement, type ReactNode } from 'react' +import { act, create, type ReactTestRenderer } from 'react-test-renderer' +import { afterEach, describe, expect, it, vi } from 'vitest' +import type { FolderListRow } from './mobile-folder-attached-worktrees' + +const seen = vi.hoisted(() => { + const state: { covered: boolean; membersObserving: boolean[]; rowsSubscribed: boolean[] } = { + covered: false, + membersObserving: [], + rowsSubscribed: [] + } + return state +}) +vi.mock('react-native', () => ({ ScrollView: 'ScrollView', View: 'View' })) +vi.mock('lucide-react-native', () => ({ GitBranch: 'GitBranch' })) +vi.mock('expo-router', () => ({ useFocusEffect: () => {} })) +vi.mock('react-native-safe-area-context', () => ({ + SafeAreaView: 'SafeAreaView', + useSafeAreaInsets: () => ({ bottom: 0 }) +})) +vi.mock('../../components/MobileStateView', () => ({ + MobileLoadErrorState: 'MobileLoadErrorState', + MobileOfflineState: 'MobileOfflineState', + MobileStateView: 'MobileStateView' +})) +vi.mock('../../transport/connection/connection-retry-action', () => ({ + connectionRetryAction: () => () => {} +})) +vi.mock('../../transport/connection/host-client-hooks', () => ({ + useForceReconnect: () => () => {} +})) +vi.mock('../../components/bottom-drawer/BottomDrawer', () => ({ + OptionPager: ({ main }: { main: ReactNode }) => main, + useOptionPager: () => ({ page: null, open: () => {}, close: () => {} }) +})) +vi.mock('../../components/list/ListGroup', () => ({ ListGroup: 'ListGroup' })) +vi.mock('../../i18n/use-mobile-translation', () => ({ + useMobileTranslation: () => (_key: string, fallback: string) => fallback +})) +vi.mock('../../navigation/use-back-claim', () => ({ useBackClaim: () => {} })) +vi.mock('../../navigation/workspace-route-handoff', () => ({ + useWorkspaceRouteHandoff: () => ({ back: () => {} }) +})) +vi.mock('../../navigation/workspace-route', () => ({ + WorkspaceExecutionScope: 'WorkspaceExecutionScope' +})) +vi.mock('../../theme/mobile-theme', () => ({ colors: {}, spacing: { lg: 16 } })) +vi.mock('../../theme/themed-styles', () => ({ + themedStyleSheet: (styles: () => unknown) => styles() +})) +vi.mock('../../theme/use-mobile-color-scheme', () => ({ useMobileColorScheme: () => {} })) +vi.mock('../MobileSourceControlHeader', () => ({ + MobileSourceControlHeader: 'MobileSourceControlHeader' +})) +vi.mock('../MobileSourceControlPanel', () => ({ MobileSourceControlPanel: 'Panel' })) +vi.mock('../mobile-source-control-styles', () => ({ styles: {} })) +vi.mock('./MobileFolderEmptyState', () => ({ MobileFolderEmptyState: 'EmptyState' })) +vi.mock('../../components/host-protocol-gates-context', () => ({ + useOptionalHostProtocolGates: () => null +})) +vi.mock('./use-folder-create-flow', () => ({ + useFolderCreateFlow: () => ({ + onCreate: async () => {}, + covered: seen.covered, + composerElement: null, + toastElement: null + }) +})) +vi.mock('./MobileFolderWorktreeRow', () => ({ + MobileFolderWorktreeRow: (props: { subscribed: boolean }) => { + seen.rowsSubscribed.push(props.subscribed) + return null + } +})) +vi.mock('./use-mobile-folder-attached-worktrees', () => ({ + useMobileFolderAttachedWorktrees: (_hostId: string, _folderId: string, observing: boolean) => { + seen.membersObserving.push(observing) + return { + folder: { worktreeId: 'folder:f-1', repoId: 'folder-workspace:f-1', displayName: 'payments' }, + worktrees: [ROW], + desktopCapabilities: [], + serverHosts: [], + connState: 'connected', + loadError: null, + refetch: () => {} + } + } +})) + +import { MobileFolderSourceControlPanel } from './MobileFolderSourceControlPanel' + +const ROW: FolderListRow = { + worktreeId: 'repo-1::/w/payments', + repoId: 'repo-1', + repo: 'orca', + displayName: 'payments', + branch: 'payments' +} + +let renderer: ReactTestRenderer | null = null +afterEach(() => { + act(() => renderer?.unmount()) + renderer = null + seen.covered = false + seen.membersObserving = [] + seen.rowsSubscribed = [] +}) + +describe('MobileFolderSourceControlPanel', () => { + it('pauses row status under the create form while the folder members stay live', () => { + seen.covered = true + act(() => { + renderer = create( + createElement(MobileFolderSourceControlPanel, { + hostId: 'host-1', + folderWorktreeId: 'folder:f-1', + name: 'payments', + embedded: true + }) + ) + }) + + expect(seen.rowsSubscribed.at(-1)).toBe(false) + expect(seen.membersObserving.at(-1)).toBe(true) + }) +}) diff --git a/mobile/src/source-control/folder/MobileFolderSourceControlPanel.tsx b/mobile/src/source-control/folder/MobileFolderSourceControlPanel.tsx index f27ba094d7b..e3d21ea0539 100644 --- a/mobile/src/source-control/folder/MobileFolderSourceControlPanel.tsx +++ b/mobile/src/source-control/folder/MobileFolderSourceControlPanel.tsx @@ -24,9 +24,14 @@ import { getWorktreeRowIdentity } from '../../worktree/worktree-host-row-identit import { MobileSourceControlHeader } from '../MobileSourceControlHeader' import { MobileSourceControlPanel } from '../MobileSourceControlPanel' import { styles as sourceControlStyles } from '../mobile-source-control-styles' +import { MobileFolderEmptyState } from './MobileFolderEmptyState' +import { useFolderCreateFlow } from './use-folder-create-flow' import { MobileFolderWorktreeRow } from './MobileFolderWorktreeRow' +import { useOptionalHostProtocolGates } from '../../components/host-protocol-gates-context' import { useMobileFolderAttachedWorktrees } from './use-mobile-folder-attached-worktrees' +const NO_CAPABILITIES: readonly string[] = [] + type Props = { hostId: string folderWorktreeId: string @@ -61,8 +66,22 @@ export function MobileFolderSourceControlPanel({ const observing = focused && !pageOpen const { folder, worktrees, desktopCapabilities, serverHosts, connState, loadError, refetch } = useMobileFolderAttachedWorktrees(hostId, folderWorktreeId, observing) + // In a server's scope these are the server's own; otherwise the desktop's. + const folderHostGates = useOptionalHostProtocolGates() const forceReconnect = useForceReconnect() const [refreshers] = useState(() => new Set<() => void>()) + const createFlow = useFolderCreateFlow({ + hostId, + folderWorktreeId, + executionHost: folder?.hostId?.startsWith('runtime:') ? folder.hostId : undefined, + desktopCapabilities, + members: worktrees, + observing, + refetch, + bottomInset: insets.bottom + }) + // Rows and repositories under a create form wait; the folder's members stay live so creates still reconcile. + const statusObserving = observing && !createFlow.covered const refresh = () => { refetch() for (const refreshNow of refreshers) { @@ -118,13 +137,17 @@ export function MobileFolderSourceControlPanel({ title={t('sourceControl.panel.unavailableTitle', 'Source Control Unavailable')} /> ) : worktrees.length === 0 ? ( - + void createFlow.onCreate(repo, target, client, createName) + } + bottomInset={insets.bottom} /> ) : ( // One card per attached worktree, as desktop shows them. @@ -141,7 +164,7 @@ export function MobileFolderSourceControlPanel({ serverHosts.find((server) => server.hostId === worktree.hostId)?.relay === 'update-needed' } - subscribed={observing} + subscribed={statusObserving} refreshers={refreshers} onOpen={open} /> @@ -160,6 +183,8 @@ export function MobileFolderSourceControlPanel({ )} {/* Every state shares the sheet surface the cards sit on, as the phone's option sheets do. */} {body} + {createFlow.toastElement} + {createFlow.composerElement} ) return ( diff --git a/mobile/src/source-control/folder/folder-repo-worktree-create.test.ts b/mobile/src/source-control/folder/folder-repo-worktree-create.test.ts new file mode 100644 index 00000000000..e89ca544001 --- /dev/null +++ b/mobile/src/source-control/folder/folder-repo-worktree-create.test.ts @@ -0,0 +1,332 @@ +import { afterEach, describe, expect, it, vi } from 'vitest' +import { FakeSession } from '../../transport/connection/mobile-endpoint-supervisor-test-fakes' +import { markRpcDeliveryUnknown } from '../../transport/rpc/rpc-delivery-ambiguity' +import type { RpcResponse } from '../../transport/rpc/rpc-wire-types' +import { + beginFolderComposerSubmission, + createFolderRepoWorktree, + isFolderRepoCreateBusy, + reconcileFolderRepoCreates, + releaseFolderComposerReservation, + type FolderRepoTarget +} from './folder-repo-worktree-create' + +const idempotency = vi.hoisted(() => { + const state: { support: { dedupeTtlMs: number } | false } = { support: false } + return state +}) +vi.mock('../../tasks/worktree-create-capability', () => ({ + readNewWorktreeRuntimeCapabilities: async () => ({ + worktreeCreateIdempotency: idempotency.support + }) +})) + +const FOLDER = 'folder:f-1' +const TAKEN = 'Branch payments already exists\nworktree_create_exact_name_taken' + +afterEach(() => { + vi.useRealTimers() + idempotency.support = false +}) + +let repoCount = 0 +// Each test's own repository: the registry is shared, as it is across screens. +function target(executionHost?: string): FolderRepoTarget { + repoCount += 1 + return { hostId: 'host-1', executionHost, folderWorktreeId: FOLDER, repoId: `repo-${repoCount}` } +} + +function refused(message: string): RpcResponse { + return { id: '1', ok: false, error: { code: 'x', message }, _meta: { runtimeId: 'r' } } +} + +const CREATED: RpcResponse = { + id: '1', + ok: true, + result: { worktree: { id: 'repo::/w/payments', displayName: 'payments' } }, + _meta: { runtimeId: 'r' } +} + +function host(...replies: (RpcResponse | Error)[]): FakeSession { + const client = new FakeSession('connected') + for (const reply of replies) { + if (reply instanceof Error) { + client.sendRequest.mockRejectedValueOnce(reply) + } else { + client.sendRequest.mockResolvedValueOnce(reply) + } + } + return client +} + +const create = (repo: FolderRepoTarget, client: FakeSession) => + createFolderRepoWorktree({ target: repo, client, name: 'payments' }) + +describe('createFolderRepoWorktree', () => { + it('sends one exact-name create attached to the folder', async () => { + const repo = target() + const client = host(CREATED) + + await expect(create(repo, client)).resolves.toEqual({ kind: 'created', name: 'payments' }) + expect(client.sendRequest.mock.calls).toEqual([ + [ + 'worktree.create', + { + repo: `id:${repo.repoId}`, + name: 'payments', + displayName: 'payments', + displayNameKind: 'user', + branchIntent: 'create-exact', + setupDecision: 'inherit', + parentWorkspace: FOLDER, + parentWorkspaceOrigin: 'manual' + }, + expect.anything() + ] + ]) + }) + + it('sends nothing for a second tap while the first create runs', async () => { + const repo = target() + const client = new FakeSession('connected') + let answer: (response: RpcResponse) => void = () => {} + client.sendRequest.mockReturnValue(new Promise((resolve) => (answer = resolve))) + + const first = create(repo, client) + await expect(create(repo, client)).resolves.toEqual({ kind: 'already-running' }) + answer(CREATED) + await first + expect(client.sendRequest).toHaveBeenCalledTimes(1) + }) + + it.each([ + ['the name is taken', TAKEN], + ['the repo asks about setup', 'Setup decision required for this repository'] + ])('keeps the repository for the composer when %s', async (_case, message) => { + const repo = target() + const outcome = await create(repo, host(refused(message))) + + expect(outcome.kind).toBe('needs-composer') + expect(isFolderRepoCreateBusy(repo)).toBe(true) + if (outcome.kind === 'needs-composer') { + releaseFolderComposerReservation(repo, outcome.reservation) + } + expect(isFolderRepoCreateBusy(repo)).toBe(false) + }) + + it('treats a lost reply as possibly created, past the busy backstop, and never offers the composer', async () => { + vi.useFakeTimers({ toFake: ['setTimeout'] }) + const repo = target() + const lost = markRpcDeliveryUnknown(new Error('connection lost')) + + await expect(create(repo, host(lost))).resolves.toEqual({ kind: 'maybe-created' }) + expect(isFolderRepoCreateBusy(repo)).toBe(true) + await expect(create(repo, host(CREATED))).resolves.toEqual({ kind: 'already-running' }) + + // The list never showed it; the card takes taps again but the create is still unresolved. + vi.advanceTimersByTime(60_000) + expect(isFolderRepoCreateBusy(repo)).toBe(false) + const retry = host(refused(TAKEN)) + await expect(create(repo, retry)).resolves.toEqual({ kind: 'maybe-created' }) + expect(retry.sendRequest).toHaveBeenCalledTimes(1) + }) + + it('retries an unconfirmed create as the name it was sent as, even after the folder is renamed', async () => { + vi.useFakeTimers({ toFake: ['setTimeout'] }) + const repo = target() + await create(repo, host(markRpcDeliveryUnknown(new Error('connection lost')))) + vi.advanceTimersByTime(60_000) + + const retry = host(refused(TAKEN)) + await createFolderRepoWorktree({ target: repo, client: retry, name: 'billing' }) + expect(retry.sendRequest.mock.calls[0]?.[1]).toMatchObject({ name: 'payments' }) + }) + + it('asks for setup when an unconfirmed create is refused for it, and resends the same exact name', async () => { + vi.useFakeTimers({ toFake: ['setTimeout'] }) + const repo = target() + await create(repo, host(markRpcDeliveryUnknown(new Error('connection lost')))) + vi.advanceTimersByTime(60_000) + + const asked = await create(repo, host(refused('Setup decision required for this repository'))) + expect(asked.kind).toBe('needs-setup-choice') + expect(isFolderRepoCreateBusy(repo)).toBe(false) + const hold = asked.kind === 'needs-setup-choice' ? asked.hold : -1 + + const resent = host(refused(TAKEN)) + await expect( + createFolderRepoWorktree({ + target: repo, + client: resent, + name: 'billing', + skipSetupFor: hold + }) + ).resolves.toEqual({ kind: 'maybe-created' }) + expect(resent.sendRequest.mock.calls[0]?.[1]).toMatchObject({ + name: 'payments', + branchIntent: 'create-exact', + setupDecision: 'skip' + }) + }) + + it('sends nothing for a setup choice once its create is listed or replaced', async () => { + vi.useFakeTimers({ toFake: ['setTimeout'] }) + const ask = async (repo: FolderRepoTarget) => { + await create(repo, host(markRpcDeliveryUnknown(new Error('connection lost')))) + vi.advanceTimersByTime(60_000) + const asked = await create(repo, host(refused('Setup decision required for this repository'))) + return asked.kind === 'needs-setup-choice' ? asked.hold : -1 + } + const listed = target() + const listedHold = await ask(listed) + const folder = { hostId: 'host-1', executionHost: undefined, folderWorktreeId: FOLDER } + reconcileFolderRepoCreates(folder, [{ repoId: listed.repoId }]) + const replaced = target() + const replacedHold = await ask(replaced) + await ask(replaced) + + const late = host(CREATED) + for (const [repo, hold] of [ + [listed, listedHold], + [replaced, replacedHold] + ] as const) { + await expect( + createFolderRepoWorktree({ + target: repo, + client: late, + name: 'billing', + skipSetupFor: hold + }) + ).resolves.toEqual({ kind: 'checking' }) + } + expect(late.sendRequest).not.toHaveBeenCalled() + }) +}) + +describe('createFolderRepoWorktree after a lost reply on a host that dedupes', () => { + it.each([ + ['answers with the worktree', CREATED, { kind: 'created', name: 'payments' }], + ['refuses the name as taken', refused(TAKEN), { kind: 'maybe-created' }] + ])('resends the same create once reconnected; the host %s', async (_case, replay, expected) => { + idempotency.support = { dedupeTtlMs: 60_000 } + const repo = target() + const client = new FakeSession('connected') + client.sendRequest + .mockImplementationOnce(async () => { + client.publishState('reconnecting') + setTimeout(() => client.publishState('connected'), 0) + throw markRpcDeliveryUnknown(new Error('connection lost')) + }) + .mockResolvedValueOnce(replay) + + await expect(create(repo, client)).resolves.toEqual(expected) + const [first, second] = client.sendRequest.mock.calls.map(([, params]) => params) + expect(second).toEqual(first) + expect(first).toHaveProperty('clientMutationId') + }) +}) + +describe('reconcileFolderRepoCreates', () => { + it('forgets a create once the folder lists its worktree on the same host, not another', async () => { + const repo = target('runtime:env-1') + await create(repo, host(CREATED)) + const folder = { hostId: 'host-1', executionHost: 'runtime:env-1', folderWorktreeId: FOLDER } + + reconcileFolderRepoCreates(folder, [{ repoId: repo.repoId, hostId: 'runtime:env-2' }]) + expect(isFolderRepoCreateBusy(repo)).toBe(true) + reconcileFolderRepoCreates(folder, [{ repoId: repo.repoId, hostId: 'runtime:env-1' }]) + expect(isFolderRepoCreateBusy(repo)).toBe(false) + }) + + it('keeps a create still on its way even if the list already shows the repository', async () => { + const repo = target() + const client = new FakeSession('connected') + let answer: (response: RpcResponse) => void = () => {} + client.sendRequest.mockReturnValue(new Promise((resolve) => (answer = resolve))) + const folder = { hostId: 'host-1', executionHost: undefined, folderWorktreeId: FOLDER } + const members = [{ repoId: repo.repoId }] + + const pending = create(repo, client) + reconcileFolderRepoCreates(folder, members) + expect(isFolderRepoCreateBusy(repo)).toBe(true) + answer(CREATED) + await pending + reconcileFolderRepoCreates(folder, members) + expect(isFolderRepoCreateBusy(repo)).toBe(false) + }) + + it("doesn't let an earlier create's timer end a newer one", async () => { + vi.useFakeTimers({ toFake: ['setTimeout'] }) + const repo = target() + await create(repo, host(markRpcDeliveryUnknown(new Error('lost')))) + vi.advanceTimersByTime(10_000) + const folder = { hostId: 'host-1', executionHost: undefined, folderWorktreeId: FOLDER } + reconcileFolderRepoCreates(folder, [{ repoId: repo.repoId }]) + await create(repo, host(CREATED)) + + vi.advanceTimersByTime(10_000) + expect(isFolderRepoCreateBusy(repo)).toBe(true) + }) +}) + +describe('beginFolderComposerSubmission', () => { + async function composing() { + const repo = target() + const outcome = await create(repo, host(refused(TAKEN))) + if (outcome.kind !== 'needs-composer') { + throw new Error('expected the composer') + } + return { repo, launch: { target: repo, reservation: outcome.reservation, name: 'payments' } } + } + + it('admits one create per repository while it is out, even after the form closes', async () => { + const { repo, launch } = await composing() + let formOpen = true + const submission = beginFolderComposerSubmission(repo, launch, () => formOpen) + + expect(submission).not.toBeNull() + formOpen = false + releaseFolderComposerReservation(repo, launch.reservation) + expect(beginFolderComposerSubmission(repo, launch, () => true)).toBeNull() + expect(await create(repo, host(CREATED))).toEqual({ kind: 'already-running' }) + + submission?.settle('uncertain') + expect(isFolderRepoCreateBusy(repo)).toBe(true) + }) + + it('gives a refused create back to the open form, and a same-host switch its own admission', async () => { + const { repo, launch } = await composing() + const other = { ...repo, repoId: `${repo.repoId}-other` } + + beginFolderComposerSubmission(repo, launch, () => true)?.settle('failed') + expect(isFolderRepoCreateBusy(repo)).toBe(true) + const switched = beginFolderComposerSubmission(other, launch, () => true) + expect(switched).not.toBeNull() + expect(beginFolderComposerSubmission(other, launch, () => true)).toBeNull() + switched?.settle('created') + releaseFolderComposerReservation(repo, launch.reservation) + expect(isFolderRepoCreateBusy(repo)).toBe(false) + expect(isFolderRepoCreateBusy(other)).toBe(true) + }) + it("never sends anything from a card for a form's unconfirmed create, whatever name it used", async () => { + vi.useFakeTimers({ toFake: ['setTimeout'] }) + const { repo, launch } = await composing() + // The form may have sent another name or branch than the card's. + beginFolderComposerSubmission(repo, launch, () => true)?.settle('uncertain') + vi.advanceTimersByTime(60_000) + + expect(beginFolderComposerSubmission(repo, launch, () => true)).toBeNull() + const tap = host(CREATED) + await expect(create(repo, tap)).resolves.toEqual({ kind: 'checking' }) + await expect( + createFolderRepoWorktree({ + target: repo, + client: tap, + name: 'payments', + skipSetupFor: 0 + }) + ).resolves.toEqual({ kind: 'checking' }) + expect(tap.sendRequest).not.toHaveBeenCalled() + expect(isFolderRepoCreateBusy(repo)).toBe(false) + }) +}) diff --git a/mobile/src/source-control/folder/folder-repo-worktree-create.ts b/mobile/src/source-control/folder/folder-repo-worktree-create.ts new file mode 100644 index 00000000000..f4828651a62 --- /dev/null +++ b/mobile/src/source-control/folder/folder-repo-worktree-create.ts @@ -0,0 +1,310 @@ +import { WORKTREE_CREATE_EXACT_NAME_TAKEN_CODE } from '../../../../src/shared/new-workspace/worktree-create-collision' +import { hasRuntimeRpcErrorCode } from '../../../../src/shared/runtime-rpc-error-code' +import type { RpcClient } from '../../transport/rpc/rpc-client-contract' +import { isRpcDeliveryUnknown } from '../../transport/rpc/rpc-delivery-ambiguity' +import { readNewWorktreeRuntimeCapabilities } from '../../tasks/worktree-create-capability' +import { createWorktreeWithNameRetry } from '../../tasks/worktree-create-retry' + +// The host's refusal before creating, when the repo asks to run or skip setup; desktop matches the same text. +const SETUP_DECISION_REQUIRED = 'Setup decision required for this repository' + +// How long a created or unconfirmed card stays busy waiting for the list; the outcome itself is kept until it shows. +const HELD_BUSY_MS = 15_000 + +/** One repository of one folder on one host. */ +export type FolderRepoTarget = { + hostId: string + /** The folder's server; undefined for the paired desktop's own. */ + executionHost: string | undefined + /** `folder:`. */ + folderWorktreeId: string + repoId: string +} + +type Phase = + /** The direct exact-name create is out. */ + | 'creating' + /** Refused before creating; a composer for it is open and nothing has been sent from it. */ + | 'composing' + /** The composer sent its create. */ + | 'submitting' + /** Created, or possibly created: kept until the folder's members show it. */ + | 'held' + +/** + * `name` is the exact name a direct create was sent as, so an unresolved one is retried as itself. + * A composer's create may have used another name or branch, so it is never resent from a card. + */ +type Operation = FolderRepoTarget & { + id: number + phase: Phase + busy: boolean + name: string + origin: 'direct' | 'composer' +} + +// In memory and shared across screens, so a remount or a reopened composer can't send a second create. +const operations = new Map() +const listeners = new Set<() => void>() +let nextId = 1 +let version = 0 + +function notify(): void { + version += 1 + listeners.forEach((listener) => listener()) +} + +export function folderRepoCreateKey(target: FolderRepoTarget): string { + return [target.hostId, target.executionHost ?? '', target.folderWorktreeId, target.repoId].join( + '\0' + ) +} + +export function subscribeFolderRepoCreates(listener: () => void): () => void { + listeners.add(listener) + return () => listeners.delete(listener) +} + +export function getFolderRepoCreatesVersion(): number { + return version +} + +/** The card shows a spinner and takes no taps while its repository's create is busy. */ +export function isFolderRepoCreateBusy(target: FolderRepoTarget): boolean { + return operations.get(folderRepoCreateKey(target))?.busy === true +} + +function start( + target: FolderRepoTarget, + phase: Phase, + name: string, + origin: Operation['origin'] +): Operation { + const operation = { ...target, id: nextId++, phase, busy: true, name, origin } + operations.set(folderRepoCreateKey(target), operation) + notify() + return operation +} + +function isCurrent(operation: Operation): boolean { + return operations.get(folderRepoCreateKey(operation))?.id === operation.id +} + +function release(operation: Operation): void { + if (isCurrent(operation)) { + operations.delete(folderRepoCreateKey(operation)) + notify() + } +} + +function hold(operation: Operation, busy = true): number | undefined { + if (!isCurrent(operation)) { + return undefined + } + // A new identity, so an earlier hold's timer can't end this one. + const held = { ...operation, id: nextId++, phase: 'held' as const, busy } + operations.set(folderRepoCreateKey(held), held) + notify() + if (!busy) { + return held.id + } + setTimeout(() => { + if (isCurrent(held)) { + operations.set(folderRepoCreateKey(held), { ...held, busy: false }) + notify() + } + }, HELD_BUSY_MS) + return held.id +} + +/** Whether `hold` is still this repository's unconfirmed direct create, waiting for a setup choice. */ +export function isFolderRepoHoldPending(target: FolderRepoTarget, hold: number): boolean { + const operation = operations.get(folderRepoCreateKey(target)) + return operation?.id === hold && operation.phase === 'held' && operation.origin === 'direct' +} + +/** Forgets created or unconfirmed creates once the folder lists a worktree from that repository on that host. */ +export function reconcileFolderRepoCreates( + folder: Pick, + members: readonly { repoId: string; hostId?: string }[] +): void { + let changed = false + for (const [key, operation] of operations) { + if ( + operation.phase === 'held' && + operation.hostId === folder.hostId && + operation.executionHost === folder.executionHost && + operation.folderWorktreeId === folder.folderWorktreeId && + members.some( + (member) => + member.repoId === operation.repoId && + (member.hostId?.startsWith('runtime:') ? member.hostId : undefined) === + operation.executionHost + ) + ) { + operations.delete(key) + changed = true + } + } + if (changed) { + notify() + } +} + +export type FolderRepoCreateOutcome = + | { kind: 'created'; name: string; warning?: string } + /** Refused before creating: a branch with that name exists, or the repo asks to run or skip setup. The repository stays reserved for the composer. */ + | { kind: 'needs-composer'; reservation: number } + /** The host may have created it: the reply was lost, or a resend was refused as taken. */ + | { kind: 'maybe-created' } + /** An unconfirmed create's resend needs a setup choice; it is resent as the same exact name with it. */ + | { kind: 'needs-setup-choice'; hold: number } + /** A composer's create is unconfirmed: nothing is sent, the folder is checked until it lists it. */ + | { kind: 'checking' } + | { kind: 'failed'; message: string } + | { kind: 'already-running' } + +/** + * Creates a worktree named after the folder in one of its repositories, attached to the folder, the + * way desktop's empty state does. Only for hosts that advertise exact-name creation. + */ +export async function createFolderRepoWorktree(args: { + target: FolderRepoTarget + /** The client that creates: the desktop's own, or scoped to the folder's server. */ + client: RpcClient + name: string + /** Resends this unconfirmed hold without setup; nothing is sent once the folder shows it or it is replaced. */ + skipSetupFor?: number +}): Promise { + const existing = operations.get(folderRepoCreateKey(args.target)) + const staleResend = + args.skipSetupFor !== undefined && !isFolderRepoHoldPending(args.target, args.skipSetupFor) + if (!staleResend && existing && (existing.phase !== 'held' || existing.busy)) { + return { kind: 'already-running' } + } + if (staleResend || existing?.origin === 'composer') { + return { kind: 'checking' } + } + // An unconfirmed create is retried as the same exact name, even after a rename: a taken name may be its own. + const unresolved = existing !== undefined + const name = existing?.name ?? args.name + const operation = start(args.target, 'creating', name, 'direct') + const settleUnresolved = (outcome: FolderRepoCreateOutcome): FolderRepoCreateOutcome => { + hold(operation) + return outcome + } + try { + const result = await createWorktreeWithNameRetry({ + client: args.client, + baseName: name, + // One exact name: a numbered suffix would be a worktree the user didn't ask for. + maxAttempts: 1, + branchIntentSupported: true, + worktreeCreateIdempotency: readNewWorktreeRuntimeCapabilities(args.client).then( + (capabilities) => capabilities?.worktreeCreateIdempotency ?? false + ), + buildParams: (name) => ({ + repo: `id:${args.target.repoId}`, + name, + displayName: name, + displayNameKind: 'user', + branchIntent: 'create-exact', + setupDecision: args.skipSetupFor === undefined ? 'inherit' : 'skip', + parentWorkspace: args.target.folderWorktreeId, + parentWorkspaceOrigin: 'manual' + }) + }) + if (!('error' in result)) { + hold(operation) + return { + kind: 'created', + name: result.name, + ...(result.warning ? { warning: result.warning } : {}) + } + } + const taken = hasRuntimeRpcErrorCode(result.error, WORKTREE_CREATE_EXACT_NAME_TAKEN_CODE) + if (taken && (result.replayed || unresolved)) { + return settleUnresolved({ kind: 'maybe-created' }) + } + const needsSetup = result.error.includes(SETUP_DECISION_REQUIRED) + if (unresolved && needsSetup) { + // That refusal did no git work, but says nothing about the earlier create; it stays unconfirmed. + const held = hold(operation, false) + return held === undefined + ? { kind: 'maybe-created' } + : { kind: 'needs-setup-choice', hold: held } + } + if (unresolved) { + return settleUnresolved({ kind: 'failed', message: result.error }) + } + if (taken || needsSetup) { + const reserved = { ...operation, phase: 'composing' as const } + operations.set(folderRepoCreateKey(reserved), reserved) + notify() + return { kind: 'needs-composer', reservation: reserved.id } + } + release(operation) + return { kind: 'failed', message: result.error } + } catch (error) { + // Delivery unknown: the host may have created it, and a fresh create would be refused as taken. + if (isRpcDeliveryUnknown(error) || unresolved) { + return settleUnresolved({ kind: 'maybe-created' }) + } + release(operation) + return { kind: 'failed', message: error instanceof Error ? error.message : String(error) } + } +} + +/** A composer closed before sending anything gives its repository back. */ +export function releaseFolderComposerReservation( + target: FolderRepoTarget, + reservation: number +): void { + const operation = operations.get(folderRepoCreateKey(target)) + if (operation?.id === reservation && operation.phase === 'composing') { + release(operation) + } +} + +export type FolderComposerSubmission = { + /** `created` and `uncertain` are kept until the folder shows them; `failed` and `cancelled` give the repository back. */ + settle: (outcome: 'created' | 'uncertain' | 'failed' | 'cancelled') => void +} + +/** + * Admits the composer's create for the repository it actually picked, before anything is sent. + * Null while another create for that repository is out. + */ +export function beginFolderComposerSubmission( + target: FolderRepoTarget, + launch: { target: FolderRepoTarget; reservation: number; name: string }, + /** Whether the composer is still open to retry a refused create. */ + formOpen: () => boolean +): FolderComposerSubmission | null { + const key = folderRepoCreateKey(target) + const existing = operations.get(key) + const ownsReservation = + key === folderRepoCreateKey(launch.target) && + existing?.id === launch.reservation && + existing.phase === 'composing' + if (existing && !ownsReservation) { + return null + } + const operation = start(target, 'submitting', launch.name, 'composer') + return { + settle: (outcome) => { + if (outcome === 'created' || outcome === 'uncertain') { + hold(operation) + return + } + // A refusal leaves the form to try again; the reservation is back with the launch's repository. + if (ownsReservation && formOpen() && isCurrent(operation)) { + const reserved = { ...operation, phase: 'composing' as const, id: launch.reservation } + operations.set(key, reserved) + notify() + return + } + release(operation) + } + } +} diff --git a/mobile/src/source-control/folder/folder-source-repos-query.test.ts b/mobile/src/source-control/folder/folder-source-repos-query.test.ts new file mode 100644 index 00000000000..523143d4bc8 --- /dev/null +++ b/mobile/src/source-control/folder/folder-source-repos-query.test.ts @@ -0,0 +1,124 @@ +import { createElement } from 'react' +import { act, create, type ReactTestRenderer } from 'react-test-renderer' +import { afterEach, describe, expect, it, vi } from 'vitest' +import { stubRpcClient } from '../../transport/rpc/rpc-client-test-stub' +import { useHostQuery } from '../../query/host-query' +import { scopeRpcClientToExecutionHost } from '../../worktree/execution-host-scoped-rpc-client' +import { + documentQueryClient, + settleQueryNotifications +} from '../../test-support/rpc-recording/hook-mount' +import { FakeSession } from '../../transport/connection/mobile-endpoint-supervisor-test-fakes' +import { + folderSourceCatalogQuery, + serverFolderSourceCatalogQuery, + selectFolderSourceRepos +} from './folder-source-repos-query' + +vi.mock('react-native', () => ({ AppState: {} })) + +const GROUP = { + id: 'group-1', + name: 'payments', + parentPath: '/src/payments', + parentGroupId: null, + createdFrom: 'folder', + tabOrder: 0, + isCollapsed: false, + color: null, + createdAt: 1, + updatedAt: 1 +} + +function hostWith(repos: unknown[]): FakeSession { + const client = new FakeSession('connected') + client.sendRequest.mockImplementation(async (method: string) => ({ + id: '1', + ok: true, + result: method === 'repo.list' ? { repos } : { groups: [GROUP] }, + _meta: { runtimeId: 'r' } + })) + return client +} + +const repo = (id: string, path: string) => ({ + id, + path, + displayName: id, + kind: 'git', + badgeColor: 'gray', + addedAt: 1 +}) + +describe('folder source repositories', () => { + it("offers a relayed server's repos in its folder", async () => { + const client = hostWith([repo('api', '/src/payments/api'), repo('elsewhere', '/src/other')]) + const catalog = await serverFolderSourceCatalogQuery.fetch!( + client, + { exec: 'runtime:env-1' }, + {}, + undefined, + { live: false, previousFromStore: false } + ) + + expect(selectFolderSourceRepos(catalog, 'group-1').map((found) => found.id)).toEqual(['api']) + }) +}) + +describe('folder source catalog reads', () => { + let renderer: ReactTestRenderer | null = null + const queries = documentQueryClient() + afterEach(async () => { + act(() => renderer?.unmount()) + renderer = null + await queries.end() + }) + + it.each([true, false])( + "reads a server folder's catalog on the desktop's one event stream (subscribed: %s)", + async (subscribed) => { + let eventStreams = 0 + const desktop = stubRpcClient({ + getLastConnectedAt: () => 1, + sendRequest: async (method) => ({ + id: '1', + ok: true, + result: method === 'repo.list' ? { repos: [] } : { groups: [GROUP] }, + _meta: { runtimeId: 'r' } + }), + subscribe: (method) => { + if (method === 'runtime.clientEvents.subscribe') { + eventStreams += 1 + } + return () => {} + } + }) + const server = scopeRpcClientToExecutionHost(desktop, 'runtime:env-1') + function Harness(): null { + useHostQuery( + folderSourceCatalogQuery, + { hostId: 'host-1', client: desktop }, + { exec: 'local' }, + {}, + { + subscribed: true + } + ) + useHostQuery( + serverFolderSourceCatalogQuery, + { hostId: 'host-1', client: server }, + { exec: 'runtime:env-1' }, + {}, + { subscribed } + ) + return null + } + await act(async () => { + renderer = create(queries.wrap(createElement(Harness))) + }) + await settleQueryNotifications() + + expect(eventStreams).toBe(1) + } + ) +}) diff --git a/mobile/src/source-control/folder/folder-source-repos-query.ts b/mobile/src/source-control/folder/folder-source-repos-query.ts new file mode 100644 index 00000000000..777b3c8fc26 --- /dev/null +++ b/mobile/src/source-control/folder/folder-source-repos-query.ts @@ -0,0 +1,73 @@ +import type { Repo } from '../../../../src/shared/repo-types' +import type { ProjectGroup } from '../../../../src/shared/project-group-types' +import { getFolderSourceRepos } from '../../../../src/shared/folder-workspaces/folder-workspace-source-repos' +import { + LOCAL_EXECUTION_HOST_ID, + getRepoExecutionHostId, + getSshTargetIdForExecutionHost +} from '../../../../src/shared/execution-host' +import { defineHostQuery } from '../../query/host-query' +import type { HostQueryTarget } from '../../query/host-query-key' +import type { RpcClient } from '../../transport/rpc/rpc-client-contract' +import { hostProjectGroupsRead } from '../../worktree/project-sections-operations' +import { listHostRepos, listServerRepos } from '../../worktree/server-repos' + +export type FolderSourceCatalog = { repos: Repo[]; groups: ProjectGroup[] } + +const NO_REPOS: Repo[] = [] + +const fetchFolderSourceCatalog = async ( + client: RpcClient, + target: HostQueryTarget +): Promise => { + const server = target.exec === LOCAL_EXECUTION_HOST_ID ? null : target.exec + const [repos, groupsRead] = await Promise.all([ + server ? listServerRepos(server, client) : listHostRepos(client), + hostProjectGroupsRead.request(client).then((reply) => hostProjectGroupsRead.interpret(reply)) + ]) + if (!repos || !groupsRead.accepted) { + throw new Error('Folder repositories unavailable') + } + // Repos from a server come stamped with it; its groups must match, or the host check drops every repo. + const groups = server + ? groupsRead.value.map((group) => ({ ...group, executionHostId: server })) + : groupsRead.value + return { repos, groups } +} + +/** The paired desktop's own repositories and project groups, re-read when its repos change. */ +export const folderSourceCatalogQuery = defineHostQuery, FolderSourceCatalog>( + { + family: 'folder.sourceCatalog', + fetch: fetchFolderSourceCatalog, + staleTime: 60_000, + refetchOnWindowFocus: true, + signal: { events: ['reposChanged'] } + } +) + +// A relayed server's changes are not signalled, so its reads hold no event stream; focus and refresh read again. +export const serverFolderSourceCatalogQuery = defineHostQuery< + Record, + FolderSourceCatalog +>({ + family: 'folder.sourceCatalog.server', + fetch: fetchFolderSourceCatalog, + staleTime: 60_000, + refetchOnWindowFocus: true +}) + +/** The folder's repositories a worktree can be created in, as desktop's empty state lists them. */ +export function selectFolderSourceRepos( + catalog: FolderSourceCatalog | undefined, + projectGroupId: string | null +): Repo[] { + if (!catalog || !projectGroupId) { + return NO_REPOS + } + const group = catalog.groups.find((candidate) => candidate.id === projectGroupId) ?? null + // Direct SSH hosts can't create worktrees from here (managed hosts route as runtimes). + return getFolderSourceRepos(catalog.repos, catalog.groups, group).filter( + (repo) => !getSshTargetIdForExecutionHost(getRepoExecutionHostId(repo)) + ) +} diff --git a/mobile/src/source-control/folder/mobile-folder-attached-worktrees.ts b/mobile/src/source-control/folder/mobile-folder-attached-worktrees.ts index 5fbae1707b5..6ce2e8040b4 100644 --- a/mobile/src/source-control/folder/mobile-folder-attached-worktrees.ts +++ b/mobile/src/source-control/folder/mobile-folder-attached-worktrees.ts @@ -11,7 +11,7 @@ import { serializeFolderLineage } from './folder-lineage-serialization' /** What a folder list row shows of a host row. */ export type FolderListRow = Pick< Worktree, - 'worktreeId' | 'hostId' | 'repo' | 'displayName' | 'branch' + 'worktreeId' | 'hostId' | 'repoId' | 'repo' | 'displayName' | 'branch' > type FolderLineageRow = MobileLineageRow & Pick @@ -36,6 +36,7 @@ export function toFolderListRow(row: Worktree): FolderListRow { listRow = { worktreeId: row.worktreeId, hostId: row.hostId, + repoId: row.repoId, repo: row.repo, displayName: row.displayName, branch: row.branch diff --git a/mobile/src/source-control/folder/use-folder-create-flow.test.tsx b/mobile/src/source-control/folder/use-folder-create-flow.test.tsx new file mode 100644 index 00000000000..c59d2644858 --- /dev/null +++ b/mobile/src/source-control/folder/use-folder-create-flow.test.tsx @@ -0,0 +1,343 @@ +import { createElement, Fragment } from 'react' +import { act, create, type ReactTestRenderer } from 'react-test-renderer' +import { afterEach, describe, expect, it, vi } from 'vitest' +import { FakeSession } from '../../transport/connection/mobile-endpoint-supervisor-test-fakes' +import { markRpcDeliveryUnknown } from '../../transport/rpc/rpc-delivery-ambiguity' +import type { RpcResponse } from '../../transport/rpc/rpc-wire-types' +import type { NewWorktreeModalProps } from '../../components/new-worktree-modal-types' +import type { FolderListRow } from './mobile-folder-attached-worktrees' +import { isFolderRepoCreateBusy, type FolderRepoTarget } from './folder-repo-worktree-create' +import { useFolderCreateFlow, type FolderCreateRepo } from './use-folder-create-flow' + +const seen = vi.hoisted(() => { + const state: { + composer: NewWorktreeModalProps | null + confirm: { visible: boolean; onConfirm?: () => void; onCancel: () => void } | null + toasts: string[] + haptics: number + } = { composer: null, confirm: null, toasts: [], haptics: 0 } + return state +}) +vi.mock('react-native', () => ({ AppState: {} })) +vi.mock('../../components/NewWorktreeModalController', () => ({ + NewWorktreeModalController: (props: NewWorktreeModalProps) => { + seen.composer = props + return null + } +})) +vi.mock('../../components/ConfirmModal', () => ({ + ConfirmModal: (props: { visible: boolean; onConfirm?: () => void; onCancel: () => void }) => { + seen.confirm = props + return null + } +})) +vi.mock('../../components/TransientToast', () => ({ + TransientToast: () => null, + useTransientToast: () => ({ + message: null, + showToast: (text: string) => seen.toasts.push(text) + }) +})) +vi.mock('../../platform/haptics', () => ({ + triggerSuccess: () => (seen.haptics += 1), + triggerError: () => (seen.haptics += 1) +})) +vi.mock('../../platform/external-link', () => ({ openExternalLink: () => {} })) +vi.mock('../../transport/connection/host-client-hooks', () => ({ + useHostClient: () => ({ client: null, state: 'connected' }) +})) +vi.mock('../../tasks/worktree-create-capability', () => ({ + readNewWorktreeRuntimeCapabilities: async () => ({ worktreeCreateIdempotency: false }) +})) +vi.mock('../../i18n/use-mobile-translation', () => ({ + useMobileTranslation: () => (_key: string, fallback: string) => fallback +})) + +const FOLDER = 'folder:f-1' +const TAKEN = 'Branch payments already exists\nworktree_create_exact_name_taken' +const CREATED: RpcResponse = { + id: '1', + ok: true, + result: { worktree: { id: 'repo::/w/payments', displayName: 'payments' } }, + _meta: { runtimeId: 'r' } +} + +let repoCount = 0 +function repoIn(): { repo: FolderCreateRepo; target: FolderRepoTarget } { + repoCount += 1 + const repoId = `flow-repo-${repoCount}` + return { + repo: { id: repoId, displayName: repoId }, + target: { hostId: 'host-1', executionHost: undefined, folderWorktreeId: FOLDER, repoId } + } +} + +function replying(reply: RpcResponse) { + const client = new FakeSession('connected') + let answer: () => void = () => {} + client.sendRequest.mockReturnValue( + new Promise((resolve) => (answer = () => resolve(reply))) + ) + return { client, answer: () => answer() } +} + +type Flow = ReturnType +let renderer: ReactTestRenderer | null = null + +function mountFlow(refetch: () => void) { + const flow: { current: Flow | null } = { current: null } + let members: FolderListRow[] = [] + function Harness() { + flow.current = useFolderCreateFlow({ + hostId: 'host-1', + folderWorktreeId: FOLDER, + executionHost: undefined, + desktopCapabilities: [], + members, + observing: true, + refetch, + bottomInset: 0 + }) + return createElement(Fragment, null, flow.current.composerElement) + } + act(() => { + renderer = create(createElement(Harness)) + }) + return { + flow, + rerender: (next: FolderListRow[]) => { + members = next + act(() => renderer?.update(createElement(Harness))) + } + } +} + +const composer = (): NewWorktreeModalProps => { + if (!seen.composer) { + throw new Error('the composer never rendered') + } + return seen.composer +} + +afterEach(() => { + vi.useRealTimers() + act(() => renderer?.unmount()) + renderer = null + seen.composer = null + seen.confirm = null + seen.toasts = [] + seen.haptics = 0 +}) + +describe('useFolderCreateFlow', () => { + it("keeps an open form when another repository's create lands", async () => { + const { flow, rerender } = mountFlow(() => {}) + const b = repoIn() + const refusal = replying({ id: '1', ok: false, error: { code: 'x', message: TAKEN } }) + const opening = flow.current!.onCreate(b.repo, b.target, refusal.client, 'payments') + refusal.answer() + await act(() => opening) + expect(composer().folderLaunch?.repoId).toBe(b.target.repoId) + + const a = repoIn() + const creating = replying(CREATED) + const created = flow.current!.onCreate(a.repo, a.target, creating.client, 'payments') + creating.answer() + await act(() => created) + rerender([ + { + worktreeId: 'a-child', + repoId: a.target.repoId, + repo: 'a', + displayName: 'payments', + branch: 'payments' + } + ]) + + expect(composer().visible).toBe(true) + expect(composer().folderLaunch?.repoId).toBe(b.target.repoId) + }) + + it('shows nothing for a create that lands after the screen is left, and still refreshes', async () => { + const refetch = vi.fn() + const { flow } = mountFlow(refetch) + const a = repoIn() + const creating = replying(CREATED) + const created = flow.current!.onCreate(a.repo, a.target, creating.client, 'payments') + + act(() => renderer?.unmount()) + renderer = null + creating.answer() + await created + + expect(refetch).toHaveBeenCalled() + expect(seen.toasts).toEqual([]) + expect(seen.haptics).toBe(0) + }) + + async function openComposer(flow: { current: Flow | null }, repo = repoIn()) { + const refusal = replying({ id: '1', ok: false, error: { code: 'x', message: TAKEN } }) + const opening = flow.current!.onCreate(repo.repo, repo.target, refusal.client, 'payments') + refusal.answer() + await act(() => opening) + return composer() + } + + it("doesn't let an earlier form's close end a newer one", async () => { + const { flow } = mountFlow(() => {}) + const open = () => openComposer(flow) + const first = await open() + act(() => first.onClose()) + const second = await open() + + act(() => first.onClose()) + expect(composer().visible).toBe(true) + expect(composer().folderLaunch?.repoId).toBe(second.folderLaunch?.repoId) + }) + it("shows nothing for an earlier form's create once a newer form is open", async () => { + const { flow } = mountFlow(() => {}) + const first = await openComposer(flow) + act(() => first.onClose()) + const second = await openComposer(flow) + + expect(first.folderLaunch?.submit.presenting()).toBe(false) + act(() => first.onCreated('repo::/w/payments-2', 'payments-2')) + expect(seen.toasts).toEqual([]) + expect(second.folderLaunch?.submit.presenting()).toBe(true) + }) + + it('gives the repository back when the screen is left with an unsent form', async () => { + const { flow } = mountFlow(() => {}) + const repo = repoIn() + await openComposer(flow, repo) + expect(isFolderRepoCreateBusy(repo.target)).toBe(true) + + act(() => renderer?.unmount()) + renderer = null + expect(isFolderRepoCreateBusy(repo.target)).toBe(false) + }) + it('resends an unconfirmed create without setup once the user agrees', async () => { + vi.useFakeTimers({ toFake: ['setTimeout'] }) + const { flow } = mountFlow(() => {}) + const a = repoIn() + const lost = new FakeSession('connected') + lost.sendRequest.mockRejectedValueOnce(markRpcDeliveryUnknown(new Error('connection lost'))) + await act(() => flow.current!.onCreate(a.repo, a.target, lost, 'payments')) + vi.advanceTimersByTime(60_000) + + const retry = new FakeSession('connected') + retry.sendRequest + .mockResolvedValueOnce({ + id: '1', + ok: false, + error: { code: 'x', message: 'Setup decision required for this repository' } + }) + .mockResolvedValueOnce(CREATED) + await act(() => flow.current!.onCreate(a.repo, a.target, retry, 'payments')) + expect(seen.confirm?.visible).toBe(true) + + await act(async () => seen.confirm?.onConfirm?.()) + expect(retry.sendRequest.mock.calls[1]?.[1]).toMatchObject({ + name: 'payments', + branchIntent: 'create-exact', + setupDecision: 'skip' + }) + }) + it("refreshes the folder when a form's create may have landed", async () => { + const refetch = vi.fn() + const { flow } = mountFlow(refetch) + const b = repoIn() + const form = await openComposer(flow, b) + + form.folderLaunch?.submit.begin({ ...b.repo, path: '/w/b' })?.settle('uncertain') + expect(refetch).toHaveBeenCalledTimes(1) + }) + async function setupRefusedRetry(flow: { current: Flow | null }) { + const a = repoIn() + const lost = new FakeSession('connected') + lost.sendRequest.mockRejectedValueOnce(markRpcDeliveryUnknown(new Error('connection lost'))) + await act(() => flow.current!.onCreate(a.repo, a.target, lost, 'payments')) + vi.advanceTimersByTime(60_000) + const retry = replying({ + id: '1', + ok: false, + error: { code: 'x', message: 'Setup decision required for this repository' } + }) + return { a, pending: flow.current!.onCreate(a.repo, a.target, retry.client, 'payments'), retry } + } + + it("doesn't open a setup choice over another form, and the repository can retry after", async () => { + vi.useFakeTimers({ toFake: ['setTimeout'] }) + const { flow } = mountFlow(() => {}) + const { a, pending, retry } = await setupRefusedRetry(flow) + const form = await openComposer(flow) + retry.answer() + await act(() => pending) + + expect(seen.confirm?.visible).toBe(false) + expect(composer().folderLaunch?.repoId).toBe(form.folderLaunch?.repoId) + expect(isFolderRepoCreateBusy(a.target)).toBe(false) + }) + + it("doesn't open a composer over a setup choice, and covers the list while it is open", async () => { + vi.useFakeTimers({ toFake: ['setTimeout'] }) + const { flow } = mountFlow(() => {}) + const { pending, retry } = await setupRefusedRetry(flow) + retry.answer() + await act(() => pending) + expect(seen.confirm?.visible).toBe(true) + expect(flow.current!.covered).toBe(true) + + const b = repoIn() + const refusal = replying({ id: '1', ok: false, error: { code: 'x', message: TAKEN } }) + const opening = flow.current!.onCreate(b.repo, b.target, refusal.client, 'payments') + refusal.answer() + await act(() => opening) + expect(composer().visible).toBe(false) + expect(isFolderRepoCreateBusy(b.target)).toBe(false) + + act(() => seen.confirm?.onCancel()) + expect(flow.current!.covered).toBe(false) + }) + it('closes a setup choice once the folder lists its create, and its stale confirm sends nothing', async () => { + vi.useFakeTimers({ toFake: ['setTimeout'] }) + const { flow, rerender } = mountFlow(() => {}) + const { a, pending, retry } = await setupRefusedRetry(flow) + retry.answer() + await act(() => pending) + const staleConfirm = seen.confirm?.onConfirm + expect(seen.confirm?.visible).toBe(true) + + rerender([ + { + worktreeId: 'a-child', + repoId: a.target.repoId, + repo: 'a', + displayName: 'payments', + branch: 'payments' + } + ]) + expect(seen.confirm?.visible).toBe(false) + await act(async () => staleConfirm?.()) + expect(retry.client.sendRequest).toHaveBeenCalledTimes(1) + expect(seen.composer?.visible).toBe(false) + }) + + it("shows nothing for an older form's create once a setup choice opens, and still refreshes", async () => { + vi.useFakeTimers({ toFake: ['setTimeout'] }) + const refetch = vi.fn() + const { flow } = mountFlow(refetch) + const form = await openComposer(flow) + act(() => form.onClose()) + const { pending, retry } = await setupRefusedRetry(flow) + retry.answer() + await act(() => pending) + expect(seen.confirm?.visible).toBe(true) + refetch.mockClear() + + expect(form.folderLaunch?.submit.presenting()).toBe(false) + act(() => form.onCreated('repo::/w/payments', 'payments')) + expect(seen.toasts).toEqual([]) + expect(refetch).toHaveBeenCalledTimes(1) + }) +}) diff --git a/mobile/src/source-control/folder/use-folder-create-flow.tsx b/mobile/src/source-control/folder/use-folder-create-flow.tsx new file mode 100644 index 00000000000..899a510ea38 --- /dev/null +++ b/mobile/src/source-control/folder/use-folder-create-flow.tsx @@ -0,0 +1,284 @@ +import { useCallback, useEffect, useRef, useState, useSyncExternalStore } from 'react' +import type { Repo } from '../../../../src/shared/repo-types' +import { getRepoExecutionHostId } from '../../../../src/shared/execution-host' +import { ConfirmModal } from '../../components/ConfirmModal' +import { NewWorktreeModalController } from '../../components/NewWorktreeModalController' +import type { MobileWorkspaceRepo } from '../../components/new-worktree-modal-types' +import { TransientToast, useTransientToast } from '../../components/TransientToast' +import { useMobileTranslation } from '../../i18n/use-mobile-translation' +import { openExternalLink } from '../../platform/external-link' +import { triggerError, triggerSuccess } from '../../platform/haptics' +import { useHostClient } from '../../transport/connection/host-client-hooks' +import type { RpcClient } from '../../transport/rpc/rpc-client-contract' +import type { FolderListRow } from './mobile-folder-attached-worktrees' +import { + beginFolderComposerSubmission, + createFolderRepoWorktree, + getFolderRepoCreatesVersion, + isFolderRepoHoldPending, + reconcileFolderRepoCreates, + releaseFolderComposerReservation, + subscribeFolderRepoCreates, + type FolderRepoTarget +} from './folder-repo-worktree-create' + +const NO_LABELS = new Map() + +/** What a create reads of a repository: its id, name and host. */ +export type FolderCreateRepo = Pick + +type SetupChoice = { + /** The unconfirmed create it resends; once that is gone the dialog closes and sends nothing. */ + hold: number + repo: FolderCreateRepo + target: FolderRepoTarget + client: RpcClient + name: string +} + +type ComposerLaunch = { + target: FolderRepoTarget + reservation: number + executionHostId: ReturnType + name: string +} + +/** + * The folder screen's creates: direct exact-name creates, the composer they fall back to, and their + * toasts. Kept above the empty state, so another repository's new card can't close a form being edited. + */ +export function useFolderCreateFlow(args: { + hostId: string + folderWorktreeId: string + /** The folder's server; undefined for the paired desktop's own. */ + executionHost: string | undefined + desktopCapabilities: readonly string[] + members: readonly FolderListRow[] + observing: boolean + refetch: () => void + bottomInset: number +}) { + const { hostId, folderWorktreeId, executionHost, members, observing, refetch } = args + const t = useMobileTranslation() + const { client: desktopClient } = useHostClient(hostId) + const { message, showToast } = useTransientToast() + const [composer, setComposer] = useState(null) + const [setupChoice, setSetupChoice] = useState(null) + // The one form on screen, composer or setup choice. Set as forms open and close, not after render, so + // two answers landing together can't both open one. + const openRef = useRef(null) + // The newest form opened, still set after it closes: an older form's late answer shows nothing over it. + const latestRef = useRef(null) + // Late answers show nothing once this screen is left or covered; the create itself still settles. + const presentingRef = useRef(observing) + useEffect(() => { + presentingRef.current = observing + }, [observing]) + useEffect( + () => () => { + presentingRef.current = false + latestRef.current = null + const open = openRef.current + openRef.current = null + // Left without sending from the form: its repository takes taps again. + if (open && 'reservation' in open) { + releaseFolderComposerReservation(open.target, open.reservation) + } + }, + [] + ) + const presenting = useCallback(() => presentingRef.current, []) + + // A created or unconfirmed create is done once the folder lists a worktree from its repository. + const createsVersion = useSyncExternalStore( + subscribeFolderRepoCreates, + getFolderRepoCreatesVersion + ) + useEffect(() => { + reconcileFolderRepoCreates({ hostId, executionHost, folderWorktreeId }, members) + }, [createsVersion, executionHost, folderWorktreeId, hostId, members]) + + const onCreate = useCallback( + async ( + repo: FolderCreateRepo, + target: FolderRepoTarget, + client: RpcClient, + name: string, + skipSetupFor?: number + ) => { + const outcome = await createFolderRepoWorktree({ target, client, name, skipSetupFor }) + if ( + outcome.kind === 'created' || + outcome.kind === 'maybe-created' || + outcome.kind === 'checking' + ) { + refetch() + } + const opensForm = outcome.kind === 'needs-composer' || outcome.kind === 'needs-setup-choice' + if (opensForm && (!presenting() || openRef.current)) { + // Left, or another form is open: keep that form and leave this repository to try again. + if (outcome.kind === 'needs-composer') { + releaseFolderComposerReservation(target, outcome.reservation) + } + return + } + if (!presenting()) { + return + } + if (outcome.kind === 'created') { + triggerSuccess() + showToast( + outcome.warning ?? + t('sourceControl.folder.created', 'Created worktree {{name}} in {{repo}}', { + name: outcome.name, + repo: repo.displayName + }) + ) + } else if (outcome.kind === 'checking') { + showToast( + t( + 'sourceControl.folder.checking', + 'A worktree from {{repo}} may already have been created. Checking the folder…', + { repo: repo.displayName } + ) + ) + } else if (outcome.kind === 'needs-setup-choice') { + const choice = { hold: outcome.hold, repo, target, client, name } + openRef.current = choice + latestRef.current = choice + setSetupChoice(choice) + } else if (outcome.kind === 'needs-composer') { + const launch = { + target, + reservation: outcome.reservation, + executionHostId: getRepoExecutionHostId(repo), + name + } + openRef.current = launch + latestRef.current = launch + setComposer(launch) + } else if (outcome.kind === 'failed') { + triggerError() + showToast( + outcome.message || + t('sourceControl.folder.createFailed', 'Could not create a worktree in {{repo}}.', { + repo: repo.displayName + }) + ) + } + }, + [presenting, refetch, showToast, t] + ) + + const launch = composer + const presentingLaunch = (opened: ComposerLaunch | null) => + presenting() && opened !== null && latestRef.current === opened + const composerElement = ( + { + const submission = beginFolderComposerSubmission( + { ...launch.target, repoId: repo.id }, + launch, + () => openRef.current === launch + ) + return ( + submission && { + settle: (outcome) => { + submission.settle(outcome) + // A lost reply may have created it: the list shows it, or the form keeps it from being sent twice. + if (outcome === 'uncertain') { + refetch() + } + } + } + ) + }, + presenting: () => presentingLaunch(launch) + } + } + } + : {})} + onCreated={(_worktreeId, createdName, warning) => { + refetch() + if (presentingLaunch(launch)) { + showToast( + warning ?? + t('sourceControl.folder.createdNamed', 'Created worktree {{name}}', { + name: createdName + }) + ) + } + }} + onClose={() => { + // Only this opening's close: an older submission settling can't close a newer form. + if (launch) { + releaseFolderComposerReservation(launch.target, launch.reservation) + if (openRef.current === launch) { + openRef.current = null + } + } + setComposer((current) => (current === launch ? null : current)) + }} + /> + ) + const choice = setupChoice + // Only this dialog's own answer: it closes itself and nothing newer. + const closeChoice = useCallback((closing: SetupChoice | null) => { + if (openRef.current === closing) { + openRef.current = null + } + setSetupChoice((current) => (current === closing ? null : current)) + }, []) + // The folder showed it, or another create replaced it: there is nothing left to retry. + useEffect(() => { + if (choice && !isFolderRepoHoldPending(choice.target, choice.hold)) { + closeChoice(choice) + } + }, [choice, closeChoice, createsVersion]) + const setupChoiceElement = ( + { + if (choice && openRef.current === choice) { + closeChoice(choice) + void onCreate(choice.repo, choice.target, choice.client, choice.name, choice.hold) + } + }} + onCancel={() => closeChoice(choice)} + /> + ) + const toastElement = + return { + onCreate, + /** A form covers the screen: the list under it waits. */ + covered: composer !== null || setupChoice !== null, + composerElement: ( + <> + {composerElement} + {setupChoiceElement} + + ), + toastElement + } +} diff --git a/mobile/src/source-control/review/use-mobile-diff-review-send-actions.ts b/mobile/src/source-control/review/use-mobile-diff-review-send-actions.ts index 0850cb6d148..503eec21acc 100644 --- a/mobile/src/source-control/review/use-mobile-diff-review-send-actions.ts +++ b/mobile/src/source-control/review/use-mobile-diff-review-send-actions.ts @@ -11,7 +11,7 @@ import { reviewTerminalListRead, reviewTerminalSendRun } from './mobile-review-t import type { MobileReviewTerminalTab } from './review-terminal-reply-schema' import { launchAgentWithPrompt } from './pr-ai-triage-launch' import { interpretOrThrowRefusalMessage } from '../../transport/rpc/rpc-refusal-message' -import { healMobileNativeChatStaleInput } from '../../session/native-chat/mobile-native-chat-stale-input' +import { healMobileNativeChatStaleInput } from '../../session/native-chat/composer/mobile-native-chat-stale-input' import type { ReviewScreenState } from './mobile-diff-review-screen-model' import type { ReviewSheetIntents } from './mobile-diff-review-sheets' diff --git a/mobile/src/tasks/blank-workspace-create.ts b/mobile/src/tasks/blank-workspace-create.ts index 5cffd77a7db..05ad977ad21 100644 --- a/mobile/src/tasks/blank-workspace-create.ts +++ b/mobile/src/tasks/blank-workspace-create.ts @@ -1,6 +1,10 @@ import type { TuiAgent } from '../../../src/shared/agent-launch/catalog/tui-agent' import type { RpcClient } from '../transport/rpc/rpc-client-contract' -import { createWorktreeWithNameRetry, type WorktreeCreateResult } from './worktree-create-retry' +import { + createWorktreeWithNameRetry, + type WorktreeCreateParent, + type WorktreeCreateResult +} from './worktree-create-retry' import type { WorktreeCreateAgentLaunch } from './agent-launch-request' import type { WorktreeCreateIdempotencyProbe } from './worktree-create-idempotency-policy' import { @@ -20,6 +24,7 @@ export async function createBlankWorkspace(args: { nameWasGenerated: boolean worktreeCreateIdempotency: WorktreeCreateIdempotencyProbe agentLaunchSupported: WorktreeCreateAgentLaunch['supported'] + parent?: WorktreeCreateParent }): Promise { const agentLaunch: WorktreeCreateAgentLaunch | undefined = args.createdWithAgentId ? { agent: args.createdWithAgentId, supported: args.agentLaunchSupported } @@ -28,6 +33,7 @@ export async function createBlankWorkspace(args: { client: args.client, baseName: args.baseName, nameWasGenerated: args.nameWasGenerated, + parent: args.parent, worktreeCreateIdempotency: args.worktreeCreateIdempotency, ...(agentLaunch ? { agentLaunch } : {}), buildParams: (name) => { diff --git a/mobile/src/tasks/composer-work-item-task.ts b/mobile/src/tasks/composer-work-item-task.ts new file mode 100644 index 00000000000..faaa71adb3b --- /dev/null +++ b/mobile/src/tasks/composer-work-item-task.ts @@ -0,0 +1,55 @@ +import type { MobileLinkedWorkItem } from './mobile-composer-source-types' +import type { WorkspaceCreateTaskItem } from './workspace-create-params' + +/** The composer's linked issue, PR or ticket, as the host's task-workspace source. */ +export function toTaskItem( + item: MobileLinkedWorkItem, + targetRepoId: string +): WorkspaceCreateTaskItem { + if (item.provider === 'github') { + return { + provider: 'github', + source: { + type: item.type === 'pr' ? 'pr' : 'issue', + repoId: item.repoId ?? targetRepoId, + number: item.number, + title: item.title, + url: item.url + } + } + } + if (item.provider === 'gitlab') { + return { + provider: 'gitlab', + source: { + type: item.type === 'mr' ? 'mr' : 'issue', + repoId: item.repoId ?? targetRepoId, + number: item.number, + title: item.title, + url: item.url + } + } + } + if (item.provider === 'jira') { + return { + provider: 'jira', + source: { + key: item.jiraIdentifier ?? '', + title: item.title, + url: item.url + } + } + } + return { + provider: 'linear', + source: { + identifier: item.linearIdentifier ?? '', + title: item.title, + url: item.url, + ...(item.linearWorkspaceId ? { workspaceId: item.linearWorkspaceId } : {}), + ...(item.linearOrganizationUrlKey + ? { organizationUrlKey: item.linearOrganizationUrlKey } + : {}) + } + } +} diff --git a/mobile/src/tasks/source-workspace-create.ts b/mobile/src/tasks/source-workspace-create.ts index d86844b6058..50368bbd580 100644 --- a/mobile/src/tasks/source-workspace-create.ts +++ b/mobile/src/tasks/source-workspace-create.ts @@ -1,20 +1,21 @@ import type { TuiAgent } from '../../../src/shared/agent-launch/catalog/tui-agent' import type { RpcClient } from '../transport/rpc/rpc-client-contract' import { resolveComposerMrBase, resolveComposerPrBase } from './composer-source-base-resolve' -import type { - MobileComposerCreateSelection, - MobileLinkedWorkItem -} from './mobile-composer-source-types' +import type { MobileComposerCreateSelection } from './mobile-composer-source-types' import { resolveMobileWorkspaceCreateName } from './mobile-workspace-name' import type { WorkspaceAgentChoice } from './workspace-agent-selection' +import { toTaskItem } from './composer-work-item-task' import { startupAgentCreateFields, buildTaskWorkspaceCreateParams, type WorkspaceCreateParams, - type WorkspaceCreateSetupDecision, - type WorkspaceCreateTaskItem + type WorkspaceCreateSetupDecision } from './workspace-create-params' -import { createWorktreeWithNameRetry, type WorktreeCreateResult } from './worktree-create-retry' +import { + createWorktreeWithNameRetry, + type WorktreeCreateParent, + type WorktreeCreateResult +} from './worktree-create-retry' import type { WorktreeCreateAgentLaunch } from './agent-launch-request' import type { WorktreeCreateIdempotencyProbe } from './worktree-create-idempotency-policy' import { getClientWorktreeCreateCandidate } from '../../../src/shared/new-workspace/worktree-create-retry-policy' @@ -36,6 +37,7 @@ export type CreateWorkspaceFromComposerArgs = { worktreeCreateIdempotency: WorktreeCreateIdempotencyProbe agentLaunchSupported: WorktreeCreateAgentLaunch['supported'] branchIntentSupported?: boolean | Promise + parent?: WorktreeCreateParent } export async function createWorkspaceFromComposerSource( @@ -57,55 +59,6 @@ function resolveComposerAgentLaunch( return agentId ? { agent: agentId, supported } : undefined } -function toTaskItem(item: MobileLinkedWorkItem, targetRepoId: string): WorkspaceCreateTaskItem { - if (item.provider === 'github') { - return { - provider: 'github', - source: { - type: item.type === 'pr' ? 'pr' : 'issue', - repoId: item.repoId ?? targetRepoId, - number: item.number, - title: item.title, - url: item.url - } - } - } - if (item.provider === 'gitlab') { - return { - provider: 'gitlab', - source: { - type: item.type === 'mr' ? 'mr' : 'issue', - repoId: item.repoId ?? targetRepoId, - number: item.number, - title: item.title, - url: item.url - } - } - } - if (item.provider === 'jira') { - return { - provider: 'jira', - source: { - key: item.jiraIdentifier ?? '', - title: item.title, - url: item.url - } - } - } - return { - provider: 'linear', - source: { - identifier: item.linearIdentifier ?? '', - title: item.title, - url: item.url, - ...(item.linearWorkspaceId ? { workspaceId: item.linearWorkspaceId } : {}), - ...(item.linearOrganizationUrlKey - ? { organizationUrlKey: item.linearOrganizationUrlKey } - : {}) - } - } -} - async function createWorkItemWorkspace(args: { client: RpcClient selection: Extract @@ -116,6 +69,7 @@ async function createWorkItemWorkspace(args: { nameIsAutoManaged?: boolean note: string | undefined worktreeCreateIdempotency: WorktreeCreateIdempotencyProbe + parent?: WorktreeCreateParent }): Promise { const { client, selection, targetRepoId, setupDecision, agent, workspaceName, note } = args const item = selection.item @@ -157,6 +111,7 @@ async function createWorkItemWorkspace(args: { const baseName = String(params.name) // Keep linked work items on terminals: structured sessions cannot hold their unsent URL draft and would submit it as a turn. return createWorktreeWithNameRetry({ + parent: args.parent, client, baseName, worktreeCreateIdempotency: args.worktreeCreateIdempotency, @@ -176,6 +131,7 @@ async function createBranchWorkspace(args: { worktreeCreateIdempotency: WorktreeCreateIdempotencyProbe agentLaunchSupported: WorktreeCreateAgentLaunch['supported'] branchIntentSupported?: boolean | Promise + parent?: WorktreeCreateParent }): Promise { const { client, @@ -206,6 +162,7 @@ async function createBranchWorkspace(args: { fallback: selection.localBranchName }) return createWorktreeWithNameRetry({ + parent: args.parent, client, baseName, worktreeCreateIdempotency: args.worktreeCreateIdempotency, @@ -232,6 +189,7 @@ async function createBranchWorkspace(args: { fallback: selection.branchNameOverride || selection.localBranchName }) return createWorktreeWithNameRetry({ + parent: args.parent, client, baseName, worktreeCreateIdempotency: args.worktreeCreateIdempotency, @@ -270,6 +228,7 @@ async function createNewBranchWorkspace(args: { note: string | undefined worktreeCreateIdempotency: WorktreeCreateIdempotencyProbe agentLaunchSupported: WorktreeCreateAgentLaunch['supported'] + parent?: WorktreeCreateParent }): Promise { const { client, @@ -287,6 +246,7 @@ async function createNewBranchWorkspace(args: { const comment = note?.trim() // Preserve typed git branch names, including slashes; sanitize only the folder, and retry suffixes against the branch name. return createWorktreeWithNameRetry({ + parent: args.parent, client, baseName: selection.branchName, worktreeCreateIdempotency: args.worktreeCreateIdempotency, diff --git a/mobile/src/tasks/worktree-create-retry.test.ts b/mobile/src/tasks/worktree-create-retry.test.ts new file mode 100644 index 00000000000..175cd7c9860 --- /dev/null +++ b/mobile/src/tasks/worktree-create-retry.test.ts @@ -0,0 +1,148 @@ +import { describe, expect, it } from 'vitest' +import { FakeSession } from '../transport/connection/mobile-endpoint-supervisor-test-fakes' +import type { RpcClient } from '../transport/rpc/rpc-client-contract' +import type { RpcResponse } from '../transport/rpc/rpc-wire-types' +import { markRpcDeliveryUnknown } from '../transport/rpc/rpc-delivery-ambiguity' + +import { createWorktreeWithNameRetry } from './worktree-create-retry' + +type Attempt = { method: string; params: unknown } + +function scriptedClient( + outcomes: ({ id: string; displayName?: string; warning?: string } | { errorMessage: string })[], + attempts: Attempt[] +): RpcClient { + let call = 0 + const client = new FakeSession('connected') + client.sendRequest.mockImplementation(async (method: string, params?: unknown) => { + attempts.push({ method, params: params ?? {} }) + const outcome = outcomes[Math.min(call, outcomes.length - 1)]! + call += 1 + if ('errorMessage' in outcome) { + return { + id: '1', + ok: false, + error: { code: 'x', message: outcome.errorMessage }, + _meta: { runtimeId: 'r' } + } + } + return { + id: '1', + ok: true, + result: { + worktree: { + id: outcome.id, + ...(outcome.displayName !== undefined ? { displayName: outcome.displayName } : {}) + }, + ...(outcome.warning !== undefined ? { warning: outcome.warning } : {}) + }, + _meta: { runtimeId: 'r' } + } + }) + return client +} + +describe('createWorktreeWithNameRetry parent', () => { + it('attaches every collision candidate to the same parent', async () => { + const attempts: Attempt[] = [] + const client = scriptedClient( + [{ errorMessage: 'already exists locally' }, { id: 'wt-child' }], + attempts + ) + + await createWorktreeWithNameRetry({ + client, + baseName: 'topic', + buildParams: (name) => ({ repo: 'id:r', name }), + parent: { parentWorkspace: 'folder:f-1', parentWorkspaceOrigin: 'manual' }, + worktreeCreateIdempotency: false + }) + + expect(attempts.map((attempt) => attempt.params)).toEqual([ + { + repo: 'id:r', + name: 'topic', + parentWorkspace: 'folder:f-1', + parentWorkspaceOrigin: 'manual' + }, + { + repo: 'id:r', + name: 'topic-2', + parentWorkspace: 'folder:f-1', + parentWorkspaceOrigin: 'manual' + } + ]) + }) +}) + +describe('createWorktreeWithNameRetry after a lost reply', () => { + it('tries no other name when the resend is refused as taken', async () => { + const client = new FakeSession('connected') + client.sendRequest + .mockImplementationOnce(async () => { + client.publishState('reconnecting') + setTimeout(() => client.publishState('connected'), 0) + throw markRpcDeliveryUnknown(new Error('connection lost')) + }) + .mockResolvedValue({ + id: '1', + ok: false, + error: { code: 'x', message: 'already exists locally' }, + _meta: { runtimeId: 'r' } + }) + + const result = await createWorktreeWithNameRetry({ + client, + baseName: 'topic', + buildParams: (name) => ({ repo: 'id:r', name }), + worktreeCreateIdempotency: { dedupeTtlMs: 60_000 } + }) + + expect(result).toMatchObject({ replayed: true }) + expect(client.sendRequest.mock.calls.map(([, params]) => params)).toEqual([ + expect.objectContaining({ name: 'topic' }), + expect.objectContaining({ name: 'topic' }) + ]) + }) + it('tries no other name when a fallback create after a refused agent launch is resent and refused', async () => { + const client = new FakeSession('connected') + const taken: RpcResponse = { + id: '1', + ok: false, + error: { code: 'x', message: 'already exists locally' }, + _meta: { runtimeId: 'r' } + } + client.sendRequest + .mockResolvedValueOnce({ + id: '1', + ok: false, + error: { code: 'method_not_found', message: 'Unknown method' }, + _meta: { runtimeId: 'r' } + }) + .mockImplementationOnce(async () => { + client.publishState('reconnecting') + setTimeout(() => client.publishState('connected'), 0) + throw markRpcDeliveryUnknown(new Error('connection lost')) + }) + .mockResolvedValue(taken) + + const result = await createWorktreeWithNameRetry({ + client, + baseName: 'topic', + buildParams: (name) => ({ repo: 'id:r', name }), + worktreeCreateIdempotency: { dedupeTtlMs: 60_000 }, + agentLaunch: { agent: 'claude', supported: { replay: false } } + }) + + expect(result).toMatchObject({ replayed: true }) + expect(client.sendRequest.mock.calls.map(([method]) => method)).toEqual([ + 'agent.launch', + 'worktree.create', + 'worktree.create' + ]) + expect(client.sendRequest.mock.calls.slice(1).map(([, params]) => params)).toEqual([ + expect.objectContaining({ name: 'topic' }), + expect.objectContaining({ name: 'topic' }) + ]) + }) +}) diff --git a/mobile/src/tasks/worktree-create-retry.ts b/mobile/src/tasks/worktree-create-retry.ts index 943ff260096..187a68096d6 100644 --- a/mobile/src/tasks/worktree-create-retry.ts +++ b/mobile/src/tasks/worktree-create-retry.ts @@ -20,7 +20,7 @@ import { type WorktreeCreateAgentLaunch } from './agent-launch-request' import { isAgentLaunchReplayUnsupportedRefusal } from '../../../src/shared/agent-launch/contracts/agent-launch-replay-refusal' -import { structuredSessionOperationId } from '../session/structured-session-operation-id' +import { structuredSessionOperationId } from '../session/native-chat/agent-session/structured-session-operation-id' import { WORKTREE_CREATE_TIMEOUT_MS } from './workspace-create-timeout' import type { WorkspaceCreateParams } from './workspace-create-params' import type { @@ -35,7 +35,12 @@ import { // Branches and remote PRs outlive worktrees and escape local preflight dedupe; retry host collision errors with numeric suffixes. export type WorktreeCreateResult = | { worktreeId: string; name: string; warning?: string } - | { error: string } + /** `replayed`: the refusal answered a resend after a lost reply, so the first send may have created it. */ + | { error: string; replayed?: true } + +export type WorktreeCreateParent = Required< + Pick +> export type CreateWorktreeWithNameRetryArgs = { client: RpcClient @@ -46,6 +51,8 @@ export type CreateWorktreeWithNameRetryArgs = { branchIntentSupported?: boolean | Promise agentLaunch?: WorktreeCreateAgentLaunch maxAttempts?: number + /** The workspace the new worktree is attached to, on every attempt. */ + parent?: WorktreeCreateParent mintMutationId?: () => string mintLaunchOperationId?: () => string } @@ -62,11 +69,12 @@ export async function createWorktreeWithNameRetry( const mintMutationId = args.mintMutationId ?? defaultWorktreeCreateMutationId const mintLaunchOperationId = args.mintLaunchOperationId ?? structuredSessionOperationId let lastError: string | null = null + let lastReplayed = false for (let attempt = 0; attempt < maxAttempts; attempt += 1) { const candidateName = args.nameWasGenerated ? getGeneratedWorktreeCreateRetryCandidate(baseName, attempt) : getClientWorktreeCreateCandidate(baseName, attempt) - const candidateParams = buildParams(candidateName, attempt) + const candidateParams = { ...buildParams(candidateName, attempt), ...args.parent } if (attempt === 0 && candidateParams.branchIntent) { if ((await args.branchIntentSupported) !== true) { return { @@ -90,6 +98,7 @@ export async function createWorktreeWithNameRetry( worktreeCreateIdempotency ) let response = sent.response + let replayed = sent.replayed if ( !response.ok && !sent.replayed && @@ -100,9 +109,15 @@ export async function createWorktreeWithNameRetry( ) { // Method refusal can mean the client advertisement lagged the probe; downgrade permanently for this create. launch = null - response = ( - await sendWorktreeCreateResilient(client, null, null, params, worktreeCreateIdempotency) - ).response + const fallback = await sendWorktreeCreateResilient( + client, + null, + null, + params, + worktreeCreateIdempotency + ) + response = fallback.response + replayed = fallback.replayed } // Ledger refusal may follow creation; never retry unnamed. Inspect raw refusal messages for legacy collision handling. if (response.ok) { @@ -118,7 +133,10 @@ export async function createWorktreeWithNameRetry( break } lastError = response.error.message + lastReplayed = replayed + // A replayed refusal may follow a create whose reply was lost; another name could be a second worktree. if ( + replayed || candidateParams.branchIntent === 'open-existing-v2' || launch?.replay || !isRetryableWorktreeCreateConflict(lastError ?? '') @@ -128,7 +146,9 @@ export async function createWorktreeWithNameRetry( } return { error: - lastError ?? translate('tasks.worktreeCreateRetry.createFailed', 'Failed to create workspace') + lastError ?? + translate('tasks.worktreeCreateRetry.createFailed', 'Failed to create workspace'), + ...(lastReplayed ? { replayed: true as const } : {}) } } diff --git a/mobile/src/session/mobile-chat-fork-create-feedback.ts b/mobile/src/terminal/session/mobile-chat-fork-create-feedback.ts similarity index 74% rename from mobile/src/session/mobile-chat-fork-create-feedback.ts rename to mobile/src/terminal/session/mobile-chat-fork-create-feedback.ts index 940eed30732..ece73f51109 100644 --- a/mobile/src/session/mobile-chat-fork-create-feedback.ts +++ b/mobile/src/terminal/session/mobile-chat-fork-create-feedback.ts @@ -1,11 +1,11 @@ -import { isRpcDeliveryUnknown } from '../transport/rpc/rpc-delivery-ambiguity' -import '../transport/connection/stable-logical-rpc-client' -import { isLogicalClientCutoverError } from '../transport/connection/logical-client-cutover-error' -import { RpcIncompatibleReplyError } from '../transport/rpc/rpc-incompatible-reply-error' -import { PROJECT_RUNTIME_REPAIR_REQUIRED_CODE } from '../../../src/shared/project-runtime-repair-message' -import { SESSION_TABS_CHAT_FORK_CLI_RUNTIME_CAPABILITY } from '../../../src/shared/session-tabs-runtime-capabilities' -import type { RpcResponse } from '../transport/rpc/rpc-wire-types' -import { createdTerminalDesktopWarning } from '../terminal/session/mobile-session-terminal-reply-schema' +import { isRpcDeliveryUnknown } from '../../transport/rpc/rpc-delivery-ambiguity' +import '../../transport/connection/stable-logical-rpc-client' +import { isLogicalClientCutoverError } from '../../transport/connection/logical-client-cutover-error' +import { RpcIncompatibleReplyError } from '../../transport/rpc/rpc-incompatible-reply-error' +import { PROJECT_RUNTIME_REPAIR_REQUIRED_CODE } from '../../../../src/shared/project-runtime-repair-message' +import { SESSION_TABS_CHAT_FORK_CLI_RUNTIME_CAPABILITY } from '../../../../src/shared/session-tabs-runtime-capabilities' +import type { RpcResponse } from '../../transport/rpc/rpc-wire-types' +import { createdTerminalDesktopWarning } from './mobile-session-terminal-reply-schema' export function hostSupportsMobileChatFork( hostCapabilities: readonly string[] | undefined diff --git a/mobile/src/terminal/session/use-mobile-session-terminal-create-actions.ts b/mobile/src/terminal/session/use-mobile-session-terminal-create-actions.ts index eef7d2e690e..cb0f22fc01a 100644 --- a/mobile/src/terminal/session/use-mobile-session-terminal-create-actions.ts +++ b/mobile/src/terminal/session/use-mobile-session-terminal-create-actions.ts @@ -11,7 +11,7 @@ import { hostSupportsMobileChatFork, mobileChatForkCreateReplyMessage, mobileChatForkRequestFailureMessage -} from '../../session/mobile-chat-fork-create-feedback' +} from './mobile-chat-fork-create-feedback' import type { MobileSessionTab } from '../../session/tabs/mobile-session-tabs' import type { Terminal } from './mobile-terminal-model' import type { MobileSessionAttachmentsModel } from '../../files/attachments/use-mobile-session-attachments' @@ -23,7 +23,7 @@ import { type MobileSessionTerminalCreateOptions } from './mobile-session-terminal-create-request' import { isAgentSessionHandleProvider } from '../../../../src/shared/agent-session/lifecycle/agent-session-provider-handle' -import { createMobileStructuredAgentSession } from '../../session/mobile-structured-agent-session-launch' +import { createMobileStructuredAgentSession } from '../../session/native-chat/agent-session/mobile-structured-agent-session-launch' import { launchesThroughHost, launchNewTabAgentThroughHost diff --git a/mobile/src/test-support/rpc-recording/adapters/diff-review-action-mount-adapters.ts b/mobile/src/test-support/rpc-recording/adapters/diff-review-action-mount-adapters.ts index 28944cd6c22..016531260e4 100644 --- a/mobile/src/test-support/rpc-recording/adapters/diff-review-action-mount-adapters.ts +++ b/mobile/src/test-support/rpc-recording/adapters/diff-review-action-mount-adapters.ts @@ -10,7 +10,7 @@ import type { } from '../../../source-control/review/mobile-diff-review-screen-model' import type { MountAdapter } from '../recording-scenario' import type { operationModuleLoader } from '../operation-module-loader' -import type * as NativeChatStaleInput from '../../../session/native-chat/mobile-native-chat-stale-input' +import type * as NativeChatStaleInput from '../../../session/native-chat/composer/mobile-native-chat-stale-input' const WORKSPACE = 'workspace-1' const HOST = 'host-1' @@ -30,7 +30,7 @@ export function diffReviewActionMountAdapters( 'mobile/src/source-control/review/mobile-diff-review-sheets.ts' ) const staleInput = modules.load( - 'mobile/src/session/native-chat/mobile-native-chat-stale-input.ts' + 'mobile/src/session/native-chat/composer/mobile-native-chat-stale-input.ts' ) staleInput.resetMobileNativeChatStaleInputForTests() const comment: DiffComment = { diff --git a/mobile/src/test-support/rpc-recording/adapters/native-chat-write-mount-adapters.ts b/mobile/src/test-support/rpc-recording/adapters/native-chat-write-mount-adapters.ts index 3ec6c51603e..93186b10ffd 100644 --- a/mobile/src/test-support/rpc-recording/adapters/native-chat-write-mount-adapters.ts +++ b/mobile/src/test-support/rpc-recording/adapters/native-chat-write-mount-adapters.ts @@ -1,7 +1,7 @@ import type { MountAdapter } from '../recording-scenario' import { mountFixture } from '../recorder-fixture-shape' import type { operationModuleLoader } from '../operation-module-loader' -import type * as NativeChatSend from '../../../session/native-chat/mobile-native-chat-send' +import type * as NativeChatSend from '../../../session/native-chat/composer/mobile-native-chat-send' import type * as NativeChatSessionOptionPersistence from '../../../session/native-chat/input/mobile-native-chat-session-option-persistence' const TERMINAL = 'terminal-1' @@ -14,7 +14,7 @@ export function nativeChatWriteMountAdapters( return { 'nativeChat.terminal-write': ({ client }) => { const send = modules.load( - 'mobile/src/session/native-chat/mobile-native-chat-send.ts' + 'mobile/src/session/native-chat/composer/mobile-native-chat-send.ts' ) const outcomes: Record = {} return { diff --git a/mobile/src/test-support/rpc-recording/adapters/session-screen-read-mount-adapters.ts b/mobile/src/test-support/rpc-recording/adapters/session-screen-read-mount-adapters.ts index 2609c0fc3cd..c7a6cb9e2e4 100644 --- a/mobile/src/test-support/rpc-recording/adapters/session-screen-read-mount-adapters.ts +++ b/mobile/src/test-support/rpc-recording/adapters/session-screen-read-mount-adapters.ts @@ -11,7 +11,7 @@ import { mountFixture } from '../recorder-fixture-shape' import type { MountAdapter } from '../recording-scenario' import type { operationModuleLoader } from '../operation-module-loader' import type * as MobileNativeChatReadability from '../../../session/native-chat/transcript/use-mobile-native-chat-readability' -import type * as MobileNativeChatStopModule from '../../../session/native-chat/use-mobile-native-chat-stop' +import type * as MobileNativeChatStopModule from '../../../session/native-chat/composer/use-mobile-native-chat-stop' const WORKSPACE = 'workspace-1' const HANDLE = 'terminal-1' @@ -163,7 +163,7 @@ export function sessionScreenReadMountAdapters( }, 'session.native-chat-stop': ({ client, effect }) => { const useStop = modules.load( - 'mobile/src/session/native-chat/use-mobile-native-chat-stop.ts' + 'mobile/src/session/native-chat/composer/use-mobile-native-chat-stop.ts' ).useMobileNativeChatStop const errors: string[] = [] let stop: () => void diff --git a/mobile/src/test-support/rpc-recording/adapters/structured-agent-launch-mount-adapters.ts b/mobile/src/test-support/rpc-recording/adapters/structured-agent-launch-mount-adapters.ts index 6e5de8860a0..a9a259b4d25 100644 --- a/mobile/src/test-support/rpc-recording/adapters/structured-agent-launch-mount-adapters.ts +++ b/mobile/src/test-support/rpc-recording/adapters/structured-agent-launch-mount-adapters.ts @@ -1,5 +1,6 @@ import type { MountAdapter } from '../recording-scenario' import type { operationModuleLoader } from '../operation-module-loader' +import type { createMobileStructuredAgentSession } from '../../../session/native-chat/agent-session/mobile-structured-agent-session-launch' const WORKSPACE = 'workspace-1' @@ -9,10 +10,10 @@ export function structuredAgentLaunchMountAdapters( ): Record { return { 'agentSession.structured-launch': ({ client }) => { - const create = modules.load< - typeof import('../../../session/mobile-structured-agent-session-launch') - >( - 'mobile/src/session/mobile-structured-agent-session-launch.ts' + const create = modules.load<{ + createMobileStructuredAgentSession: typeof createMobileStructuredAgentSession + }>( + 'mobile/src/session/native-chat/agent-session/mobile-structured-agent-session-launch.ts' ).createMobileStructuredAgentSession let launched: unknown = 'unlaunched' return { diff --git a/mobile/src/test-support/rpc-recording/adapters/workspace-settings-mounts.ts b/mobile/src/test-support/rpc-recording/adapters/workspace-settings-mounts.ts index 53a17673548..5717b27b063 100644 --- a/mobile/src/test-support/rpc-recording/adapters/workspace-settings-mounts.ts +++ b/mobile/src/test-support/rpc-recording/adapters/workspace-settings-mounts.ts @@ -102,7 +102,9 @@ export function workspaceSettingsMounts( getAgentLaunchSupport: async () => false, transitionDrawer: (view: unknown) => context.effect('drawer', view), onCreated: (id: unknown, name: unknown) => context.effect('created', { id, name }), - onClose: () => context.effect('close', null) + onClose: () => context.effect('close', null), + // Not opened from a folder. + folderLaunch: undefined }) let state: ReturnType const hook = hookMount(() => { diff --git a/mobile/src/transport/rpc/unvalidated-rpc-request-port-inventory.ts b/mobile/src/transport/rpc/unvalidated-rpc-request-port-inventory.ts index 55b32fc1059..30679763873 100644 --- a/mobile/src/transport/rpc/unvalidated-rpc-request-port-inventory.ts +++ b/mobile/src/transport/rpc/unvalidated-rpc-request-port-inventory.ts @@ -45,7 +45,10 @@ export const UNVALIDATED_RPC_REQUEST_PORT_PENDING: readonly UnvalidatedRpcReques { file: 'src/accounts/MobileAccountsScreen.tsx', references: 2 }, // callAgentSession accepts dynamic methods and generic results; typed operations require restructuring its callers. - { file: 'src/session/mobile-structured-agent-session-rpc.ts', references: 1 }, + { + file: 'src/session/native-chat/agent-session/mobile-structured-agent-session-rpc.ts', + references: 1 + }, // The recorded create-terminal prompt uses a unique empty-refusal fallback absent from existing terminal.send operations. { file: 'src/session/use-mobile-session-terminal-create-actions.ts', references: 1 }, diff --git a/mobile/src/transport/web-bundle/mobile-web-bundle-brotli-fetch.test.ts b/mobile/src/transport/web-bundle/mobile-web-bundle-brotli-fetch.test.ts index d88a73b0ad5..2df9a40a4e7 100644 --- a/mobile/src/transport/web-bundle/mobile-web-bundle-brotli-fetch.test.ts +++ b/mobile/src/transport/web-bundle/mobile-web-bundle-brotli-fetch.test.ts @@ -96,7 +96,7 @@ function brotliHost() { } describe('fetchMobileWebBundle from a host that ships brotli copies', () => { - it('reads the copy where the manifest lists one, inflates it, and reports progress in asset bytes', async () => { + it('reads the copy where the manifest lists one, inflates it, and reports progress in the bytes it moves', async () => { const host = brotliHost() const progress: MobileWebBundleFetchProgress[] = [] @@ -111,6 +111,7 @@ describe('fetchMobileWebBundle from a host that ships brotli copies', () => { 3 ) expect(host.methods.filter((method) => method === 'mobileWeb.bundle.range')).toHaveLength(1) - expect(progress.at(-1)).toMatchObject({ receivedBytes: 1332, totalBytes: 1332 }) + // The 46-byte copy plus the 12-byte mark, not the 1,332 bytes they inflate to. + expect(progress.at(-1)).toMatchObject({ receivedBytes: 58, totalBytes: 58 }) }) }) diff --git a/mobile/src/transport/web-bundle/mobile-web-bundle-fetch.test.ts b/mobile/src/transport/web-bundle/mobile-web-bundle-fetch.test.ts index 643778934ec..276a5df91e9 100644 --- a/mobile/src/transport/web-bundle/mobile-web-bundle-fetch.test.ts +++ b/mobile/src/transport/web-bundle/mobile-web-bundle-fetch.test.ts @@ -35,6 +35,7 @@ type HostOptions = { buildId?: string intercept?: (call: HostCall) => unknown onInFlight?: (inFlight: number) => void + catalogs?: readonly string[] } /** Box first, so params that are not an object read as absent instead of throwing. */ @@ -51,7 +52,8 @@ function bundleHost(files: Record, options: HostOptions = {}) { path, sha256: toHex(sha256(content)), byteLength: content.byteLength, - contentType: 'text/plain' + contentType: 'text/plain', + ...(options.catalogs?.includes(path) ? { kind: 'catalog' } : {}) })) .sort((left, right) => (left.path < right.path ? -1 : 1)) // Derive fixture ids from final asset lists unless the test explicitly selects a mismatch. @@ -156,4 +158,18 @@ describe('fetchMobileWebBundle', () => { await expect(failed).rejects.toThrow(/index\.html hashed [0-9a-f]{64}, not/) expect(await refusalOf(failed)).toBe('asset-checksum-mismatch') }) + + it('leaves language-catalog chunks on the desktop and fetches the rest', async () => { + const host = bundleHost( + { 'index.html': 'abcdef', 'assets/de.js': 'catalog' }, + { catalogs: ['assets/de.js'] } + ) + + const fetched = await fetchMobileWebBundle({ client: host.client }) + + expect([...fetched.assets.keys()]).toEqual(['index.html']) + expect(host.calls.some((call) => paramField(call.params, 'path') === 'assets/de.js')).toBe( + false + ) + }) }) diff --git a/mobile/src/transport/web-bundle/mobile-web-bundle-fetch.ts b/mobile/src/transport/web-bundle/mobile-web-bundle-fetch.ts index abd4440ef64..60d00a83979 100644 --- a/mobile/src/transport/web-bundle/mobile-web-bundle-fetch.ts +++ b/mobile/src/transport/web-bundle/mobile-web-bundle-fetch.ts @@ -1,10 +1,11 @@ import { CryptoDigestAlgorithm, digest } from 'expo-crypto' import { PrioritySemaphore } from '../../../../src/shared/priority-semaphore' import { mobileWebBundleManifestRead } from './mobile-web-bundle-operations' -import type { - MobileWebBundleAssetRead, - MobileWebBundleManifestRead, - MobileWebBundleManifestReply +import { + shellDownloadedAssets, + type MobileWebBundleAssetRead, + type MobileWebBundleManifestRead, + type MobileWebBundleManifestReply } from './mobile-web-bundle-reply-schemas' import type { RpcClient } from '../rpc/rpc-client-contract' import { MobileWebBundleFetchError } from './mobile-web-bundle-fetch-refusal' @@ -42,6 +43,7 @@ export const MOBILE_WEB_BUNDLE_WINDOW_STALL_MS = 30_000 const WINDOW_READ_BACKSTOP_MS = (MAX_CONCURRENT_WINDOW_READS + 1) * MOBILE_WEB_BUNDLE_WINDOW_STALL_MS +// Bytes are what the reader moves (a brotli copy where it reads one, else the asset); reused assets add none. export type MobileWebBundleFetchProgress = { readonly completedAssets: number readonly totalAssets: number @@ -52,7 +54,7 @@ export type MobileWebBundleFetchProgress = { export type MobileWebBundleFetchResult = { readonly manifest: MobileWebBundleManifestRead readonly assets: ReadonlyMap - // stageGeneration must copy every reused asset or fail rather than stage an incomplete tree. + // stageGeneration must copy every reused asset or fail rather than stage an incomplete tree (skipped catalogs aside). readonly reused: readonly string[] readonly totalBytes: number readonly elapsedMs: number @@ -92,10 +94,12 @@ export async function fetchMobileWebBundle(args: { const manifest = opened.manifest const reader = mobileWebBundleWindowReader(args.client, opened) const connection = connectionReadsOf(args.client) + // Before reuse: a skipped catalog an older generation lists may not be on disk there either. + const wanted = shellDownloadedAssets(manifest) const candidates = new Set( - args.reusable === undefined ? [] : manifest.assets.filter((entry) => args.reusable?.has(entry)) + args.reusable === undefined ? [] : wanted.filter((entry) => args.reusable?.has(entry)) ) - const fetched = manifest.assets.filter((entry) => !candidates.has(entry)) + const fetched = wanted.filter((entry) => !candidates.has(entry)) const assets = new Map() const reused: string[] = [] let receivedBytes = 0 @@ -180,7 +184,7 @@ export async function fetchMobileWebBundle(args: { downloadedAssets += 1 } // Per window, not per asset: the largest asset goes first, so asset completions bunch at the end. - receivedBytes += assetBytesCredited(asset, offset, bytes.byteLength) + receivedBytes += bytes.byteLength reportProgress() } @@ -246,7 +250,7 @@ export async function fetchMobileWebBundle(args: { const countDownload = (entries: readonly MobileWebBundleAssetRead[]): void => { downloadAssets += entries.length - downloadBytes += entries.reduce((sum, entry) => sum + entry.byteLength, 0) + downloadBytes += entries.reduce((sum, entry) => sum + reader.streamLength(entry), 0) } try { @@ -297,18 +301,6 @@ function planWindowReads( }) } -// Progress stays in asset bytes, the unit of the session's total: a window of a brotli copy counts for its -// share of the asset, and an asset's windows add up to exactly its byteLength. -function assetBytesCredited(asset: AssetReassembly, offset: number, byteLength: number): number { - const streamBytes = asset.stream.byteLength - if (streamBytes === asset.entry.byteLength) { - return byteLength - } - const at = (position: number): number => - Math.floor((asset.entry.byteLength * position) / streamBytes) - return at(offset + byteLength) - at(offset) -} - async function verifyReassembledAsset( asset: AssetReassembly, reader: MobileWebBundleWindowReader diff --git a/mobile/src/transport/web-bundle/mobile-web-bundle-reply-schemas.ts b/mobile/src/transport/web-bundle/mobile-web-bundle-reply-schemas.ts index 602d3d5d4ea..cc72d59b214 100644 --- a/mobile/src/transport/web-bundle/mobile-web-bundle-reply-schemas.ts +++ b/mobile/src/transport/web-bundle/mobile-web-bundle-reply-schemas.ts @@ -46,7 +46,9 @@ const assetSchema = z.looseObject({ .nonnegative() .max(MOBILE_WEB_BUNDLE_MAX_ASSET_BYTES) .optional() - .catch(undefined) + .catch(undefined), + // A kind this build cannot read is a plain asset, downloaded like any other. + kind: z.string().optional().catch(undefined) }) // Read unknown schema versions as numbers so compatibility can name the required update. @@ -132,3 +134,11 @@ export const MobileWebBundleBrotliRangeReplySchema = z.looseObject({ export type MobileWebBundleManifestReply = z.output export type MobileWebBundleManifestRead = MobileWebBundleManifestReply['manifest'] export type MobileWebBundleAssetRead = MobileWebBundleManifestRead['assets'][number] + +// Language-catalog chunks stay on the desktop: this shell grants the page hostCatalogs, and the +// page reads its one catalog over RPC. Everything else is the generation, on disk. +export function shellDownloadedAssets(manifest: { + readonly assets: readonly Asset[] +}): Asset[] { + return manifest.assets.filter((asset) => asset.kind !== 'catalog') +} diff --git a/mobile/src/transport/web-bundle/mobile-web-bundle-window-reader.ts b/mobile/src/transport/web-bundle/mobile-web-bundle-window-reader.ts index 7a27848b680..3182c2744a9 100644 --- a/mobile/src/transport/web-bundle/mobile-web-bundle-window-reader.ts +++ b/mobile/src/transport/web-bundle/mobile-web-bundle-window-reader.ts @@ -7,9 +7,10 @@ import { mobileWebBundleRangeRead } from './mobile-web-bundle-operations' import { decodeMobileWebBundleRange } from './mobile-web-bundle-range-decode' -import type { - MobileWebBundleAssetRead, - MobileWebBundleManifestReply +import { + shellDownloadedAssets, + type MobileWebBundleAssetRead, + type MobileWebBundleManifestReply } from './mobile-web-bundle-reply-schemas' import { MobileWebBundleFetchError } from './mobile-web-bundle-fetch-refusal' import type { RpcClient } from '../rpc/rpc-client-contract' @@ -66,16 +67,7 @@ export function mobileWebBundleWindowReader( } } const native = pairedE2EENativeCodec() - // Hermes has no brotli, so without the native codec every asset stays on gzip ranges. - const brotliLengths = new Map( - native === null - ? [] - : opened.manifest.assets.flatMap((asset) => - asset.brotliByteLength !== undefined && asset.brotliByteLength < asset.byteLength - ? [[asset.path, asset.brotliByteLength] as const] - : [] - ) - ) + const brotliLengths = brotliStreamLengths(opened) return { windowBytes: rangeBytes, streamLength: (asset) => brotliLengths.get(asset.path) ?? asset.byteLength, @@ -108,6 +100,34 @@ export function mobileWebBundleWindowReader( } } +// The assets a reader fetches as their brotli copy, by path, with that copy's length. Hermes has no brotli, +// so without the native codec, and on a host with no range grid, every asset stays on gzip ranges or chunks. +function brotliStreamLengths( + opened: Pick +): ReadonlyMap { + if (opened.rangeBytes === undefined || pairedE2EENativeCodec() === null) { + return new Map() + } + return new Map( + opened.manifest.assets.flatMap((asset) => + asset.brotliByteLength !== undefined && asset.brotliByteLength < asset.byteLength + ? [[asset.path, asset.brotliByteLength] as const] + : [] + ) + ) +} + +// Bytes a whole download moves, in the unit of fetch progress: each brotli copy's length where one is read. +export function mobileWebBundleStreamBytes( + opened: Pick +): number { + const brotliLengths = brotliStreamLengths(opened) + return shellDownloadedAssets(opened.manifest).reduce( + (sum, asset) => sum + (brotliLengths.get(asset.path) ?? asset.byteLength), + 0 + ) +} + // Chunks and brotli windows carry their bytes as they are. function rawWindowReply({ dataBase64, diff --git a/mobile/src/worktree/mobile-agent-child-row-text.ts b/mobile/src/worktree/mobile-agent-child-row-text.ts index f65c9bad302..3b244776904 100644 --- a/mobile/src/worktree/mobile-agent-child-row-text.ts +++ b/mobile/src/worktree/mobile-agent-child-row-text.ts @@ -5,7 +5,7 @@ import { } from '../../../src/shared/agent-status/presentation/agent-child-row-lead-trail' import type { AgentChildRowModel } from '../../../src/shared/agent-status/presentation/agent-child-row-model' import type { AgentChildDisplayState } from '../../../src/shared/agent-status/child-work/agent-status-child-work-display' -import { sayMobileBackgroundTask } from '../session/mobile-background-task-copy' +import { sayMobileBackgroundTask } from '../session/native-chat/input/mobile-background-task-copy' import { translate } from '../i18n/mobile-i18n' import { agentStateLabel } from './agent-row-display' diff --git a/mobile/web-entry/index.tsx b/mobile/web-entry/index.tsx index a2da5aad055..df11b8b7952 100644 --- a/mobile/web-entry/index.tsx +++ b/mobile/web-entry/index.tsx @@ -17,6 +17,7 @@ import { type PageMountTarget } from '../src/mobile-web-shell/bridge/page-bootstrap' import { storageReadResultSchema } from '../src/mobile-web-shell/bridge/bridge-native-verbs' +import { BRIDGE_HOST_CATALOGS_GRANT } from '../src/mobile-web-shell/bridge/bridge-frame-fields' import { publishPageStorage, refreshPageTerminalSettings @@ -33,6 +34,7 @@ import { PageFaultBoundary } from '../src/mobile-web-shell/bridge/page-fault-bou import type { BridgeUiLocale } from '../src/mobile-web-shell/bridge/bridge-envelope' import { BRIDGE_OPEN_ROUTE_PARAM } from '../src/mobile-web-shell/bridge/bridge-route-update' import { activateMobileUiLocale, subscribeMobileUiLanguage } from '../src/i18n/mobile-i18n' +import { startPageLocaleCatalogs } from '../src/i18n/page-locale-catalog-source' import { getUiIntlLocale } from '../src/i18n/ui-intl-locale' import { readDeviceUiLocaleTags, resolveUiLocaleFromTags } from '../src/i18n/system-ui-locale' import { publishPageHostProfile } from '../src/mobile-web-shell/bridge/page-host-profile' @@ -158,6 +160,12 @@ bootstrapShellPage({ // Apply before the first render so no component paints the default dark palette first. applyMobileColorScheme(session.colorScheme) client.onColorSchemeUpdate(applyMobileColorScheme) + const deviceStore = createPageDeviceStore(client) + publishPageDeviceStore(deviceStore) + // A shell that skipped the catalog chunks has the page read its catalog from the desktop; before the first load. + if (session.grants.native.includes(BRIDGE_HOST_CATALOGS_GRANT)) { + startPageLocaleCatalogs({ client, store: deviceStore }) + } // Subscribe before the first catalog load so a switch during startup is not lost; the latest request wins. let uiLocaleActivation = activatePageUiLocale(session.uiLocale) client.onUiLocaleUpdate((locale) => { @@ -187,8 +195,6 @@ bootstrapShellPage({ ).value : null ) - const deviceStore = createPageDeviceStore(client) - publishPageDeviceStore(deviceStore) // An open-target boot paints the shell's target first, so that is the screen to preload and restore. const route = bootRoute(session.route?.params?.[BRIDGE_OPEN_ROUTE_PARAM]) const queryClient = createOrcaQueryClient() diff --git a/package.json b/package.json index 3c157b155c9..79d88915ab6 100644 --- a/package.json +++ b/package.json @@ -141,6 +141,7 @@ "sync:localization-protected-copy": "node config/scripts/localization/catalog-validation/protected-copy-keys.mjs --fix", "verify:localization-extraction": "node config/scripts/localization/source-extraction/verify-localization-extraction.mjs", "verify:localization-coverage": "node config/scripts/localization/source-extraction/audit-localization-coverage.mjs --check", + "verify:startup-worktree-localization-coverage": "node config/scripts/localization/source-extraction/audit-localization-coverage.mjs --check --native-dialog-fields --source-root src/main/startup --source-root src/shared/worktree --allowlist config/startup-worktree-localization-allowlist.json", "verify:mobile-localization": "node config/scripts/localization/catalog-validation/verify-mobile-localization.mjs", "sync:mobile-localization": "node config/scripts/localization/catalog-validation/verify-mobile-localization.mjs --fix", "verify:mobile-localization-coverage": "node config/scripts/localization/source-extraction/audit-localization-coverage.mjs --check --source-root mobile/app --source-root mobile/src --source-root mobile/web-entry --allowlist config/mobile-localization-coverage-allowlist.json", @@ -379,7 +380,7 @@ "tailwind-merge": "^3.7.0", "tailwindcss": "^4.3.3", "tar": "7.5.22", - "tsrs": "0.18.0-ts7.1.0-dev.20260929", + "tsrs": "0.22.0-ts7.1.0-beta", "tw-animate-css": "^1.4.0", "typescript": "^7.0.2", "typescript-api": "npm:typescript@6.0.3", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 16c159b227e..59e5770f157 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -666,8 +666,8 @@ importers: specifier: 7.5.22 version: 7.5.22 tsrs: - specifier: 0.18.0-ts7.1.0-dev.20260929 - version: 0.18.0-ts7.1.0-dev.20260929 + specifier: 0.22.0-ts7.1.0-beta + version: 0.22.0-ts7.1.0-beta tw-animate-css: specifier: ^1.4.0 version: 1.4.0 @@ -4186,40 +4186,52 @@ packages: cpu: [x64] os: [win32] - '@tsrs/darwin-arm64@0.18.0-ts7.1.0-dev.20260929': - resolution: {integrity: sha512-sAirMpaGA9uRQm2W+t4zC7PjnijNuFa4PCSIfLKKo0JyAUCRfnMeev0UGBQ9F3g+9Nz187tvikUs5Irh5+eajA==} + '@tsrs/darwin-arm64@0.22.0-ts7.1.0-beta': + resolution: {integrity: sha512-mY0dMEtFxig4h5At3nByjZe8E4DTDPqqz73kkxQ6gqW5K9ym+u/VHQhtnpTF6ZOTkYyjP3bTaj5T8HcyoGVddA==} engines: {node: '>=16.20.0'} cpu: [arm64] os: [darwin] - '@tsrs/linux-arm64-gnu@0.18.0-ts7.1.0-dev.20260929': - resolution: {integrity: sha512-zm9/z9yylig68JiZF4Aq0Cm26n09KEU8YoQRlG7tdDWTBNAIViYw8knxnWYsjMWVZ2XiU4mYq1xdrOKuOgABHg==} + '@tsrs/darwin-x64@0.22.0-ts7.1.0-beta': + resolution: {integrity: sha512-dvsSnyU8rpI3OqTIH2xxjt9ThvZC52BsL6/LS69eWg7Ieq2oni1PnLels5gGTFqvHFoRbezi5Y0KY7PQ1OmK5w==} + engines: {node: '>=16.20.0'} + cpu: [x64] + os: [darwin] + + '@tsrs/linux-arm64-gnu@0.22.0-ts7.1.0-beta': + resolution: {integrity: sha512-igg42LxSN/DHFqafvDqZW2JNBMH8WIwc1JE/IY4QUDOXNhZnUfDgEu9xo1QYwbgryeo5llmhRwM4CI/BQUWF1Q==} engines: {node: '>=16.20.0'} cpu: [arm64] os: [linux] libc: [glibc] - '@tsrs/linux-arm64-musl@0.18.0-ts7.1.0-dev.20260929': - resolution: {integrity: sha512-Lw7VVU/YQ9JcarODICEiwzMLdFqZprqh5RGTgbS5Uc6I95P635/g5xA1pOC8RVs4efBvAR30J54iDG3l5JEYiw==} + '@tsrs/linux-arm64-musl@0.22.0-ts7.1.0-beta': + resolution: {integrity: sha512-f0zCqMkxPof7QVwjdgA8Fb0n6BtX5MOdILH/xfS+He6gRLCoECky0ejbsgLWCpB06GMlsL1gCbDr0/tmc91APg==} engines: {node: '>=16.20.0'} cpu: [arm64] os: [linux] libc: [musl] - '@tsrs/linux-x64-gnu@0.18.0-ts7.1.0-dev.20260929': - resolution: {integrity: sha512-EdBwBgNICGu1r1h23ixdcKwsMo6E9ll7ZsY3mNERNYqE1Pwdtcat99d5E7zB1J+oy/Xk6YqiizaB6nolIjpDTw==} + '@tsrs/linux-x64-gnu@0.22.0-ts7.1.0-beta': + resolution: {integrity: sha512-/e511w7xXmxBf14paz8eMLUbmlIc33Sy1E00y1FqmnUK04FTotWl+80mNvIVX5NrlOOJgrh+B125t1CHWu/8vQ==} engines: {node: '>=16.20.0'} cpu: [x64] os: [linux] libc: [glibc] - '@tsrs/linux-x64-musl@0.18.0-ts7.1.0-dev.20260929': - resolution: {integrity: sha512-LHk+AOAtXuTlhJhOJ2+elriEIX17ycXljojeNxrrzckOipTG1LksoVWuCSas2nu00EnWAzrdKpt9oqPylUKZfQ==} + '@tsrs/linux-x64-musl@0.22.0-ts7.1.0-beta': + resolution: {integrity: sha512-B3aDOdS5+h77HcFep+KtOI+XmLm2G+FQPQC3KPSDjS/IG0tY9GPSc14mYnLwgO++dXluukO/oufk3J4Lo0CFjg==} engines: {node: '>=16.20.0'} cpu: [x64] os: [linux] libc: [musl] + '@tsrs/win32-x64@0.22.0-ts7.1.0-beta': + resolution: {integrity: sha512-cZ69w+wOECbU6YF5UWi15TK73eX1pgoMEHKSmUF4K8PbS7DPIh/nWMsdb3rM8Ee1SUZ9ONCx+S6myh64SRi3Bg==} + engines: {node: '>=16.20.0'} + cpu: [x64] + os: [win32] + '@types/aria-query@5.0.4': resolution: {integrity: sha512-rfT93uj5s0PRL7EzccGMs3brplhcrghnDoV26NqKhCAS1hVo+WdNsPvE/yb6ilfr5hi2MEk6d5EWJTKdxg8jVw==} @@ -7940,8 +7952,8 @@ packages: tslib@2.8.1: resolution: {integrity: sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==} - tsrs@0.18.0-ts7.1.0-dev.20260929: - resolution: {integrity: sha512-9T0b4Uam/yMFIK16GUx0fUrJqYZnJ/gvSmV9JB8NTyDePvwCI45WFWxyEV/UMV3KfdNRJG/PBsm3fSIB9WmWsA==} + tsrs@0.22.0-ts7.1.0-beta: + resolution: {integrity: sha512-DEnEqQZRM3sHCV7MnQKVeTh61U2SX+0WksVlWp4eVayy0NffQ2oiCOjgH/Eye3sMPYkGwpM3tht3HtVI9NdURg==} engines: {node: '>=16.20.0'} hasBin: true @@ -11174,19 +11186,25 @@ snapshots: '@transcribe-cpp/win32-x64-cpu-vulkan@0.4.1': optional: true - '@tsrs/darwin-arm64@0.18.0-ts7.1.0-dev.20260929': + '@tsrs/darwin-arm64@0.22.0-ts7.1.0-beta': optional: true - '@tsrs/linux-arm64-gnu@0.18.0-ts7.1.0-dev.20260929': + '@tsrs/darwin-x64@0.22.0-ts7.1.0-beta': optional: true - '@tsrs/linux-arm64-musl@0.18.0-ts7.1.0-dev.20260929': + '@tsrs/linux-arm64-gnu@0.22.0-ts7.1.0-beta': optional: true - '@tsrs/linux-x64-gnu@0.18.0-ts7.1.0-dev.20260929': + '@tsrs/linux-arm64-musl@0.22.0-ts7.1.0-beta': optional: true - '@tsrs/linux-x64-musl@0.18.0-ts7.1.0-dev.20260929': + '@tsrs/linux-x64-gnu@0.22.0-ts7.1.0-beta': + optional: true + + '@tsrs/linux-x64-musl@0.22.0-ts7.1.0-beta': + optional: true + + '@tsrs/win32-x64@0.22.0-ts7.1.0-beta': optional: true '@types/aria-query@5.0.4': {} @@ -15511,13 +15529,15 @@ snapshots: tslib@2.8.1: {} - tsrs@0.18.0-ts7.1.0-dev.20260929: + tsrs@0.22.0-ts7.1.0-beta: optionalDependencies: - '@tsrs/darwin-arm64': 0.18.0-ts7.1.0-dev.20260929 - '@tsrs/linux-arm64-gnu': 0.18.0-ts7.1.0-dev.20260929 - '@tsrs/linux-arm64-musl': 0.18.0-ts7.1.0-dev.20260929 - '@tsrs/linux-x64-gnu': 0.18.0-ts7.1.0-dev.20260929 - '@tsrs/linux-x64-musl': 0.18.0-ts7.1.0-dev.20260929 + '@tsrs/darwin-arm64': 0.22.0-ts7.1.0-beta + '@tsrs/darwin-x64': 0.22.0-ts7.1.0-beta + '@tsrs/linux-arm64-gnu': 0.22.0-ts7.1.0-beta + '@tsrs/linux-arm64-musl': 0.22.0-ts7.1.0-beta + '@tsrs/linux-x64-gnu': 0.22.0-ts7.1.0-beta + '@tsrs/linux-x64-musl': 0.22.0-ts7.1.0-beta + '@tsrs/win32-x64': 0.22.0-ts7.1.0-beta tsx@4.23.15: dependencies: diff --git a/src/cli/handlers/orchestration/agent-server-route.test.ts b/src/cli/handlers/orchestration/agent-server-route.test.ts deleted file mode 100644 index b84bae4609c..00000000000 --- a/src/cli/handlers/orchestration/agent-server-route.test.ts +++ /dev/null @@ -1,105 +0,0 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import type * as RuntimeClientModule from '../../runtime-client' -import { refuseAgentServerRoute, requirePeerMailCarrier } from './agent-server-route' - -const { callerShow } = vi.hoisted(() => ({ callerShow: vi.fn() })) -vi.mock('../../runtime-client', async (importOriginal) => { - const actual = await importOriginal() - return { - ...actual, - RuntimeClient: class { - call = callerShow - } - } -}) - -function ctx(command: string[], flags: [string, string | boolean][]) { - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: a handler context with only the fields this function reads. - return { - flags: new Map(flags), - client: { isRemote: true }, - cwd: '/', - json: false, - rawArgs: [...command, ...flags.flatMap(([name, value]) => [`--${name}`, String(value)])] - } as unknown as Parameters[1] -} - -describe('an agent pointing mail at another server', () => { - beforeEach(() => { - vi.stubEnv('ORCA_AGENT_LAUNCH_TOKEN', 'launch-token') - vi.stubEnv('ORCA_AGENT_SESSION_ID', '') - vi.stubEnv('ORCA_CLI_COMMAND', 'orca') - callerShow.mockResolvedValue({ result: { caller: null, terminal: true } }) - }) - - afterEach(() => { - vi.unstubAllEnvs() - callerShow.mockReset() - }) - - it('is refused with the --on command to run instead', async () => { - await expect( - refuseAgentServerRoute( - 'send', - ctx( - ['orchestration', 'send'], - [ - ['environment', 'devB'], - ['to', 'term_b'], - ['subject', 'hi'] - ] - ) - ) - ).rejects.toMatchObject({ - code: 'agent_server_route_refused', - message: - 'send with --environment devB runs on devB and nothing comes back to you. To message an agent on devB, use: orca orchestration send --on devB --to term_b --subject hi' - }) - }) - - it('refuses a check against another server: the mailbox is local', async () => { - await expect( - refuseAgentServerRoute('check', ctx(['orchestration', 'check'], [['environment', 'devB']])) - ).rejects.toMatchObject({ - code: 'mailbox_is_local', - message: - 'Your mailbox is on this Orca; replies from devB arrive here. Drop --environment devB.' - }) - }) - - it('leaves a person in a shell running the command on that server', async () => { - vi.stubEnv('ORCA_AGENT_LAUNCH_TOKEN', '') - await expect( - refuseAgentServerRoute('send', ctx(['orchestration', 'send'], [['environment', 'devB']])) - ).resolves.toBeUndefined() - expect(callerShow).not.toHaveBeenCalled() - }) - - it('leaves a launch its own Orca does not verify running on that server', async () => { - callerShow.mockResolvedValue({ result: { caller: null, terminal: false } }) - await expect( - refuseAgentServerRoute('send', ctx(['orchestration', 'send'], [['environment', 'devB']])) - ).resolves.toBeUndefined() - }) -}) - -describe('send --on from an older Orca', () => { - it('is refused before anything is sent', async () => { - const call = vi - .fn() - .mockResolvedValue({ result: { capabilities: ['orchestration.contract.v1'] } }) - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: a handler context with only the fields this function reads. - const context = { - flags: new Map([['on', 'devB']]), - client: { call }, - cwd: '/', - json: false - } as unknown as Parameters[0] - - await expect(requirePeerMailCarrier(context)).rejects.toMatchObject({ - code: 'server_mail_unsupported' - }) - expect(call).toHaveBeenCalledTimes(1) - expect(call).toHaveBeenCalledWith('status.get') - }) -}) diff --git a/src/main/agent-hooks/server/server-status-application.ts b/src/main/agent-hooks/server/server-status-application.ts index 8c179190ab4..e7a625f10ed 100644 --- a/src/main/agent-hooks/server/server-status-application.ts +++ b/src/main/agent-hooks/server/server-status-application.ts @@ -14,6 +14,7 @@ import type { } from '../../../shared/agent-status/contracts/agent-status-observation' import { AGENT_STATUS_2A_CURRENT_PRODUCER_MODE } from '../../../shared/agent-status/transport/agent-status-legacy-adapter' import { mainAgentState } from '../../../shared/agent-status/lifecycle/main-agent-status' +import { previousCodexTurnContext } from '../../../shared/agent-hook-listener/providers/codex-session-start' import { admitLegacyAgentStatus } from '../../../shared/agent-hook-listener/listener-state' import type { EnrichedAgentHookEventPayload } from './server-types' import { agentTypeToPromptSentAgentKind } from './server-status-identity' @@ -33,7 +34,12 @@ function resolveTurnStartedAt( payload.toolAgentId === undefined && payload.isReplay !== true && payload.providerSessionOnly !== true && - isNewTurnEvent(payload.source, payload.hookEventName) + isNewTurnEvent(payload.source, payload.hookEventName) && + !( + payload.source === 'codex' && + payload.hookEventName === 'SessionStart' && + !payload.hasExplicitPrompt + ) ) { return payload.payload.sessionBoundary === true ? undefined : at } @@ -127,9 +133,17 @@ export abstract class AgentHookServerStatusApplication extends AgentHookServerSt now = Date.now(), observedAt?: number ): EnrichedAgentHookEventPayload { + // Only live submissions open a new turn; cached starts restate historical context. + if ( + !payload.isReplay && + (payload.hookEventName === 'UserPromptSubmit' || payload.hasExplicitPrompt === true) + ) { + this.activeHookTurnCompletedAtByPaneKey.delete(payload.paneKey) + } const previous = this.state.lastStatusByPaneKey.get(payload.paneKey) as | EnrichedAgentHookEventPayload | undefined + const previousTurn = previousCodexTurnContext(previous, payload) const commandCodeNewTurn = previous !== undefined && isCommandCodeNewTurnWhileWorking({ @@ -143,13 +157,13 @@ export abstract class AgentHookServerStatusApplication extends AgentHookServerSt incomingPromptInteractionKey: payload.promptInteractionKey }) const stateStartedAt = - previous && previous.payload.state === payload.payload.state && !commandCodeNewTurn - ? previous.stateStartedAt + previousTurn && previousTurn.payload.state === payload.payload.state && !commandCodeNewTurn + ? previousTurn.stateStartedAt : (observedAt ?? now) - const turnStartedAt = resolveTurnStartedAt(previous, payload, observedAt ?? now) + const turnStartedAt = resolveTurnStartedAt(previousTurn, payload, observedAt ?? now) // Relay rows carry their execution host's turn-end evidence. const { hostTurn, ...turnEnd } = reduceHostTurnEnd( - previous, + previousTurn, payload, observedAt ?? now, payload.connectionId === null @@ -174,9 +188,9 @@ export abstract class AgentHookServerStatusApplication extends AgentHookServerSt ...turnEnd, ...(hostTurn ? { hostTurn } : {}) }, - previous, + previousTurn, leadReplyOf(payload), - !!previous && this.sameTerminalOwner(previous, payload) + !!previousTurn && this.sameTerminalOwner(previousTurn, payload) ) } diff --git a/src/main/agent-hooks/server/server-status-update.ts b/src/main/agent-hooks/server/server-status-update.ts index 4e1a6bb92a3..df37b55c600 100644 --- a/src/main/agent-hooks/server/server-status-update.ts +++ b/src/main/agent-hooks/server/server-status-update.ts @@ -6,10 +6,8 @@ import { needsHookRootEvidence, readHookProcessVerdict } from '../../../shared/agent-hook-listener/presence/agent-hook-owner-presence' -import { - reconcileCodexStatusEvent, - markCodexLeadTurnInterrupted -} from '../../../shared/agent-hook-listener/providers/codex-state' +import { markCodexLeadTurnInterrupted } from '../../../shared/agent-hook-listener/providers/codex-state' +import { reconcileCodexStatusEvent } from '../../../shared/agent-hook-listener/providers/codex-session-start' import { resolveAgentStatusIdentity, shouldSuppressInheritedTerminalStatus @@ -160,10 +158,6 @@ export abstract class AgentHookServerStatusUpdate extends AgentHookServerStatusA this.commitStatusRowMutation(rowBefore, previous) return previous } - // Any submitted prompt (incl. a replayed Codex start) opens a new turn; OSC must not inherit the old stamp. - if (payload.hookEventName === 'UserPromptSubmit' || payload.hasExplicitPrompt === true) { - this.activeHookTurnCompletedAtByPaneKey.delete(payload.paneKey) - } if (terminalOwnedPayload.connectionId) { this.connectionTimestampWatermarkById.set(terminalOwnedPayload.connectionId, now) } @@ -194,9 +188,15 @@ export abstract class AgentHookServerStatusUpdate extends AgentHookServerStatusA const stateReconciledPayload = reconcileCodexStatusEvent( this.state, terminalOwnedPayload, - previous?.payload, + previous, codexRosterAuthority ) + if (!stateReconciledPayload) { + return undefined + } + if (previous && stateReconciledPayload === previous) { + return previous + } // Relay restart loses root context; child hooks must not erase persisted resume/model identity. const rootContextPreservingPayload = retainHookRootContext( stateReconciledPayload, diff --git a/src/main/agent-hooks/server/testing/providers/codex/server-codex-session-start.test.ts b/src/main/agent-hooks/server/testing/providers/codex/server-codex-session-start.test.ts new file mode 100644 index 00000000000..31dd5bd0635 --- /dev/null +++ b/src/main/agent-hooks/server/testing/providers/codex/server-codex-session-start.test.ts @@ -0,0 +1,438 @@ +import { mkdtempSync, rmSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { expect, it, vi } from 'vitest' +import { RelayAgentHookServer } from '../../../../../../wsl-guest/agent-hook-server' +import { buildCachedPaneReplayEnvelope } from '../../../../../../wsl-guest/agent-hook-cached-pane-status' +import type { AgentHookEventPayload } from '../../../../../../shared/agent-hook-listener/listener-event' +import type { AgentHookRelayEnvelope } from '../../../../../../shared/agent-hook-listener/transport/agent-hook-relay' +import { AgentHookServer } from '../../../agent-hook-server' +import { selectFreshExplicitAgentStatus } from '../../../../../runtime/workspaces/process-listing/runtime-hook-agent-row-selection' +import { buildBody, postHookEvent, PANE } from '../../server.test-fixtures' + +function previousRoot(children: number): AgentHookEventPayload { + return { + paneKey: PANE, + connectionId: null, + worktreeId: 'old-owner', + source: 'codex', + hookEventName: 'SubagentStart', + toolAgentId: 'old-0', + providerSession: { key: 'session_id', id: 'old-root' }, + payload: { + agentType: 'codex', + state: 'working', + model: 'old-model', + prompt: 'old task', + mainAgent: { state: 'done', stateStartedAt: 1000 }, + subagents: Array.from({ length: children }, (_, index) => ({ + id: `old-${index}`, + state: 'working', + startedAt: 1000 + })) + } + } +} + +it.each([10, 100])( + 'retires %i foreign-session children at a cached startup boundary', + (children) => { + const desktop = new AgentHookServer() + desktop.beginRemoteRelaySession('wsl:Ubuntu') + desktop.ingestRemote(previousRoot(children), 'wsl:Ubuntu') + expect(desktop.getStatusSnapshot()[0].subagents).toHaveLength(children) + if (children === 100) { + desktop.beginRemoteRelaySession('wsl:Ubuntu') + } + const incoming: AgentHookEventPayload = { + ...previousRoot(0), + toolAgentId: undefined, + hookEventName: 'SessionStart', + providerSession: { key: 'session_id', id: 'new-root' }, + payload: { + agentType: 'codex', + state: 'done', + sessionBoundary: true, + prompt: 'new context', + model: 'new-model', + mainAgent: { state: 'done', outcome: 'cancellation', stateStartedAt: 2000 } + } + } + desktop.ingestRemote( + buildCachedPaneReplayEnvelope({ event: incoming, meta: { source: 'codex' } }), + 'wsl:Ubuntu' + ) + expect(desktop.getStatusSnapshot()[0]).toMatchObject({ + state: 'done', + restoredUnconfirmed: true, + providerSession: { id: 'new-root' }, + prompt: 'new context', + model: 'new-model', + mainAgent: { state: 'done', outcome: 'cancellation', stateStartedAt: 2000 } + }) + expect(desktop.getStatusSnapshot()[0].subagents).toBeUndefined() + expect(desktop._getStateForTests().codexSubagentRosterByPaneKey.get(PANE)?.size).toBe(0) + desktop.ingestRemote({ ...incoming, hookEventName: undefined }, 'wsl:Ubuntu') + expect(desktop.getStatusSnapshot()[0].subagents).toBeUndefined() + } +) + +it.each(['previous', 'incoming'] as const)( + 'preserves live context when the %s session ID is missing', + (missing) => { + const desktop = new AgentHookServer() + const previous = previousRoot(1) + vi.useFakeTimers({ toFake: ['Date'] }) + vi.setSystemTime(1_000) + try { + desktop.ingestRemote( + { + ...previous, + hookEventName: 'UserPromptSubmit', + toolAgentId: undefined, + hasExplicitPrompt: true, + providerSession: missing === 'previous' ? undefined : previous.providerSession, + payload: { ...previous.payload, mainAgent: { state: 'working', stateStartedAt: 1000 } } + }, + 'wsl:Ubuntu' + ) + expect(desktop.getStatusSnapshot()[0].turnStartedAt).toBe(1_000) + vi.setSystemTime(3_000) + desktop.ingestRemote( + { + ...previous, + toolAgentId: undefined, + hookEventName: 'SessionStart', + providerSession: + missing === 'incoming' ? undefined : { key: 'session_id', id: 'new-root' }, + payload: { agentType: 'codex', state: 'working', prompt: '' } + }, + 'wsl:Ubuntu' + ) + expect(desktop.getStatusSnapshot()[0]).toMatchObject({ + state: 'working', + prompt: 'old task', + model: 'old-model', + mainAgent: { state: 'working', stateStartedAt: 1000 }, + subagents: [{ id: 'old-0', state: 'working' }], + turnStartedAt: 1_000 + }) + } finally { + desktop.stop() + vi.useRealTimers() + } + } +) + +it.each(['local', 'relay', 'old-relay', 'old-relay-no-main'] as const)( + 'separates Codex session identity from live turns on %s', + async (route) => { + vi.useFakeTimers({ toFake: ['Date'] }) + vi.setSystemTime(1_000) + const directory = mkdtempSync(join(tmpdir(), 'codex-session-start-')) + const desktop = new AgentHookServer() + let forwarded: AgentHookRelayEnvelope | undefined + const relay = + route === 'local' + ? undefined + : new RelayAgentHookServer({ + endpointDir: directory, + forward: (event) => { + forwarded = event + return desktop.ingestRemote( + route.startsWith('old-') && event.hookEventName === 'SessionStart' + ? { + ...event, + payload: { + ...event.payload, + state: 'working', + sessionBoundary: undefined, + mainAgent: + route === 'old-relay-no-main' + ? undefined + : { state: 'working', stateStartedAt: 900 } + } + } + : event, + 'ssh-connection' + ) + } + }) + await desktop.start({ env: 'production' }) + await relay?.start() + async function post(payload: Record): Promise { + const body = buildBody({ session_id: 'root-session', ...payload }) + const coordinates = relay?.getCoordinates() + const response = coordinates + ? await fetch(`http://127.0.0.1:${coordinates.port}/hook/codex`, { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + Connection: 'close', + 'X-Orca-Agent-Hook-Token': coordinates.token + }, + body: JSON.stringify(body) + }) + : await postHookEvent(desktop, body, '/hook/codex') + expect(response.status).toBe(204) + } + try { + await post({ hook_event_name: 'SessionStart', source: 'startup' }) + expect(desktop.getStatusSnapshot()[0]).toMatchObject({ + state: 'done', + sessionBoundary: true, + mainAgent: { state: 'done' } + }) + expect(desktop.getStatusSnapshot()[0].turnStartedAt).toBeUndefined() + expect(desktop.getStatusSnapshot()[0].turnEndedAt).toBeUndefined() + await post({ hook_event_name: 'UserPromptSubmit', turn_id: 'turn-1', prompt: 'review' }) + expect(desktop.getStatusSnapshot()[0].turnStartedAt).toBe(1_000) + await post({ hook_event_name: 'SubagentStart', agent_id: 'child-session' }) + vi.setSystemTime(2_000) + await post({ hook_event_name: 'SessionStart', source: 'compact' }) + expect(desktop.getStatusSnapshot()[0]).toMatchObject({ + state: 'working', + prompt: 'review', + turnStartedAt: 1_000, + mainAgent: { state: 'working', stateStartedAt: 1_000 }, + subagents: [{ id: 'child-session', state: 'working' }], + providerSession: { id: 'root-session' } + }) + await post({ hook_event_name: 'SessionStart', source: 'future-continuation' }) + expect(desktop.getStatusSnapshot()[0].mainAgent).toMatchObject({ stateStartedAt: 1_000 }) + // A schema-shaped legacy child start must not take over its parent's row. + await post({ + hook_event_name: 'SessionStart', + source: 'resume', + session_id: 'child-session', + transcript_path: join(directory, 'child-rollout.jsonl') + }) + expect(desktop.getStatusSnapshot()[0]).toMatchObject({ + mainAgent: { state: 'working', stateStartedAt: 1_000 }, + providerSession: { id: 'root-session' } + }) + if (route === 'local') { + vi.setSystemTime(2_500) + await post({ hook_event_name: 'UserPromptSubmit', turn_id: 'turn-1', prompt: 'review' }) + expect(desktop.getStatusSnapshot()[0].mainAgent).toMatchObject({ stateStartedAt: 1_000 }) + } + vi.setSystemTime(3_000) + await post({ + hook_event_name: 'PreToolUse', + tool_name: 'request_user_input', + tool_input: { questions: [] } + }) + vi.setSystemTime(4_000) + await post({ hook_event_name: 'SessionStart', source: 'compact' }) + expect(desktop.getStatusSnapshot()[0]).toMatchObject({ + state: 'waiting', + turnStartedAt: route === 'local' ? 2_500 : 1_000, + prompt: 'review', + toolName: 'request_user_input', + mainAgent: { state: 'waiting', stateStartedAt: 3_000 }, + subagents: [{ id: 'child-session', state: 'working' }] + }) + if (route === 'local' || route === 'relay') { + vi.setSystemTime(5_000) + await post({ hook_event_name: 'PostToolUse', tool_name: 'Bash' }) + vi.setSystemTime(6_000) + await post({ hook_event_name: 'UserPromptSubmit', turn_id: 'turn-2', prompt: 'next turn' }) + expect(desktop.getStatusSnapshot()[0].mainAgent).toMatchObject({ stateStartedAt: 6_000 }) + await post({ hook_event_name: 'Stop' }) + await post({ hook_event_name: 'SubagentStart', agent_id: 'child-session' }) + expect(desktop.getStatusSnapshot()[0]).toMatchObject({ + state: 'working', + mainAgent: { state: 'done', stateStartedAt: 6_000 }, + subagents: [{ id: 'child-session', state: 'working' }] + }) + vi.setSystemTime(7_000) + await post({ hook_event_name: 'SessionStart', source: 'compact' }) + expect(desktop.getStatusSnapshot()[0]).toMatchObject({ + state: 'working', + mainAgent: { state: 'done', stateStartedAt: 6_000 }, + subagents: [{ id: 'child-session', state: 'working' }] + }) + await post({ hook_event_name: 'SubagentStop', agent_id: 'child-session' }) + await post({ hook_event_name: 'Interrupt' }) + vi.setSystemTime(8_000) + await post({ hook_event_name: 'SessionStart', source: 'compact' }) + expect(desktop.getStatusSnapshot()[0]).toMatchObject({ + state: 'done', + sessionBoundary: true, + turnStartedAt: 6_000, + mainAgent: { state: 'done', stateStartedAt: 6_000, outcome: 'cancellation' } + }) + await post({ + hook_event_name: 'UserPromptSubmit', + turn_id: 'turn-3', + prompt: 'old session work' + }) + expect(desktop.getStatusSnapshot()[0].turnStartedAt).toBe(8_000) + vi.setSystemTime(9_000) + await post({ hook_event_name: 'Stop', last_assistant_message: 'old reply' }) + expect(desktop.getStatusSnapshot()[0].turnEndedAt).toBe(9_000) + if (route === 'relay') { + expect(forwarded).toMatchObject({ turnEndedAt: 9_000, turnEndDisposition: 'identified' }) + } + if (route === 'local') { + expect(desktop.getAcceptedReply(PANE, 9_000)).toBe('old reply') + } + vi.setSystemTime(route === 'local' ? 9_000 : 10_000) + await post({ + hook_event_name: 'SessionStart', + source: 'startup', + session_id: 'replacement-session', + transcript_path: join(directory, 'replacement.jsonl') + }) + expect(desktop.getStatusSnapshot()[0]).toMatchObject({ + state: 'done', + sessionBoundary: true, + mainAgent: { state: 'done' }, + providerSession: { id: 'replacement-session' } + }) + if (route === 'relay') { + expect(forwarded).toMatchObject({ + hookEventName: 'SessionStart', + providerSession: { id: 'replacement-session' } + }) + expect(forwarded?.turnEndedAt).toBeUndefined() + expect(forwarded?.turnEndDisposition).toBeUndefined() + } + expect(desktop.getStatusSnapshot()[0].turnStartedAt).toBeUndefined() + expect(desktop.getStatusSnapshot()[0].turnEndedAt).toBeUndefined() + expect(desktop.getStatusSnapshot()[0].turnEndDisposition).toBeUndefined() + expect(desktop.getStatusSnapshot()[0].stateStartedAt).toBe( + route === 'local' ? 9_000 : 10_000 + ) + expect(desktop.getAcceptedReply(PANE, 9_000)).toBeUndefined() + vi.setSystemTime(11_000) + await post({ + hook_event_name: 'UserPromptSubmit', + session_id: 'replacement-session', + prompt: 'replacement task' + }) + expect(desktop.getStatusSnapshot()[0]).toMatchObject({ + state: 'working', + prompt: 'replacement task', + turnStartedAt: 11_000 + }) + } + } finally { + relay?.stop() + desktop.stop() + vi.useRealTimers() + rmSync(directory, { recursive: true, force: true }) + } + } +) + +it('does not confirm restored work from an older relay startup or redate a submitted replay', async () => { + const directory = mkdtempSync(join(tmpdir(), 'codex-restored-start-')) + const first = new AgentHookServer() + const desktop = new AgentHookServer() + const event = { + paneKey: PANE, + source: 'codex' as const, + providerSession: { key: 'session_id' as const, id: 'root-session' }, + payload: { + state: 'working' as const, + agentType: 'codex' as const, + prompt: 'old task', + mainAgent: { state: 'working' as const, stateStartedAt: 1_000 } + } + } + try { + await first.start({ env: 'production', userDataPath: directory }) + first.ingestRemote({ ...event, hookEventName: 'UserPromptSubmit' }, 'ssh-connection') + first.flushStatusPersistSync() + first.stop() + await desktop.start({ env: 'production', userDataPath: directory }) + expect(desktop.getStatusSnapshot()[0].restoredUnconfirmed).toBe(true) + desktop.ingestRemote({ ...event, hookEventName: 'SessionStart' }, 'ssh-connection') + expect(desktop.getStatusSnapshot()[0]).toMatchObject({ + state: 'working', + restoredUnconfirmed: true, + providerSession: { id: 'root-session' }, + mainAgent: { state: 'working', stateStartedAt: 1_000 } + }) + desktop.ingestRemote( + { + ...event, + hookEventName: 'SessionStart', + hasExplicitPrompt: true, + isReplay: true + }, + 'ssh-connection' + ) + expect(desktop.getStatusSnapshot()[0].restoredUnconfirmed).toBe(true) + desktop.ingestRemote( + { + ...event, + hookEventName: 'SubagentStart', + toolAgentId: 'child-1', + payload: { + ...event.payload, + subagents: [{ id: 'child-1', state: 'working', startedAt: 1_000 }] + } + }, + 'ssh-connection' + ) + expect(desktop.getStatusSnapshot()[0]).toMatchObject({ + restoredUnconfirmed: true, + subagents: [{ id: 'child-1', state: 'working' }] + }) + desktop.ingestRemote( + { + ...event, + hookEventName: 'UserPromptSubmit', + hasExplicitPrompt: true, + payload: { ...event.payload, mainAgent: { state: 'working', stateStartedAt: 6_000 } } + }, + 'ssh-connection' + ) + expect(desktop.getStatusSnapshot()[0].restoredUnconfirmed).toBeUndefined() + desktop.ingestRemote( + { + ...event, + hookEventName: 'Interrupt', + payload: { + ...event.payload, + state: 'done', + mainAgent: { state: 'done', outcome: 'cancellation', stateStartedAt: 7_000 } + } + }, + 'ssh-connection' + ) + const stopped = desktop.getStatusSnapshot()[0] + expect(stopped.mainAgent).toMatchObject({ state: 'done', outcome: 'cancellation' }) + desktop.ingestRemote( + { ...event, hookEventName: 'SessionStart', hasExplicitPrompt: true, isReplay: true }, + 'ssh-connection' + ) + expect(desktop.getStatusSnapshot()[0]).toEqual(stopped) + expect( + selectFreshExplicitAgentStatus({ + handle: 'fixture', + paneKey: PANE, + hookRows: desktop.getStatusSnapshot() + })?.mainAgentWorkingStartedAt + ).toBeNull() + vi.spyOn(Date, 'now').mockReturnValue(stopped.receivedAt + 31 * 60_000) + desktop.ingestRemote( + { ...event, hookEventName: 'SessionStart', hasExplicitPrompt: true, isReplay: true }, + 'ssh-connection' + ) + expect( + selectFreshExplicitAgentStatus({ + handle: 'fixture', + paneKey: PANE, + hookRows: desktop.getStatusSnapshot() + }) + ).toBeNull() + } finally { + vi.restoreAllMocks() + first.stop() + desktop.stop() + rmSync(directory, { recursive: true, force: true }) + } +}) diff --git a/src/main/agent-hooks/server/testing/providers/codex/server-codex-side-thread.test.ts b/src/main/agent-hooks/server/testing/providers/codex/server-codex-side-thread.test.ts index b2602cf3297..9f9c337af8d 100644 --- a/src/main/agent-hooks/server/testing/providers/codex/server-codex-side-thread.test.ts +++ b/src/main/agent-hooks/server/testing/providers/codex/server-codex-side-thread.test.ts @@ -71,101 +71,3 @@ it('keeps the main Codex turn working through a /side chat after Orca restarts', server.stop() } }) - -it('lets a new ephemeral Codex conversation take over a pane whose last turn finished', async () => { - const dir = mkdtempSync(join(tmpdir(), 'codex-side-thread-')) - dirs.push(dir) - const server = new AgentHookServer() - await server.start({ env: 'production' }) - try { - const main = { session_id: MAIN, transcript_path: join(dir, 'rollout-main.jsonl') } - await postHookEvent( - server, - buildBody({ ...main, hook_event_name: 'UserPromptSubmit', prompt: 'main task' }), - '/hook/codex' - ) - await postHookEvent(server, buildBody({ ...main, hook_event_name: 'Stop' }), '/hook/codex') - const next = { session_id: SIDE, transcript_path: null } - await postHookEvent( - server, - buildBody({ ...next, hook_event_name: 'SessionStart', source: 'startup' }), - '/hook/codex' - ) - await postHookEvent( - server, - buildBody({ ...next, hook_event_name: 'UserPromptSubmit', prompt: 'next task' }), - '/hook/codex' - ) - expect(server.getStatusSnapshot()[0]).toMatchObject({ - state: 'working', - prompt: 'next task', - providerSession: { id: SIDE } - }) - } finally { - server.stop() - } -}) - -// codex-rs/tui/src/app/thread_title.rs starts this rollout-less thread on the first user message (#30049). -const TITLE_THREAD = { session_id: SIDE, transcript_path: null } -const TITLE_PROMPT = 'Generate a concise, single-line task title of at most 36 characters' -// codex-rs/context-fragments/src/recap_prompt.rs; auto-recap runs after the user returns. -const RECAP_PROMPT = 'Write a brief catch-up for a user returning to this task. Return JSON' - -it.each([ - { thread: 'titles the thread during the main turn', prompt: TITLE_PROMPT, mainStopFirst: false }, - { thread: 'titles the thread after the main turn', prompt: TITLE_PROMPT, mainStopFirst: true }, - { thread: 'writes a recap', prompt: RECAP_PROMPT, mainStopFirst: true } -])('keeps the main Codex row when Codex $thread', async ({ prompt, mainStopFirst }) => { - const dir = mkdtempSync(join(tmpdir(), 'codex-side-thread-')) - dirs.push(dir) - const server = new AgentHookServer() - await server.start({ env: 'production' }) - const post = (payload: Record): Promise => - postHookEvent(server, buildBody(payload), '/hook/codex') - try { - const main = { session_id: MAIN, transcript_path: join(dir, 'rollout-main.jsonl') } - await post({ ...main, hook_event_name: 'UserPromptSubmit', prompt: 'main task' }) - if (mainStopFirst) { - await post({ ...main, hook_event_name: 'Stop' }) - } - const expected = { - state: mainStopFirst ? 'done' : 'working', - prompt: 'main task', - providerSession: { id: MAIN } - } - await post({ ...TITLE_THREAD, hook_event_name: 'SessionStart', source: 'startup' }) - expect(server.getStatusSnapshot()[0]).toMatchObject(expected) - await post({ ...TITLE_THREAD, hook_event_name: 'UserPromptSubmit', prompt }) - await post({ ...TITLE_THREAD, hook_event_name: 'Stop' }) - expect(server.getStatusSnapshot()[0]).toMatchObject(expected) - if (!mainStopFirst) { - await post({ ...main, hook_event_name: 'Stop' }) - expect(server.getStatusSnapshot()[0]).toMatchObject({ ...expected, state: 'done' }) - } - } finally { - server.stop() - } -}) - -it('lets a new ephemeral Codex conversation take over a row still working, without its old prompt', async () => { - const dir = mkdtempSync(join(tmpdir(), 'codex-side-thread-')) - dirs.push(dir) - const server = new AgentHookServer() - await server.start({ env: 'production' }) - const post = (payload: Record): Promise => - postHookEvent(server, buildBody(payload), '/hook/codex') - try { - const main = { session_id: MAIN, transcript_path: join(dir, 'rollout-main.jsonl') } - await post({ ...main, hook_event_name: 'UserPromptSubmit', prompt: 'main task' }) - await post({ ...TITLE_THREAD, hook_event_name: 'SessionStart', source: 'startup' }) - await post({ ...TITLE_THREAD, hook_event_name: 'UserPromptSubmit', prompt: 'next task' }) - expect(server.getStatusSnapshot()[0]).toMatchObject({ - state: 'working', - prompt: 'next task', - providerSession: { id: SIDE } - }) - } finally { - server.stop() - } -}) diff --git a/src/main/agent-hooks/server/testing/providers/codex/server-ingest-codex-async-question.test.ts b/src/main/agent-hooks/server/testing/providers/codex/server-ingest-codex-async-question.test.ts index e38f537c8ce..79714496a2f 100644 --- a/src/main/agent-hooks/server/testing/providers/codex/server-ingest-codex-async-question.test.ts +++ b/src/main/agent-hooks/server/testing/providers/codex/server-ingest-codex-async-question.test.ts @@ -103,38 +103,4 @@ describe('Codex async questions', () => { expect(answered).toMatchObject({ state: 'working' }) expect(answered?.interactivePrompt).toBeUndefined() }) - - it('drops open questions when the user sends a plain message instead of a reply', () => { - const pane = codexPane() - pane.report({ hook_event_name: 'UserPromptSubmit', turn_id: 'turn-1', prompt: 'Set up a db' }) - pane.report(ASK) - expect(pane.report(ACCEPTED).main).toMatchObject(waitingOnQuestion) - - // Orca's chat card answers an async question as a quoted message, as Codex clients do. - const steered = pane.report({ - hook_event_name: 'UserPromptSubmit', - turn_id: 'turn-1', - prompt: '> Which database should the probe use?\n\nSQLite' - }).main - expect(steered).toMatchObject({ state: 'working' }) - expect(steered?.interactivePrompt).toBeUndefined() - }) - - it('drops an unanswered question when the turn ends', () => { - const pane = codexPane() - pane.report({ hook_event_name: 'UserPromptSubmit', turn_id: 'turn-1', prompt: 'Set up a db' }) - pane.report(ASK) - expect(pane.report(ACCEPTED).main).toMatchObject(waitingOnQuestion) - - expect(pane.report({ hook_event_name: 'Stop', turn_id: 'turn-1' }).main).toMatchObject({ - state: 'done' - }) - const next = pane.report({ - hook_event_name: 'UserPromptSubmit', - turn_id: 'turn-2', - prompt: 'Next' - }).main - expect(next).toMatchObject({ state: 'working' }) - expect(next?.interactivePrompt).toBeUndefined() - }) }) diff --git a/src/main/agent-hooks/server/testing/remote-ingress/server-ingest-remote-codex-transcript.test.ts b/src/main/agent-hooks/server/testing/remote-ingress/server-ingest-remote-codex-transcript.test.ts index 47ee6fd17ca..9a841ef9f90 100644 --- a/src/main/agent-hooks/server/testing/remote-ingress/server-ingest-remote-codex-transcript.test.ts +++ b/src/main/agent-hooks/server/testing/remote-ingress/server-ingest-remote-codex-transcript.test.ts @@ -1,4 +1,6 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { buildCachedPaneReplayEnvelope } from '../../../../../wsl-guest/agent-hook-cached-pane-status' +import type { AgentHookEventPayload } from '../../../../../shared/agent-hook-listener/listener-event' import { AgentHookServer, _internals } from '../../agent-hook-server' import { PANE } from '../server.test-fixtures' @@ -18,9 +20,11 @@ afterEach(() => { }) describe('remote Codex unlabelled roster removals', () => { - const childStart = (id: string, startedAt: number) => ({ + const childStart = (id: string, startedAt: number): AgentHookEventPayload => ({ paneKey: PANE, + connectionId: null, source: 'codex', + providerSession: { key: 'session_id', id: 'root' }, hookEventName: 'SubagentStart', toolAgentId: id, payload: { @@ -34,6 +38,7 @@ describe('remote Codex unlabelled roster removals', () => { const emptyPoll = (mainState: 'working' | 'done', toolAgentId?: string) => ({ paneKey: PANE, source: 'codex', + providerSession: { key: 'session_id', id: 'root' }, toolAgentId, payload: { agentType: 'codex', @@ -48,11 +53,22 @@ describe('remote Codex unlabelled roster removals', () => { server.beginRemoteRelaySession('wsl:Ubuntu') server.ingestRemote(childStart(CHILD, 1), 'wsl:Ubuntu') server.beginRemoteRelaySession('wsl:Ubuntu') + const replay = buildCachedPaneReplayEnvelope({ + event: { ...childStart(CHILD, 1), hookEventName: 'SessionStart', toolAgentId: undefined }, + meta: { source: 'codex' } + }) + server.ingestRemote(replay, 'wsl:Ubuntu') server.ingestRemote(emptyPoll('done'), 'wsl:Ubuntu') expect(server.getStatusSnapshotForPane(PANE)[0]).toMatchObject({ state: 'working', subagents: [expect.objectContaining({ id: CHILD })] }) + server._getStateForTests().codexSubagentRosterByPaneKey.delete(PANE) + server.ingestRemote(replay, 'wsl:Ubuntu') + server.ingestRemote(emptyPoll('done'), 'wsl:Ubuntu') + expect(server.getStatusSnapshotForPane(PANE)[0]?.subagents?.map((child) => child.id)).toEqual([ + CHILD + ]) server.ingestRemote(childStart(CHILD, 1), 'wsl:Ubuntu') server.ingestRemote(emptyPoll('done'), 'wsl:Ubuntu') diff --git a/src/main/claude-accounts/claude-profile-provisioning.test.ts b/src/main/claude-accounts/claude-profile-provisioning.test.ts index 24a54ea7e39..58b70c7aa23 100644 --- a/src/main/claude-accounts/claude-profile-provisioning.test.ts +++ b/src/main/claude-accounts/claude-profile-provisioning.test.ts @@ -150,6 +150,7 @@ describe('Claude profile refresh from the default home', () => { firstStartTime: 'source-start', firstStartVersion: '1.0.0', groveConfigCache: { a: 1 }, + groveChoiceSeenAt: { 'account-a': 99, 'account-b': 10 }, cachedArtifactRoster: [], clientDataCacheSlots: {}, passesEligibilityCache: {}, @@ -163,7 +164,10 @@ describe('Claude profile refresh from the default home', () => { subscriptionNoticeCount: 2 }) expect((await provision(f)).surfaces['.claude.json']).toBe('synced') - expect(f.read(join(f.profileHome, '.claude.json'))).toEqual(shared) + expect(f.read(join(f.profileHome, '.claude.json'))).toEqual({ + ...shared, + groveChoiceSeenAt: { 'account-a': 99, 'account-b': 10 } + }) expect(fs.readdirSync(f.profileHome).filter((name) => name.endsWith('.tmp'))).toEqual([]) expect(fs.existsSync(join(f.profileHome, '.credentials.json'))).toBe(false) @@ -172,6 +176,7 @@ describe('Claude profile refresh from the default home', () => { oauthAccount: { emailAddress: 'profile@example.com' }, userID: 'profile-id', groveConfigCache: { b: 2 }, + groveChoiceSeenAt: { 'account-a': 120, 'account-b': 5 }, theme: 'light', onlyHere: true }) @@ -180,6 +185,7 @@ describe('Claude profile refresh from the default home', () => { oauthAccount: { emailAddress: 'profile@example.com' }, userID: 'profile-id', groveConfigCache: { b: 2 }, + groveChoiceSeenAt: { 'account-a': 120, 'account-b': 10 }, onlyHere: true, ...shared }) diff --git a/src/main/claude-accounts/claude-profile-provisioning.ts b/src/main/claude-accounts/claude-profile-provisioning.ts index a47a3e0ca62..ffd28dbb913 100644 --- a/src/main/claude-accounts/claude-profile-provisioning.ts +++ b/src/main/claude-accounts/claude-profile-provisioning.ts @@ -153,8 +153,12 @@ function isAccountBoundState(key: string): boolean { ) } -// Preserve account-only project and server entries during merging. -const MERGED_BY_ENTRY: ReadonlySet = new Set(['projects', 'mcpServers']) +// Merge per entry so a profile keeps its own projects, servers, and Grove confirmations. +const MERGED_BY_ENTRY: ReadonlySet = new Set([ + 'projects', + 'mcpServers', + 'groveChoiceSeenAt' +]) function isPlainRecord(value: unknown): value is Record { return typeof value === 'object' && value !== null && !Array.isArray(value) @@ -174,6 +178,15 @@ function mergeEntries(key: string, current: unknown, source: unknown): unknown { } } } + if (key === 'groveChoiceSeenAt') { + // Claude trusts a confirmation only while it is fresh, so keep each account's newest one. + for (const [account, seenAt] of Object.entries(current)) { + const theirs = source[account] + if (typeof seenAt === 'number' && (typeof theirs !== 'number' || seenAt > theirs)) { + merged[account] = seenAt + } + } + } return merged } diff --git a/src/main/claude-usage/claude-model-pricing.test.ts b/src/main/claude-usage/claude-model-pricing.test.ts index 5eea907a6cd..08a90fae976 100644 --- a/src/main/claude-usage/claude-model-pricing.test.ts +++ b/src/main/claude-usage/claude-model-pricing.test.ts @@ -1,6 +1,6 @@ import { describe, expect, it } from 'vitest' import type { ClaudeUsageTokenTotals } from './types' -import { estimateCostUsd, normalizeModelForPricing } from './claude-model-pricing' +import { estimateCostUsd } from './claude-model-pricing' const MTOK = 1_000_000 @@ -18,61 +18,10 @@ function estimate(model: string, ...counts: number[]): number | null { return estimateCostUsd(model, tokens(...counts)) } -describe('model pricing name matching', () => { - it.each([ - [' ANTHROPIC/claude-opus-4.1-thinking ', 'claude-opus-4-1'], - ['claude-opus-4-20250514', 'claude-opus-4'], - ['claude-opus-4.20250514', 'claude-opus-4'], - ['claude-opus-4@20250514', 'claude-opus-4'], - ['claude-opus-4-5@20251101', 'claude-opus-4-5'], - ['us.anthropic.claude-sonnet-4-5-20250929-v1:0', 'claude-sonnet-4-5'], - ['claude-sonnet-5-thinking', 'claude-sonnet-5'], - ['claude-sonnet-5-5', 'claude-sonnet-5-5'], - ['claude-sonnet-5.5[1m]', 'claude-sonnet-5-5'], - ['claude-opus-5.5[1m]', 'claude-opus-5-5'], - ['claude-opus-5-5-thinking', 'claude-opus-5-5'], - ['claude-fable-5-1[1m]', 'claude-fable-5-1'], - ['claude-fable-5-1m', 'claude-fable-5'], - ['claude-opus-4.8-thinking', 'claude-opus-4-8'], - ['claude-3-5-sonnet-20241022', 'claude-sonnet-3-5'], - ['claude-3.5-sonnet', 'claude-sonnet-3-5'], - ['claude-3-7-sonnet-20250219', 'claude-sonnet-3-7'], - ['claude-3-5-haiku-20241022', 'claude-haiku-3-5'], - ['claude-3-haiku-20240307', 'claude-haiku-3'], - ['claude-4.5-sonnet-thinking', 'claude-sonnet-4-5'], - ['model_placeholder_m26', 'claude-opus-4-6'] - ])('reads the family and version out of %s', (model, key) => { - expect(normalizeModelForPricing(model)).toBe(key) - }) - - it.each([ - 'claude-opus-5-6', - 'claude-sonnet-5-6', - 'claude-fable-5-3', - 'claude-opus-6', - 'claude-opus-4.9', - 'claude-opus-5-50', - 'claude-sonnet-50', - 'claude-3-opus-20240229', - 'sonnet', - 'gpt-5' - ])('leaves %s unpriced', (model) => { - expect(normalizeModelForPricing(model)).toBeNull() - }) -}) - describe('estimateCostUsd cache-write TTL rates', () => { it('splits a mixed write bucket without double-billing the 1-hour share', () => { expect(estimate('claude-opus-5', 0, 0, 0, 1_000_000, 400_000)).toBeCloseTo(7.75) }) - - it('clamps a 1-hour count that exceeds the reported write total', () => { - expect(estimate('claude-opus-5', 0, 0, 0, 1_000, 5_000)).toBeCloseTo(0.01) - }) - - it('still returns null for unknown models', () => { - expect(estimate('gpt-5', 0, 0, 0, 1_000_000, 1_000_000)).toBeNull() - }) }) describe('estimateCostUsd long-context requests', () => { @@ -89,17 +38,6 @@ describe('estimateCostUsd long-context requests', () => { }) ).toBeCloseTo(0.1 + 0.5) }) - - it('ignores a long-context subset for a model with flat rates', () => { - const long = tokens(MTOK) - expect(estimateCostUsd('claude-sonnet-4-6', { ...long, longContext: long })).toBeCloseTo(3) - }) - - it('clamps a long-context subset larger than its totals', () => { - expect( - estimateCostUsd('claude-haiku-5-5', { ...tokens(MTOK), longContext: tokens(3 * MTOK) }) - ).toBeCloseTo(0.5) - }) }) // Rate source: platform.claude.com/docs/en/about-claude/pricing. diff --git a/src/main/claude/structured/launch/claude-structured-child-env.test.ts b/src/main/claude/structured/launch/claude-structured-child-env.test.ts index 3eda5aa1cfb..b9c63b68c70 100644 --- a/src/main/claude/structured/launch/claude-structured-child-env.test.ts +++ b/src/main/claude/structured/launch/claude-structured-child-env.test.ts @@ -3,11 +3,7 @@ import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, expect, it, vi } from 'vitest' import { runProcess } from '@orca/process-host' -import { - claudeChildEnv, - resolveClaudeChildEnvSources, - withOrcaClaudeEntrypoint -} from './claude-structured-child-env' +import { claudeChildEnv, resolveClaudeChildEnvSources } from './claude-structured-child-env' import { resolveStructuredAgentCommand } from '../../../native-chat/structured-agent-command-resolution' afterEach(() => { @@ -36,92 +32,6 @@ it('resolves a custom Claude command against the login shell PATH', async () => } }) -it('isolates inherited Claude stamps before applying launch settings', () => { - const sources = { - command: 'claude', - prefixArgs: [], - overlay: undefined, - inheritedEnv: { - CLAUDE_CODE_ENTRYPOINT: 'cli', - CLAUDECODE: '1', - CLAUDE_CODE_MESSAGING_SOCKET: 'parent-socket', - CLAUDE_AGENT_SDK_VERSION: 'parent-sdk', - CLAUDE_EFFORT: 'parent-effort', - CLAUDE_CODE_HTTP_PROXY: 'http://user-proxy' - } - } - const options = { runtimeOnPath: false } - expect(claudeChildEnv(sources, undefined, options)).toEqual({ - CLAUDE_CODE_ENTRYPOINT: 'orca', - CLAUDE_CODE_HTTP_PROXY: 'http://user-proxy' - }) - const overlay = { CLAUDE_CODE_ENTRYPOINT: 'custom', CLAUDE_EFFORT: 'configured-effort' } - expect(claudeChildEnv({ ...sources, overlay }, undefined, options)).toEqual({ - ...overlay, - CLAUDE_CODE_HTTP_PROXY: 'http://user-proxy' - }) -}) - -it('keeps a differently cased Windows launch value over the Orca default', () => { - const inherited = { - Claude_Code_Entrypoint: 'cli', - CLAUDE_CODE_MESSAGING_TOKEN: 'parent-token', - Claude_Agent_Sdk_Version: 'parent-sdk', - PATH: 'C:\\bin' - } - expect( - withOrcaClaudeEntrypoint( - inherited, - { claude_code_entrypoint: 'company-client', claude_agent_sdk_version: 'configured-sdk' }, - 'win32' - ) - ).toEqual({ - PATH: 'C:\\bin', - CLAUDE_CODE_ENTRYPOINT: 'company-client', - CLAUDE_AGENT_SDK_VERSION: 'configured-sdk' - }) - expect(withOrcaClaudeEntrypoint(inherited, undefined, 'win32')).toEqual({ - PATH: 'C:\\bin', - CLAUDE_CODE_ENTRYPOINT: 'orca' - }) - expect( - withOrcaClaudeEntrypoint( - inherited, - { - CLAUDE_CODE_ENTRYPOINT: 'first', - claude_code_entrypoint: 'last' - }, - 'win32' - ) - ).toEqual({ PATH: 'C:\\bin', CLAUDE_CODE_ENTRYPOINT: 'last' }) -}) - -it('uses configured Windows values for both Claude lookup and its final child', async () => { - vi.stubGlobal('process', { ...process, platform: 'win32' }) - const sources = await resolveClaudeChildEnvSources({ - resolveInheritedEnv: async () => ({ - PATH: '/inherited/bin', - TOKEN: 'inherited', - CLAUDE_CONFIG_DIR: '/ambient' - }), - resolveEnv: () => ({ - path: '/configured/bin', - tOKEN: 'configured', - claude_config_dir: '/configured/home' - }), - resolveCommand: (options) => { - expect(options?.pathEnv).toBe('/configured/bin') - return { command: '/configured/bin/claude.exe', prefixArgs: [] } - } - }) - expect(claudeChildEnv(sources, undefined, { runtimeOnPath: false })).toEqual({ - PATH: '/configured/bin', - TOKEN: 'configured', - CLAUDE_CONFIG_DIR: '/configured/home', - CLAUDE_CODE_ENTRYPOINT: 'orca' - }) -}) - it.skipIf(process.platform !== 'win32')( 'passes configured values through a real Windows child despite inherited casing', async () => { diff --git a/src/main/daemon/sessions/session-launch-note.ts b/src/main/daemon/sessions/session-launch-note.ts index c8be96ad8df..9ed81b8cb47 100644 --- a/src/main/daemon/sessions/session-launch-note.ts +++ b/src/main/daemon/sessions/session-launch-note.ts @@ -1,37 +1,20 @@ -import { - createOsc133CommandFinishedScanner, - type Osc133CommandFinishedScanner -} from '../../../shared/terminal/output/terminal-osc133-command-finished' import type { DaemonLaunchNote, DaemonLaunchNoteChange } from '../protocol/daemon-launch-note-protocol' -/** Main's live launch here; retired on command-finished too, since it can finish while main is down. */ +/** Main's live launch here, so a reattach after a main restart can re-arm it. + * Why no output scan: a finish while main is down is caught by reattach's foreground check. */ export class SessionLaunchNote { current: DaemonLaunchNote | null = null - private retirement: Osc133CommandFinishedScanner | null = null - - scan(data: string): void { - this.retirement?.scan(data) - } change(change: DaemonLaunchNoteChange): void { - const token = this.current?.launchToken if ('retire' in change) { - if (change.retire === token) { + if (change.retire === this.current?.launchToken) { this.current = null - this.retirement = null } return } - // Re-arming the same launch keeps the scanner, whose carry may hold a split marker. - const note = change.arm - if (note.launchToken !== token) { - this.current = note - this.retirement = createOsc133CommandFinishedScanner(() => - this.change({ retire: note.launchToken }) - ) - } + this.current = change.arm } } diff --git a/src/main/daemon/sessions/session.ts b/src/main/daemon/sessions/session.ts index 38c89f0a845..f5d84d66099 100644 --- a/src/main/daemon/sessions/session.ts +++ b/src/main/daemon/sessions/session.ts @@ -76,7 +76,6 @@ export class Session extends SessionProcessInspection { try { this.subprocess.onData((data) => { if (!this._disposed) { - this.launchNote.scan(data) this.shellReady.ingestSubprocessData(data) } }) diff --git a/src/main/daemon/sessions/testing/session-launch-note.test.ts b/src/main/daemon/sessions/testing/session-launch-note.test.ts deleted file mode 100644 index a2daee9b086..00000000000 --- a/src/main/daemon/sessions/testing/session-launch-note.test.ts +++ /dev/null @@ -1,26 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { SessionLaunchNote } from '../session-launch-note' - -const NOTE = { launchToken: 'launch-1', launchConfig: { agentArgs: '--verbose', agentEnv: {} } } -const NEXT = { launchToken: 'launch-2', launchConfig: { agentArgs: '', agentEnv: {} } } - -// The launch can finish while main is down, so the daemon must retire the note without main. -describe('a daemon session launch note', () => { - it('retires when the launched command finishes, even across a same-launch re-arm', () => { - const note = new SessionLaunchNote() - note.change({ arm: NOTE }) - note.scan('agent output\x1b]133;') - note.change({ arm: NOTE }) - expect(note.current).toEqual(NOTE) - note.scan('D;143\x07') - expect(note.current).toBeNull() - }) - - it('ignores a retire for an earlier launch', () => { - const note = new SessionLaunchNote() - note.change({ arm: NOTE }) - note.change({ arm: NEXT }) - note.change({ retire: 'launch-1' }) - expect(note.current).toEqual(NEXT) - }) -}) diff --git a/src/main/gitlab/gitlab-project-ref-resolution.ts b/src/main/gitlab/gitlab-project-ref-resolution.ts index 755119dcc65..3e3b57a90df 100644 --- a/src/main/gitlab/gitlab-project-ref-resolution.ts +++ b/src/main/gitlab/gitlab-project-ref-resolution.ts @@ -1,6 +1,7 @@ import { glabExecFileAsync } from '../git/runner' import type { GitAdmissionTier } from '../git/command-runner/git-exec-options' import { addWslEnvKeys } from '../../shared/wsl-env' +import { normalizeForgeWebHost } from '../../shared/git/remotes/git-remote-host-alias' import { isTransientGitProbeError, readRemoteUrl } from '../git/remotes/remote-url-probe' import { NEGATIVE_ENTRY_TTL_MS } from '../git/remotes/remote-ref-probe-cache' import { readLocalGitConfigSignature } from '../github/local-git-config-signature' @@ -153,12 +154,19 @@ async function resolveProjectRefForRemote( if (stdout === null) { return null } + // Stray glab host entries for GitHub/Bitbucket hosts must not claim their remotes (#40386). + // Match the real host only: `github:team/project` is an scp remote on an SSH alias named github. + const remoteCandidate = parseRemoteProjectRefCandidate(stdout) + const remoteHost = remoteCandidate && normalizeForgeWebHost(remoteCandidate.host) + if (remoteHost === 'github.com' || remoteHost === 'bitbucket.org') { + publish(null) + return null + } const result = parseGitLabProjectRef(stdout, knownHosts) if (result) { publish(result) return result } - const remoteCandidate = parseRemoteProjectRefCandidate(stdout) if ( remoteCandidate && (await isGlabConfiguredForRemoteHost( diff --git a/src/main/gitlab/gl-utils.test.ts b/src/main/gitlab/gl-utils.test.ts index 0dc0af56435..d9ed1766812 100644 --- a/src/main/gitlab/gl-utils.test.ts +++ b/src/main/gitlab/gl-utils.test.ts @@ -138,6 +138,36 @@ describe('gitlab project ref resolution', () => { expect((await getIssueProjectRef('/repo'))?.path).toBe('team/recovered') expect(gitRemoteGetUrlCalls('upstream')).toHaveLength(2) }) + + // `glab auth status --hostname ` output (glab 1.102) for a host with a stray config entry. + function rejectHostnameProbeWithStatusBlock(host: string): void { + glabExecFileAsyncMock.mockRejectedValue( + Object.assign(new Error('glab auth status failed'), { + stdout: '', + stderr: [ + host, + ` x ${host}: API call failed: 404 Not Found`, + ' ✓ Token found: **************************' + ].join('\n') + }) + ) + } + + it.each([ + ['https://github.com/owner/repo.git', 'github.com'], + ['git@bitbucket.org:owner/repo.git', 'bitbucket.org'] + ])('does not claim %s from a stray glab %s host entry', async (url, host) => { + mockGitRemoteCommands({ origin: url }) + rejectHostnameProbeWithStatusBlock(host) + + await expect(getProjectRef('/repo')).resolves.toBeNull() + }) + + it('does not claim a github.com remote listed in the glab known-host inventory', async () => { + mockGitRemoteCommands({ origin: 'git@github.com:owner/repo.git' }) + + await expect(getProjectRef('/repo', ['gitlab.com', 'github.com'])).resolves.toBeNull() + }) }) describe('GitLab operation admission', () => { diff --git a/src/main/ipc/repos/sparse-preset-validation-transport.test.ts b/src/main/ipc/repos/sparse-preset-validation-transport.test.ts index 93317219bbb..03d2923212d 100644 --- a/src/main/ipc/repos/sparse-preset-validation-transport.test.ts +++ b/src/main/ipc/repos/sparse-preset-validation-transport.test.ts @@ -1,57 +1,8 @@ -import { describe, expect, it, vi } from 'vitest' -import type { BrowserWindow } from 'electron' -import type { Store } from '../../persistence/loading-store/store' -import { registerSparsePresetHandlers } from './sparse-preset-handlers' +import { describe, expect, it } from 'vitest' import { normalizeSparsePresetDirectories } from './sparse-preset-validation' import { mapRuntimeError } from '../../runtime/rpc/errors' -import { - InvalidSparseDirectoryError, - normalizeSparseDirectories -} from '../sparse-checkout-directories' - -const { handlers } = vi.hoisted(() => ({ - handlers: new Map unknown>() -})) -vi.mock('electron', () => ({ - ipcMain: { - handle: (channel: string, handler: (event: unknown, args: unknown) => unknown) => - handlers.set(channel, handler) - } -})) -vi.mock('../../persistence/moving-wsl-projects/wsl-move-scope-guard', () => ({ - assertWslMoveProjectWritable: vi.fn() -})) describe('sparse preset validation transport', () => { - it('identifies both absolute and parent-segment directory failures by type', () => { - expect(() => normalizeSparseDirectories(['/outside'])).toThrow(InvalidSparseDirectoryError) - expect(() => normalizeSparseDirectories(['../outside'])).toThrow(InvalidSparseDirectoryError) - }) - - it.each([ - { name: '', directories: ['src'], code: 'name_required' }, - { name: 'a'.repeat(81), directories: ['src'], code: 'name_too_long' }, - { name: 'Preset', directories: [], code: 'directories_required' }, - { name: 'Preset', directories: ['../outside'], code: 'directories_invalid' }, - { name: 'Preset', directories: ['/outside'], code: 'directories_invalid' } - ])( - 'returns IPC code $code instead of saving an invalid preset', - ({ name, directories, code }) => { - const saveSparsePreset = vi.fn() - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: validation only reads these store methods. - const store = { getRepo: () => ({}), saveSparsePreset } as unknown as Store - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: invalid input returns before the window is accessed. - registerSparsePresetHandlers({} as BrowserWindow, store) - const result = handlers.get('sparsePresets:save')?.(undefined, { - repoId: 'repo', - name, - directories - }) - expect(result).toMatchObject({ errorCode: code }) - expect(saveSparsePreset).not.toHaveBeenCalled() - } - ) - it('keeps the validation reason in the RPC envelope', () => { let failure: unknown try { diff --git a/src/main/native-chat/agent-session-wire/publication/history/agent-session-conversation-outline.ts b/src/main/native-chat/agent-session-wire/publication/history/agent-session-conversation-outline.ts index f97f1816cd9..471afbe4da6 100644 --- a/src/main/native-chat/agent-session-wire/publication/history/agent-session-conversation-outline.ts +++ b/src/main/native-chat/agent-session-wire/publication/history/agent-session-conversation-outline.ts @@ -62,6 +62,7 @@ export function readAgentSessionConversationOutline( } return { sessionId: snapshot.sessionId, + humanMessagesOnly: true, cursor: snapshot.cursor, entries: first === 0 ? entries : entries.slice(first), omittedEntries: first diff --git a/src/main/native-chat/agent-session-wire/publication/history/testing/agent-session-conversation-outline.test.ts b/src/main/native-chat/agent-session-wire/publication/history/testing/agent-session-conversation-outline.test.ts index 5750ec4081a..d8383bc965b 100644 --- a/src/main/native-chat/agent-session-wire/publication/history/testing/agent-session-conversation-outline.test.ts +++ b/src/main/native-chat/agent-session-wire/publication/history/testing/agent-session-conversation-outline.test.ts @@ -39,4 +39,15 @@ describe('conversation outline read', () => { expect(replyBytes(outline)).toBeLessThanOrEqual(HISTORY_PAGE_CONTENT_BUDGET_BYTES) expect(outline.entries.at(-1)?.itemId).toBe('user-10000') }) + + // Newer clients ignore an unmarked outline, which older hosts may fill with agent-written inputs. + it('marks its outline as listing only messages a person wrote', () => { + expect(readAgentSessionConversationOutline(snapshot([]))).toEqual({ + sessionId: 'session-1', + humanMessagesOnly: true, + cursor: { epoch: 'epoch-1', sequence: 0 }, + entries: [], + omittedEntries: 0 + }) + }) }) diff --git a/src/main/plugins/panels/plugin-panel-bridge.ts b/src/main/plugins/panels/plugin-panel-bridge.ts index 1ac88a88b00..3131a7b92df 100644 --- a/src/main/plugins/panels/plugin-panel-bridge.ts +++ b/src/main/plugins/panels/plugin-panel-bridge.ts @@ -122,7 +122,7 @@ export class PluginPanelBridge { } this.replays.delete(panelId) for (const event of owed) { - const payload = await readPluginWorkspaceChange(delegate) + const payload = (await readPluginWorkspaceChange(delegate)).change if ( this.channels.get(panelId) === channel && this.subscriptions.get(panelId)?.has(event) && diff --git a/src/main/plugins/plugin-runtime-binding.test.ts b/src/main/plugins/plugin-runtime-binding.test.ts index 2fec343379c..8c26efb5829 100644 --- a/src/main/plugins/plugin-runtime-binding.test.ts +++ b/src/main/plugins/plugin-runtime-binding.test.ts @@ -285,6 +285,17 @@ describe('workspace.changed', () => { expect(events.emitEvent).toHaveBeenLastCalledWith('workspace.changed', { context: { branch: 'main', displayName: 'w', terminals: [] } }) + // Same projected payload, different focused workspace: still a change. + source.resolveActiveWorktreeContext.mockResolvedValueOnce({ + worktreeId: 'repo::/other', + path: '/w', + branch: 'refs/heads/main', + displayName: 'w' + }) + source.listTerminals.mockResolvedValueOnce({ terminals: [] }) + written() + await vi.advanceTimersByTimeAsync(20) + expect(events.emitEvent).toHaveBeenCalledTimes(3) stop() } finally { vi.useRealTimers() diff --git a/src/main/plugins/plugin-runtime-binding.ts b/src/main/plugins/plugin-runtime-binding.ts index 6c904680d46..279a2872e15 100644 --- a/src/main/plugins/plugin-runtime-binding.ts +++ b/src/main/plugins/plugin-runtime-binding.ts @@ -139,20 +139,28 @@ export function createPluginAgentStatusForwarder( } } -/** The `workspace.changed` payload for the context as it is now. */ -export async function readPluginWorkspaceChange( - delegate: PluginRuntimeDelegate -): Promise<{ context: PluginWorkspaceContext }> { +/** + * The `workspace.changed` payload for the context as it is now, plus the focused worktree id the + * watcher dedupes on (kept out of the payload because it can embed a provider path). + */ +export async function readPluginWorkspaceChange(delegate: PluginRuntimeDelegate): Promise<{ + change: { context: PluginWorkspaceContext } + worktreeId: string | null +}> { const context = await delegate.resolveActiveWorktreeContext().catch(() => null) const terminals = context ? await listWorkspaceTerminals(delegate, context.worktreeId).catch(() => []) : [] - return { context: projectPluginWorkspaceContext(context, terminals) } + return { + change: { context: projectPluginWorkspaceContext(context, terminals) }, + worktreeId: context?.worktreeId ?? null + } } /** * `workspace.changed`: after workspace session writes settle (focus moves, terminals open, close * or are renamed), re-read the context and emit when it differs from the last one sent. + * Why: compare by worktree id too, so focus moving between identical-looking workspaces still emits. */ export function watchPluginWorkspaceContext(input: { delegate: PluginRuntimeDelegate @@ -168,8 +176,8 @@ export function watchPluginWorkspaceContext(input: { last = null return } - const change = await readPluginWorkspaceChange(input.delegate) - const signature = JSON.stringify(change) + const { change, worktreeId } = await readPluginWorkspaceChange(input.delegate) + const signature = JSON.stringify({ worktreeId, change }) if (signature !== last) { last = signature input.events.emitEvent('workspace.changed', change) diff --git a/src/main/runtime/agent-session/environment/structured-agent-environment-overrides.test.ts b/src/main/runtime/agent-session/environment/structured-agent-environment-overrides.test.ts deleted file mode 100644 index 1a31295d11e..00000000000 --- a/src/main/runtime/agent-session/environment/structured-agent-environment-overrides.test.ts +++ /dev/null @@ -1,26 +0,0 @@ -import { afterEach, expect, it, vi } from 'vitest' -import { createStructuredAgentEnvironmentResolvers } from './structured-agent-shell-environment' - -afterEach(() => vi.unstubAllGlobals()) - -it.each([ - ['win32', { TOKEN: 'configured', PATH: '/configured/bin', KEEP: 'keep' }], - [ - 'linux', - { - TOKEN: 'inherited', - PATH: '/inherited/bin', - tOKEN: 'configured', - path: '/configured/bin', - KEEP: 'keep' - } - ] -] as const)('composes the effective agent environment on %s', async (platform, expected) => { - vi.stubGlobal('process', { ...process, platform }) - const environment = createStructuredAgentEnvironmentResolvers({ - resolveEnvironment: async () => ({ TOKEN: 'inherited', PATH: '/inherited/bin', KEEP: 'keep' }), - resolveAgentLaunchEnv: () => ({ tOKEN: 'configured', path: '/configured/bin' }) - }) - expect(await environment.resolveAgentEnvironment('claude')).toEqual(expected) - expect(await environment.resolveAgentEnvironment('codex')).toEqual(expected) -}) diff --git a/src/main/runtime/agent-session/launch/structured-agent-launch-env-preflight.test.ts b/src/main/runtime/agent-session/launch/structured-agent-launch-env-preflight.test.ts deleted file mode 100644 index 41906268caa..00000000000 --- a/src/main/runtime/agent-session/launch/structured-agent-launch-env-preflight.test.ts +++ /dev/null @@ -1,21 +0,0 @@ -import { afterEach, expect, it, vi } from 'vitest' -import { resolveHostStructuredAgentLaunchEnvironment } from './structured-agent-launch-support' -import type * as Environment from '../environment/structured-agent-shell-environment' - -vi.mock('../environment/structured-agent-shell-environment', async (importOriginal) => ({ - ...(await importOriginal()), - resolveHostAgentBaseEnvironment: async () => ({ - TOKEN: 'inherited', - PATH: '/inherited/bin', - KEEP: 'keep' - }) -})) -afterEach(() => vi.unstubAllGlobals()) - -it('uses the configured Windows environment for launch preflight', async () => { - vi.stubGlobal('process', { ...process, platform: 'win32' }) - const env = await resolveHostStructuredAgentLaunchEnvironment('claude', { - agentDefaultEnv: { claude: { tOKEN: 'configured', path: '/configured/bin' } } - }) - expect(env).toEqual({ TOKEN: 'configured', PATH: '/configured/bin', KEEP: 'keep' }) -}) diff --git a/src/main/runtime/daemon-launch-note-reattach.test.ts b/src/main/runtime/daemon-launch-note-reattach.test.ts index 66185017d8f..bd97df9a6ca 100644 --- a/src/main/runtime/daemon-launch-note-reattach.test.ts +++ b/src/main/runtime/daemon-launch-note-reattach.test.ts @@ -29,52 +29,6 @@ function attach( }) } -function holdLaunch(runtime: OrcaRuntimeService) { - runtime.registerPty(PTY_ID, 'worktree-1', null, { - tabId: TAB_ID, - leafId: LEAF_ID, - incarnationId: INCARNATION, - agentLaunchAuthority: { - launchToken: 'launch-1', - launchAgent: 'claude', - launchConfig: LAUNCH_CONFIG - } - }) -} - -// Some hosts register a spawn before they report its incarnation. -async function launchedBeforeItsIncarnation(foreground: 'agent' | 'unknown') { - const runtime = new OrcaRuntimeService(null) - Object.assign(runtime, { - resolveTerminalWorkspaceLaunchScope: async () => ({ - id: 'worktree-1', - path: '/tmp/worktree-1', - connectionId: null - }) - }) - runtime.setPtyController({ - write: vi.fn(() => true), - kill: vi.fn(), - getForegroundProcess: async () => null, - setLaunchNote: vi.fn(), - spawn: async () => { - runtime.registerPty(PTY_ID, 'worktree-1', null, { tabId: TAB_ID, leafId: LEAF_ID }) - return { id: PTY_ID } - } - }) - vi.spyOn(runtime, 'readLaunchedAgentForeground').mockResolvedValue(foreground) - await runtime.createTerminal('id:worktree-1', { - tabId: TAB_ID, - leafId: LEAF_ID, - command: 'claude', - launchAgent: 'claude', - launchConfig: LAUNCH_CONFIG, - presentation: 'background' - }) - expect(runtime.getLaunchStatementForPaneKey(PANE_KEY, 'claude')).toEqual(LAUNCH_CONFIG) - return runtime -} - function makeRuntime() { const runtime = new OrcaRuntimeService(null) const setLaunchNote = vi.fn() @@ -87,64 +41,7 @@ function makeRuntime() { return { runtime, setLaunchNote } } -async function reattach( - foreground: 'agent' | 'shell' | 'unknown', - mainHoldsLaunch = false, - launchNote: typeof NOTE | null | 'omitted' = NOTE, - finishedOnReattach = false -) { - const { runtime, setLaunchNote } = makeRuntime() - vi.spyOn(runtime, 'readLaunchedAgentForeground').mockResolvedValue(foreground) - if (mainHoldsLaunch) { - holdLaunch(runtime) - } - attach(runtime, launchNote === 'omitted' ? undefined : launchNote) - await new Promise((resolve) => setTimeout(resolve, 0)) - if (finishedOnReattach) { - attach(runtime, null) - } - return { - config: runtime.getLaunchStatementForPaneKey(PANE_KEY, 'claude'), - retired: setLaunchNote.mock.calls.some(([, change]) => 'retire' in change) - } -} - -// Nothing reaches a daemon PTY while main is down, so only the same agent still running keeps the note. describe('a daemon reattach after a main restart', () => { - it('re-arms the unretired launch while its agent still runs', async () => { - expect(await reattach('agent')).toEqual({ config: LAUNCH_CONFIG, retired: false }) - }) - - it('says no launch runs when the foreground is the shell', async () => { - expect(await reattach('shell')).toEqual({ config: null, retired: true }) - }) - - it('says no launch runs when the daemon retired its note', async () => { - expect((await reattach('agent', false, null)).config).toBeNull() - }) - - // Undecided: readers keep their earlier same-session rule rather than drop the settings. - it('makes no statement when the foreground is unreadable', async () => { - expect((await reattach('unknown')).config).toBeUndefined() - }) - - it('settles an undecided pane when a later attach reports its launch finished', async () => { - expect((await reattach('unknown', false, NOTE, true)).config).toBeNull() - }) - - it('makes no statement for a daemon that keeps no launch notes', async () => { - expect((await reattach('agent', false, 'omitted')).config).toBeUndefined() - }) - - it('settles an undecided pane once main sees its command finish', async () => { - const { runtime } = makeRuntime() - vi.spyOn(runtime, 'readLaunchedAgentForeground').mockResolvedValue('unknown') - attach(runtime, NOTE) - await new Promise((resolve) => setTimeout(resolve, 0)) - runtime.emitDaemonPtyTransientFact(PTY_ID, { kind: 'command-finished', exitCode: 0 }) - expect(runtime.getLaunchStatementForPaneKey(PANE_KEY, 'claude')).toBeNull() - }) - it('does not let an earlier foreground read revive a launch a later attach saw finish', async () => { const { runtime } = makeRuntime() let answer: (foreground: 'agent') => void = () => {} @@ -157,94 +54,4 @@ describe('a daemon reattach after a main restart', () => { await new Promise((resolve) => setTimeout(resolve, 0)) expect(runtime.getLaunchStatementForPaneKey(PANE_KEY, 'claude')).toBeNull() }) - - it('makes no statement for an older relay that reports no incarnation', () => { - const { runtime } = makeRuntime() - runtime.registerPty(PTY_ID, 'worktree-1', 'ssh-1', { - tabId: TAB_ID, - leafId: LEAF_ID, - reattach: {} - }) - expect(runtime.getLaunchStatementForPaneKey(PANE_KEY, 'claude')).toBeUndefined() - }) - - it('starts a replacement process decided even when its spawn is announced first', () => { - const { runtime } = makeRuntime() - const binding = { tabId: TAB_ID, leafId: LEAF_ID } - attach(runtime, undefined) - runtime.onPtySpawned(PTY_ID, 'next-incarnation') - runtime.registerPty(PTY_ID, 'worktree-1', null, { - ...binding, - incarnationId: 'next-incarnation' - }) - expect(runtime.getLaunchStatementForPaneKey(PANE_KEY, 'claude')).toBeNull() - }) - - it('drops a held launch when a new process replaces it in the same terminal', () => { - const { runtime } = makeRuntime() - const binding = { tabId: TAB_ID, leafId: LEAF_ID } - holdLaunch(runtime) - runtime.onPtySpawned(PTY_ID, 'next-incarnation') - runtime.registerPty(PTY_ID, 'worktree-1', null, { - ...binding, - incarnationId: 'next-incarnation' - }) - expect(runtime.getLaunchStatementForPaneKey(PANE_KEY, 'claude')).toBeNull() - }) - - // A finished launch stays finished for its process; only a fresh launch supersedes it. - it.each([ - ['a daemon that keeps no notes', undefined], - ['a note the daemon has not retired', NOTE] - ] as const)('keeps a finished launch gone when %s reattaches', async (_, launchNote) => { - const { runtime } = makeRuntime() - vi.spyOn(runtime, 'readLaunchedAgentForeground').mockResolvedValue('agent') - holdLaunch(runtime) - runtime.emitDaemonPtyTransientFact(PTY_ID, { kind: 'command-finished', exitCode: 0 }) - attach(runtime, launchNote) - await new Promise((resolve) => setTimeout(resolve, 0)) - expect(runtime.getLaunchStatementForPaneKey(PANE_KEY, 'claude')).toBeNull() - }) - - it('lets a replacement process prove its own launch through a reattach', async () => { - const { runtime } = makeRuntime() - vi.spyOn(runtime, 'readLaunchedAgentForeground').mockResolvedValue('agent') - attach(runtime, undefined) - attach(runtime, NOTE, 'next-incarnation') - await new Promise((resolve) => setTimeout(resolve, 0)) - expect(runtime.getLaunchStatementForPaneKey(PANE_KEY, 'claude')).toEqual(LAUNCH_CONFIG) - }) - - // Learning the process's first incarnation is no replacement: what main knew still holds. - it.each([ - ['keeps no notes', undefined], - ['still has the note', NOTE] - ] as const)( - 'keeps a launch that finished before its first incarnation gone when a host that %s attaches', - async (_, launchNote) => { - const runtime = await launchedBeforeItsIncarnation('agent') - runtime.emitDaemonPtyTransientFact(PTY_ID, { kind: 'command-finished', exitCode: 0 }) - attach(runtime, launchNote) - await new Promise((resolve) => setTimeout(resolve, 0)) - expect(runtime.getLaunchStatementForPaneKey(PANE_KEY, 'claude')).toBeNull() - } - ) - - it.each([ - ['keeps no notes', undefined], - ['sends the note late', NOTE] - ] as const)( - 'keeps a running launch when its first incarnation arrives from a host that %s', - async (_, launchNote) => { - const runtime = await launchedBeforeItsIncarnation('unknown') - attach(runtime, launchNote) - await new Promise((resolve) => setTimeout(resolve, 0)) - expect(runtime.getLaunchStatementForPaneKey(PANE_KEY, 'claude')).toEqual(LAUNCH_CONFIG) - } - ) - - // The renderer attaches a pane the CLI launched before its agent has started. - it('leaves a launch main already holds when the attach still sees its shell', async () => { - expect(await reattach('shell', true)).toEqual({ config: LAUNCH_CONFIG, retired: false }) - }) }) diff --git a/src/main/runtime/rpc/methods/mobile-delivery/mobile-web-bundle.test-fixture.ts b/src/main/runtime/rpc/methods/mobile-delivery/mobile-web-bundle.test-fixture.ts index ff015a62f71..ea816a3e2a6 100644 --- a/src/main/runtime/rpc/methods/mobile-delivery/mobile-web-bundle.test-fixture.ts +++ b/src/main/runtime/rpc/methods/mobile-delivery/mobile-web-bundle.test-fixture.ts @@ -10,7 +10,8 @@ import { MOBILE_WEB_BUNDLE_CHUNK_BYTES } from '../../../../../shared/mobile-web- import { computeMobileWebBundleId, mobileWebBundleBrotliPath, - type MobileWebBundleAsset + type MobileWebBundleAsset, + type MobileWebBundleCatalog } from '../../../../../shared/mobile-web-bundle/manifest-contract' export const sha256Hex = (bytes: Buffer): string => createHash('sha256').update(bytes).digest('hex') @@ -52,14 +53,24 @@ export type SyntheticMobileWebBundle = { root: string buildId: string assets: MobileWebBundleAsset[] + catalogs: MobileWebBundleCatalog[] } export function writeSyntheticMobileWebBundle( root: string, seed: number, - extraAssets: readonly SyntheticAsset[] = [] + extraAssets: readonly SyntheticAsset[] = [], + localeCatalogs: Readonly>> = {} ): SyntheticMobileWebBundle { mkdirSync(join(root, 'assets'), { recursive: true }) + const catalogs = Object.entries(localeCatalogs).map(([locale, catalog]) => { + const bytes = Buffer.from(JSON.stringify(catalog), 'utf8') + const sha256 = sha256Hex(bytes) + const path = `catalogs/${sha256}.json` + mkdirSync(join(root, 'catalogs'), { recursive: true }) + writeFileSync(join(root, path), bytes) + return { locale, path, sha256, byteLength: bytes.byteLength } + }) const written = [...syntheticAssets(seed), ...extraAssets] const copies = new Map() for (const asset of written) { @@ -91,11 +102,12 @@ export function writeSyntheticMobileWebBundle( entrypoint: 'index.html', totalBytes: assets.reduce((total, asset) => total + asset.byteLength, 0), assets, - routes: [] + routes: [], + ...(catalogs.length === 0 ? {} : { catalogs }) }), 'utf8' ) - return { root, buildId, assets } + return { root, buildId, assets, catalogs } } /** Only the envelope reads runtimeId; bundle methods read directly from this install. */ diff --git a/src/main/runtime/rpc/methods/mobile-delivery/mobile-web-bundle.test.ts b/src/main/runtime/rpc/methods/mobile-delivery/mobile-web-bundle.test.ts index 0a426114237..4ad687cb8f2 100644 --- a/src/main/runtime/rpc/methods/mobile-delivery/mobile-web-bundle.test.ts +++ b/src/main/runtime/rpc/methods/mobile-delivery/mobile-web-bundle.test.ts @@ -214,6 +214,47 @@ describe('an install that carries a mobile web bundle', () => { }) }) +describe('the language catalogs a build serves on request', () => { + let bundle: SyntheticMobileWebBundle + + beforeEach(() => { + bundle = writeSyntheticMobileWebBundle(join(scratch, 'out', 'mobile-web'), 1, [], { + de: { greeting: 'Hallo' } + }) + }) + + it('serves the listed catalog, then nothing to a phone that already holds it', async () => { + const [german] = bundle.catalogs + + const first = await call('mobileWeb.bundle.localeCatalog', { locale: 'de' }) + const again = await call('mobileWeb.bundle.localeCatalog', { + locale: 'de', + knownSha256: german.sha256 + }) + + expect(first.ok && first.result).toEqual({ + locale: 'de', + sha256: german.sha256, + catalog: { greeting: 'Hallo' } + }) + expect(again.ok && again.result).toEqual({ + locale: 'de', + sha256: german.sha256, + catalog: null + }) + }) + + it('refuses a locale the build has no catalog for, and a catalog file that changed', async () => { + writeFileSync(join(bundle.root, bundle.catalogs[0].path), '{"greeting":"Servus"}') + + const french = await call('mobileWeb.bundle.localeCatalog', { locale: 'fr' }) + const changed = await call('mobileWeb.bundle.localeCatalog', { locale: 'de' }) + + expect(errorMessage(french)).toBe('mobile_web_bundle_asset_unknown') + expect(errorMessage(changed)).toBe('mobile_web_bundle_asset_changed') + }) +}) + describe('where the resolver probes', () => { it('finds the bundle beside an out/main app path', async () => { const bundle = writeSyntheticMobileWebBundle(join(scratch, 'out', 'mobile-web'), 3) diff --git a/src/main/runtime/rpc/methods/mobile-delivery/mobile-web-bundle.ts b/src/main/runtime/rpc/methods/mobile-delivery/mobile-web-bundle.ts index 1d700f41cf2..c7fe1de157b 100644 --- a/src/main/runtime/rpc/methods/mobile-delivery/mobile-web-bundle.ts +++ b/src/main/runtime/rpc/methods/mobile-delivery/mobile-web-bundle.ts @@ -1,6 +1,9 @@ -/** Serve only this install's bundle over authenticated RPC: manifest, then chunks or advertised ranges. +/** Serve only this install's bundle over authenticated RPC: manifest, then chunks or advertised ranges, and the page's language catalog. * Never proxy to SSH/relay execution hosts: the phone paired with this desktop. * Verify/read failures map to asset-changed without exposing host paths. */ +import { createHash } from 'node:crypto' +import { readFile } from 'node:fs/promises' +import { join } from 'node:path' import { MOBILE_WEB_BUNDLE_BROTLI_RANGE_METHOD, MOBILE_WEB_BUNDLE_CHUNK_BYTES, @@ -20,6 +23,12 @@ import { mobileWebBundleBrotliPath, type MobileWebBundleAsset } from '../../../../../shared/mobile-web-bundle/manifest-contract' +import { + MOBILE_WEB_BUNDLE_LOCALE_CATALOG_METHOD, + MobileWebBundleLocaleCatalogParamsSchema, + type MobileWebBundleLocaleCatalogParams, + type MobileWebBundleLocaleCatalogResult +} from '../../../../../shared/mobile-web-bundle/locale-catalog-contract' import { loadBundledMobileWebBundle, type BundledMobileWebBundle @@ -55,6 +64,42 @@ function abortIfDisconnected(ctx: RpcContext): void { } } +/** Answer from the build's own catalog file, so the page reads the strings it was built with. */ +async function readLocaleCatalog( + params: MobileWebBundleLocaleCatalogParams, + ctx: RpcContext +): Promise { + const bundle = requireBundle() + const entry = bundle.manifest.catalogs?.find((catalog) => catalog.locale === params.locale) + if (!entry) { + throw bundleError('mobile_web_bundle_asset_unknown') + } + if (params.knownSha256 === entry.sha256) { + return { locale: entry.locale, sha256: entry.sha256, catalog: null } + } + // Its own budget, so a page's one catalog read never waits behind its shell's bundle download. + const release = acquireMobileWebBundleReadSlot(`catalog:${mobileWebBundleReadBucket(ctx)}`) + if (!release) { + throw bundleError('mobile_web_bundle_read_limited') + } + try { + abortIfDisconnected(ctx) + const bytes = await readFile(join(bundle.root, entry.path)) + if (createHash('sha256').update(bytes).digest('hex') !== entry.sha256) { + throw bundleError('mobile_web_bundle_asset_changed') + } + const catalog: unknown = JSON.parse(bytes.toString('utf8')) + if (typeof catalog !== 'object' || catalog === null || Array.isArray(catalog)) { + throw bundleError('mobile_web_bundle_asset_changed') + } + return { locale: entry.locale, sha256: entry.sha256, catalog: { ...catalog } } + } catch (error) { + throw asContractError(error, entry.path) + } finally { + release() + } +} + /** Map unreadable, missing or truncated assets to asset-changed; host paths stay private. */ function asContractError(error: unknown, path: string): unknown { if (error instanceof InvalidArgumentError || isClientDisconnectedError(error)) { @@ -201,5 +246,11 @@ export const MOBILE_WEB_BUNDLE_METHODS = [ handler: (params, ctx): Promise => // The raw asset's hash still gates every window of its copy. readVerifiedWindow(ctx, params, MOBILE_WEB_BUNDLE_CHUNK_BYTES, rawWindowReply, brotliCopyOf) + }), + defineMethod({ + name: MOBILE_WEB_BUNDLE_LOCALE_CATALOG_METHOD, + permission: 'workspace', + params: MobileWebBundleLocaleCatalogParamsSchema, + handler: readLocaleCatalog }) ] diff --git a/src/main/runtime/rpc/methods/structured-sessions/attachments/structured-agent-session-queued-image-lifecycle.test.ts b/src/main/runtime/rpc/methods/structured-sessions/attachments/structured-agent-session-queued-image-lifecycle.test.ts deleted file mode 100644 index 35ef7a9d3d1..00000000000 --- a/src/main/runtime/rpc/methods/structured-sessions/attachments/structured-agent-session-queued-image-lifecycle.test.ts +++ /dev/null @@ -1,793 +0,0 @@ -import { journalInputSourceBody } from '../../../../../native-chat/agent-session-journal/input-order/journal-input-source' -import { - streamState, - queuedImageTestBody -} from '../protocol/structured-agent-session-wire-record.test-fixture' -import { - appendTestJournalQueueRow, - openTestJournalHostDatabase -} from '../../../../../native-chat/agent-session-journal/store-lifecycle/journal-host-database-test-support' - -import { finishTestJournalHistoricalInputs } from '../../../../../native-chat/agent-session-journal/replay/journal-historical-inputs.test-support' -import { - reduceStructuredAgentSession, - EMPTY_STRUCTURED_AGENT_SESSION -} from '../../../../../../shared/agent-session/structured-agent-session-reducer' -import { projectStructuredAgentSessionMessages } from '../../../../../../shared/agent-session/view/structured-agent-session-message-projection' -import { afterAll, afterEach, beforeAll, expect, it, vi } from 'vitest' -import { - createQueuedMessageTestRig, - type QueuedMessageTestRig -} 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 { setStructuredAgentSessionHost } from '../../../../../native-chat/agent-session-wire/host/structured-agent-session-registry' -import { - HOST_TEST_SESSION as SESSION, - HOST_TEST_THREAD as THREAD, - hostTestOperationId -} from '../../../../../native-chat/agent-session-wire/host/testing/structured-agent-session-host-test-data' -import { call, openStream } from '../protocol/structured-agent-session-rpc.test-fixture' - -import { STRUCTURED_MOBILE_CLIENT } from '../protocol/structured-agent-session-rpc-client.test-fixture' -import { DESKTOP_RENDERER_RUNTIME_CLIENT_CAPABILITIES } from '../../../../../ipc/desktop-renderer-runtime-capabilities' -import { - queuedImageHistoryReader, - projectQueuedImageCardHistory -} from './structured-agent-session-queued-image-capability' -import type { - AgentJournalSubmission, - AgentJournalMessageItem -} from '../../../../../../shared/agent-session/journal/agent-session-journal-types' -import type { AgentSessionQueuedMessage } from '../../../../../../shared/agent-session/requests/agent-session-queued-message-wire' -import type { - AgentSessionHistoryRequest, - AgentSessionSubscribeEvent -} from '../../../../../../shared/agent-session/agent-session-wire' -import { - agentJournalItemKey, - agentJournalSubmissionKey -} from '../../../../../../shared/agent-session/journal/agent-session-journal-item-key' -import type { NativeChatMessage } from '../../../../../../shared/native-chat/native-chat-types' - -// Load the real phone readers at runtime; their RN ambient types belong to the mobile compiler. -const { mobileQueuedMessageCards } = await vi.importActual<{ - mobileQueuedMessageCards: ( - cards: readonly AgentSessionQueuedMessage[] | null, - submissions: readonly Pick[], - facts?: { agentWorking?: boolean } - ) => unknown[] -}>('../../../../../../../mobile/src/session/mobile-structured-queued-message-cards') -const { buildMobileNativeChatTransientData } = await vi.importActual<{ - buildMobileNativeChatTransientData: (input: { - messages: NativeChatMessage[] - folded: NativeChatMessage[] - streaming: string | null - pending: [] - imagePreviewsByMessageId: Record - }) => { data: NativeChatMessage[] } -}>('../../../../../../../mobile/src/session/native-chat/mobile-native-chat-render-data') -const { isRenderableImageUri } = await vi.importActual<{ - isRenderableImageUri: (uri: string | undefined) => boolean -}>('../../../../../../../mobile/src/session/native-chat/visual/mobile-native-chat-image-preview') - -beforeAll(() => { - vi.spyOn(Date, 'now').mockReturnValue(1_800_000_000_000) -}) - -afterAll(() => vi.restoreAllMocks()) - -const OLD = { ...STRUCTURED_MOBILE_CLIENT, clientId: 'old-phone', connectionId: 'old-phone' } -const MODERN = { - clientId: 'modern', - connectionId: 'modern', - clientKind: 'runtime' as const, - clientCapabilities: [...DESKTOP_RENDERER_RUNTIME_CLIENT_CAPABILITIES] -} -let rig: QueuedMessageTestRig | undefined -const current = () => { - if (!rig) { - throw new Error('missing rig') - } - return rig -} -const journal = () => { - const value = current().host.collaboratorsForTests().sessions.get(SESSION)?.journal - if (!value) { - throw new Error('missing journal') - } - return value -} -afterEach(async () => { - setStructuredAgentSessionHost(null) - await rig?.dispose() - rig = undefined -}) -async function history( - request: Omit = { direction: 'tail' }, - old = true -) { - const result = await current().host.history( - { sessionId: SESSION, ...request }, - undefined, - old ? queuedImageHistoryReader(OLD) : undefined - ) - const answer = old ? projectQueuedImageCardHistory(result, OLD) : result - return answer -} -async function imageBody(text = 'original') { - return queuedImageTestBody(current().root, text) -} -async function sendImage(body: AgentJournalMessageItem) { - const id = hostTestOperationId() - const fields = { body, options: { model: 'default' } } - expect( - await call( - 'agentSession.send', - { envelope: current().envelope(fields, 'agentSession.send', id), ...fields }, - OLD - ) - ).toMatchObject({ result: { ok: true } }) - return id -} -async function failedImage() { - await current().host.close(SESSION, 'evict') - current().failNextStart(new Error('fixture start failed')) - const body = await imageBody() - const id = await sendImage(body) - await eventually(async () => expect(await current().drafts()).toHaveLength(1)) - return { - id, - body, - card: journal() - .queuedMessages.list() - .find((row) => row.state === 'returned')! - } -} - -it('publishes a complete image row to old readers before it has a submission', async () => { - rig = await createQueuedMessageTestRig({ restartable: true }) - setStructuredAgentSessionHost(rig.host) - await rig.workingSend() - const frames = await openStream('agentSession.subscribe', { sessionId: SESSION }, OLD) - const body = await imageBody('waiting image') - const id = hostTestOperationId() - const fields = { body, delivery: 'queue-if-active' as const } - const params = { envelope: rig.envelope(fields, 'agentSession.send', id), ...fields } - expect(await call('agentSession.send', params, OLD)).toMatchObject({ - result: { ok: true, value: { queued: { messageId: id } } } - }) - expect(journal().submission(id)).toBeUndefined() - expect((await history()).page.items).toContainEqual( - expect.objectContaining({ itemId: agentJournalSubmissionKey(id), body }) - ) - await eventually(() => - expect(streamState(frames).items).toContainEqual( - expect.objectContaining({ itemId: agentJournalSubmissionKey(id), body }) - ) - ) - expect(await call('agentSession.send', params, OLD)).toMatchObject({ - result: { ok: true, replayed: true, value: { queued: { messageId: id } } } - }) - expect((await history({ direction: 'tail' }, false)).page.queuedMessages).toContainEqual( - expect.objectContaining({ messageId: id, body }) - ) -}) - -it('installs old-reader source and exact controls through RPC, disk reopen, Send and Delete without changing capable readers', async () => { - rig = await createQueuedMessageTestRig({ restartable: true }) - setStructuredAgentSessionHost(rig.host) - const { id, body, card } = await failedImage() - expect(card.body).toEqual(body) - expect(isRenderableImageUri(body.blocks.find((block) => block.type === 'image-ref')?.path)).toBe( - false - ) - const old = await call('agentSession.history', { sessionId: SESSION, direction: 'tail' }, OLD) - expect(old).toMatchObject({ - result: { - page: { - items: expect.arrayContaining([ - expect.objectContaining({ itemId: agentJournalSubmissionKey(id), body }) - ]), - queuedMessages: [ - expect.objectContaining({ - messageId: card.messageId, - body: expect.objectContaining({ command: { name: 'compact' } }) - }) - ] - } - } - }) - expect( - await call('agentSession.history', { sessionId: SESSION, direction: 'tail' }, MODERN) - ).toMatchObject({ result: { page: { queuedMessages: [expect.objectContaining({ body })] } } }) - await rig.quitRestartHostProcess() - setStructuredAgentSessionHost(rig.host) - const reopened = await history() - expect(reopened.page.items).toContainEqual( - expect.objectContaining({ itemId: agentJournalSubmissionKey(id), body }) - ) - expect(reopened.page.submissions.find((send) => send.clientMessageId === id)).not.toHaveProperty( - 'keptAsQueuedMessageId' - ) - const frames = await openStream('agentSession.subscribe', { sessionId: SESSION }, OLD) - const modernFrames = await openStream('agentSession.subscribe', { sessionId: SESSION }, MODERN) - const immutable = journal().submission(id) - const receipt = journal().receiptFor(id) - const sendFields = { messageId: card.messageId } - const sendParams = { - envelope: rig.envelope(sendFields, 'agentSession.queuedMessageSend', hostTestOperationId()), - ...sendFields - } - expect(await call('agentSession.queuedMessageSend', sendParams, OLD)).toMatchObject({ - result: { ok: true } - }) - await eventually(() => expect(rig!.dispatch).toHaveBeenCalled()) - const dispatches = rig.dispatch.mock.calls.length - expect(await call('agentSession.queuedMessageSend', sendParams, OLD)).toMatchObject({ - result: { ok: true } - }) - expect(rig.dispatch.mock.calls.length).toBe(dispatches) - expect(rig.dispatch.mock.calls.at(-1)?.[0]).toMatchObject({ body }) - expect((await rig.handoff(card.messageId))?.options).toEqual({ model: 'default' }) - expect((await history()).page.queuedMessages).toEqual([]) - expect(journal().submission(id)).toEqual(immutable) - expect(journal().receiptFor(id)).toEqual(receipt) - expect(journal().submissionBody(id)).toEqual(body) - expect( - frames.some( - (frame) => - 'result' in frame && - frame.result && - JSON.stringify(frame.result).includes('"queuedMessages":[]') - ) - ).toBe(true) - expect( - modernFrames.some( - (frame) => - 'result' in frame && - frame.result && - JSON.stringify(frame.result).includes('"queuedMessages":[]') - ) - ).toBe(true) - expect( - frames.filter( - (frame) => - 'result' in frame && frame.result && JSON.stringify(frame.result).includes('"type":"reset"') - ) - ).toEqual([]) - await rig.stop() - await rig.settleAccepted((await rig.handoff(card.messageId))!.clientMessageId, 'echo') - await rig.host.close(SESSION, 'evict') - rig.failNextStart(new Error('again')) - const deleted = await sendImage(body) - await eventually(async () => expect((await rig!.drafts()).length).toBeGreaterThan(0)) - const exact = journal() - .queuedMessages.list() - .find((row) => row.messageId === deleted || row.recovers === deleted)! - await openStream('agentSession.subscribe', { sessionId: SESSION }, OLD) - const fields = { messageId: exact.messageId } - expect( - await call( - 'agentSession.queuedMessageDelete', - { - envelope: rig.envelope(fields, 'agentSession.queuedMessageDelete', hostTestOperationId()), - ...fields - }, - OLD - ) - ).toMatchObject({ result: { ok: true } }) - const deletedPage = (await history()).page - expect( - projectStructuredAgentSessionMessages(deletedPage.items, [], deletedPage.submissions).some( - (item) => item.id === agentJournalSubmissionKey(deleted) - ) - ).toBe(false) - await rig.quitRestartHostProcess() - const reopenedDeleted = (await history()).page - expect( - projectStructuredAgentSessionMessages( - reopenedDeleted.items, - [], - reopenedDeleted.submissions - ).some((item) => item.id === agentJournalSubmissionKey(deleted)) - ).toBe(false) -}) - -it('keeps a hidden original pageable beyond1024 rows and preserves edited recovery through a refused original settlement', async () => { - rig = await createQueuedMessageTestRig({ restartable: true }) - setStructuredAgentSessionHost(rig.host) - const { id, body, card } = await failedImage() - const j = journal() - const fence = rig.store.getRecord(SESSION)!.lease.runtimeFence - await j.rollEpoch('unreconcilable_prefix', fence) - expect( - j.snapshot().items.find((item) => item.itemId === agentJournalSubmissionKey(id)) - ).toBeUndefined() - for (let i = 0; i < 1030; i++) { - await j.appendItem( - { provider: 'legacy', agent: 'codex', sessionId: 'history', recordId: `row-${i}` }, - { kind: 'status', text: `${i}` }, - { fence, turnScope: { kind: 'thread' } } - ) - } - const tail = await history() - expect(tail.page.hasOlder).toBe(true) - expect( - tail.page.items.find((item) => item.itemId === agentJournalSubmissionKey(id)) - ).toBeUndefined() - let before = tail.page.window.nextCursor - let older = await history({ direction: 'before', cursor: before, limit: 200 }) - while ( - older.page.hasOlder && - !older.page.items.some((item) => item.itemId === agentJournalSubmissionKey(id)) - ) { - before = older.page.window.nextCursor - older = await history({ direction: 'before', cursor: before, limit: 200 }) - } - expect(older.page.items).toContainEqual( - expect.objectContaining({ itemId: agentJournalSubmissionKey(id), body }) - ) - expect((await history({ direction: 'after', cursor: { epoch: 'stale', sequence: 0 } })).ok).toBe( - false - ) - const rpc = await call( - 'agentSession.history', - { sessionId: SESSION, direction: 'before', cursor: before, limit: 200 }, - OLD - ) - expect(rpc).toMatchObject({ - result: { - page: { - queuedMessages: [ - expect.objectContaining({ - messageId: card.messageId, - body: expect.objectContaining({ command: { name: 'compact' } }) - }) - ] - } - } - }) - const fields = { - messageId: card.messageId, - expectedBodyFingerprint: card.fingerprint, - text: 'original' - } - expect( - await call( - 'agentSession.queuedMessageUpdate', - { - envelope: rig.envelope(fields, 'agentSession.queuedMessageUpdate', hostTestOperationId()), - ...fields - }, - MODERN - ) - ).toMatchObject({ result: { ok: true, value: { status: 'unchanged' } } }) - expect( - (await history({ direction: 'before', cursor: before, limit: 200 })).page.items - ).toContainEqual(expect.objectContaining({ itemId: agentJournalSubmissionKey(id) })) - const changed = { ...fields, text: 'changed' } - expect( - await call( - 'agentSession.queuedMessageUpdate', - { - envelope: rig.envelope(changed, 'agentSession.queuedMessageUpdate', hostTestOperationId()), - ...changed - }, - MODERN - ) - ).toMatchObject({ result: { ok: true, value: { status: 'updated' } } }) - const selected = await history({ - direction: 'before', - cursor: before, - limit: 200 - }) - expect( - selected.page.items.find((item) => item.itemId === agentJournalSubmissionKey(id)) - ).toBeUndefined() - expect(j.queuedMessages.get(card.messageId)).toMatchObject({ - body: { blocks: [{ type: 'text', text: 'changed' }, body.blocks[1]] }, - options: { model: 'default' } - }) - const pub = rig.host.collaboratorsForTests().subscribers.readQueuePublication(SESSION)! - const { projectQueuedImageCardPublication } = - await import('./structured-agent-session-queued-image-capability') - const oldCards = projectQueuedImageCardPublication(pub, OLD) - const model = mobileQueuedMessageCards(oldCards.queuedMessages, selected.page.submissions, { - agentWorking: true - }) - expect(model).toMatchObject([{ messageId: card.messageId, command: true, waitsForAgent: true }]) - expect( - mobileQueuedMessageCards(oldCards.queuedMessages, selected.page.submissions, { - agentWorking: false - })[0] - ).not.toHaveProperty('waitsForAgent') - await rig.settleAccepted(id, 'late-original') - expect(j.submission(id)?.dispatchState).toBe('rejected') - expect(j.queuedMessages.get(card.messageId)?.body.blocks[0]).toEqual({ - type: 'text', - text: 'changed' - }) - expect( - j.snapshot().items.find((item) => item.itemId === agentJournalSubmissionKey(id)) - ).toBeUndefined() - await rig.quitRestartHostProcess() - await history() - expect(journal().queuedMessages.get(card.messageId)?.body.blocks[0]).toEqual({ - type: 'text', - text: 'changed' - }) - expect( - journal() - .snapshot() - .items.find((item) => item.itemId === agentJournalSubmissionKey(id)) - ).toBeUndefined() -}) - -it.each([false, true])( - 'retires the source after changed Save (second failed handoff: %s), retaining its exact live control and independent edited handoff', - async (secondFailure) => { - rig = await createQueuedMessageTestRig({ restartable: true }) - setStructuredAgentSessionHost(rig.host) - const { id, body, card } = await failedImage() - let presentedId = id - if (secondFailure) { - rig.failNextStart(new Error('second queued start failed')) - const fields = { messageId: card.messageId } - expect( - await call( - 'agentSession.queuedMessageSend', - { - envelope: rig.envelope(fields, 'agentSession.queuedMessageSend', hostTestOperationId()), - ...fields - }, - OLD - ) - ).toMatchObject({ result: { ok: true } }) - await eventually(async () => - expect((await rig!.handoff(card.messageId))?.dispatchState).toBe('rejected') - ) - presentedId = (await rig.handoff(card.messageId))!.clientMessageId - expect(journal().submission(presentedId)).toMatchObject({ queuedMessageId: card.messageId }) - expect(journal().submission(presentedId)).not.toHaveProperty('keptAsQueuedMessageId') - } - const before = await history() - const immutable = journal().submission(presentedId) - const receipt = journal().receiptFor(presentedId) - expect( - projectStructuredAgentSessionMessages(before.page.items, [], before.page.submissions) - ).toContainEqual(expect.objectContaining({ id: agentJournalSubmissionKey(presentedId) })) - const messages = projectStructuredAgentSessionMessages( - before.page.items, - [], - before.page.submissions - ) - const transient = buildMobileNativeChatTransientData({ - messages, - folded: messages, - streaming: null, - pending: [], - imagePreviewsByMessageId: { - [agentJournalSubmissionKey(presentedId)]: ['file:///device/composer-preview.png'] - } - }) - expect(JSON.stringify(transient.data)).toContain('file:///device/composer-preview.png') - const frames = await openStream('agentSession.subscribe', { sessionId: SESSION }, OLD) - const fields = { - messageId: card.messageId, - expectedBodyFingerprint: journal().queuedMessages.get(card.messageId)!.fingerprint, - text: 'edited original' - } - expect( - await call( - 'agentSession.queuedMessageUpdate', - { - envelope: rig.envelope(fields, 'agentSession.queuedMessageUpdate', hostTestOperationId()), - ...fields - }, - MODERN - ) - ).toMatchObject({ result: { ok: true, value: { status: 'updated' } } }) - const changed = await history() - expect(journal().submission(presentedId)).toEqual(immutable) - expect(journal().receiptFor(presentedId)).toEqual(receipt) - expect( - projectStructuredAgentSessionMessages(changed.page.items, [], changed.page.submissions).some( - (item) => item.id === agentJournalSubmissionKey(presentedId) - ) - ).toBe(false) - expect( - mobileQueuedMessageCards(changed.page.queuedMessages ?? [], changed.page.submissions) - ).toMatchObject([ - { messageId: card.messageId, command: true, text: expect.stringContaining('edited original') } - ]) - expect(frames).toEqual( - expect.arrayContaining([ - expect.objectContaining({ - result: expect.objectContaining({ - type: 'batch', - batch: expect.objectContaining({ - submissions: expect.arrayContaining([ - expect.objectContaining({ - clientMessageId: presentedId, - keptAsQueuedMessageId: card.messageId - }) - ]) - }) - }) - }), - expect.objectContaining({ - result: expect.objectContaining({ - queuedMessages: expect.arrayContaining([ - expect.objectContaining({ - messageId: card.messageId, - body: expect.objectContaining({ command: { name: 'compact' } }) - }) - ]) - }) - }) - ]) - ) - const live = frames.reduce((state, frame) => { - if (!frame.ok) { - throw new Error('subscription failed') - } - if (!frame.result) { - return state - } - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: Only the installed agentSession.subscribe dispatcher writes these frames; this test feeds its serialized events to the real reducer. - const event = frame.result as AgentSessionSubscribeEvent - return reduceStructuredAgentSession(state, { type: 'event', event }) - }, EMPTY_STRUCTURED_AGENT_SESSION) - expect( - projectStructuredAgentSessionMessages(live.items, [], live.submissions).some( - (item) => item.id === agentJournalSubmissionKey(presentedId) - ) - ).toBe(false) - expect(mobileQueuedMessageCards(live.queuedMessages ?? null, live.submissions)).toMatchObject([ - { messageId: card.messageId, command: true, text: expect.stringContaining('edited original') } - ]) - expect(journal().submissionBody(presentedId)).toEqual(body) - expect(journal().submissionBody(id)).toEqual(body) - expect((await history({ direction: 'tail' }, false)).page.queuedMessages).toMatchObject([ - { - messageId: card.messageId, - body: { blocks: [{ type: 'text', text: 'edited original' }, body.blocks[1]] } - } - ]) - expect(isRenderableImageUri('file:///device/composer-preview.png')).toBe(true) - expect(isRenderableImageUri('data:image/png;base64,AA==')).toBe(true) - expect( - isRenderableImageUri(body.blocks.find((block) => block.type === 'image-ref')?.path) - ).toBe(false) - const send = { messageId: card.messageId } - expect( - await call( - 'agentSession.queuedMessageSend', - { - envelope: rig.envelope(send, 'agentSession.queuedMessageSend', hostTestOperationId()), - ...send - }, - OLD - ) - ).toMatchObject({ result: { ok: true } }) - await eventually(async () => expect(await rig!.handoff(card.messageId)).toBeDefined()) - const handed = (await rig.handoff(card.messageId))! - expect(handed.clientMessageId).not.toBe(id) - const handedBody = journal().submissionBody(handed.clientMessageId) - expect(handedBody).toEqual({ - ...body, - blocks: [{ type: 'text', text: 'edited original' }, body.blocks[1]] - }) - expect(handed.options).toEqual({ model: 'default' }) - await rig.settleAccepted(id, 'old-u-after-edited-v') - expect((await rig.handoff(card.messageId))?.dispatchState).toBe(handed.dispatchState) - expect((await history()).page.queuedMessages).toEqual([]) - await rig.quitRestartHostProcess() - const reopened = (await history()).page - expect(reopened.queuedMessages).toMatchObject([{ messageId: card.messageId, state: 'waiting' }]) - expect(reopened.queuedMessages).toHaveLength(1) - expect(journal().submission(id)?.dispatchState).toBe('rejected') - expect(journal().submissionBody(handed.clientMessageId)).toEqual(handedBody) - expect(journal().queuedMessages.get(card.messageId)?.body).toEqual(handedBody) - } -) - -it('keeps an image-only waiting queue and pause visible through Resume and a failed queued start', async () => { - rig = await createQueuedMessageTestRig({ restartable: true }) - setStructuredAgentSessionHost(rig.host) - const working = await sendImage(await imageBody('prior work')) - await eventually(() => expect(rig!.dispatch).toHaveBeenCalled()) - const full = await imageBody() - const body = { ...full, blocks: full.blocks.filter((block) => block.type === 'image-ref') } - const id = hostTestOperationId() - const fields = { body, options: { model: 'default' }, delivery: 'queue-if-active' } - expect( - await call( - 'agentSession.send', - { - envelope: rig.envelope(fields, 'agentSession.send', id), - ...fields - }, - MODERN - ) - ).toMatchObject({ result: { ok: true, value: { queued: { messageId: id } } } }) - await rig.stop() - await rig.settleAccepted(working, 'waiting-image-prior-turn') - const paused = (await history()).page - expect(paused.queuePause).toMatchObject({ reason: 'stopped' }) - expect(paused.queuedMessages).toMatchObject([{ messageId: id, state: 'waiting' }]) - expect( - mobileQueuedMessageCards(paused.queuedMessages ?? [], paused.submissions, { - agentWorking: false - }) - ).toMatchObject([{ messageId: id, command: true }]) - await rig.quitRestartHostProcess() - setStructuredAgentSessionHost(rig.host) - rig.failNextStart(new Error('queued resume start failed')) - expect( - await call( - 'agentSession.queuedMessagesResume', - { - envelope: rig.envelope({}, 'agentSession.queuedMessagesResume', hostTestOperationId()) - }, - OLD - ) - ).toMatchObject({ result: { ok: true } }) - await eventually(async () => - expect(await rig!.drafts()).toEqual([{ messageId: id, state: 'returned' }]) - ) - const failed = (await history()).page - expect(failed.queuePause).toBeNull() - expect(failed.queuedMessages).toMatchObject([{ messageId: id, state: 'returned' }]) - expect(journal().queuedMessages.get(id)).toMatchObject({ body, options: { model: 'default' } }) - const handoff = (await rig.handoff(id))! - expect( - projectStructuredAgentSessionMessages(failed.items, [], failed.submissions) - ).toContainEqual( - expect.objectContaining({ id: agentJournalSubmissionKey(handoff.clientMessageId) }) - ) - const exact = { messageId: id } - expect( - await call( - 'agentSession.queuedMessageDelete', - { - envelope: rig.envelope(exact, 'agentSession.queuedMessageDelete', hostTestOperationId()), - ...exact - }, - OLD - ) - ).toMatchObject({ result: { ok: true } }) - expect((await history()).page.queuedMessages).toEqual([]) - expect(journal().submissionBody(handoff.clientMessageId)).toEqual(body) -}) - -it.each([ - { image: false, edit: false }, - { image: true, edit: false }, - { image: true, edit: true } -])( - 'keeps ordinary uncertain original through cold/late proof, independent of a saved physical edit ($image/$edit)', - async ({ image, edit }) => { - rig = await createQueuedMessageTestRig({ - restartable: true, - ...(edit ? { legacyInputs: true } : {}) - }) - setStructuredAgentSessionHost(rig.host) - const full = await imageBody('Original first paragraph.\n\nKeep the complete final paragraph.') - const body = { - ...full, - blocks: image - ? [ - ...full.blocks, - { type: 'text' as const, text: 'Final prose after the image.' }, - full.blocks[1] - ] - : full.blocks.filter((block) => block.type !== 'image-ref') - } - const id = await sendImage(body) - await eventually(() => expect(rig!.dispatch).toHaveBeenCalledTimes(1)) - await eventually(() => expect(journal().submission(id)?.handedOverAt).toBeDefined()) - await rig.stop() - await rig.host.flushStreamedEvents(SESSION) - await rig.host.collaboratorsForTests().serialize(SESSION, async () => {}) - expect(journal().queuedMessages.list()).toEqual([]) - if (edit) { - appendTestJournalQueueRow( - openTestJournalHostDatabase(rig.root).db, - journal(), - `recovery:${id}`, - { - op: 'queued', - body, - recovers: id, - position: 0, - queuedAt: journal().cursor(), - options: { model: 'default' }, - returned: { reason: 'prior-build uncertainty', rejection: { kind: 'unconfirmed' } } - } - ) - finishTestJournalHistoricalInputs(journal()) - } - const card = journal().queuedMessages.get(`recovery:${id}`) - const original = journal().submission(id)! - const receipt = journal().receiptFor(id) - expect(original).toMatchObject({ dispatchState: 'unknown', providerItemId: null }) - await openStream('agentSession.subscribe', { sessionId: SESSION }, OLD) - await rig.quitRestartHostProcess() - setStructuredAgentSessionHost(rig.host) - await openStream('agentSession.subscribe', { sessionId: SESSION }, OLD) - if (card) { - const fields = { - messageId: card.messageId, - expectedBodyFingerprint: card.fingerprint, - text: 'Independent changed prose.' - } - const params = { - envelope: rig.envelope(fields, 'agentSession.queuedMessageUpdate', hostTestOperationId()), - ...fields - } - expect(await call('agentSession.queuedMessageUpdate', params, MODERN)).toMatchObject({ - result: { ok: true, value: { status: 'updated' } } - }) - const edited = journal().queuedMessages.get(`recovery:${id}`)! - expect(edited.body).toEqual({ - ...body, - blocks: [ - { type: 'text', text: fields.text }, - ...body.blocks.filter((block) => block.type !== 'text') - ] - }) - expect(edited.options).toEqual(card.options) - expect(edited.state).toBe('waiting') - expect(await call('agentSession.queuedMessageUpdate', params, MODERN)).toMatchObject({ - result: { ok: true } - }) - expect(journal().queuedMessages.get(`recovery:${id}`)).toEqual(edited) - } - const input = structuredClone(journal().queuedMessages.displayState().inputs.sources.get(id)) - expect(journalInputSourceBody(input)).toEqual(body) - expect(input?.kind === 'submission' ? input.options : input?.submission.options).toEqual( - original.options - ) - expect(input?.fence).toBe(original.fence) - const beforeProof = journal().queuedMessages.get(`recovery:${id}`) - expect(journal().submission(id)).toEqual(original) - expect(journal().receiptFor(id)).toEqual(receipt) - expect(journal().submissionBody(id)).toEqual(body) - // The existing rig delivers a Codex identity through host.settleLateDispatch, never a journal receipt edit. - await rig.settleAccepted(id, 'pinned-original-late-echo') - expect(journal().submission(id)).toMatchObject({ - dispatchState: 'accepted', - options: original.options, - payloadFingerprint: original.payloadFingerprint, - fence: rig.store.getRecord(SESSION)!.lease.runtimeFence - }) - const acceptedReceipt = journal().receiptFor(id) - expect(acceptedReceipt).toMatchObject({ - clientMessageId: id, - providerItemId: agentJournalItemKey({ - provider: 'codex', - threadId: THREAD, - turnId: 'turn-pinned-original-late-echo', - ordinal: 0 - }) - }) - expect(acceptedReceipt).not.toEqual(receipt) - await rig.settleAccepted(id, 'pinned-original-late-echo') - expect(journal().receiptFor(id)).toEqual(acceptedReceipt) - expect(journal().queuedMessages.displayState().inputs.sources.get(id)).toEqual(input) - expect(journal().submissionBody(id)).toEqual(body) - expect(rig.dispatch).toHaveBeenCalledTimes(1) - if (card) { - expect(journal().queuedMessages.get(`recovery:${id}`)).toEqual(beforeProof) - await history() - } else { - expect(journal().queuedMessages.get(`recovery:${id}`)).toBeNull() - } - await rig.quitRestartHostProcess() - await history() - expect(journal().queuedMessages.get(`recovery:${id}`)).toEqual(beforeProof) - } -) diff --git a/src/main/runtime/rpc/server/runtime-rpc-mobile-paired-desktop-methods.ts b/src/main/runtime/rpc/server/runtime-rpc-mobile-paired-desktop-methods.ts index 333dd8868ed..945761935cd 100644 --- a/src/main/runtime/rpc/server/runtime-rpc-mobile-paired-desktop-methods.ts +++ b/src/main/runtime/rpc/server/runtime-rpc-mobile-paired-desktop-methods.ts @@ -5,6 +5,7 @@ export const PAIRED_DESKTOP_METHODS = [ // Device and pairing concerns of the phone's own pairing. 'mobileWeb.bundle.brotliRange', 'mobileWeb.bundle.chunk', + 'mobileWeb.bundle.localeCatalog', 'mobileWeb.bundle.manifest', 'mobileWeb.bundle.range', 'notifications.getMissedSince', diff --git a/src/main/runtime/rpc/terminal-agent-prompt-socket.test.ts b/src/main/runtime/rpc/terminal-agent-prompt-socket.test.ts index 629c3535517..ed807aa74fc 100644 --- a/src/main/runtime/rpc/terminal-agent-prompt-socket.test.ts +++ b/src/main/runtime/rpc/terminal-agent-prompt-socket.test.ts @@ -25,6 +25,9 @@ import { bindPaneFirst } from '../orca-runtime-tests/bind-first-pane.test-fixtur import * as inputAdmission from '../terminal/input/terminal-input-admission' import { writePtyFromRuntimeController } from '../../ipc/pty/runtime/operations' import { getLocalPtyProvider } from '../../ipc/pty/provider/registry' +import { createHookListenerState } from '../../../shared/agent-hook-listener/listener-state' +import { normalizeHookPayload } from '../../../shared/agent-hook-listener/normalization/normalize-hook-payload' +import { AgentHookServer } from '../../agent-hooks/server/agent-hook-server' vi.mock('../../git/worktrees/catalog/worktree-scan-cache', async (importOriginal) => { const listings = getWorktreeListingMocks() @@ -59,11 +62,29 @@ const { getWorktreeListingMocks } = vi.hoisted(() => { return { getWorktreeListingMocks: () => (listings ??= createWorktreeListingMocks()) } }) -it.each(['before', 'after', 'paired', 'orchestration'] as const)( +it.each([ + 'before', + 'after', + 'paired', + 'orchestration', + 'codex-startup', + 'codex-replay', + 'codex-cold-replay' +] as const)( 'real CLI phone admission and delivery: %s', async (boundary) => { const disconnect = boundary === 'before' || boundary === 'after' const paired = boundary === 'paired' + const codex = boundary.startsWith('codex-') + const replay = boundary === 'codex-replay' || boundary === 'codex-cold-replay' + const hookServer = replay ? new AgentHookServer() : undefined + await hookServer?.start({ env: 'production' }) + const text = codex ? 'x'.repeat(1_000) : 'first' + const hookState = createHookListenerState() + let hook: ReturnType = null + let promptHandle = '' + let held = true + let enters = 0 const latch = () => Promise.withResolvers() const [pasted, release, closed, received] = [latch(), latch(), latch(), latch()] const root = mkdtempSync(join(tmpdir(), 'orca-prompt-socket-')) @@ -71,14 +92,88 @@ it.each(['before', 'after', 'paired', 'orchestration'] as const)( const endpoint = kind === 'named-pipe' ? `\\\\.\\pipe\\${root.split(/[/\\]/).at(-1)}` : join(root, 'rpc') const transport = new UnixSocketTransport({ endpoint, kind }) - const providerWrite = vi.spyOn(getLocalPtyProvider(), 'write').mockReturnValue(true) + vi.spyOn(getLocalPtyProvider(), 'write').mockReturnValue(true) const promptAdmission = vi.spyOn(inputAdmission, 'assertTerminalInputAdmitted') const rawAdmission = vi.spyOn(inputAdmission, 'createTerminalInputReservation') const { runtime, handle, writes } = await createAgentPromptSubmissionRuntime( - () => pasted.resolve(), - 'claude', - (host, id, data) => writePtyFromRuntimeController({ runtime: host }, id, data, 'driving') + (_host, data) => { + pasted.resolve() + if (codex && data === '\r') { + enters += 1 + held = enters === 1 + hook = normalizeHookPayload( + hookState, + 'codex', + { + paneKey: 'tab-prompt:22222222-2222-4222-8222-222222222222', + payload: held + ? { + hook_event_name: 'SessionStart', + source: 'startup', + session_id: '11111111-1111-4111-8111-111111111111' + } + : { + hook_event_name: 'UserPromptSubmit', + session_id: '11111111-1111-4111-8111-111111111111', + turn_id: 'turn-1', + prompt: text + } + }, + 'production' + ) + if (hook && hookServer) { + if (!held || boundary !== 'codex-cold-replay') { + hookServer.ingestRemote(hook, 'fixture-connection') + } + if (held) { + hookServer.ingestRemote( + { + ...hook, + hasExplicitPrompt: true, + isReplay: true, + payload: { + ...hook.payload, + state: 'working', + prompt: 'old task', + sessionBoundary: undefined, + mainAgent: { state: 'working', stateStartedAt: 1_000 } + } + }, + 'fixture-connection' + ) + } + } + } + }, + codex ? 'codex' : 'claude', + (host, id, data) => writePtyFromRuntimeController({ runtime: host }, id, data, 'driving'), + { + getAgentStatusSnapshot: () => + hookServer + ? hookServer + .getStatusSnapshot() + .map((row) => ({ ...row, terminalHandle: promptHandle })) + : hook + ? [ + { + ...hook.payload, + paneKey: hook.paneKey, + terminalHandle: promptHandle, + receivedAt: hook.payload.mainAgent?.stateStartedAt ?? 1_000, + stateStartedAt: hook.payload.mainAgent?.stateStartedAt ?? 1_000, + connectionId: null + } + ] + : [] + } ) + promptHandle = handle + if (codex) { + Object.defineProperty(runtime, 'getPtyWriteHostPlatform', { value: () => 'win32' }) + Object.defineProperty(runtime, 'readCurrentTerminalWaitScreen', { + value: async () => ({ lines: [], draft: held ? '[Pasted Content 1000 chars]' : undefined }) + }) + } const db = new OrchestrationDb(':memory:') runtime.setOrchestrationDb(db) const methods = [...STATUS_METHODS, ...TERMINAL_METHODS, ...ORCHESTRATION_METHODS] @@ -134,7 +229,10 @@ it.each(['before', 'after', 'paired', 'orchestration'] as const)( PATH: process.env.PATH, SystemRoot: process.env.SystemRoot } - let args = ['terminal', 'send', '--terminal', handle, '--text', 'first', '--enter', '--json'] + let args = ['terminal', 'send', '--terminal', handle, '--text', text, '--enter', '--json'] + if (codex) { + args.push('--wait-submit', '5') + } if (paired) { args = args.filter((arg) => arg !== '--enter') } @@ -207,13 +305,22 @@ it.each(['before', 'after', 'paired', 'orchestration'] as const)( expect(JSON.parse(output).result).toMatchObject( boundary === 'orchestration' ? { injected: true } : { send: { accepted: true } } ) - expect(writes).toEqual(paired ? ['first'] : [expect.stringContaining('first'), '\r']) + expect(writes).toEqual( + paired + ? ['first'] + : codex + ? [expect.stringContaining(text), '\r', '\r'] + : [expect.stringContaining('first'), '\r'] + ) + if (codex) { + expect(held).toBe(false) + expect(JSON.parse(output).result.send.prompt.stages).toContain('turn_started') + } expect(paired ? rawAdmission : promptAdmission).toHaveBeenCalledWith( runtime, paired ? 'programmatic' : 'pty-prompt', - undefined + codex ? 'programmatic' : undefined ) - expect(providerWrite).toHaveBeenCalledTimes(writes.length) expect(runtime.getDriver('pty-prompt')).toEqual({ kind: 'mobile', clientId: 'phone-A' }) return } @@ -251,6 +358,7 @@ it.each(['before', 'after', 'paired', 'orchestration'] as const)( } await exited await server?.stop() + hookServer?.stop() await transport.stop() await Promise.allSettled(done) db.close() diff --git a/src/main/runtime/sidebar-inputs/workspace-git-identity.test.ts b/src/main/runtime/sidebar-inputs/workspace-git-identity.test.ts index e528eb2bd61..3ee40cb8eee 100644 --- a/src/main/runtime/sidebar-inputs/workspace-git-identity.test.ts +++ b/src/main/runtime/sidebar-inputs/workspace-git-identity.test.ts @@ -27,6 +27,9 @@ describe('WorkspaceGitIdentity', () => { it('clears branch-scoped links on a branch switch it saw, never on the first sight', () => { const identity = new WorkspaceGitIdentity() expect(identity.observeScan([row({ branch: 'refs/heads/z' })], SCANNED)).toEqual([]) + expect(identity.observeScan([row({ branch: '' })], SCANNED)).toEqual([]) + expect(identity.observeScan([row({ branch: 'refs/heads/z' })], SCANNED)).toEqual([]) + expect(identity.observeScan([row({ branch: '' })], SCANNED)).toEqual([]) const clears = identity.observeScan([row()], SCANNED) expect(clears).toEqual([ { @@ -38,6 +41,12 @@ describe('WorkspaceGitIdentity', () => { expect(identity.observeScan([row({ linkedPR: null })], SCANNED)).toEqual([]) }) + it('preserves review links when first opened detached without a known owning branch', () => { + const identity = new WorkspaceGitIdentity() + expect(identity.observeScan([row({ branch: '' })], SCANNED)).toEqual([]) + expect(identity.observeScan([row({ branch: 'refs/heads/b' })], SCANNED)).toEqual([]) + }) + it('keeps a PR linked on a new branch that a cached rescan still reported as the old one', () => { const identity = new WorkspaceGitIdentity() const cachedRun = {} diff --git a/src/main/runtime/sidebar-inputs/workspace-git-identity.ts b/src/main/runtime/sidebar-inputs/workspace-git-identity.ts index e09bfe5f883..8d7cbff00ba 100644 --- a/src/main/runtime/sidebar-inputs/workspace-git-identity.ts +++ b/src/main/runtime/sidebar-inputs/workspace-git-identity.ts @@ -1,16 +1,17 @@ import type { Worktree } from '../../../shared/worktree/types' -import type { WorktreeMeta } from '../../../shared/worktree/meta-types' import { composeWorktreeHostIdentity, hostWorktreeTarget, type HostScopedWorktreeKey, type HostWorktreeTarget } from '../../../shared/worktree/host-qualified-identity' +import type { HOSTED_REVIEW_LINK_KEYS } from '../../../shared/worktree/hosted-review-links' import { - CLEARED_HOSTED_REVIEW_LINK_UPDATES, - HOSTED_REVIEW_LINK_KEYS, - canonicalHostedReviewBranchIdentity -} from '../../../shared/worktree/hosted-review-links' + branchHostedReviewOwner, + hostedReviewClearUpdates, + type HostedReviewClearUpdates, + type HostedReviewOwner +} from '../../../shared/worktree/hosted-review-branch-ownership' import { getRepoHostIdentityForParts, type HostScopedRepoKey @@ -27,6 +28,7 @@ type IdentityRow = Pick< | 'displayNameMode' | 'pushTarget' > & + Partial> & Partial> /** A row from a scan that reached a verdict, with the git run (scan-cache entry) it came from. */ @@ -38,28 +40,20 @@ type Observed = { branch: string displayName: string gitRun: object | null - /** The links as they stood when git last confirmed `branch`. */ - links: string + /** The branch owning the review context, with its links as they stood when git last confirmed it. */ + owner: HostedReviewOwner | undefined } export type HostedReviewLinkClear = { target: HostWorktreeTarget - updates: Pick + updates: HostedReviewClearUpdates } function keyOf(row: Pick): HostScopedWorktreeKey { return composeWorktreeHostIdentity(row.hostId, row.id) } -function linksSignature(row: IdentityRow): string { - return JSON.stringify([...HOSTED_REVIEW_LINK_KEYS.map((key) => row[key] ?? null), row.pushTarget]) -} - -function hasBranchScopedLinks(row: IdentityRow): boolean { - return HOSTED_REVIEW_LINK_KEYS.some((key) => row[key] != null) || row.pushTarget !== undefined -} - -/** On confirmed branch switches, clear old-branch links and update automatic names; detached heads retain the last name. Replaces worktree-git-identity-update.ts. */ +/** On proven branch switches, clear old-branch links and update automatic names; detached heads retain the last name and review ownership. Replaces worktree-git-identity-update.ts. */ export class WorkspaceGitIdentity { private readonly observed = new Map() private readonly detachedTitles = new Map() @@ -91,36 +85,37 @@ export class WorkspaceGitIdentity { } else if (before.branch !== '' && row.displayNameMode === 'automatic') { this.detachedTitles.set(key, before.displayName) } - const switched = - sameInstance && - canonicalHostedReviewBranchIdentity(before.branch) !== - canonicalHostedReviewBranchIdentity(row.branch) - // A link written since git last confirmed the old branch may belong to the new one: kept. - const cleared = switched && hasBranchScopedLinks(row) && linksSignature(row) === before.links - if (cleared && row.hostId !== undefined) { - clears.push({ - target: hostWorktreeTarget({ id: row.id, hostId: row.hostId }), - updates: CLEARED_HOSTED_REVIEW_LINK_UPDATES - }) + const previousOwner = sameInstance ? before.owner : undefined + const updates = hostedReviewClearUpdates(previousOwner, row.branch, row) + if (updates && row.hostId !== undefined) { + clears.push({ target: hostWorktreeTarget({ id: row.id, hostId: row.hostId }), updates }) } if (row.instanceId === undefined) { this.observed.delete(key) continue } - // A cached scan repeats an old branch; only a new git run (or a switch) confirms links on it. - const confirmed = - !sameInstance || switched || (row.gitRun !== null && row.gitRun !== before.gitRun) + const afterClear = updates ? { ...row, ...updates } : row + let owner: HostedReviewOwner | undefined + if (row.branch === '') { + owner = previousOwner + } else { + const branchOwner = branchHostedReviewOwner(row.branch, afterClear) + // A cached scan repeats an old branch; only a new git run (or a change) confirms links on it. + const repeatsCachedScan = + sameInstance && + updates === null && + previousOwner !== undefined && + previousOwner.branch === branchOwner.branch && + (row.gitRun === null || row.gitRun === before.gitRun) + owner = repeatsCachedScan ? previousOwner : branchOwner + } this.observed.set(key, { instanceId: row.instanceId, repoKey: getRepoHostIdentityForParts(row.repoId, row.hostId ?? ''), branch: row.branch, displayName: this.title(row), gitRun: row.gitRun, - links: cleared - ? linksSignature({ ...row, ...CLEARED_HOSTED_REVIEW_LINK_UPDATES }) - : confirmed - ? linksSignature(row) - : (before?.links ?? linksSignature(row)) + owner }) } for (const [key, observed] of this.observed) { diff --git a/src/main/runtime/speech/runtime-mobile-speech-catalog.ts b/src/main/runtime/speech/runtime-mobile-speech-catalog.ts index 6619e4f7e0b..e5a7580d6b5 100644 --- a/src/main/runtime/speech/runtime-mobile-speech-catalog.ts +++ b/src/main/runtime/speech/runtime-mobile-speech-catalog.ts @@ -1,4 +1,5 @@ import type { VoiceSettings } from '../../../shared/speech-types' +import { stopAfterSilenceSeconds } from '../../../shared/dictation-silence-stop' import type { RuntimeSpeechModelSummary, RuntimeSpeechSetupState @@ -69,6 +70,7 @@ export class RuntimeMobileSpeechCatalog { dictationMode: voice.dictationMode === 'hold' ? 'hold' : 'toggle', dictationHoldToRecord: voice.dictationHoldToRecord !== false, removeFillerWords: voice.removeFillerWords !== false, + stopAfterSilenceSeconds: stopAfterSilenceSeconds(voice), // The phone has no Whisper prompt to bias, and its text pass would only join the name; keeping the // hint out also spares a phone page from before hints, which would treat the name as a full term. dictationTerms: hostDictationTerms(store, worktreeId).filter((entry) => !entry.hint), diff --git a/src/main/ssh/connection/testing/ssh-connection-test-harness.ts b/src/main/ssh/connection/testing/ssh-connection-test-harness.ts index 71d39576faa..97897ebb59b 100644 --- a/src/main/ssh/connection/testing/ssh-connection-test-harness.ts +++ b/src/main/ssh/connection/testing/ssh-connection-test-harness.ts @@ -11,6 +11,7 @@ import type * as SystemSshFileBinaryTransfer from '../../system-transport/file-t import type * as SystemSshFileTransfer from '../../system-transport/file-transfer/system-ssh-file-transfer' import type * as SshGConfigResolution from '../../config/ssh-g-config-resolution' import { resetSsh2ClientState, ssh2Mock } from './ssh-connection-test-client' +import { resetSshUserDisconnectsForTests } from '../ssh-user-disconnect' export type SystemSshBinaryModuleMock = { findSystemSsh: typeof findSystemSshMock } @@ -105,6 +106,7 @@ export function withSshGConfigResolutionMocks(actual: typeof SshGConfigResolutio } export function resetSshConnectionMocks(): void { + resetSshUserDisconnectsForTests() resetSsh2ClientState() getOrcaControlSocketPathMock.mockReset() getOrcaControlSocketPathMock.mockReturnValue(null) diff --git a/src/renderer/src/App.tsx b/src/renderer/src/App.tsx index b3eaaea1d6e..403dfb08d56 100644 --- a/src/renderer/src/App.tsx +++ b/src/renderer/src/App.tsx @@ -7,7 +7,7 @@ import { BrowserWebAuthnAccountDialog } from './components/browser-webauthn-acco import { BrowserExtensionInstallDialog } from './components/browser-extension-install-dialog' import { BrowserPagePrompts } from './components/browser-pane/browser-page-prompts' import { LinkRoutingPreferenceDialogProvider } from './components/link-routing-preference-dialog' -import { SkillFreshnessNudge } from './components/skills/SkillFreshnessNudge' +import { SkillFreshnessNudge } from './components/skills/freshness/SkillFreshnessNudge' import PinnedTabCloseDialog from './components/terminal-pane/layout/close/PinnedTabCloseDialog' import RunningTerminalCloseDialog from './components/terminal-pane/layout/close/RunningTerminalCloseDialog' import WorktreeBaseFallbackDialog from './components/WorktreeBaseFallbackDialog' diff --git a/src/renderer/src/app-shell/AppRootSurfaces.tsx b/src/renderer/src/app-shell/AppRootSurfaces.tsx index e97fe473f52..916fb186043 100644 --- a/src/renderer/src/app-shell/AppRootSurfaces.tsx +++ b/src/renderer/src/app-shell/AppRootSurfaces.tsx @@ -11,9 +11,9 @@ import NewWorkspaceComposerModal from '../components/NewWorkspaceComposerModal' import { CrashReportDialog } from '../components/crash-report/CrashReportDialog' import { MarkdownTemplatePicker } from '../components/editor/markdown/documents/MarkdownTemplatePicker' import RecentTabSwitcher from '../components/tab-bar/RecentTabSwitcher' -import { SkillFreshnessUpdateDialog } from '../components/skills/SkillFreshnessUpdateDialog' +import { SkillFreshnessUpdateDialog } from '../components/skills/freshness/SkillFreshnessUpdateDialog' import { StarNagAgentValueMomentObserver } from '../components/star-nag/StarNagAgentValueMomentObserver' -import { NativeChatResumeOnRestartModal } from '../components/NativeChatResumeRuntimeModal' +import { NativeChatResumeOnRestartModal } from '../components/native-chat-recovery/NativeChatResumeRuntimeModal' import { StarNagToastHost } from '../components/star-nag/StarNagToastHost' import { TelemetryFirstLaunchSurface } from '../components/TelemetryFirstLaunchSurface' import { ZoomOverlay } from '../components/ZoomOverlay' diff --git a/src/renderer/src/app-shell/AppWorkspaceShell.tsx b/src/renderer/src/app-shell/AppWorkspaceShell.tsx index 4b890eccee7..ac4293de10e 100644 --- a/src/renderer/src/app-shell/AppWorkspaceShell.tsx +++ b/src/renderer/src/app-shell/AppWorkspaceShell.tsx @@ -4,6 +4,7 @@ import { useTranslate } from '@/i18n/use-translate' import { useAppStore } from '@/store' import { usePluginViewCaptureStore } from '@/store/plugins/capture/plugin-view-capture' import { pendingCreationOpensNativeChat } from '@/lib/workspace/creation/pending-worktree-creation' +import { showsFloatingRightSidebarToggle } from '@/lib/right-sidebar-visibility' import Sidebar from '../components/Sidebar' import RightSidebar from '../components/right-sidebar' import { RecoverableRenderErrorBoundary } from '../components/error-boundaries/RecoverableRenderErrorBoundary' @@ -194,7 +195,7 @@ export function AppWorkspaceShell(props: { ) : null}
{/* Match the open sidebar header’s alignment to prevent toggle jitter. */} - {layout.workspaceChromeActive && !layout.rightSidebarOpen && ( + {showsFloatingRightSidebarToggle(layout) && (
- {layout.showRightSidebarControls ? : null} +
)}
diff --git a/src/renderer/src/app-shell/app-command-handlers.ts b/src/renderer/src/app-shell/app-command-handlers.ts index 1ff366fd1a5..064e4bc6865 100644 --- a/src/renderer/src/app-shell/app-command-handlers.ts +++ b/src/renderer/src/app-shell/app-command-handlers.ts @@ -1,4 +1,4 @@ -import { canShowRightSidebarForView } from '@/lib/right-sidebar-visibility' +import { canShowRightSidebarForView, canToggleRightSidebar } from '@/lib/right-sidebar-visibility' import { runBuiltInOrReplacement } from '@/lib/plugin-command-replacements' import { isFloatingWorkspacePanelFocused } from '@/lib/floating-workspace-terminal-actions' import { hasVisibleOverlay } from '@/lib/visible-overlay' @@ -270,7 +270,7 @@ export function createAppCommandHandlers( [ 'sidebar.right.toggle', () => - canRevealRightSidebar + canToggleRightSidebar(activeView) ? claim('sidebar.right.toggle', () => actions.toggleRightSidebar()) : false ], diff --git a/src/renderer/src/components/ClaudeAccountSwitchSessionTree.tsx b/src/renderer/src/components/ClaudeAccountSwitchSessionTree.tsx index 8b712f06a6a..25ad85b58f6 100644 --- a/src/renderer/src/components/ClaudeAccountSwitchSessionTree.tsx +++ b/src/renderer/src/components/ClaudeAccountSwitchSessionTree.tsx @@ -16,12 +16,12 @@ import { } from '@/lib/worktree-default-display-name' import { makePaneKey } from '../../../shared/workspace-layout/stable-pane-id' import { useAppStore } from '../store' -import { ResumeTreeRow } from './NativeChatResumeTreeRow' +import { ResumeTreeRow } from './native-chat-recovery/tree/NativeChatResumeTreeRow' import { resumeSelectionState, toggleResumeSelection -} from './native-chat-resume-on-restart-grouping' -import { moveInTree } from './native-chat-resume-tree-keys' +} from './native-chat-recovery/tree/native-chat-resume-on-restart-grouping' +import { moveInTree } from './native-chat-recovery/tree/native-chat-resume-tree-keys' type SessionRowData = ClaudeSessionMoveCandidate & { reason?: string } diff --git a/src/renderer/src/components/NativeChatRemoteResume.test.tsx b/src/renderer/src/components/NativeChatRemoteResume.test.tsx deleted file mode 100644 index c189ce7e8a7..00000000000 --- a/src/renderer/src/components/NativeChatRemoteResume.test.tsx +++ /dev/null @@ -1,121 +0,0 @@ -// @vitest-environment happy-dom -import { act } from 'react' - -import { afterEach, expect, it, vi } from 'vitest' -import { - createResumeModalFixture, - offered, - type RestartRpc, - type ResumeStatusStream -} from './native-chat-resume-modal.test-support' - -import { - createNativeChatRestartStore, - type NativeChatRestartStore -} from './native-chat-resume-on-restart-store' -import type { RuntimeEnvironmentStatus } from '../../../shared/remote-runtime/host-status/runtime-host-status' - -const rpc = vi.hoisted(() => vi.fn()) -const stream: ResumeStatusStream = vi.hoisted(() => ({ emit: () => {}, snapshot: new Map() })) -vi.mock('../runtime/native-chat/requests/structured-agent-session-call', () => ({ - callStructuredAgentSession: rpc -})) - -vi.mock('../runtime/native-chat/requests/structured-agent-session-subscriptions', () => ({ - subscribeStructuredAgentSessionStatus: async ( - _target: unknown, - emit: ResumeStatusStream['emit'] - ) => { - stream.emit = emit - emit({ type: 'snapshot', sessions: [] }) - return { - unsubscribe: () => {} - } - } -})) -vi.mock('sonner', async () => - (await import('./native-chat-resume-sonner-mock.test-support')).resumeSonnerMock() -) -createResumeModalFixture(rpc, stream) -const stores: NativeChatRestartStore[] = [] -afterEach(() => { - for (const store of stores.splice(0)) { - store._resetNativeChatRestartOffer() - store.consumeNativeChatResumeOnRestartDialogRequest() - } - vi.useRealTimers() - vi.unstubAllGlobals() - vi.restoreAllMocks() -}) -function store() { - const value = createNativeChatRestartStore({ kind: 'environment', environmentId: 'ssh' }) - stores.push(value) - vi.stubGlobal('api', { runtimeEnvironments: { desktopCreatedChatIds: async () => ['a'] } }) - return value -} -function ready(runtimeId: string): RuntimeEnvironmentStatus { - return { - checkedAt: 0, - status: { - runtimeId, - rendererGraphEpoch: 0, - graphStatus: 'ready', - authoritativeWindowId: null, - liveTabCount: 0, - liveLeafCount: 0 - } - } -} - -it('snoozes server failures locally through reconnect and reopens for a new runtime', async () => { - const remote = store() - rpc.mockResolvedValue({ sessions: offered }) - await act(async () => remote.observeRuntimeStatus(ready('first'))) - await remote.dismissNativeChatRestartOffer(['a']) - expect(rpc).toHaveBeenCalledTimes(1) - expect(remote.getNativeChatRestartOffer().candidates).toHaveLength(2) - remote.observeRuntimeStatus(undefined) - await act(async () => remote.observeRuntimeStatus(ready('first'))) - expect(remote.getNativeChatResumeOnRestartDialogRequest()).toBe(false) - await act(async () => remote.observeRuntimeStatus(ready('second'))) - expect(remote.getNativeChatResumeOnRestartDialogRequest()).toBe(true) -}) - -it.each(['failure', 'success', 'history'])( - 'supersedes an older ordinary read through all awaits (%s)', - async (mode) => { - const remote = store() - rpc.mockResolvedValue({ sessions: offered }) - await act(async () => remote.observeRuntimeStatus(ready('r1'))) - const old = Promise.withResolvers() - const history = Promise.withResolvers() - if (mode === 'history') { - vi.stubGlobal('api', { - runtimeEnvironments: { desktopCreatedChatIds: () => history.promise } - }) - rpc.mockResolvedValueOnce({ sessions: [] }) - await act(async () => remote.refreshNativeChatRestartOffer()) - rpc.mockResolvedValue({ sessions: offered }) - } else { - rpc.mockReturnValueOnce(old.promise) - } - let read: Promise - await act(async () => { - read = remote.refreshNativeChatRestartOffer() - }) - rpc.mockResolvedValue({ sessions: mode === 'failure' ? offered : [] }) - remote.observeRuntimeStatus(undefined) - await act(async () => remote.observeRuntimeStatus(ready('r1'))) - await act(async () => { - if (mode === 'failure') { - old.reject(new Error('obsolete failure')) - } else { - old.resolve({ sessions: offered }) - } - history.resolve(['a']) - await read! - }) - expect(remote.getNativeChatRestartOffer().candidates).toHaveLength(mode === 'failure' ? 2 : 0) - expect(remote.getNativeChatResumeOnRestartDialogRequest()).toBe(mode === 'failure') - } -) diff --git a/src/renderer/src/components/NativeChatResumeOnRestartGroups.selection.test.tsx b/src/renderer/src/components/NativeChatResumeOnRestartGroups.selection.test.tsx deleted file mode 100644 index f6c3909762a..00000000000 --- a/src/renderer/src/components/NativeChatResumeOnRestartGroups.selection.test.tsx +++ /dev/null @@ -1,134 +0,0 @@ -// @vitest-environment happy-dom - -import { act } from 'react' -import { createRoot, type Root } from 'react-dom/client' -import { afterEach, beforeEach, expect, it } from 'vitest' -import { useAppStore } from '../store' -import { getHostContextLabel } from '../../../shared/worktree/host-context-labels' -import type { ExecutionHostId } from '../../../shared/execution-host' -import { - candidate, - chatBox, - countOf, - disclosureOf, - nodeBox, - onToggleSpy, - seedTree, - treeOutline, - unretryable, - worktree -} from './native-chat-resume-tree.test-support' -import { ResumeTreeHarness as Harness } from './NativeChatResumeTreeHarness.test-support' - -globalThis.IS_REACT_ACT_ENVIRONMENT = true -let root: Root -let container: HTMLElement - -function render(props: React.ComponentProps): void { - act(() => root.render()) -} - -function state(box: HTMLElement): string | null { - return box.getAttribute('aria-checked') -} - -beforeEach(() => { - onToggleSpy.mockReset() - useAppStore.setState(useAppStore.getInitialState(), true) - container = document.createElement('div') - document.body.append(container) - root = createRoot(container) -}) - -afterEach(() => { - act(() => root.unmount()) - container.remove() - useAppStore.setState(useAppStore.getInitialState(), true) -}) - -it('is tri-state at every level, each node over every chat under it', () => { - const remote: ExecutionHostId = 'ssh:build-server' - render({ candidates: seedTree({ parent: remote, child: remote }) }) - const machine = getHostContextLabel(remote) - expect([machine, 'orca', 'parent', 'child', 'other'].map((name) => countOf(name))).toEqual([ - '4 of 4', - '4 of 4', - '3 of 3', - '2 of 2', - '1 of 1' - ]) - - act(() => chatBox('in-child').click()) - expect([machine, 'orca', 'parent', 'child', 'other'].map((name) => state(nodeBox(name)))).toEqual( - ['mixed', 'mixed', 'mixed', 'mixed', 'true'] - ) - expect(countOf(machine)).toBe('3 of 4') - expect(countOf('child')).toBe('1 of 2') - - // Partly selected: ticking selects everything under the node, nested workspaces included. - act(() => nodeBox('parent').click()) - expect(state(chatBox('in-child'))).toBe('true') - expect(state(nodeBox(machine))).toBe('true') - - act(() => nodeBox(machine).click()) - for (const id of ['in-parent', 'in-child', 'also-in-child', 'in-other']) { - expect(state(chatBox(id))).toBe('false') - } - expect(countOf('orca')).toBe('0 of 4') -}) - -it('selects every eligible chat in a project, never an unretryable one or another project’s', () => { - const candidates = seedTree() - const mobile = worktree('mobile', { repoId: 'repo-2', id: 'repo-2::/mobile/mobile' }) - useAppStore.setState((current) => ({ - repos: [ - ...current.repos, - { id: 'repo-2', path: '/mobile', displayName: 'orca-mobile', badgeColor: '#999', addedAt: 1 } - ], - worktreesByRepo: { ...current.worktreesByRepo, 'repo-2': [mobile] } - })) - const stuck = unretryable(candidates[3]!) - render({ - candidates: [...candidates, candidate('in-mobile', mobile)], - initiallySelected: ['in-mobile'], - failureFor: (sessionId) => (sessionId === 'in-other' ? stuck : undefined) - }) - expect(countOf('orca')).toBe('0 of 3') - expect(chatBox('in-other').hasAttribute('disabled')).toBe(true) - - act(() => nodeBox('orca').click()) - expect(countOf('orca')).toBe('3 of 3') - expect(state(nodeBox('orca'))).toBe('true') - const touched = onToggleSpy.mock.calls.map(([sessionId]) => sessionId) - expect(touched).not.toContain('in-other') - expect(touched).not.toContain('in-mobile') - expect(countOf('orca-mobile')).toBe('1 of 1') -}) - -it('starts expanded; collapsing hides a node’s rows and keeps their selection', () => { - render({ candidates: seedTree() }) - const parent = disclosureOf('parent') - expect(parent.getAttribute('aria-expanded')).toBe('true') - expect(parent.getAttribute('aria-label')).toBe('Collapse parent') - expect(parent.tabIndex).toBe(-1) - act(() => chatBox('in-child').click()) - - act(() => parent.click()) - expect(treeOutline()).toEqual([ - '1:project:orca', - '2:workspace:parent', - '2:workspace:other', - '3:chat:in-other' - ]) - expect(disclosureOf('parent').getAttribute('aria-label')).toBe('Expand parent') - expect(nodeBox('parent').closest('[role="treeitem"]')?.getAttribute('aria-expanded')).toBe( - 'false' - ) - // Hidden, not forgotten: the node still counts the pick made inside it. - expect(state(nodeBox('parent'))).toBe('mixed') - expect(countOf('parent')).toBe('2 of 3') - - act(() => disclosureOf('parent').click()) - expect(state(chatBox('in-child'))).toBe('false') - expect(state(chatBox('also-in-child'))).toBe('true') -}) diff --git a/src/renderer/src/components/NativeChatResumeOnRestartGroups.test.tsx b/src/renderer/src/components/NativeChatResumeOnRestartGroups.test.tsx deleted file mode 100644 index 1b45bfcd55d..00000000000 --- a/src/renderer/src/components/NativeChatResumeOnRestartGroups.test.tsx +++ /dev/null @@ -1,73 +0,0 @@ -// @vitest-environment happy-dom - -import { act } from 'react' -import { createRoot, type Root } from 'react-dom/client' -import { afterEach, beforeEach, expect, it, vi } from 'vitest' -import { useAppStore } from '../store' -import { getDefaultSettings } from '../../../shared/constants' -import type { ExecutionHostId } from '../../../shared/execution-host' -import { - candidate, - chatBox, - lineage, - onToggleSpy, - seedTree, - worktree -} from './native-chat-resume-tree.test-support' -import { ResumeTreeHarness as Harness } from './NativeChatResumeTreeHarness.test-support' - -globalThis.IS_REACT_ACT_ENVIRONMENT = true -let root: Root -let container: HTMLElement - -function render(props: React.ComponentProps): void { - act(() => root.render()) -} - -beforeEach(() => { - onToggleSpy.mockReset() - useAppStore.setState(useAppStore.getInitialState(), true) - container = document.createElement('div') - document.body.append(container) - root = createRoot(container) -}) - -afterEach(() => { - act(() => root.unmount()) - vi.restoreAllMocks() - container.remove() - useAppStore.setState(useAppStore.getInitialState(), true) -}) - -it('lists every offered chat exactly once, even with one workspace id on two hosts', () => { - const remote: ExecutionHostId = 'ssh:build-server' - const candidates = seedTree() - const remoteParent = worktree('parent', { hostId: remote, instanceId: 'instance-remote' }) - useAppStore.setState((state) => ({ - worktreesByRepo: { 'repo-1': [...state.worktreesByRepo['repo-1']!, remoteParent] } - })) - const twin = candidate('on-remote', remoteParent) - render({ candidates: [...candidates, twin] }) - - for (const entry of [...candidates, twin]) { - expect( - container.querySelectorAll(`[role="checkbox"][aria-label*="Prompt ${entry.sessionId}"]`) - ).toHaveLength(1) - } - // Same id, different machine: two separate workspace nodes. - expect(container.querySelectorAll('[aria-label="Select all chats in parent"]')).toHaveLength(2) -}) - -it('lists every chat when workspace lineage loops', () => { - const a = worktree('a') - const b = worktree('b') - useAppStore.setState({ - settings: getDefaultSettings(''), - worktreesByRepo: { 'repo-1': [a, b] }, - worktreeLineageById: { [a.id]: lineage(a, b), [b.id]: lineage(b, a) } - }) - render({ candidates: [candidate('in-a', a), candidate('in-b', b)] }) - - expect(chatBox('in-a')).toBeTruthy() - expect(chatBox('in-b')).toBeTruthy() -}) diff --git a/src/renderer/src/components/NativeChatResumeTreeHarness.test-support.tsx b/src/renderer/src/components/NativeChatResumeTreeHarness.test-support.tsx deleted file mode 100644 index 02f482ba820..00000000000 --- a/src/renderer/src/components/NativeChatResumeTreeHarness.test-support.tsx +++ /dev/null @@ -1,47 +0,0 @@ -// Mount the resume tree with dialog-owned selection for group-toggle tests. - -import { useState } from 'react' -import { ResumeOnRestartGroups } from './NativeChatResumeOnRestartGroups' -import { TooltipProvider } from './ui/tooltip' -import type { ResumeCandidate, ResumeFailure } from './native-chat-resume-on-restart-grouping' -import { onToggleSpy } from './native-chat-resume-tree.test-support' - -/** Owns the selection the way the dialog does, so group toggles show their effect. */ -export function ResumeTreeHarness({ - candidates, - initiallySelected, - busy = false, - failureFor -}: { - candidates: ResumeCandidate[] - initiallySelected?: string[] - busy?: boolean - failureFor?: (sessionId: string) => ResumeFailure | undefined -}): React.JSX.Element { - const [selected, setSelected] = useState>( - () => new Set(initiallySelected ?? candidates.map((entry) => entry.sessionId)) - ) - return ( - - { - onToggleSpy(sessionId, checked) - setSelected((current) => { - const next = new Set(current) - if (checked) { - next.add(sessionId) - } else { - next.delete(sessionId) - } - return next - }) - }} - failureFor={failureFor} - /> - - ) -} diff --git a/src/renderer/src/components/activity/activity-event-builder.ts b/src/renderer/src/components/activity/activity-event-builder.ts index 57b65b1fc25..f92f3354a83 100644 --- a/src/renderer/src/components/activity/activity-event-builder.ts +++ b/src/renderer/src/components/activity/activity-event-builder.ts @@ -15,9 +15,8 @@ import type { TerminalTab } from '../../../../shared/workspace-layout/terminal-t import type { Worktree } from '../../../../shared/worktree/types' import type { ActivityEvent, ActivityLiveAgentSnapshot } from './activity-thread-types' import { capActivityEvents } from './activity-event-cap' -import { newestActivityHistoryEntries } from './activity-pane-events' +import './activity-pane-events' import { - createActivityEventBuildCache, resolveActivityTabIndexes, resolvePaneBuild, type ActivityEventBuildCache @@ -30,8 +29,6 @@ import { } from './activity-event-builder-context' import type { Translate } from '@/i18n/use-translate' -export { createActivityEventBuildCache, type ActivityEventBuildCache, newestActivityHistoryEntries } - export type BuildActivityEventsArgs = { chatNames: StructuredChatTabNames agentStatusByPaneKey: Record diff --git a/src/renderer/src/components/activity/use-agent-pane-threads.ts b/src/renderer/src/components/activity/use-agent-pane-threads.ts index 5f0f444d29d..48daeb648e6 100644 --- a/src/renderer/src/components/activity/use-agent-pane-threads.ts +++ b/src/renderer/src/components/activity/use-agent-pane-threads.ts @@ -1,7 +1,8 @@ import { useDeferredValue, useMemo, useRef } from 'react' import { useAppStore } from '@/store' import { useStructuredChatTabNames } from '@/runtime/native-chat/naming/structured-chat-name-observation' -import { buildActivityEvents, createActivityEventBuildCache } from './activity-event-builder' +import { buildActivityEvents } from './activity-event-builder' +import { createActivityEventBuildCache } from '@/components/activity/activity-event-build-cache' import { freshActivityLiveAgentState } from './activity-event-state' import { useAgentPaneThreadsDefaultHostId, diff --git a/src/renderer/src/components/agent/AgentLaunchPickerMenu.select.test.tsx b/src/renderer/src/components/agent/AgentLaunchPickerMenu.select.test.tsx index 42aac33f20c..e9077348be8 100644 --- a/src/renderer/src/components/agent/AgentLaunchPickerMenu.select.test.tsx +++ b/src/renderer/src/components/agent/AgentLaunchPickerMenu.select.test.tsx @@ -67,10 +67,7 @@ function Form({ query, onPick }: { query: string; onPick: (draft?: AgentPickerDr ) } -it.each([ - ['an agent row', ''], - ['a search-result row', 'astra low'] -])( +it.each([['a search-result row', 'astra low']])( 'applies each model and effort picked in %s setup to the form and keeps the panel on them', (_row, query) => { const onPick = vi.fn() diff --git a/src/renderer/src/components/artifacts/ArtifactPublishedLinkPanel.tsx b/src/renderer/src/components/artifacts/ArtifactPublishedLinkPanel.tsx index 41b9bd77269..ff9d79009a2 100644 --- a/src/renderer/src/components/artifacts/ArtifactPublishedLinkPanel.tsx +++ b/src/renderer/src/components/artifacts/ArtifactPublishedLinkPanel.tsx @@ -3,6 +3,7 @@ import { Check, Copy, ExternalLink, Loader2, RefreshCw } from 'lucide-react' import { Button } from '@/components/ui/button' import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip' import { useTranslate } from '@/i18n/use-translate' +import { cn } from '@/lib/utils' import { copyArtifactLink, openArtifactInBrowser } from './artifact-link-actions' export function ArtifactPublishedLinkPanel({ @@ -109,17 +110,36 @@ export function ArtifactPublishedLinkPanel({ type="button" variant="outline" size="sm" - className="w-full" + className="h-auto min-h-8 w-full whitespace-normal" disabled={publishing} onClick={onUpdate} > - {publishing ? : } - {publishing - ? t('auto.components.artifacts.ArtifactPublishedLinkPanel.updating', 'Updating…') - : t( + {/* Both labels share one grid cell, so a wrapped label cannot resize the popover mid-update. */} + + + + {t( 'auto.components.artifacts.ArtifactPublishedLinkPanel.update', 'Update shared content' )} + + + + {t('auto.components.artifacts.ArtifactPublishedLinkPanel.updating', 'Updating…')} + + ) : null}
diff --git a/src/renderer/src/components/automations/AutomationEditorSettingsSidebar.test.tsx b/src/renderer/src/components/automations/AutomationEditorSettingsSidebar.test.tsx deleted file mode 100644 index fedae0d26ae..00000000000 --- a/src/renderer/src/components/automations/AutomationEditorSettingsSidebar.test.tsx +++ /dev/null @@ -1,186 +0,0 @@ -// @vitest-environment happy-dom - -import { cleanup, fireEvent, render, screen } from '@testing-library/react' -import { useState } from 'react' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { AGENT_CATALOG } from '@/lib/agent-catalog/agent-catalog' -import { TooltipProvider } from '@/components/ui/tooltip' -import { useAppStore } from '@/store' -import { setLocalRuntimeCapabilitiesForTests } from '@/runtime/hosts/capabilities/local-runtime-capabilities' -import { AUTOMATION_RUNTIME_CAPABILITIES } from '../../../../shared/automations/automation-runtime-capabilities' - -import { clearNativeChatComposerDraftsForTests } from '../native-chat/drafts/native-chat-draft-reset' -import type { AutomationAuthorityRef } from '../../../../shared/automations/ownership/automation-owner-ref' -import type { AutomationHostCatalogEntry } from './automation-host-catalog-types' -import type { AutomationCreateDestinationControl } from './use-automation-create-destination' -import type { AutomationDraft } from './AutomationEditorDialog' - -import { AutomationEditorSettingsSidebar } from './AutomationEditorSettingsSidebar' - -// Why: only the Agent field is under test; the sibling fields own their own coverage. -vi.mock('./AutomationProjectCombobox', () => ({ default: () => null })) -vi.mock('./AutomationWorkspaceField', () => ({ AutomationWorkspaceField: () => null })) -vi.mock('./AutomationSessionField', () => ({ AutomationSessionField: () => null })) -vi.mock('./AutomationSchedulePicker', () => ({ AutomationSchedulePicker: () => null })) -vi.mock('./AutomationMissedRunGraceField', () => ({ AutomationMissedRunGraceField: () => null })) -vi.mock('./AutomationPrecheckFields', () => ({ AutomationPrecheckFields: () => null })) -vi.mock('./AutomationSetupDecisionField', () => ({ AutomationSetupDecisionField: () => null })) -vi.mock('./AutomationDestinationField', () => ({ AutomationDestinationField: () => null })) -vi.mock('@/hooks/useShortcutLabel', () => ({ useOptionalShortcutLabel: () => null })) -vi.mock('../tab-bar/use-new-tab-agent-menu-rows', () => ({ - useAgentMenuObservation: () => ({ - model: { state: 'loading' }, - contextKey: 'automation-test', - detection: { - detectedIds: [], - isLoading: false, - isRefreshing: false, - detectionFailed: false, - needsServerUpdate: false, - refresh: async () => [] - } - }) -})) -vi.mock('../agent/use-agent-launch-picker-inventory', () => ({ - useAgentLaunchPickerInventory: (_id: unknown, model: { rows: { agent: string }[] }) => - model.rows.map((row) => ({ - agent: row.agent, - label: row.agent, - rows: [row], - ownerKey: `automation-${row.agent}`, - surfaces: ['terminal'], - defaultSurface: 'terminal', - terminal: { model: 'gpt-5.4', permissionMode: 'ask' }, - structured: {}, - arguments: '--base', - catalog: { - origin: 'probe', - fetchedAt: 1, - models: [ - { id: 'gpt-5.4', label: 'Model A', isDefault: true, efforts: [] }, - { id: 'gpt-5.5', label: 'Model B', isDefault: false, efforts: [] } - ] - } - })) -})) - -const DRAFT: AutomationDraft = { - name: '', - prompt: '', - agentId: 'codex', - extraAgentArgs: '', - projectId: '', - workspaceMode: 'existing', - workspaceId: '', - baseBranch: '', - reuseSession: false, - precheckCommand: '', - precheckTimeoutSeconds: '30', - preset: 'weekly', - time: '09:15', - dayOfWeek: '5', - customSchedule: '', - missedRunGraceMinutes: '720', - savedSchedule: null, - scheduleWarning: null -} - -function destinationControl( - authority: AutomationAuthorityRef | null -): AutomationCreateDestinationControl { - if (!authority) { - return { - entries: [], - projects: [], - onSelect: vi.fn(), - resolution: { status: 'choice-required', reason: 'unselected' } - } - } - const entry: AutomationHostCatalogEntry = { - stableRef: { authority, selector: { kind: 'self' } }, - owner: { authority, selector: { kind: 'self' } }, - stableKey: 'test-host', - label: 'Test host', - authorityLabel: 'Test host', - kind: 'self', - catalogState: 'authoritative', - authorityHealth: 'fresh', - executionHealth: 'connected', - querySupport: 'scoped' - } - return { - entries: [entry], - projects: [], - onSelect: vi.fn(), - resolution: { status: 'ready', authority, destination: { selector: { kind: 'self' } }, entry } - } -} - -function renderSidebar( - onDraftChange: (updater: (d: AutomationDraft) => AutomationDraft) => void, - initial = DRAFT, - authority: AutomationAuthorityRef | null = { kind: 'desktop' }, - destination = destinationControl(authority) -) { - function Form() { - const [draft, setDraft] = useState(initial) - return ( - - repoId} - repoMap={new Map()} - worktrees={[]} - settings={null} - draft={draft} - visibleAgents={AGENT_CATALOG} - pickerTriggerClassName="" - onProjectChange={vi.fn()} - onDraftChange={(updater) => { - onDraftChange(updater) - setDraft(updater) - }} - onSetupDecisionTouched={vi.fn()} - /> - - ) - } - return render(
) -} - -beforeEach(() => { - clearNativeChatComposerDraftsForTests() - setLocalRuntimeCapabilitiesForTests(AUTOMATION_RUNTIME_CAPABILITIES) -}) -afterEach(() => { - cleanup() - vi.restoreAllMocks() - setLocalRuntimeCapabilitiesForTests(null) - useAppStore.setState({ runtimeStatusByEnvironmentId: new Map() }) -}) - -function openPicker() { - fireEvent.pointerDown(screen.getByRole('button', { name: 'Select agent' }), { button: 0 }) -} - -describe('AutomationEditorSettingsSidebar agent picker', () => { - it('discards an unaccepted setup when the editor owner closes', () => { - const onDraftChange = vi.fn() - const form = renderSidebar(onDraftChange) - openPicker() - fireEvent.click(screen.getByRole('button', { name: 'Configure Codex' })) - fireEvent.change(document.querySelector('textarea')!, { target: { value: '--unaccepted' } }) - form.unmount() - renderSidebar(onDraftChange) - openPicker() - fireEvent.click(screen.getByRole('button', { name: 'Configure Codex' })) - expect(document.querySelector('textarea')).toHaveProperty('value', '--base') - expect(onDraftChange).not.toHaveBeenCalled() - }) -}) diff --git a/src/renderer/src/components/automations/AutomationTimeField.test.tsx b/src/renderer/src/components/automations/AutomationTimeField.test.tsx deleted file mode 100644 index 3a230ca8a87..00000000000 --- a/src/renderer/src/components/automations/AutomationTimeField.test.tsx +++ /dev/null @@ -1,80 +0,0 @@ -// @vitest-environment happy-dom - -import '@testing-library/jest-dom/vitest' -import React from 'react' -import { cleanup, render, screen } from '@testing-library/react' -import userEvent from '@testing-library/user-event' -import { afterEach, describe, expect, it, vi } from 'vitest' -import { AutomationTimeField } from './AutomationTimeField' - -afterEach(() => { - cleanup() -}) - -function ControlledTimeField({ - initialTime = '09:15', - mode = 'time', - onTimeChange -}: { - initialTime?: string - mode?: 'time' | 'minute' - onTimeChange?: (time: string) => void -}): React.JSX.Element { - const [time, setTime] = React.useState(initialTime) - return ( - { - setTime(next) - onTimeChange?.(next) - }} - /> - ) -} - -describe('AutomationTimeField interactions', () => { - it('commits typed hour/minute and toggles AM/PM into 24h storage', async () => { - const user = userEvent.setup() - const onTimeChange = vi.fn() - render() - - const hour = screen.getByLabelText('Hour') - await user.clear(hour) - await user.type(hour, '11') - expect(onTimeChange).toHaveBeenLastCalledWith('11:15') - - onTimeChange.mockClear() - const minute = screen.getByLabelText('Minute') - await user.clear(minute) - await user.type(minute, '05') - expect(onTimeChange).toHaveBeenLastCalledWith('11:05') - - onTimeChange.mockClear() - await user.click(screen.getByRole('button', { name: /^AM or PM:/ })) - expect(onTimeChange).toHaveBeenLastCalledWith('23:05') - expect(screen.getByRole('button', { name: /^AM or PM:/ })).toHaveTextContent('PM') - }) - - it('treats empty blur as min and does not re-fire after 2-digit auto-commit', async () => { - const user = userEvent.setup() - const onTimeChange = vi.fn() - render() - - const minute = screen.getByLabelText('Minute') - await user.clear(minute) - await user.tab() - expect(onTimeChange).toHaveBeenLastCalledWith('09:00') - expect(minute).toHaveValue('00') - - onTimeChange.mockClear() - await user.click(minute) - await user.clear(minute) - await user.type(minute, '30') - // 2-digit entry auto-commits once; blur must not emit a second identical update. - const callsAfterType = onTimeChange.mock.calls.length - expect(onTimeChange).toHaveBeenLastCalledWith('09:30') - await user.tab() - expect(onTimeChange.mock.calls.length).toBe(callsAfterType) - }) -}) diff --git a/src/renderer/src/components/automations/AutomationsPage.cross-authority-actions.spec.tsx b/src/renderer/src/components/automations/AutomationsPage.cross-authority-actions.spec.tsx index 8b9e79938fd..5e7a062f7d0 100644 --- a/src/renderer/src/components/automations/AutomationsPage.cross-authority-actions.spec.tsx +++ b/src/renderer/src/components/automations/AutomationsPage.cross-authority-actions.spec.tsx @@ -43,21 +43,6 @@ function runtimeAutomationCalls(): string[] { describe('AutomationsPage row actions under a colliding automation id', () => { installAutomationsPageHarness() - it('names the selected row’s own host, not the desktop that listed it', async () => { - await collidingHosts() - await renderPage() - await settleHostQueries() - - const remote = listedRows().find((candidate) => candidate.automation.name === 'Remote nightly') - await act(async () => { - mocks.listPanel?.selectAutomationRow(remote?.key ?? '') - }) - - // The record’s local target means local to its server; the catalog entry supplies the displayed host. - expect(mocks.detailPane?.selected?.name).toBe('Remote nightly') - expect(mocks.detailPane?.selectedHostEntry?.authorityLabel).toBe('GPU box') - }) - it('runs the selected desktop row on the desktop, not on the runtime holding the same id', async () => { await collidingHosts() const { container } = await renderPage() diff --git a/src/renderer/src/components/automations/AutomationsPage.refresh-selection.spec.tsx b/src/renderer/src/components/automations/AutomationsPage.refresh-selection.spec.tsx index 36b4a3a5aa6..2a96389539d 100644 --- a/src/renderer/src/components/automations/AutomationsPage.refresh-selection.spec.tsx +++ b/src/renderer/src/components/automations/AutomationsPage.refresh-selection.spec.tsx @@ -17,11 +17,7 @@ import { settleHostQueries } from './automations-page-test-harness' import { listedRows } from './automations-page-listed-items' -import { makeAutomation, makeRun, WORKSPACE_ID } from './automations-page-fixtures' -import { - AUTOMATIONS_CHANGED_EVENT, - emitAutomationsChangedWindowEvent -} from '@/lib/automations-changed-window-event' +import { makeAutomation, makeRun } from './automations-page-fixtures' async function openAutomationRow(container: HTMLElement, name: string): Promise { const row = [ @@ -32,267 +28,9 @@ async function openAutomationRow(container: HTMLElement, name: string): Promise< await settleHostQueries() } -describe('AutomationsPage refresh', () => { - installAutomationsPageHarness() - - it.each(['desktop', 'runtime'] as const)( - 'refreshes count and exact saved output on successive %s completion events without re-entry', - async (authority) => { - const automation = makeAutomation({ name: 'Selected nightly' }) - scopedList(authority === 'desktop' ? [automation] : []) - api.automations.list.mockResolvedValue(authority === 'desktop' ? [automation] : []) - if (authority === 'runtime') { - runtimeHost([automation], []) - mocks.state.automationHostFilter = RUNTIME_SELF_FILTER - } - const { container } = await renderPage() - await openAutomationRow(container, automation.name) - const count = container.querySelector('[data-testid="detail-run-count"]') - expect(count?.textContent).toBe('0') - const reads = (): unknown[][] => - mocks.callRuntimeRpc.mock.calls.filter(([, method]) => method === 'automation.runs') - const beforeEvents = reads().length - for (const unrelated of [ - { - environmentId: authority === 'desktop' ? 'gpu' : null, - selector: { kind: 'self' as const } - }, - { - environmentId: authority === 'runtime' ? 'gpu' : null, - selector: { kind: 'ssh' as const, targetId: 'elsewhere' } - } - ]) { - await act(async () => emitAutomationsChangedWindowEvent({ ...unrelated, reason: 'run' })) - await settleHostQueries() - expect(reads()).toHaveLength(beforeEvents) - expect(container.querySelector('[data-testid="detail-run-count"]')).toBe(count) - } - const event = { - ...(authority === 'runtime' ? { environmentId: 'gpu' } : {}), - selector: { kind: 'self' as const }, - reason: 'run' as const - } - const first = makeRun({ - id: 'first-completed', - outputSnapshot: { - format: 'plain_text', - content: 'First exact reply', - capturedAt: 1, - truncated: false - } - }) - const answer = (runs: (typeof first)[]): void => { - api.automations.listRuns.mockResolvedValue(runs) - if (authority === 'runtime') { - mocks.state.runtimeAnswers = { automations: [automation], runs } - } - } - answer([first]) - await act(async () => emitAutomationsChangedWindowEvent(event)) - await settleHostQueries() - expect(count?.textContent).toBe('1') - expect(mocks.detailPane?.selectedRuns).toEqual([first]) - expect(reads()).toHaveLength(beforeEvents + 1) - await act(async () => mocks.detailPane?.openAutomationRunPage(first)) - expect(container.textContent).toContain('First exact reply') - const revised = { - ...first, - outputSnapshot: { ...first.outputSnapshot!, content: 'Settled first exact reply' } - } - const second = makeRun({ id: 'second-completed' }) - answer([second, revised]) - await act(async () => emitAutomationsChangedWindowEvent(event)) - await settleHostQueries() - expect(container.textContent).toContain('Settled first exact reply') - expect(reads()).toHaveLength(beforeEvents + 2) - await act(async () => - container.querySelector('[aria-label="Back to runs"]')?.click() - ) - expect(container.querySelector('[data-testid="detail-run-count"]')?.textContent).toBe('2') - expect(mocks.detailPane?.selectedRuns.map((run) => run.id)).toEqual([ - 'second-completed', - 'first-completed' - ]) - for (const [target, , params, options] of reads().slice(beforeEvents)) { - expect(target).toEqual( - authority === 'runtime' - ? { kind: 'environment', environmentId: 'gpu' } - : { kind: 'local' } - ) - expect(params).toEqual({ - automationId: automation.id, - expectedOwner: SELF_PRECONDITION, - preview: true - }) - if (authority === 'runtime') { - expect(options).toMatchObject({ expectedEnvironmentPairingRevision: 4 }) - } - } - await settleHostQueries() - expect(reads()).toHaveLength(beforeEvents + 2) - } - ) -}) - describe('AutomationsPage selection', () => { installAutomationsPageHarness() - it('keeps an acquired exact run through definition removal, failed history settlement and Back', async () => { - const automation = makeAutomation({ id: 'a-1', name: 'Nightly' }) - const leafId = '11111111-1111-4111-8111-111111111111' - const run = makeRun({ - id: 'old-run', - automationId: automation.id, - workspaceId: WORKSPACE_ID, - workspaceDisplayName: 'Original workspace', - terminalSessionId: 'recorded-tab', - terminalPaneKey: `recorded-tab:${leafId}`, - terminalPtyId: 'recorded-pty', - outputSnapshot: { - format: 'plain_text', - content: 'Saved exact historical output', - capturedAt: 1, - truncated: false - } - }) - scopedList([automation]) - api.automations.list.mockResolvedValue([automation]) - api.automations.listRuns.mockResolvedValue([run]) - mocks.state.selectedAutomationId = automation.id - mocks.state.setSelectedAutomationId = (id: string | null) => { - mocks.state.selectedAutomationId = id - } - mocks.state.tabsByWorktree = {} - mocks.state.folderWorkspaces = [] - mocks.state.projectGroups = [] - mocks.state.unifiedTabsByWorktree = { - [WORKSPACE_ID]: [ - { - id: 'recorded-tab', - entityId: 'recorded-tab', - worktreeId: WORKSPACE_ID, - contentType: 'terminal', - executionHostId: 'local' - } - ] - } - mocks.state.terminalLayoutsByTabId = { - 'recorded-tab': { - root: { type: 'leaf', leafId }, - activeLeafId: leafId, - ptyIdsByLeafId: { [leafId]: 'recorded-pty' } - } - } - mocks.state.ptyIdsByTabId = { 'recorded-tab': ['recorded-pty'] } - const { container, rerender } = await renderPage() - await openAutomationRow(container, 'Nightly') - const retryHistory = mocks.detailPane?.recoverSelectedRuns - await act(async () => mocks.detailPane?.openAutomationRunPage(run)) - expect(container.textContent).toContain('Saved exact historical output') - expect( - [...container.querySelectorAll('button')].some((button) => button.textContent === 'View run') - ).toBe(true) - scopedList([]) - api.automations.list.mockResolvedValue([]) - api.automations.listRuns.mockRejectedValue(new Error('History temporarily unavailable')) - const readsBeforeFailure = api.automations.listRuns.mock.calls.length - await act(async () => - emitAutomationsChangedWindowEvent({ selector: { kind: 'self' }, reason: 'run' }) - ) - await settleHostQueries() - expect(api.automations.listRuns.mock.calls.length).toBe(readsBeforeFailure + 1) - expect(container.textContent).toContain('Saved exact historical output') - await rerender() - const readsBeforeRetry = api.automations.listRuns.mock.calls.length - await act(async () => retryHistory?.('retry')) - await settleHostQueries() - expect(api.automations.listRuns.mock.calls.length).toBeGreaterThan(readsBeforeRetry) - expect(container.textContent).toContain('Saved exact historical output') - expect(container.querySelector('[aria-label="Back to runs"]')).not.toBeNull() - expect( - [...container.querySelectorAll('button')].some((button) => button.textContent === 'View run') - ).toBe(true) - await act(async () => - container.querySelector('[aria-label="Back to runs"]')?.click() - ) - expect(container.querySelector('[data-testid="list-panel"]')).not.toBeNull() - expect(mocks.toastMessage).not.toHaveBeenCalledWith('Run history no longer available.') - }) - - it('reacquires a same-row SSH incarnation only after explicit selection, retaining old output through Retry and Back', async () => { - const automation = makeAutomation({ id: 'ssh-a', name: 'Captured SSH' }) - mocks.state.selectedAutomationId = automation.id - mocks.state.setSelectedAutomationId = (id: string | null) => { - mocks.state.selectedAutomationId = id - } - const run = makeRun({ - id: 'older-ssh-run', - automationId: automation.id, - outputSnapshot: { - format: 'plain_text', - content: 'Captured old output', - capturedAt: 1, - truncated: false - } - }) - mocks.state.folderWorkspaces = [] - mocks.state.projectGroups = [] - let generation = 7 - mocks.state.sshTargetLabels = new Map([['box', 'Box']]) - mocks.state.sshTargetGenerations = new Map([['box', generation]]) - mocks.state.sshConnectionStates = new Map([['box', { status: 'connected' }]]) - api.automations.listScoped.mockImplementation(async (args) => ({ - automations: args?.selector?.kind === 'ssh' ? [automation] : [], - items: - args?.selector?.kind === 'ssh' - ? [ - { - automationId: automation.id, - selector: { kind: 'ssh', targetId: 'box', targetGeneration: generation } - } - ] - : [], - orphanCount: 0 - })) - api.automations.listRuns.mockResolvedValue([run]) - const { container, rerender } = await renderPage() - await openAutomationRow(container, 'Captured SSH') - await act(async () => mocks.detailPane?.openAutomationRunPage(run)) - expect(container.textContent).toContain('Captured old output') - generation = 9 - mocks.state.sshTargetGenerations = new Map([['box', generation]]) - await rerender() - await act(async () => window.dispatchEvent(new Event(AUTOMATIONS_CHANGED_EVENT))) - await settleHostQueries() - expect(container.textContent).toContain('Captured old output') - const back = container.querySelector('[aria-label="Back to runs"]') - expect(back).not.toBeNull() - await act(async () => back?.click()) - expect(container.querySelector('[data-testid="detail-pane"]')).not.toBeNull() - const beforeRetry = api.automations.listRuns.mock.calls.length - await act(async () => mocks.detailPane?.recoverSelectedRuns('retry')) - await settleHostQueries() - expect(api.automations.listRuns.mock.calls.length).toBeGreaterThan(beforeRetry) - expect( - api.automations.listRuns.mock.calls - .slice(beforeRetry) - .every(([args]) => args?.expectedOwner?.selector?.targetGeneration !== 9) - ).toBe(true) - expect(mocks.detailPane?.selectedRuns).toEqual([run]) - const automations = [...container.querySelectorAll('nav button')].find( - (button) => button.textContent === 'Automations' - ) - expect(automations).toBeTruthy() - await act(async () => automations?.click()) - const beforeReselect = api.automations.listRuns.mock.calls.length - await openAutomationRow(container, 'Captured SSH') - expect( - api.automations.listRuns.mock.calls - .slice(beforeReselect) - .some(([args]) => args?.expectedOwner?.selector?.targetGeneration === 9) - ).toBe(true) - }) - it('fetches the newly selected automation runs when the selection changes', async () => { scopedList([ makeAutomation({ id: 'a-1', name: 'Nightly' }), diff --git a/src/renderer/src/components/automations/AutomationsPage.run-navigation.test.tsx b/src/renderer/src/components/automations/AutomationsPage.run-navigation.test.tsx deleted file mode 100644 index 355cad9cdf4..00000000000 --- a/src/renderer/src/components/automations/AutomationsPage.run-navigation.test.tsx +++ /dev/null @@ -1,113 +0,0 @@ -// @vitest-environment happy-dom - -import { act } from 'react' -import { within } from '@testing-library/react' -import { describe, expect, it, vi } from 'vitest' -import type { AutomationRun } from '../../../../shared/automations/history/automation-run' -import { - api, - installAutomationsPageHarness, - mocks, - renderPage, - scopedList, - settleHostQueries -} from './automations-page-test-harness' -import { makeAutomation, makeRun } from './automations-page-fixtures' - -vi.mock('@tanstack/react-virtual', async () => { - const { createVirtualizerStub } = await import('./virtualizer-test-stub') - return { useVirtualizer: createVirtualizerStub() } -}) - -installAutomationsPageHarness() - -async function loadCachedHistory() { - const automation = makeAutomation() - const oldRun = makeRun({ id: 'run-26', runNumber: 26 }) - api.automations.list.mockResolvedValue([automation]) - scopedList([automation]) - api.automations.listRuns.mockResolvedValue([oldRun]) - mocks.state.selectedAutomationId = automation.id - mocks.state.setPendingAutomationRunNavigation = mocks.setPendingRunNavigation - mocks.setPendingRunNavigation.mockImplementation((navigation) => { - mocks.state.pendingAutomationRunNavigation = navigation - }) - const page = await renderPage() - await settleHostQueries() - return { ...page, automation, oldRun } -} - -async function openDashboardRun( - container: HTMLElement, - newRun: AutomationRun, - oldRun: AutomationRun -) { - const fresh = Promise.withResolvers() - api.automations.listRuns.mockImplementation((args?: { limit?: number }) => - args?.limit ? Promise.resolve([newRun, oldRun]) : fresh.promise - ) - await act(async () => within(container).getByRole('button', { name: 'Runs' }).click()) - await act(async () => { - within(container) - .getByRole('button', { name: new RegExp(newRun.title) }) - .click() - }) - return fresh -} - -describe('AutomationsPage run navigation', () => { - it('keeps the runs dashboard open when the user backs out of a pending read', async () => { - const { container, oldRun } = await loadCachedHistory() - const newRun = makeRun({ id: 'run-27', title: 'Nightly run 27' }) - const fresh = await openDashboardRun(container, newRun, oldRun) - const breadcrumb = within(container).getByRole('navigation', { - name: 'Automations breadcrumb' - }) - - await act(async () => within(breadcrumb).getByRole('button', { name: 'Runs' }).click()) - await act(async () => fresh.resolve([newRun, oldRun])) - - expect(mocks.state.pendingAutomationRunNavigation).toBeNull() - expect(within(container).getByRole('textbox', { name: 'Search runs…' })).toBeTruthy() - expect(container.querySelector('[aria-label="Run context"]')).toBeNull() - expect(mocks.toastMessage).not.toHaveBeenCalled() - }) - - it('returns to automation details when cancelling a workspace run link from there', async () => { - const { container, rerender, automation, oldRun } = await loadCachedHistory() - await act(async () => within(container).getByRole('button', { name: 'Nightly' }).click()) - const fresh = Promise.withResolvers() - api.automations.listRuns.mockReturnValue(fresh.promise) - mocks.state.pendingAutomationRunNavigation = { - automationId: automation.id, - runId: oldRun.id - } - await rerender() - - expect(within(container).getByRole('status')).toBeTruthy() - await act(async () => { - window.dispatchEvent( - new KeyboardEvent('keydown', { key: 'Escape', bubbles: true, cancelable: true }) - ) - }) - expect(mocks.state.pendingAutomationRunNavigation).toBeNull() - await act(async () => fresh.resolve([oldRun])) - - expect(within(container).getByTestId('detail-pane')).toBeTruthy() - expect(container.querySelector('[aria-label="Run context"]')).toBeNull() - expect(mocks.toastMessage).not.toHaveBeenCalled() - }) - - it('shows the history error when opening a run from the dashboard fails', async () => { - const { container, oldRun } = await loadCachedHistory() - const newRun = makeRun({ id: 'run-27', title: 'Nightly run 27' }) - const fresh = await openDashboardRun(container, newRun, oldRun) - - await act(async () => fresh.reject(new Error('Host disconnected'))) - - expect(mocks.state.pendingAutomationRunNavigation).toBeNull() - expect(mocks.toastMessage).not.toHaveBeenCalled() - expect(container.querySelector('[data-testid="detail-pane"]')).not.toBeNull() - expect(mocks.detailPane?.selectedRunsNotice?.message).toContain('Host disconnected') - }) -}) diff --git a/src/renderer/src/components/automations/AutomationsPageDeleteDialogs.tsx b/src/renderer/src/components/automations/AutomationsPageDeleteDialogs.tsx index e5bb6cef3bc..190e1f2dcb4 100644 --- a/src/renderer/src/components/automations/AutomationsPageDeleteDialogs.tsx +++ b/src/renderer/src/components/automations/AutomationsPageDeleteDialogs.tsx @@ -1,5 +1,8 @@ import React from 'react' -import { AutomationDeleteDialog, ExternalAutomationDeleteDialog } from './AutomationDeleteDialogs' +import { + AutomationDeleteDialog, + ExternalAutomationDeleteDialog +} from './authoring/AutomationDeleteDialogs' type Props = { deleteTarget: React.ComponentProps['deleteTarget'] diff --git a/src/renderer/src/components/automations/AutomationsPageListPanel.tsx b/src/renderer/src/components/automations/AutomationsPageListPanel.tsx index 28a5ac5b224..9cfefc8b39d 100644 --- a/src/renderer/src/components/automations/AutomationsPageListPanel.tsx +++ b/src/renderer/src/components/automations/AutomationsPageListPanel.tsx @@ -1,7 +1,7 @@ import React from 'react' import type { AutomationsPageController } from './use-automations-page-controller' -import { AutomationsListPanel } from './AutomationsListPanel' -import { nextAutomationListSort } from './automation-list-view' +import { AutomationsListPanel } from './listing/AutomationsListPanel' +import { nextAutomationListSort } from './listing/automation-list-view' export function AutomationsPageListPanel({ controller, diff --git a/src/renderer/src/components/automations/AutomationsPageSkeleton.tsx b/src/renderer/src/components/automations/AutomationsPageSkeleton.tsx index cc8e5a2f85d..10c081c2a23 100644 --- a/src/renderer/src/components/automations/AutomationsPageSkeleton.tsx +++ b/src/renderer/src/components/automations/AutomationsPageSkeleton.tsx @@ -1,6 +1,6 @@ import React from 'react' import { cn } from '@/lib/utils' -import { AUTOMATIONS_TABLE_GRID_CLASS } from './automations-table-layout' +import { AUTOMATIONS_TABLE_GRID_CLASS } from './listing/automations-table-layout' import { LIST_TABLE_CONTAINER_CLASS, LIST_TABLE_HEADER_CLASS, diff --git a/src/renderer/src/components/automations/AutomationsPageSurface.tsx b/src/renderer/src/components/automations/AutomationsPageSurface.tsx index 61593de5d8c..dff56fff22d 100644 --- a/src/renderer/src/components/automations/AutomationsPageSurface.tsx +++ b/src/renderer/src/components/automations/AutomationsPageSurface.tsx @@ -1,16 +1,19 @@ import React from 'react' import { useTranslate } from '@/i18n/use-translate' import { LoadingSpinner } from '@/components/LoadingSpinner' -import { AutomationEditorDialog } from './AutomationEditorDialog' -import { AutomationsDetailPane } from './AutomationsDetailPane' +import { AutomationEditorDialog } from './authoring/AutomationEditorDialog' +import { AutomationsDetailPane } from './details/AutomationsDetailPane' import { AutomationsPageSkeleton } from './AutomationsPageSkeleton' -import { getAutomationAuthorityTarget } from './automation-host-client' -import { automationProjectName, type AutomationListRow } from './automation-list-row-identity' -import type { AutomationHostRecoveryAction } from './automation-host-status-descriptors' +import { getAutomationAuthorityTarget } from './hosts/automation-host-client' +import { + automationProjectName, + type AutomationListRow +} from './listing/automation-list-row-identity' +import type { AutomationHostRecoveryAction } from './hosts/automation-host-status-descriptors' import { AutomationsPageTopBar } from './AutomationsPageTopBar' import type { AutomationsPageController } from './use-automations-page-controller' -import { AutomationRunsDashboardSurface } from './AutomationRunsDashboardSurface' -import { AutomationRunDetailsPage } from './AutomationRunDetailsPage' +import { AutomationRunsDashboardSurface } from './runs/AutomationRunsDashboardSurface' +import { AutomationRunDetailsPage } from './runs/AutomationRunDetailsPage' import { AutomationsPageDeleteDialogs } from './AutomationsPageDeleteDialogs' import { AutomationsPageListPanel } from './AutomationsPageListPanel' export function AutomationsPageSurface({ diff --git a/src/renderer/src/components/automations/AutomationsPageTopBar.tsx b/src/renderer/src/components/automations/AutomationsPageTopBar.tsx index e5ab99a505c..ae24bc32293 100644 --- a/src/renderer/src/components/automations/AutomationsPageTopBar.tsx +++ b/src/renderer/src/components/automations/AutomationsPageTopBar.tsx @@ -1,9 +1,9 @@ import React from 'react' import { useTranslate } from '@/i18n/use-translate' -import { AutomationOwnerConflictNotice } from './AutomationOwnerConflictNotice' +import { AutomationOwnerConflictNotice } from './hosts/AutomationOwnerConflictNotice' import { AutomationsPageBreadcrumb } from './AutomationsPageBreadcrumb' -import type { AutomationHostRecoveryAction } from './automation-host-status-descriptors' -import type { AutomationActionNotice } from './automation-row-action-dispatch' +import type { AutomationHostRecoveryAction } from './hosts/automation-host-status-descriptors' +import type { AutomationActionNotice } from './hosts/automation-row-action-dispatch' export function AutomationsPageTopBar({ pageView, diff --git a/src/renderer/src/components/automations/AutomationAgentLaunchPicker.tsx b/src/renderer/src/components/automations/authoring/AutomationAgentLaunchPicker.tsx similarity index 92% rename from src/renderer/src/components/automations/AutomationAgentLaunchPicker.tsx rename to src/renderer/src/components/automations/authoring/AutomationAgentLaunchPicker.tsx index beee205e96a..7d41df74e03 100644 --- a/src/renderer/src/components/automations/AutomationAgentLaunchPicker.tsx +++ b/src/renderer/src/components/automations/authoring/AutomationAgentLaunchPicker.tsx @@ -1,7 +1,7 @@ import { useCallback, useMemo, useState, type ComponentProps } from 'react' -import { useAppStore } from '@/store' +import { useAppStore } from '@/store/index' import { AgentLaunchPicker } from '@/components/agent/AgentLaunchPicker' -import { useAgentPickerDraftScope } from '@/components/agent/AgentLaunchSetupButton' +import { useAgentPickerDraftScope } from '@/components/agent/agent-launch-picker-drafts' import { useAgentLaunchPickerInventory } from '@/components/agent/use-agent-launch-picker-inventory' import { useAgentMenuObservation } from '@/components/tab-bar/use-new-tab-agent-menu-rows' import { @@ -11,15 +11,15 @@ import { type ProspectiveWorkspace } from '@/lib/agent-session/launch/routing/agent-launch-route-input' import type { AgentCatalogEntry } from '@/lib/agent-catalog/agent-catalog' -import { parseExecutionHostId } from '../../../../shared/execution-host' -import { AUTOMATION_LAUNCH_SETUP_RUNTIME_CAPABILITY } from '../../../../shared/automations/automation-runtime-capabilities' -import { automationLegacyArguments } from '../../../../shared/automations/launch/automation-legacy-arguments' -import type { AutomationAuthorityRef } from '../../../../shared/automations/ownership/automation-owner-ref' +import { parseExecutionHostId } from '../../../../../shared/execution-host' +import { AUTOMATION_LAUNCH_SETUP_RUNTIME_CAPABILITY } from '../../../../../shared/automations/automation-runtime-capabilities' +import { automationLegacyArguments } from '../../../../../shared/automations/launch/automation-legacy-arguments' +import type { AutomationAuthorityRef } from '../../../../../shared/automations/ownership/automation-owner-ref' import { Button } from '@/components/ui/button' import { useTranslate } from '@/i18n/use-translate' import { draftExtraAgentArgsNeedFreshSession } from './automation-draft-model' import type { AgentDetectionTarget } from '@/hooks/useDetectedAgents' -import type { AgentPickerEntry } from '../../../../shared/agent-launch/picker/agent-launch-picker' +import type { AgentPickerEntry } from '../../../../../shared/agent-launch/picker/agent-launch-picker' import type { NewTabAgentMenuModel } from '@/components/tab-bar/new-tab-agent-menu-model' import { useAutomationAgentPickerEntries } from './use-automation-agent-picker-entries' import { AutomationExtraAgentArgsField } from './AutomationExtraAgentArgsField' @@ -30,7 +30,7 @@ import { editAutomationLegacyDraft, editsSupplementalArguments } from './automation-launch-draft' -import type { GlobalSettings } from '../../../../shared/global-settings-types' +import type { GlobalSettings } from '../../../../../shared/global-settings-types' function legacyArgumentsDraft(draft: AutomationDraft): AutomationDraft { return { diff --git a/src/renderer/src/components/automations/AutomationCustomCronPanel.tsx b/src/renderer/src/components/automations/authoring/AutomationCustomCronPanel.tsx similarity index 93% rename from src/renderer/src/components/automations/AutomationCustomCronPanel.tsx rename to src/renderer/src/components/automations/authoring/AutomationCustomCronPanel.tsx index 6e744c62e49..99451dab731 100644 --- a/src/renderer/src/components/automations/AutomationCustomCronPanel.tsx +++ b/src/renderer/src/components/automations/authoring/AutomationCustomCronPanel.tsx @@ -2,11 +2,11 @@ import React from 'react' import { CheckCircle2, CircleAlert } from 'lucide-react' import { Input } from '@/components/ui/input' import { cn } from '@/lib/utils' -import { describeAutomationSchedule } from '../../../../shared/automations/scheduling/automation-schedules' -import { getAutomationCronExpressionFields } from '../../../../shared/automations/scheduling/automation-schedule-parsing' -import { formatUiAutomationScheduleDescriptor } from './automation-schedule-label' +import { describeAutomationSchedule } from '../../../../../shared/automations/scheduling/automation-schedules' +import { getAutomationCronExpressionFields } from '../../../../../shared/automations/scheduling/automation-schedule-parsing' +import { formatUiAutomationScheduleDescriptor } from '../details/automation-schedule-label' import type { AutomationDraft } from './AutomationEditorDialog' -import { Field } from './automation-page-parts' +import { Field } from '../automation-page-parts' import { translate } from '@/i18n/i18n' import { useIntlLocale, useTranslate, type Translate } from '@/i18n/use-translate' diff --git a/src/renderer/src/components/automations/AutomationDeleteDialogs.tsx b/src/renderer/src/components/automations/authoring/AutomationDeleteDialogs.tsx similarity index 95% rename from src/renderer/src/components/automations/AutomationDeleteDialogs.tsx rename to src/renderer/src/components/automations/authoring/AutomationDeleteDialogs.tsx index e440982e095..f5f46a51520 100644 --- a/src/renderer/src/components/automations/AutomationDeleteDialogs.tsx +++ b/src/renderer/src/components/automations/authoring/AutomationDeleteDialogs.tsx @@ -9,13 +9,13 @@ import { DialogHeader, DialogTitle } from '@/components/ui/dialog' -import type { Automation } from '../../../../shared/automations/automation-definition' +import type { Automation } from '../../../../../shared/automations/automation-definition' import type { ExternalAutomationJob, ExternalAutomationManager -} from '../../../../shared/automations/external/external-automation' -import { getExternalAutomationScheduleDisplay } from './external-automation-schedule-display' -import { getExternalProviderLabel } from './external-automation-display' +} from '../../../../../shared/automations/external/external-automation' +import { getExternalAutomationScheduleDisplay } from '../external/external-automation-schedule-display' +import { getExternalProviderLabel } from '../external/external-automation-display' import { Trans } from 'react-i18next' import { i18n } from '@/i18n/i18n' import { useIntlLocale, useTranslate } from '@/i18n/use-translate' diff --git a/src/renderer/src/components/automations/AutomationDestinationField.tsx b/src/renderer/src/components/automations/authoring/AutomationDestinationField.tsx similarity index 96% rename from src/renderer/src/components/automations/AutomationDestinationField.tsx rename to src/renderer/src/components/automations/authoring/AutomationDestinationField.tsx index c2d8492df83..3d1971ec4d8 100644 --- a/src/renderer/src/components/automations/AutomationDestinationField.tsx +++ b/src/renderer/src/components/automations/authoring/AutomationDestinationField.tsx @@ -1,14 +1,14 @@ import React from 'react' import { HostCombobox } from '@/components/host-picker/HostCombobox' import { useTranslate } from '@/i18n/use-translate' -import { AutomationHostLabel, AutomationHostStatusBadges } from './AutomationHostBadges' -import { Field } from './automation-page-parts' +import { AutomationHostLabel, AutomationHostStatusBadges } from '../hosts/AutomationHostBadges' +import { Field } from '../automation-page-parts' import { automationCreateHostEligible, automationCreateHostOffered, automationCreateUpdateRequiredAuthorityLabels } from './automation-create-destination' -import { groupAutomationHostEntriesByAuthority } from './automation-host-picker-groups' +import { groupAutomationHostEntriesByAuthority } from '../hosts/automation-host-picker-groups' import type { AutomationCreateDestinationControl } from './use-automation-create-destination' // This host stores/schedules the automation and may differ from workspace execution; saving an existing record elsewhere moves it. diff --git a/src/renderer/src/components/automations/AutomationEditorDialog.tsx b/src/renderer/src/components/automations/authoring/AutomationEditorDialog.tsx similarity index 87% rename from src/renderer/src/components/automations/AutomationEditorDialog.tsx rename to src/renderer/src/components/automations/authoring/AutomationEditorDialog.tsx index 9a8b4ac659e..55e3087582b 100644 --- a/src/renderer/src/components/automations/AutomationEditorDialog.tsx +++ b/src/renderer/src/components/automations/authoring/AutomationEditorDialog.tsx @@ -1,6 +1,6 @@ -import type { AutomationAuthorityRef } from '../../../../shared/automations/ownership/automation-owner-ref' +import type { AutomationAuthorityRef } from '../../../../../shared/automations/ownership/automation-owner-ref' import React from 'react' -import { useAppStore } from '@/store' +import { useAppStore } from '@/store/index' import { selectAgentLaunchRouteView } from '@/lib/agent-session/launch/routing/agent-launch-route-input' import { useChatProgramFacts } from '@/lib/host-chat-program-acquisition' import { @@ -10,26 +10,26 @@ import { } from './automation-launch-surface' import { Dialog, DialogContent } from '@/components/ui/dialog' import { getAgentCatalog } from '@/lib/agent-catalog/agent-catalog' -import { filterEnabledTuiAgents } from '../../../../shared/agent-launch/catalog/tui-agent-selection' +import { filterEnabledTuiAgents } from '../../../../../shared/agent-launch/catalog/tui-agent-selection' import type { AutomationLaunchPreferences, AutomationLaunchSetupPatch -} from '../../../../shared/automations/launch/automation-launch-types' +} from '../../../../../shared/automations/launch/automation-launch-types' import type { AutomationSchedulePreset, AutomationWorkspaceMode -} from '../../../../shared/automations/automation-definition' -import type { GlobalSettings } from '../../../../shared/global-settings-types' -import type { OrcaHooks } from '../../../../shared/orca-yaml-hook-types' -import type { ProjectHostSetup } from '../../../../shared/project-types' -import type { Repo } from '../../../../shared/repo-types' -import type { TuiAgent } from '../../../../shared/agent-launch/catalog/tui-agent' -import type { SetupDecision } from '../../../../shared/worktree/create-types' -import type { Worktree } from '../../../../shared/worktree/types' +} from '../../../../../shared/automations/automation-definition' +import type { GlobalSettings } from '../../../../../shared/global-settings-types' +import type { OrcaHooks } from '../../../../../shared/orca-yaml-hook-types' +import type { ProjectHostSetup } from '../../../../../shared/project-types' +import type { Repo } from '../../../../../shared/repo-types' +import type { TuiAgent } from '../../../../../shared/agent-launch/catalog/tui-agent' +import type { SetupDecision } from '../../../../../shared/worktree/create-types' +import type { Worktree } from '../../../../../shared/worktree/types' import { closeUnfocusedMonacoFindOrPreventDialogDismiss } from '@/components/editor/monaco-find-widget' -import { AutomationOwnerConflictNotice } from './AutomationOwnerConflictNotice' -import type { AutomationActionNotice } from './automation-row-action-dispatch' -import type { AutomationHostRecoveryAction } from './automation-host-status-descriptors' +import { AutomationOwnerConflictNotice } from '../hosts/AutomationOwnerConflictNotice' +import type { AutomationActionNotice } from '../hosts/automation-row-action-dispatch' +import type { AutomationHostRecoveryAction } from '../hosts/automation-host-status-descriptors' import type { AutomationCreateDestinationControl } from './use-automation-create-destination' import { AutomationEditorDialogFooter } from './AutomationEditorDialogFooter' import { AutomationEditorDialogHeader } from './AutomationEditorDialogHeader' diff --git a/src/renderer/src/components/automations/AutomationEditorDialogFooter.tsx b/src/renderer/src/components/automations/authoring/AutomationEditorDialogFooter.tsx similarity index 100% rename from src/renderer/src/components/automations/AutomationEditorDialogFooter.tsx rename to src/renderer/src/components/automations/authoring/AutomationEditorDialogFooter.tsx diff --git a/src/renderer/src/components/automations/AutomationEditorDialogHeader.tsx b/src/renderer/src/components/automations/authoring/AutomationEditorDialogHeader.tsx similarity index 100% rename from src/renderer/src/components/automations/AutomationEditorDialogHeader.tsx rename to src/renderer/src/components/automations/authoring/AutomationEditorDialogHeader.tsx diff --git a/src/renderer/src/components/automations/AutomationEditorPromptEditor.test.tsx b/src/renderer/src/components/automations/authoring/AutomationEditorPromptEditor.test.tsx similarity index 58% rename from src/renderer/src/components/automations/AutomationEditorPromptEditor.test.tsx rename to src/renderer/src/components/automations/authoring/AutomationEditorPromptEditor.test.tsx index 4db710ee4f4..d9614be0865 100644 --- a/src/renderer/src/components/automations/AutomationEditorPromptEditor.test.tsx +++ b/src/renderer/src/components/automations/authoring/AutomationEditorPromptEditor.test.tsx @@ -15,7 +15,7 @@ vi.mock('@monaco-editor/react', () => ({ loader: { config: vi.fn() } })) vi.mock('@/lib/editor/monaco/monaco-setup', () => ({ monaco: {} })) -vi.mock('@/store', () => ({ +vi.mock('@/store/index', () => ({ useAppStore: (selector: (state: Record) => unknown) => selector({ settings: { theme: 'dark', terminalFontSize: 13, terminalFontFamily: 'monospace' }, @@ -30,12 +30,7 @@ vi.mock('@/components/editor/monaco-content-sync', () => ({ syncContentUpdate })) -import { closeUnfocusedMonacoFindOrPreventDialogDismiss } from '@/components/editor/monaco-find-widget' -import { - AUTOMATION_PROMPT_EDITOR_SLOT, - AutomationEditorPromptEditor, - getAutomationPromptEditorRoot -} from './AutomationEditorPromptEditor' +import { AutomationEditorPromptEditor } from './AutomationEditorPromptEditor' afterEach(() => { cleanup() @@ -75,37 +70,4 @@ describe('AutomationEditorPromptEditor', () => { editorDom.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape', bubbles: true })) expect(onDismiss).toHaveBeenCalledTimes(1) }) - - it('scopes find-widget lookups to the prompt editor slot, not the document', () => { - const dialog = document.createElement('div') - const editorRoot = document.createElement('div') - editorRoot.setAttribute('data-slot', AUTOMATION_PROMPT_EDITOR_SLOT) - const nameField = document.createElement('input') - const background = document.createElement('div') - const backgroundFind = document.createElement('div') - backgroundFind.className = 'find-widget' - const closeButton = document.createElement('button') - closeButton.className = 'button codicon-widget-close' - const onBackgroundClose = vi.fn() - closeButton.addEventListener('click', onBackgroundClose) - backgroundFind.append(closeButton) - background.append(backgroundFind) - dialog.append(editorRoot, nameField) - document.body.append(dialog, background) - - expect(getAutomationPromptEditorRoot(dialog)).toBe(editorRoot) - // Radix Escape fires on document; document-wide lookup could find editors behind the dialog. - expect(getAutomationPromptEditorRoot(document)).toBeNull() - expect(getAutomationPromptEditorRoot(null)).toBeNull() - expect( - closeUnfocusedMonacoFindOrPreventDialogDismiss({ - root: getAutomationPromptEditorRoot(dialog), - eventTarget: nameField - }) - ).toBe(false) - expect(onBackgroundClose).not.toHaveBeenCalled() - - dialog.remove() - background.remove() - }) }) diff --git a/src/renderer/src/components/automations/AutomationEditorPromptEditor.tsx b/src/renderer/src/components/automations/authoring/AutomationEditorPromptEditor.tsx similarity index 100% rename from src/renderer/src/components/automations/AutomationEditorPromptEditor.tsx rename to src/renderer/src/components/automations/authoring/AutomationEditorPromptEditor.tsx diff --git a/src/renderer/src/components/automations/AutomationEditorPromptSection.tsx b/src/renderer/src/components/automations/authoring/AutomationEditorPromptSection.tsx similarity index 100% rename from src/renderer/src/components/automations/AutomationEditorPromptSection.tsx rename to src/renderer/src/components/automations/authoring/AutomationEditorPromptSection.tsx diff --git a/src/renderer/src/components/automations/AutomationEditorSettingsSidebar.tsx b/src/renderer/src/components/automations/authoring/AutomationEditorSettingsSidebar.tsx similarity index 90% rename from src/renderer/src/components/automations/AutomationEditorSettingsSidebar.tsx rename to src/renderer/src/components/automations/authoring/AutomationEditorSettingsSidebar.tsx index 6c89609af50..f7a0c642f9a 100644 --- a/src/renderer/src/components/automations/AutomationEditorSettingsSidebar.tsx +++ b/src/renderer/src/components/automations/authoring/AutomationEditorSettingsSidebar.tsx @@ -1,15 +1,15 @@ -import type { AutomationAuthorityRef } from '../../../../shared/automations/ownership/automation-owner-ref' +import type { AutomationAuthorityRef } from '../../../../../shared/automations/ownership/automation-owner-ref' import { AutomationAgentLaunchPicker } from './AutomationAgentLaunchPicker' import type { ProspectiveWorkspace } from '@/lib/agent-session/launch/routing/agent-launch-route-input' import { useTranslate } from '@/i18n/use-translate' -import { isValidAutomationSchedule } from '../../../../shared/automations/scheduling/automation-schedule-parsing' -import type { GlobalSettings } from '../../../../shared/global-settings-types' -import type { OrcaHooks } from '../../../../shared/orca-yaml-hook-types' -import type { ProjectHostSetup } from '../../../../shared/project-types' -import type { Repo } from '../../../../shared/repo-types' -import type { Worktree } from '../../../../shared/worktree/types' +import { isValidAutomationSchedule } from '../../../../../shared/automations/scheduling/automation-schedule-parsing' +import type { GlobalSettings } from '../../../../../shared/global-settings-types' +import type { OrcaHooks } from '../../../../../shared/orca-yaml-hook-types' +import type { ProjectHostSetup } from '../../../../../shared/project-types' +import type { Repo } from '../../../../../shared/repo-types' +import type { Worktree } from '../../../../../shared/worktree/types' import type { AgentCatalogEntry } from '@/lib/agent-catalog/agent-catalog' -import { AUTOMATION_EDITOR_SECTION_LABEL_CLASS, Field } from './automation-page-parts' +import { AUTOMATION_EDITOR_SECTION_LABEL_CLASS, Field } from '../automation-page-parts' import { AutomationMissedRunGraceField } from './AutomationMissedRunGraceField' import { AutomationPrecheckFields } from './AutomationPrecheckFields' import AutomationProjectCombobox from './AutomationProjectCombobox' diff --git a/src/renderer/src/components/automations/AutomationExtraAgentArgsField.tsx b/src/renderer/src/components/automations/authoring/AutomationExtraAgentArgsField.tsx similarity index 96% rename from src/renderer/src/components/automations/AutomationExtraAgentArgsField.tsx rename to src/renderer/src/components/automations/authoring/AutomationExtraAgentArgsField.tsx index 26d21337223..e00587e9adf 100644 --- a/src/renderer/src/components/automations/AutomationExtraAgentArgsField.tsx +++ b/src/renderer/src/components/automations/authoring/AutomationExtraAgentArgsField.tsx @@ -6,8 +6,8 @@ import { getExtraAgentArgsPlaceholder, hasExtraAgentArgs, supportsExtraAgentArgs -} from '../../../../shared/agent-launch/startup/automation-extra-agent-args' -import { AUTOMATION_EDITOR_SECTION_LABEL_CLASS } from './automation-page-parts' +} from '../../../../../shared/agent-launch/startup/automation-extra-agent-args' +import { AUTOMATION_EDITOR_SECTION_LABEL_CLASS } from '../automation-page-parts' import { draftExtraAgentArgsNeedFreshSession, getDraftExtraAgentArgsError diff --git a/src/renderer/src/components/automations/AutomationMissedRunGraceField.tsx b/src/renderer/src/components/automations/authoring/AutomationMissedRunGraceField.tsx similarity index 97% rename from src/renderer/src/components/automations/AutomationMissedRunGraceField.tsx rename to src/renderer/src/components/automations/authoring/AutomationMissedRunGraceField.tsx index 1da1c632957..cb92db8ffe9 100644 --- a/src/renderer/src/components/automations/AutomationMissedRunGraceField.tsx +++ b/src/renderer/src/components/automations/authoring/AutomationMissedRunGraceField.tsx @@ -7,7 +7,7 @@ import { SelectValue } from '@/components/ui/select' import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip' -import { AUTOMATION_EDITOR_SECTION_LABEL_CLASS, Field } from './automation-page-parts' +import { AUTOMATION_EDITOR_SECTION_LABEL_CLASS, Field } from '../automation-page-parts' import type { AutomationDraft } from './AutomationEditorDialog' import { useTranslate } from '@/i18n/use-translate' diff --git a/src/renderer/src/components/automations/AutomationPrecheckFields.tsx b/src/renderer/src/components/automations/authoring/AutomationPrecheckFields.tsx similarity index 97% rename from src/renderer/src/components/automations/AutomationPrecheckFields.tsx rename to src/renderer/src/components/automations/authoring/AutomationPrecheckFields.tsx index 696e93da1b9..53458d156e0 100644 --- a/src/renderer/src/components/automations/AutomationPrecheckFields.tsx +++ b/src/renderer/src/components/automations/authoring/AutomationPrecheckFields.tsx @@ -5,7 +5,7 @@ import { SelectTrigger, SelectValue } from '@/components/ui/select' -import { AUTOMATION_EDITOR_SECTION_LABEL_CLASS, Field } from './automation-page-parts' +import { AUTOMATION_EDITOR_SECTION_LABEL_CLASS, Field } from '../automation-page-parts' import type { AutomationDraft } from './AutomationEditorDialog' import { useTranslate } from '@/i18n/use-translate' diff --git a/src/renderer/src/components/automations/AutomationProjectCombobox.tsx b/src/renderer/src/components/automations/authoring/AutomationProjectCombobox.tsx similarity index 98% rename from src/renderer/src/components/automations/AutomationProjectCombobox.tsx rename to src/renderer/src/components/automations/authoring/AutomationProjectCombobox.tsx index c68704f2f67..490c23c1751 100644 --- a/src/renderer/src/components/automations/AutomationProjectCombobox.tsx +++ b/src/renderer/src/components/automations/authoring/AutomationProjectCombobox.tsx @@ -4,15 +4,15 @@ import { Button } from '@/components/ui/button' import { Command, CommandInput, CommandList } from '@/components/ui/command' import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover' import RepoBadgeLabel from '@/components/repo/RepoBadgeLabel' -import { useAppStore } from '@/store' -import { isGitRepoKind } from '../../../../shared/repo-kind' -import { getRepoExecutionHostId } from '../../../../shared/execution-host' +import { useAppStore } from '@/store/index' +import { isGitRepoKind } from '../../../../../shared/repo-kind' +import { getRepoExecutionHostId } from '../../../../../shared/execution-host' import { isRepoSearchQueryTooLarge, searchRepos } from '@/lib/repo-search' import { cn } from '@/lib/utils' import { useMountedRef } from '@/hooks/useMountedRef' import { useTranslate } from '@/i18n/use-translate' import { projectHostCountLabel } from '@/components/project-host-count-label' -import type { Repo } from '../../../../shared/repo-types' +import type { Repo } from '../../../../../shared/repo-types' import { getAutomationProjectGroupForRepo, getAutomationProjectGroups, diff --git a/src/renderer/src/components/automations/AutomationSchedulePicker.test.ts b/src/renderer/src/components/automations/authoring/AutomationSchedulePicker.test.ts similarity index 100% rename from src/renderer/src/components/automations/AutomationSchedulePicker.test.ts rename to src/renderer/src/components/automations/authoring/AutomationSchedulePicker.test.ts diff --git a/src/renderer/src/components/automations/AutomationSchedulePicker.tsx b/src/renderer/src/components/automations/authoring/AutomationSchedulePicker.tsx similarity index 92% rename from src/renderer/src/components/automations/AutomationSchedulePicker.tsx rename to src/renderer/src/components/automations/authoring/AutomationSchedulePicker.tsx index 5b30f4d85b9..7a8147234fc 100644 --- a/src/renderer/src/components/automations/AutomationSchedulePicker.tsx +++ b/src/renderer/src/components/automations/authoring/AutomationSchedulePicker.tsx @@ -6,14 +6,14 @@ import { SelectTrigger, SelectValue } from '@/components/ui/select' -import type { AutomationSchedulePreset } from '../../../../shared/automations/automation-definition' -import { buildAutomationCronSchedule } from '../../../../shared/automations/scheduling/automation-schedule-occurrences' -import { isValidAutomationSchedule } from '../../../../shared/automations/scheduling/automation-schedule-parsing' +import type { AutomationSchedulePreset } from '../../../../../shared/automations/automation-definition' +import { buildAutomationCronSchedule } from '../../../../../shared/automations/scheduling/automation-schedule-occurrences' +import { isValidAutomationSchedule } from '../../../../../shared/automations/scheduling/automation-schedule-parsing' import type { AutomationDraft } from './AutomationEditorDialog' import { AutomationCustomCronPanel } from './AutomationCustomCronPanel' -import { acceptsAutomationDraftSchedule } from '../../../../shared/automations/scheduling/automation-schedule-input-gate' +import { acceptsAutomationDraftSchedule } from '../../../../../shared/automations/scheduling/automation-schedule-input-gate' import { AutomationTimeField, parseAutomationTime } from './AutomationTimeField' -import { Field } from './automation-page-parts' +import { Field } from '../automation-page-parts' import { translate } from '@/i18n/i18n' import { useIntlLocale, useTranslate, type Translate } from '@/i18n/use-translate' import { getUiWeekdayNames } from '@/i18n/weekday-names' diff --git a/src/renderer/src/components/automations/AutomationSessionField.tsx b/src/renderer/src/components/automations/authoring/AutomationSessionField.tsx similarity index 96% rename from src/renderer/src/components/automations/AutomationSessionField.tsx rename to src/renderer/src/components/automations/authoring/AutomationSessionField.tsx index 685bef4f1cc..5113ada679f 100644 --- a/src/renderer/src/components/automations/AutomationSessionField.tsx +++ b/src/renderer/src/components/automations/authoring/AutomationSessionField.tsx @@ -1,7 +1,7 @@ import { Info } from 'lucide-react' import { ToggleGroup, ToggleGroupItem } from '@/components/ui/toggle-group' import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip' -import { AUTOMATION_EDITOR_SECTION_LABEL_CLASS, Field } from './automation-page-parts' +import { AUTOMATION_EDITOR_SECTION_LABEL_CLASS, Field } from '../automation-page-parts' import type { AutomationDraft } from './AutomationEditorDialog' import { useTranslate } from '@/i18n/use-translate' diff --git a/src/renderer/src/components/automations/AutomationSetupDecisionField.tsx b/src/renderer/src/components/automations/authoring/AutomationSetupDecisionField.tsx similarity index 94% rename from src/renderer/src/components/automations/AutomationSetupDecisionField.tsx rename to src/renderer/src/components/automations/authoring/AutomationSetupDecisionField.tsx index b31109af38d..a4ff868a06c 100644 --- a/src/renderer/src/components/automations/AutomationSetupDecisionField.tsx +++ b/src/renderer/src/components/automations/authoring/AutomationSetupDecisionField.tsx @@ -5,9 +5,9 @@ import { cn } from '@/lib/utils' import { useTranslate } from '@/i18n/use-translate' import { getVisibleAutomationSetupDecision } from './automation-setup-decision' import type { AutomationDraft } from './AutomationEditorDialog' -import type { OrcaHooks } from '../../../../shared/orca-yaml-hook-types' -import type { ProjectHostSetup } from '../../../../shared/project-types' -import type { Repo } from '../../../../shared/repo-types' +import type { OrcaHooks } from '../../../../../shared/orca-yaml-hook-types' +import type { ProjectHostSetup } from '../../../../../shared/project-types' +import type { Repo } from '../../../../../shared/repo-types' type AutomationSetupDecisionFieldProps = { draft: AutomationDraft diff --git a/src/renderer/src/components/automations/AutomationSurfaceField.tsx b/src/renderer/src/components/automations/authoring/AutomationSurfaceField.tsx similarity index 88% rename from src/renderer/src/components/automations/AutomationSurfaceField.tsx rename to src/renderer/src/components/automations/authoring/AutomationSurfaceField.tsx index 578df279d75..14932800b73 100644 --- a/src/renderer/src/components/automations/AutomationSurfaceField.tsx +++ b/src/renderer/src/components/automations/authoring/AutomationSurfaceField.tsx @@ -1,8 +1,8 @@ import { ToggleGroup, ToggleGroupItem } from '@/components/ui/toggle-group' import { useTranslate } from '@/i18n/use-translate' -import { nativeChatPreferenceFor } from '../../../../shared/structured-native-chat-launch-route' -import type { GlobalSettings } from '../../../../shared/global-settings-types' -import { Field, AUTOMATION_EDITOR_SECTION_LABEL_CLASS } from './automation-page-parts' +import { nativeChatPreferenceFor } from '../../../../../shared/structured-native-chat-launch-route' +import type { GlobalSettings } from '../../../../../shared/global-settings-types' +import { Field, AUTOMATION_EDITOR_SECTION_LABEL_CLASS } from '../automation-page-parts' import { automationDraftSurface } from './automation-launch-surface' import type { AutomationDraft } from './AutomationEditorDialog' diff --git a/src/renderer/src/components/automations/AutomationTemplateEmptyState.tsx b/src/renderer/src/components/automations/authoring/AutomationTemplateEmptyState.tsx similarity index 100% rename from src/renderer/src/components/automations/AutomationTemplateEmptyState.tsx rename to src/renderer/src/components/automations/authoring/AutomationTemplateEmptyState.tsx diff --git a/src/renderer/src/components/automations/AutomationTimeField.tsx b/src/renderer/src/components/automations/authoring/AutomationTimeField.tsx similarity index 100% rename from src/renderer/src/components/automations/AutomationTimeField.tsx rename to src/renderer/src/components/automations/authoring/AutomationTimeField.tsx diff --git a/src/renderer/src/components/automations/AutomationWorkspaceField.tsx b/src/renderer/src/components/automations/authoring/AutomationWorkspaceField.tsx similarity index 92% rename from src/renderer/src/components/automations/AutomationWorkspaceField.tsx rename to src/renderer/src/components/automations/authoring/AutomationWorkspaceField.tsx index ad51852484d..2c336336b0c 100644 --- a/src/renderer/src/components/automations/AutomationWorkspaceField.tsx +++ b/src/renderer/src/components/automations/authoring/AutomationWorkspaceField.tsx @@ -3,10 +3,10 @@ import { ToggleGroup, ToggleGroupItem } from '@/components/ui/toggle-group' import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip' import { CreateFromPicker } from '@/components/repo/CreateFromPicker' import { useTranslate } from '@/i18n/use-translate' -import type { AutomationWorkspaceMode } from '../../../../shared/automations/automation-definition' -import type { Repo } from '../../../../shared/repo-types' -import type { Worktree } from '../../../../shared/worktree/types' -import { AUTOMATION_EDITOR_SECTION_LABEL_CLASS, Field } from './automation-page-parts' +import type { AutomationWorkspaceMode } from '../../../../../shared/automations/automation-definition' +import type { Repo } from '../../../../../shared/repo-types' +import type { Worktree } from '../../../../../shared/worktree/types' +import { AUTOMATION_EDITOR_SECTION_LABEL_CLASS, Field } from '../automation-page-parts' import { WorkspaceCombobox } from './WorkspaceCombobox' import type { AutomationDraft } from './AutomationEditorDialog' diff --git a/src/renderer/src/components/automations/WorkspaceCombobox.tsx b/src/renderer/src/components/automations/authoring/WorkspaceCombobox.tsx similarity index 98% rename from src/renderer/src/components/automations/WorkspaceCombobox.tsx rename to src/renderer/src/components/automations/authoring/WorkspaceCombobox.tsx index 1cce751348a..a262dfe5940 100644 --- a/src/renderer/src/components/automations/WorkspaceCombobox.tsx +++ b/src/renderer/src/components/automations/authoring/WorkspaceCombobox.tsx @@ -10,7 +10,7 @@ import { } from '@/components/ui/command' import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover' import { cn } from '@/lib/utils' -import type { Worktree } from '../../../../shared/worktree/types' +import type { Worktree } from '../../../../../shared/worktree/types' import { useTranslate } from '@/i18n/use-translate' export function WorkspaceCombobox({ diff --git a/src/renderer/src/components/automations/automation-create-destination.ts b/src/renderer/src/components/automations/authoring/automation-create-destination.ts similarity index 92% rename from src/renderer/src/components/automations/automation-create-destination.ts rename to src/renderer/src/components/automations/authoring/automation-create-destination.ts index 0fbe5a5bbee..18cc3d8dfcd 100644 --- a/src/renderer/src/components/automations/automation-create-destination.ts +++ b/src/renderer/src/components/automations/authoring/automation-create-destination.ts @@ -3,24 +3,24 @@ import type { AutomationAuthorityRef, AutomationOwnerRef -} from '../../../../shared/automations/ownership/automation-owner-ref' -import type { AutomationDestination } from '../../../../shared/automations/ownership/automation-owner-precondition' +} from '../../../../../shared/automations/ownership/automation-owner-ref' +import type { AutomationDestination } from '../../../../../shared/automations/ownership/automation-owner-precondition' import { hostStableKey, isSameAutomationOwner -} from '../../../../shared/automations/ownership/automation-owner-key' -import { getRepoSshConnectionId, parseExecutionHostId } from '../../../../shared/execution-host' -import type { Repo } from '../../../../shared/repo-types' +} from '../../../../../shared/automations/ownership/automation-owner-key' +import { getRepoSshConnectionId, parseExecutionHostId } from '../../../../../shared/execution-host' +import type { Repo } from '../../../../../shared/repo-types' import type { AutomationCatalogHydrationEvidence, AutomationHostCatalogEntry -} from './automation-host-catalog-types' -import { automationAuthorityCatalogKey } from './automation-host-catalog-types' +} from '../hosts/automation-host-catalog-types' +import { automationAuthorityCatalogKey } from '../hosts/automation-host-catalog-types' import { repoConnectionIdIn, type AutomationAuthorityRepoTables -} from './automation-authority-identity' -import { automationHostRecoveryActions } from './automation-host-status-descriptors' +} from '../hosts/automation-authority-identity' +import { automationHostRecoveryActions } from '../hosts/automation-host-status-descriptors' export type AutomationCreateDestinationChoiceReason = /** No host is selected and nothing may be assumed. */ diff --git a/src/renderer/src/components/automations/automation-create-projects.ts b/src/renderer/src/components/automations/authoring/automation-create-projects.ts similarity index 76% rename from src/renderer/src/components/automations/automation-create-projects.ts rename to src/renderer/src/components/automations/authoring/automation-create-projects.ts index e53a9e70891..b16915b23a6 100644 --- a/src/renderer/src/components/automations/automation-create-projects.ts +++ b/src/renderer/src/components/automations/authoring/automation-create-projects.ts @@ -2,9 +2,9 @@ import { getRepoExecutionHostId, parseExecutionHostId, toRuntimeExecutionHostId -} from '../../../../shared/execution-host' -import type { Repo } from '../../../../shared/repo-types' -import type { AutomationHostTarget } from './automation-host-client' +} from '../../../../../shared/execution-host' +import type { Repo } from '../../../../../shared/repo-types' +import type { AutomationHostTarget } from '../hosts/automation-host-client' /** Runtime creation uses that host’s repo catalog; desktop storage retains its SSH-capable catalog. */ export function getAutomationCreateRepos( diff --git a/src/renderer/src/components/automations/automation-delete-confirm-preference.ts b/src/renderer/src/components/automations/authoring/automation-delete-confirm-preference.ts similarity index 100% rename from src/renderer/src/components/automations/automation-delete-confirm-preference.ts rename to src/renderer/src/components/automations/authoring/automation-delete-confirm-preference.ts diff --git a/src/renderer/src/components/automations/automation-draft-model.ts b/src/renderer/src/components/automations/authoring/automation-draft-model.ts similarity index 87% rename from src/renderer/src/components/automations/automation-draft-model.ts rename to src/renderer/src/components/automations/authoring/automation-draft-model.ts index cf776994c35..d084574cf52 100644 --- a/src/renderer/src/components/automations/automation-draft-model.ts +++ b/src/renderer/src/components/automations/authoring/automation-draft-model.ts @@ -1,12 +1,12 @@ -import { buildAutomationRrule } from '../../../../shared/automations/scheduling/automation-schedule-occurrences' -import { automationLaunchInputs } from '../../../../shared/automations/launch/automation-launch-choices' +import { buildAutomationRrule } from '../../../../../shared/automations/scheduling/automation-schedule-occurrences' +import { automationLaunchInputs } from '../../../../../shared/automations/launch/automation-launch-choices' import { getAgentCatalog } from '@/lib/agent-catalog/agent-catalog' -import type { AutomationPrecheck } from '../../../../shared/automations/automation-definition' -import type { Worktree } from '../../../../shared/worktree/types' +import type { AutomationPrecheck } from '../../../../../shared/automations/automation-definition' +import type { Worktree } from '../../../../../shared/worktree/types' import { hasExtraAgentArgs, parseExtraAgentArgs -} from '../../../../shared/agent-launch/startup/automation-extra-agent-args' +} from '../../../../../shared/agent-launch/startup/automation-extra-agent-args' import type { AutomationDraft } from './AutomationEditorDialog' import { extraAgentArgsErrorText } from './automation-extra-agent-args-error-copy' diff --git a/src/renderer/src/components/automations/automation-edit-draft.ts b/src/renderer/src/components/automations/authoring/automation-edit-draft.ts similarity index 85% rename from src/renderer/src/components/automations/automation-edit-draft.ts rename to src/renderer/src/components/automations/authoring/automation-edit-draft.ts index e379eb47a33..3156c8c19df 100644 --- a/src/renderer/src/components/automations/automation-edit-draft.ts +++ b/src/renderer/src/components/automations/authoring/automation-edit-draft.ts @@ -1,11 +1,11 @@ -import { automationCanonicalLaunchSetup } from '../../../../shared/automations/launch/automation-canonical-launch-setup' -import type { Automation } from '../../../../shared/automations/automation-definition' +import { automationCanonicalLaunchSetup } from '../../../../../shared/automations/launch/automation-canonical-launch-setup' +import type { Automation } from '../../../../../shared/automations/automation-definition' import { translate } from '@/i18n/i18n' -import { getAutomationRunRepoId } from '../../../../shared/automations/history/automation-run-identity' +import { getAutomationRunRepoId } from '../../../../../shared/automations/history/automation-run-identity' import { isRunnableAutomationSchedule, tryParseAutomationRrule -} from '../../../../shared/automations/scheduling/automation-schedule-parsing' +} from '../../../../../shared/automations/scheduling/automation-schedule-parsing' import type { AutomationDraft } from './AutomationEditorDialog' import { AUTOMATION_DEFAULT_TIME, formatTimeInput } from './automation-draft-model' import { getAutomationSetupDecisionDraftValue } from './automation-setup-decision' diff --git a/src/renderer/src/components/automations/automation-editor-prompt-options.ts b/src/renderer/src/components/automations/authoring/automation-editor-prompt-options.ts similarity index 100% rename from src/renderer/src/components/automations/automation-editor-prompt-options.ts rename to src/renderer/src/components/automations/authoring/automation-editor-prompt-options.ts diff --git a/src/renderer/src/components/automations/automation-extra-agent-args-error-copy.ts b/src/renderer/src/components/automations/authoring/automation-extra-agent-args-error-copy.ts similarity index 95% rename from src/renderer/src/components/automations/automation-extra-agent-args-error-copy.ts rename to src/renderer/src/components/automations/authoring/automation-extra-agent-args-error-copy.ts index 3badaa76ade..aca921a61c2 100644 --- a/src/renderer/src/components/automations/automation-extra-agent-args-error-copy.ts +++ b/src/renderer/src/components/automations/authoring/automation-extra-agent-args-error-copy.ts @@ -3,7 +3,7 @@ import { EXTRA_AGENT_ARGS_FAILURE_COPY as EN, type ExtraAgentArgsFailure, type ExtraAgentArgsFailureCode -} from '../../../../shared/agent-launch/startup/automation-extra-agent-args' +} from '../../../../../shared/agent-launch/startup/automation-extra-agent-args' const COPY: Record) => string> = { unsupportedAgent: () => diff --git a/src/renderer/src/components/automations/automation-launch-draft.ts b/src/renderer/src/components/automations/authoring/automation-launch-draft.ts similarity index 82% rename from src/renderer/src/components/automations/automation-launch-draft.ts rename to src/renderer/src/components/automations/authoring/automation-launch-draft.ts index b95c199fe21..dc3052a3358 100644 --- a/src/renderer/src/components/automations/automation-launch-draft.ts +++ b/src/renderer/src/components/automations/authoring/automation-launch-draft.ts @@ -1,13 +1,13 @@ -import { automationLegacyArguments } from '../../../../shared/automations/launch/automation-legacy-arguments' -import { automationCanonicalLaunchSetup } from '../../../../shared/automations/launch/automation-canonical-launch-setup' -import { hasModernAutomationLaunchSetup } from '../../../../shared/automations/launch/automation-launch-setup' +import { automationLegacyArguments } from '../../../../../shared/automations/launch/automation-legacy-arguments' +import { automationCanonicalLaunchSetup } from '../../../../../shared/automations/launch/automation-canonical-launch-setup' +import { hasModernAutomationLaunchSetup } from '../../../../../shared/automations/launch/automation-launch-setup' import { foldAutomationSourceEdit, type AutomationLaunchEdit -} from '../../../../shared/automations/launch/automation-launch-source-edits' -import { parseExtraAgentArgs } from '../../../../shared/agent-launch/startup/automation-extra-agent-args' -import type { AgentPickerDraft } from '../../../../shared/agent-launch/picker/agent-launch-picker' -import type { TuiAgent } from '../../../../shared/agent-launch/catalog/tui-agent' +} from '../../../../../shared/automations/launch/automation-launch-source-edits' +import { parseExtraAgentArgs } from '../../../../../shared/agent-launch/startup/automation-extra-agent-args' +import type { AgentPickerDraft } from '../../../../../shared/agent-launch/picker/agent-launch-picker' +import type { TuiAgent } from '../../../../../shared/agent-launch/catalog/tui-agent' import type { AutomationDraft } from './AutomationEditorDialog' export function editsSupplementalArguments(draft: AutomationDraft, modern: boolean): boolean { diff --git a/src/renderer/src/components/automations/automation-launch-surface.ts b/src/renderer/src/components/automations/authoring/automation-launch-surface.ts similarity index 87% rename from src/renderer/src/components/automations/automation-launch-surface.ts rename to src/renderer/src/components/automations/authoring/automation-launch-surface.ts index 7f4a33eb19b..e14fc76a84f 100644 --- a/src/renderer/src/components/automations/automation-launch-surface.ts +++ b/src/renderer/src/components/automations/authoring/automation-launch-surface.ts @@ -1,22 +1,22 @@ -import { encodeAutomationLaunchEdit } from '../../../../shared/automations/launch/automation-launch-source-edits' +import { encodeAutomationLaunchEdit } from '../../../../../shared/automations/launch/automation-launch-source-edits' import { applyAutomationLaunchSetupPatch, hasModernAutomationLaunchSetup -} from '../../../../shared/automations/launch/automation-launch-setup' -import { automationCanonicalLaunchSetup } from '../../../../shared/automations/launch/automation-canonical-launch-setup' +} from '../../../../../shared/automations/launch/automation-launch-setup' +import { automationCanonicalLaunchSetup } from '../../../../../shared/automations/launch/automation-canonical-launch-setup' import type { Automation, AutomationUpdateInput, AutomationCreateInput -} from '../../../../shared/automations/automation-definition' -import type { GlobalSettings } from '../../../../shared/global-settings-types' -import { AUTOMATION_SURFACE_RUNTIME_CAPABILITY } from '../../../../shared/automations/automation-runtime-capabilities' +} from '../../../../../shared/automations/automation-definition' +import type { GlobalSettings } from '../../../../../shared/global-settings-types' +import { AUTOMATION_SURFACE_RUNTIME_CAPABILITY } from '../../../../../shared/automations/automation-runtime-capabilities' import { STRUCTURED_AGENT_SESSION_RUNTIME_CAPABILITY, STRUCTURED_AGENT_SESSION_CLIENT_LAUNCH_MODE_CAPABILITY -} from '../../../../shared/agent-session/agent-session-runtime-capabilities' -import { STRUCTURED_AGENT_SESSION_REGISTERED_AGENTS_RUNTIME_CAPABILITY } from '../../../../shared/agent-session/structured-agent-session-surface-capabilities' -import { nativeChatPreferenceFor } from '../../../../shared/structured-native-chat-launch-route' +} from '../../../../../shared/agent-session/agent-session-runtime-capabilities' +import { STRUCTURED_AGENT_SESSION_REGISTERED_AGENTS_RUNTIME_CAPABILITY } from '../../../../../shared/agent-session/structured-agent-session-surface-capabilities' +import { nativeChatPreferenceFor } from '../../../../../shared/structured-native-chat-launch-route' import { buildAgentLaunchRouteInput, type AgentLaunchRouteStore, diff --git a/src/renderer/src/components/automations/automation-legacy-schedule-editing.test.ts b/src/renderer/src/components/automations/authoring/automation-legacy-schedule-editing.test.ts similarity index 79% rename from src/renderer/src/components/automations/automation-legacy-schedule-editing.test.ts rename to src/renderer/src/components/automations/authoring/automation-legacy-schedule-editing.test.ts index 0a6a49893b9..f6db545bc1d 100644 --- a/src/renderer/src/components/automations/automation-legacy-schedule-editing.test.ts +++ b/src/renderer/src/components/automations/authoring/automation-legacy-schedule-editing.test.ts @@ -1,10 +1,10 @@ import { describe, expect, it } from 'vitest' -import type { Automation } from '../../../../shared/automations/automation-definition' -import { isValidAutomationSchedule } from '../../../../shared/automations/scheduling/automation-schedule-parsing' +import type { Automation } from '../../../../../shared/automations/automation-definition' +import { isValidAutomationSchedule } from '../../../../../shared/automations/scheduling/automation-schedule-parsing' import { buildAutomationEditDraft } from './automation-edit-draft' -import { acceptsAutomationDraftSchedule } from '../../../../shared/automations/scheduling/automation-schedule-input-gate' +import { acceptsAutomationDraftSchedule } from '../../../../../shared/automations/scheduling/automation-schedule-input-gate' // `*/90` on minutes was accepted before the oversized-step refusal (#15895) and still runs, // firing at :00. Only a row persisted by an older build can hold it. @@ -70,9 +70,4 @@ describe('editing an automation whose saved schedule predates the input gate', ( }) // Only oversized steps receive legacy leniency; unparseable schedules still need warnings. - it('keeps warning about a saved schedule that cannot be parsed', () => { - const draft = buildAutomationEditDraft(makeAutomation({ rrule: '0 9 32 * *' })) - expect(draft.customSchedule).toBe('') - expect(draft.scheduleWarning).toBeTruthy() - }) }) diff --git a/src/renderer/src/components/automations/automation-management-actions.ts b/src/renderer/src/components/automations/authoring/automation-management-actions.ts similarity index 88% rename from src/renderer/src/components/automations/automation-management-actions.ts rename to src/renderer/src/components/automations/authoring/automation-management-actions.ts index cec9ce5db34..df1e5eeb9b7 100644 --- a/src/renderer/src/components/automations/automation-management-actions.ts +++ b/src/renderer/src/components/automations/authoring/automation-management-actions.ts @@ -1,13 +1,16 @@ -import { deleteAutomationForTarget, updateAutomationForTarget } from './automation-host-client' -import type { AutomationUpdateInput } from '../../../../shared/automations/automation-definition' +import { + deleteAutomationForTarget, + updateAutomationForTarget +} from '../hosts/automation-host-client' +import type { AutomationUpdateInput } from '../../../../../shared/automations/automation-definition' import { dispatchAutomationDelete, dispatchAutomationUpdate -} from './automation-row-action-dispatch' +} from '../hosts/automation-row-action-dispatch' import { persistSkipDeleteAutomationConfirm } from './automation-delete-confirm-preference' -import type { AutomationListRow } from './automation-list-row-identity' -import type { AutomationsPageActionContext } from './automations-page-action-context' -import type { SetupTrustMismatch } from '../../../../shared/worktree/create-types' +import type { AutomationListRow } from '../listing/automation-list-row-identity' +import type { AutomationsPageActionContext } from '../automations-page-action-context' +import type { SetupTrustMismatch } from '../../../../../shared/worktree/create-types' import { reviewAutomationSkippedSetup } from './automation-setup-review' /** Fenced toggle/delete handlers and the confirmation preference flow. */ diff --git a/src/renderer/src/components/automations/automation-orca-save-operations.ts b/src/renderer/src/components/automations/authoring/automation-orca-save-operations.ts similarity index 92% rename from src/renderer/src/components/automations/automation-orca-save-operations.ts rename to src/renderer/src/components/automations/authoring/automation-orca-save-operations.ts index f3108678dcb..109cd8b3d3f 100644 --- a/src/renderer/src/components/automations/automation-orca-save-operations.ts +++ b/src/renderer/src/components/automations/authoring/automation-orca-save-operations.ts @@ -3,20 +3,20 @@ import type { Automation, AutomationCreateInput, AutomationUpdateInput -} from '../../../../shared/automations/automation-definition' +} from '../../../../../shared/automations/automation-definition' import type { AutomationAuthorityRef, StableAutomationCatalogRef -} from '../../../../shared/automations/ownership/automation-owner-ref' -import type { AutomationDestination } from '../../../../shared/automations/ownership/automation-owner-precondition' +} from '../../../../../shared/automations/ownership/automation-owner-ref' +import type { AutomationDestination } from '../../../../../shared/automations/ownership/automation-owner-precondition' import { translate } from '@/i18n/i18n' import type { Translate } from '@/i18n/use-translate' import { deleteAutomationForTarget, listAutomationsForTarget, updateAutomationForTarget -} from './automation-host-client' -import { createAutomationAtDestination } from './automation-owner-action-runner' +} from '../hosts/automation-host-client' +import { createAutomationAtDestination } from '../hosts/automation-owner-action-runner' import { dispatchAutomationDelete, dispatchAutomationReread, @@ -25,16 +25,16 @@ import { type AutomationActionNotice, type AutomationDispatchContext, type AutomationDispatchResult -} from './automation-row-action-dispatch' +} from '../hosts/automation-row-action-dispatch' import { revalidateAutomationCreateDestination, type AutomationCreateDestination } from './automation-create-destination' -import type { AutomationHostTarget } from './automation-host-client' -import type { AutomationAuthorityChangeReason } from './automation-host-invalidation' +import type { AutomationHostTarget } from '../hosts/automation-host-client' +import type { AutomationAuthorityChangeReason } from '../hosts/automation-host-invalidation' import type { AutomationSaveContext } from './automation-save-context' -import { automationAuthorityCatalogKey } from './automation-host-catalog-types' -import { createNonSecureContextUuid as createBrowserUuid } from '../../../../shared/non-secure-context-uuid' +import { automationAuthorityCatalogKey } from '../hosts/automation-host-catalog-types' +import { createNonSecureContextUuid as createBrowserUuid } from '../../../../../shared/non-secure-context-uuid' export type AutomationMoveOperationContext = { automationDispatchContext: AutomationDispatchContext diff --git a/src/renderer/src/components/automations/automation-orca-save.ts b/src/renderer/src/components/automations/authoring/automation-orca-save.ts similarity index 96% rename from src/renderer/src/components/automations/automation-orca-save.ts rename to src/renderer/src/components/automations/authoring/automation-orca-save.ts index c3d7a76dc0f..eb6de9e658b 100644 --- a/src/renderer/src/components/automations/automation-orca-save.ts +++ b/src/renderer/src/components/automations/authoring/automation-orca-save.ts @@ -3,7 +3,7 @@ import { recordedAutomationRunContext, isSameAutomationWorkspace } from './automation-recorded-target' -import { capturedAutomationOwner } from './automation-captured-owner' +import { capturedAutomationOwner } from '../hosts/automation-captured-owner' import { automationChatSupport, automationDraftLaunchSetup, @@ -15,16 +15,16 @@ import type { Automation, AutomationCreateInput, AutomationUpdateInput -} from '../../../../shared/automations/automation-definition' -import { getRepoExecutionHostId } from '../../../../shared/execution-host' +} from '../../../../../shared/automations/automation-definition' +import { getRepoExecutionHostId } from '../../../../../shared/execution-host' import { ensureHooksApproved } from '@/lib/ensure-hooks-confirmed' import { translate } from '@/i18n/i18n' -import { useAppStore } from '@/store' -import { listAutomationsForTarget } from './automation-host-client' +import { useAppStore } from '@/store/index' +import { listAutomationsForTarget } from '../hosts/automation-host-client' import { dispatchAutomationReread, type AutomationDispatchResult -} from './automation-row-action-dispatch' +} from '../hosts/automation-row-action-dispatch' import { buildDraftPrecheck, buildDraftSchedule } from './automation-draft-model' import { buildAutomationRunContextForRepo } from './automation-run-context' import { resolveAutomationSetupDecisionForSave } from './automation-setup-decision' diff --git a/src/renderer/src/components/automations/automation-project-groups.ts b/src/renderer/src/components/automations/authoring/automation-project-groups.ts similarity index 90% rename from src/renderer/src/components/automations/automation-project-groups.ts rename to src/renderer/src/components/automations/authoring/automation-project-groups.ts index 212d577f07b..6c1a61e5424 100644 --- a/src/renderer/src/components/automations/automation-project-groups.ts +++ b/src/renderer/src/components/automations/authoring/automation-project-groups.ts @@ -1,6 +1,9 @@ -import { getRepoExecutionHostId, LOCAL_EXECUTION_HOST_ID } from '../../../../shared/execution-host' -import { getProjectIdentityKey } from '../../../../shared/project-host-setup-projection' -import type { Repo } from '../../../../shared/repo-types' +import { + getRepoExecutionHostId, + LOCAL_EXECUTION_HOST_ID +} from '../../../../../shared/execution-host' +import { getProjectIdentityKey } from '../../../../../shared/project-host-setup-projection' +import type { Repo } from '../../../../../shared/repo-types' export type AutomationProjectGroup = { projectKey: string diff --git a/src/renderer/src/components/automations/automation-recorded-target.ts b/src/renderer/src/components/automations/authoring/automation-recorded-target.ts similarity index 73% rename from src/renderer/src/components/automations/automation-recorded-target.ts rename to src/renderer/src/components/automations/authoring/automation-recorded-target.ts index 91f2014b738..e5485d44490 100644 --- a/src/renderer/src/components/automations/automation-recorded-target.ts +++ b/src/renderer/src/components/automations/authoring/automation-recorded-target.ts @@ -1,8 +1,8 @@ -import type { Automation } from '../../../../shared/automations/automation-definition' -import { AUTOMATION_ORPHAN_ISSUES } from '../../../../shared/automations/ownership/automation-list-scope' -import { parseExecutionHostId } from '../../../../shared/execution-host' -import { automationAuthorityCatalogKey } from './automation-host-catalog-types' -import type { AutomationCapturedOwner } from './automation-captured-owner' +import type { Automation } from '../../../../../shared/automations/automation-definition' +import { AUTOMATION_ORPHAN_ISSUES } from '../../../../../shared/automations/ownership/automation-list-scope' +import { parseExecutionHostId } from '../../../../../shared/execution-host' +import { automationAuthorityCatalogKey } from '../hosts/automation-host-catalog-types' +import type { AutomationCapturedOwner } from '../hosts/automation-captured-owner' import type { AutomationCreateDestination } from './automation-create-destination' export function isSameAutomationWorkspace( diff --git a/src/renderer/src/components/automations/automation-run-context.ts b/src/renderer/src/components/automations/authoring/automation-run-context.ts similarity index 76% rename from src/renderer/src/components/automations/automation-run-context.ts rename to src/renderer/src/components/automations/authoring/automation-run-context.ts index 5418f94f20f..8f5d55a035d 100644 --- a/src/renderer/src/components/automations/automation-run-context.ts +++ b/src/renderer/src/components/automations/authoring/automation-run-context.ts @@ -1,10 +1,10 @@ import { buildWorkspaceRunContext, type WorkspaceRunContext -} from '../../../../shared/work-items/task-source-context' -import type { ProjectHostSetup } from '../../../../shared/project-types' -import type { Repo } from '../../../../shared/repo-types' -import { getRepoExecutionHostId } from '../../../../shared/execution-host' +} from '../../../../../shared/work-items/task-source-context' +import type { ProjectHostSetup } from '../../../../../shared/project-types' +import type { Repo } from '../../../../../shared/repo-types' +import { getRepoExecutionHostId } from '../../../../../shared/execution-host' export function buildAutomationRunContextForRepo(args: { repoId: string diff --git a/src/renderer/src/components/automations/automation-save-action.ts b/src/renderer/src/components/automations/authoring/automation-save-action.ts similarity index 93% rename from src/renderer/src/components/automations/automation-save-action.ts rename to src/renderer/src/components/automations/authoring/automation-save-action.ts index 4080cffef2e..03fba22b0c0 100644 --- a/src/renderer/src/components/automations/automation-save-action.ts +++ b/src/renderer/src/components/automations/authoring/automation-save-action.ts @@ -1,14 +1,14 @@ -import { useAppStore } from '@/store' +import { useAppStore } from '@/store/index' import { automationChatSupport, automationDraftSurface, automationLaunchWorkspace } from './automation-launch-surface' import { toast } from 'sonner' -import { isTuiAgentEnabled } from '../../../../shared/agent-launch/catalog/tui-agent-selection' -import { isValidAutomationSchedule } from '../../../../shared/automations/scheduling/automation-schedule-parsing' +import { isTuiAgentEnabled } from '../../../../../shared/agent-launch/catalog/tui-agent-selection' +import { isValidAutomationSchedule } from '../../../../../shared/automations/scheduling/automation-schedule-parsing' import { translate } from '@/i18n/i18n' -import { acceptsAutomationDraftSchedule } from '../../../../shared/automations/scheduling/automation-schedule-input-gate' +import { acceptsAutomationDraftSchedule } from '../../../../../shared/automations/scheduling/automation-schedule-input-gate' import { draftExtraAgentArgsNeedFreshSession, getDraftExtraAgentArgsError, diff --git a/src/renderer/src/components/automations/automation-save-completion.ts b/src/renderer/src/components/automations/authoring/automation-save-completion.ts similarity index 92% rename from src/renderer/src/components/automations/automation-save-completion.ts rename to src/renderer/src/components/automations/authoring/automation-save-completion.ts index 4b9794af39a..160c5bc580a 100644 --- a/src/renderer/src/components/automations/automation-save-completion.ts +++ b/src/renderer/src/components/automations/authoring/automation-save-completion.ts @@ -1,5 +1,5 @@ -import type { Automation } from '../../../../shared/automations/automation-definition' -import { useAppStore } from '@/store' +import type { Automation } from '../../../../../shared/automations/automation-definition' +import { useAppStore } from '@/store/index' import type { AutomationCreateDestination } from './automation-create-destination' import type { AutomationSaveContext } from './automation-save-context' import { showAutomationSavedToast } from './automation-orca-save-operations' diff --git a/src/renderer/src/components/automations/automation-save-context.ts b/src/renderer/src/components/automations/authoring/automation-save-context.ts similarity index 63% rename from src/renderer/src/components/automations/automation-save-context.ts rename to src/renderer/src/components/automations/authoring/automation-save-context.ts index c0f69d4eeed..ea4449c7b5b 100644 --- a/src/renderer/src/components/automations/automation-save-context.ts +++ b/src/renderer/src/components/automations/authoring/automation-save-context.ts @@ -1,8 +1,8 @@ -import type { AutomationsPageListState } from './use-automations-page-list-state' -import type { AutomationsPageLocalState } from './use-automations-page-local-state' -import type { AutomationsPageRefresh } from './use-automations-page-refresh' +import type { AutomationsPageListState } from '../listing/use-automations-page-list-state' +import type { AutomationsPageLocalState } from '../use-automations-page-local-state' +import type { AutomationsPageRefresh } from '../use-automations-page-refresh' import type { AutomationsPageSetupState } from './use-automations-page-setup-state' -import type { AutomationsPageStoreState } from './use-automations-page-store-state' +import type { AutomationsPageStoreState } from '../use-automations-page-store-state' import type { AutomationsPageDestinationState } from './use-automations-page-destination-state' import type { AutomationsPageDestinationFormState } from './use-automations-page-destination-form' diff --git a/src/renderer/src/components/automations/automation-setup-decision.test.ts b/src/renderer/src/components/automations/authoring/automation-setup-decision.test.ts similarity index 96% rename from src/renderer/src/components/automations/automation-setup-decision.test.ts rename to src/renderer/src/components/automations/authoring/automation-setup-decision.test.ts index e99e6edfb46..76d9b1b8b28 100644 --- a/src/renderer/src/components/automations/automation-setup-decision.test.ts +++ b/src/renderer/src/components/automations/authoring/automation-setup-decision.test.ts @@ -1,6 +1,6 @@ import { describe, expect, it } from 'vitest' -import type { ProjectHostSetup } from '../../../../shared/project-types' -import type { Repo } from '../../../../shared/repo-types' +import type { ProjectHostSetup } from '../../../../../shared/project-types' +import type { Repo } from '../../../../../shared/repo-types' import { getVisibleAutomationSetupDecision, resolveAutomationSetupDecisionForSave diff --git a/src/renderer/src/components/automations/automation-setup-decision.ts b/src/renderer/src/components/automations/authoring/automation-setup-decision.ts similarity index 77% rename from src/renderer/src/components/automations/automation-setup-decision.ts rename to src/renderer/src/components/automations/authoring/automation-setup-decision.ts index b385ad0d4e9..0a012cecc2d 100644 --- a/src/renderer/src/components/automations/automation-setup-decision.ts +++ b/src/renderer/src/components/automations/authoring/automation-setup-decision.ts @@ -1,13 +1,13 @@ -import { getAutomationSetupDefaultDecision } from '../../../../shared/automations/launch/automation-setup-decision' +import { getAutomationSetupDefaultDecision } from '../../../../../shared/automations/launch/automation-setup-decision' -import type { AutomationWorkspaceMode } from '../../../../shared/automations/automation-definition' -import type { OrcaHooks, SetupRunPolicy } from '../../../../shared/orca-yaml-hook-types' -import type { ProjectHostSetup } from '../../../../shared/project-types' -import type { Repo } from '../../../../shared/repo-types' -import type { SetupDecision } from '../../../../shared/worktree/create-types' -import { findAutomationRepo } from '../../../../shared/automations/ownership/automation-repo-target' -import { getRepoExecutionHostId } from '../../../../shared/execution-host' -import { getSetupConfig } from '../../../../shared/orca-hook-setup-config' +import type { AutomationWorkspaceMode } from '../../../../../shared/automations/automation-definition' +import type { OrcaHooks, SetupRunPolicy } from '../../../../../shared/orca-yaml-hook-types' +import type { ProjectHostSetup } from '../../../../../shared/project-types' +import type { Repo } from '../../../../../shared/repo-types' +import type { SetupDecision } from '../../../../../shared/worktree/create-types' +import { findAutomationRepo } from '../../../../../shared/automations/ownership/automation-repo-target' +import { getRepoExecutionHostId } from '../../../../../shared/execution-host' +import { getSetupConfig } from '../../../../../shared/orca-hook-setup-config' type AutomationSetupSource = { setupScript: string diff --git a/src/renderer/src/components/automations/automation-setup-review.ts b/src/renderer/src/components/automations/authoring/automation-setup-review.ts similarity index 89% rename from src/renderer/src/components/automations/automation-setup-review.ts rename to src/renderer/src/components/automations/authoring/automation-setup-review.ts index 6ffe96eebb0..f93f37175cb 100644 --- a/src/renderer/src/components/automations/automation-setup-review.ts +++ b/src/renderer/src/components/automations/authoring/automation-setup-review.ts @@ -1,17 +1,17 @@ import { toast } from 'sonner' import { translate } from '@/i18n/i18n' -import { useAppStore } from '@/store' +import { useAppStore } from '@/store/index' import { confirmCreatedWorktreeSetupContent, ensureHooksApproved, type HookTrustApproval } from '@/lib/ensure-hooks-confirmed' import type { AutomationSaveContext } from './automation-save-context' -import type { Automation } from '../../../../shared/automations/automation-definition' -import type { AutomationUsageSummary } from '../../../../shared/automations/history/automation-usage-summary' -import { getAutomationRunRepoId } from '../../../../shared/automations/history/automation-run-identity' -import type { SetupDecision, SetupTrustMismatch } from '../../../../shared/worktree/create-types' -import type { ExecutionHostId } from '../../../../shared/execution-host' +import type { Automation } from '../../../../../shared/automations/automation-definition' +import type { AutomationUsageSummary } from '../../../../../shared/automations/history/automation-usage-summary' +import { getAutomationRunRepoId } from '../../../../../shared/automations/history/automation-run-identity' +import type { SetupDecision, SetupTrustMismatch } from '../../../../../shared/worktree/create-types' +import type { ExecutionHostId } from '../../../../../shared/execution-host' /** A skipped setup still waiting for approval; null once the automation approves that content. */ export type PendingAutomationSetupReview = { content: SetupTrustMismatch | null } diff --git a/src/renderer/src/components/automations/automation-templates.ts b/src/renderer/src/components/automations/authoring/automation-templates.ts similarity index 95% rename from src/renderer/src/components/automations/automation-templates.ts rename to src/renderer/src/components/automations/authoring/automation-templates.ts index 07bbb809dcd..d65b01ad459 100644 --- a/src/renderer/src/components/automations/automation-templates.ts +++ b/src/renderer/src/components/automations/authoring/automation-templates.ts @@ -1,5 +1,5 @@ -import type { AutomationSchedulePreset } from '../../../../shared/automations/automation-definition' -import type { TuiAgent } from '../../../../shared/agent-launch/catalog/tui-agent' +import type { AutomationSchedulePreset } from '../../../../../shared/automations/automation-definition' +import type { TuiAgent } from '../../../../../shared/agent-launch/catalog/tui-agent' import { translate } from '@/i18n/i18n' import { createLocalizedCatalog } from '@/i18n/localized-catalog' diff --git a/src/renderer/src/components/automations/use-automation-agent-picker-entries.ts b/src/renderer/src/components/automations/authoring/use-automation-agent-picker-entries.ts similarity index 91% rename from src/renderer/src/components/automations/use-automation-agent-picker-entries.ts rename to src/renderer/src/components/automations/authoring/use-automation-agent-picker-entries.ts index fb7d2ba5a49..d672fcd21e5 100644 --- a/src/renderer/src/components/automations/use-automation-agent-picker-entries.ts +++ b/src/renderer/src/components/automations/authoring/use-automation-agent-picker-entries.ts @@ -9,9 +9,9 @@ import { agentPickerDraft, type AgentPickerDraft, type AgentPickerEntry -} from '../../../../shared/agent-launch/picker/agent-launch-picker' -import { automationLaunchChoices } from '../../../../shared/automations/launch/automation-launch-choices' -import { mergeExtraAgentArgs } from '../../../../shared/agent-launch/startup/automation-extra-agent-args' +} from '../../../../../shared/agent-launch/picker/agent-launch-picker' +import { automationLaunchChoices } from '../../../../../shared/automations/launch/automation-launch-choices' +import { mergeExtraAgentArgs } from '../../../../../shared/agent-launch/startup/automation-extra-agent-args' import type { AutomationDraft } from './AutomationEditorDialog' import { automationChatSupport } from './automation-launch-surface' diff --git a/src/renderer/src/components/automations/use-automation-create-destination.ts b/src/renderer/src/components/automations/authoring/use-automation-create-destination.ts similarity index 95% rename from src/renderer/src/components/automations/use-automation-create-destination.ts rename to src/renderer/src/components/automations/authoring/use-automation-create-destination.ts index f861781eedc..c820a1c4493 100644 --- a/src/renderer/src/components/automations/use-automation-create-destination.ts +++ b/src/renderer/src/components/automations/authoring/use-automation-create-destination.ts @@ -2,12 +2,12 @@ import { useCallback, useMemo, useRef, useState } from 'react' import { translate } from '@/i18n/i18n' -import type { Repo } from '../../../../shared/repo-types' +import type { Repo } from '../../../../../shared/repo-types' import type { AutomationHostCatalog, AutomationHostCatalogEntry -} from './automation-host-catalog-types' -import type { AutomationAuthorityRepoTables } from './automation-authority-identity' +} from '../hosts/automation-host-catalog-types' +import type { AutomationAuthorityRepoTables } from '../hosts/automation-authority-identity' import { automationCreateEligibleProjects, automationCreateProjectMismatch, @@ -19,7 +19,7 @@ import { type AutomationCreateDestinationChoiceReason, type AutomationCreateDestinationResolution } from './automation-create-destination' -import type { AutomationActionNotice } from './automation-row-action-dispatch' +import type { AutomationActionNotice } from '../hosts/automation-row-action-dispatch' export type AutomationCreateDestinationControl = { entries: readonly AutomationHostCatalogEntry[] diff --git a/src/renderer/src/components/automations/use-automation-draft-effects.ts b/src/renderer/src/components/automations/authoring/use-automation-draft-effects.ts similarity index 95% rename from src/renderer/src/components/automations/use-automation-draft-effects.ts rename to src/renderer/src/components/automations/authoring/use-automation-draft-effects.ts index e834c7b8e29..4f629e3c2fb 100644 --- a/src/renderer/src/components/automations/use-automation-draft-effects.ts +++ b/src/renderer/src/components/automations/authoring/use-automation-draft-effects.ts @@ -1,11 +1,11 @@ import { useCallback, useEffect } from 'react' import type { AutomationTemplate } from './automation-templates' import { getDefaultWorktree } from './automation-draft-model' -import { hasModernAutomationLaunchSetup } from '../../../../shared/automations/launch/automation-launch-setup' +import { hasModernAutomationLaunchSetup } from '../../../../../shared/automations/launch/automation-launch-setup' import type { AutomationsPageDestinationState } from './use-automations-page-destination-state' import type { AutomationsPageDestinationFormState } from './use-automations-page-destination-form' -import type { AutomationsPageLocalState } from './use-automations-page-local-state' -import type { AutomationsPageRefresh } from './use-automations-page-refresh' +import type { AutomationsPageLocalState } from '../use-automations-page-local-state' +import type { AutomationsPageRefresh } from '../use-automations-page-refresh' import type { AutomationsPageSetupState } from './use-automations-page-setup-state' /** Synchronizes draft defaults, setup policy, and templates. */ diff --git a/src/renderer/src/components/automations/use-automation-editor-actions.ts b/src/renderer/src/components/automations/authoring/use-automation-editor-actions.ts similarity index 93% rename from src/renderer/src/components/automations/use-automation-editor-actions.ts rename to src/renderer/src/components/automations/authoring/use-automation-editor-actions.ts index 82b640d7c75..83f7f7eaa11 100644 --- a/src/renderer/src/components/automations/use-automation-editor-actions.ts +++ b/src/renderer/src/components/automations/authoring/use-automation-editor-actions.ts @@ -1,18 +1,18 @@ import { useCallback } from 'react' -import { toRuntimeExecutionHostId } from '../../../../shared/execution-host' -import { useAppStore } from '@/store' +import { toRuntimeExecutionHostId } from '../../../../../shared/execution-host' +import { useAppStore } from '@/store/index' import { buildAutomationEditDraft } from './automation-edit-draft' import { AUTOMATION_DEFAULT_TIME, getDefaultWorktree } from './automation-draft-model' import type { AutomationTemplate } from './automation-templates' -import { dispatchAutomationReread } from './automation-row-action-dispatch' -import { listAutomationsForTarget } from './automation-host-client' +import { dispatchAutomationReread } from '../hosts/automation-row-action-dispatch' +import { listAutomationsForTarget } from '../hosts/automation-host-client' import { automationCreateHostFor } from './automation-create-destination' import type { AutomationDraft } from './AutomationEditorDialog' -import type { AutomationListRow } from './automation-list-row-identity' +import type { AutomationListRow } from '../listing/automation-list-row-identity' import type { AutomationsPageDestinationState } from './use-automations-page-destination-state' import type { AutomationsPageDestinationFormState } from './use-automations-page-destination-form' -import type { AutomationsPageLocalState } from './use-automations-page-local-state' -import type { AutomationsPageStoreState } from './use-automations-page-store-state' +import type { AutomationsPageLocalState } from '../use-automations-page-local-state' +import type { AutomationsPageStoreState } from '../use-automations-page-store-state' import { selectWorktreesByRepo } from '@/store/workspaces/catalog/workspace-record-fields' /** Dialog open/edit actions, including host-captured re-reads and project changes. */ diff --git a/src/renderer/src/components/automations/use-automation-migrate-action.ts b/src/renderer/src/components/automations/authoring/use-automation-migrate-action.ts similarity index 96% rename from src/renderer/src/components/automations/use-automation-migrate-action.ts rename to src/renderer/src/components/automations/authoring/use-automation-migrate-action.ts index 5f1ff3f8662..7da73b5ce72 100644 --- a/src/renderer/src/components/automations/use-automation-migrate-action.ts +++ b/src/renderer/src/components/automations/authoring/use-automation-migrate-action.ts @@ -3,7 +3,7 @@ import { toast } from 'sonner' import { resolveAutomationCreateDestination } from './automation-create-destination' import { createAutomationSaveAction } from './automation-save-action' import type { AutomationSaveContext } from './automation-save-context' -import type { AutomationListRow } from './automation-list-row-identity' +import type { AutomationListRow } from '../listing/automation-list-row-identity' import type { AutomationEditorActions } from './use-automation-editor-actions' /** Migrate: the editor's own move-to-server save, run without opening the dialog. */ diff --git a/src/renderer/src/components/automations/use-automations-page-destination-form.ts b/src/renderer/src/components/automations/authoring/use-automations-page-destination-form.ts similarity index 93% rename from src/renderer/src/components/automations/use-automations-page-destination-form.ts rename to src/renderer/src/components/automations/authoring/use-automations-page-destination-form.ts index d5bb66ccdf2..1142cf1664d 100644 --- a/src/renderer/src/components/automations/use-automations-page-destination-form.ts +++ b/src/renderer/src/components/automations/authoring/use-automations-page-destination-form.ts @@ -1,13 +1,13 @@ import { resolveAutomationEditDestination } from './automation-orca-save-operations' -import { AUTOMATION_ORPHAN_ISSUES } from '../../../../shared/automations/ownership/automation-list-scope' +import { AUTOMATION_ORPHAN_ISSUES } from '../../../../../shared/automations/ownership/automation-list-scope' import { recordedAutomationRunContext, isSameAutomationWorkspace } from './automation-recorded-target' import { useCallback, useEffect, useMemo } from 'react' -import { toRuntimeExecutionHostId } from '../../../../shared/execution-host' +import { toRuntimeExecutionHostId } from '../../../../../shared/execution-host' import { useTranslate } from '@/i18n/use-translate' -import { automationWorktreesForRepo } from './automation-list-row-identity' +import { automationWorktreesForRepo } from '../listing/automation-list-row-identity' import { getAutomationCreateRepos } from './automation-create-projects' import { automationCreateEligibleProjects, @@ -23,15 +23,18 @@ import { getAutomationOwnerTarget, getAutomationTargetFromHostId, type AutomationHostTarget -} from './automation-host-client' -import { automationAuthorityCatalogKey } from './automation-host-catalog-types' -import { capturedAutomationOwner, type AutomationCapturedOwner } from './automation-captured-owner' +} from '../hosts/automation-host-client' +import { automationAuthorityCatalogKey } from '../hosts/automation-host-catalog-types' +import { + capturedAutomationOwner, + type AutomationCapturedOwner +} from '../hosts/automation-captured-owner' import { buildAutomationRunContextForRepo } from './automation-run-context' import type { AutomationCreateDestinationControl } from './use-automation-create-destination' import type { AutomationsPageDestinationState } from './use-automations-page-destination-state' -import type { AutomationsPageListState } from './use-automations-page-list-state' -import type { AutomationsPageLocalState } from './use-automations-page-local-state' -import type { AutomationsPageStoreState } from './use-automations-page-store-state' +import type { AutomationsPageListState } from '../listing/use-automations-page-list-state' +import type { AutomationsPageLocalState } from '../use-automations-page-local-state' +import type { AutomationsPageStoreState } from '../use-automations-page-store-state' /** Editor project/workspace projections for the captured create or edit host. */ export function useAutomationsPageDestinationForm({ diff --git a/src/renderer/src/components/automations/use-automations-page-destination-state.ts b/src/renderer/src/components/automations/authoring/use-automations-page-destination-state.ts similarity index 89% rename from src/renderer/src/components/automations/use-automations-page-destination-state.ts rename to src/renderer/src/components/automations/authoring/use-automations-page-destination-state.ts index c0d47c2da88..2d45137da48 100644 --- a/src/renderer/src/components/automations/use-automations-page-destination-state.ts +++ b/src/renderer/src/components/automations/authoring/use-automations-page-destination-state.ts @@ -2,49 +2,52 @@ import { useCallback, useEffect, useMemo } from 'react' import type { AutomationAuthorityRef, StableAutomationCatalogRef -} from '../../../../shared/automations/ownership/automation-owner-ref' +} from '../../../../../shared/automations/ownership/automation-owner-ref' import { getRepoExecutionHostId, normalizeExecutionHostId, toSshExecutionHostId, toRuntimeExecutionHostId -} from '../../../../shared/execution-host' +} from '../../../../../shared/execution-host' import { automationCreateHostOffered, automationCreateHostStableKey } from './automation-create-destination' -import { getAutomationHostTargetFromKey, type AutomationHostTarget } from './automation-host-client' +import { + getAutomationHostTargetFromKey, + type AutomationHostTarget +} from '../hosts/automation-host-client' import { capturedAutomationOwner, isAutomationActionEnabled, type AutomationRowAction -} from './automation-captured-owner' +} from '../hosts/automation-captured-owner' import { automationRowCatalogRef, automationWriteChangeEvent -} from './automation-write-invalidation' -import { automationRowRecoveryHost } from './automation-notice-recovery-host' +} from '../hosts/automation-write-invalidation' +import { automationRowRecoveryHost } from '../hosts/automation-notice-recovery-host' import type { AutomationActionNotice, AutomationDispatchContext -} from './automation-row-action-dispatch' +} from '../hosts/automation-row-action-dispatch' import { automationRuntimePairingRevision, groupReposByAutomationAuthority -} from './automation-authority-identity' +} from '../hosts/automation-authority-identity' import { resolveIndexedWorktreeOwner } from '@/lib/workspace/ownership/worktree-runtime-owner-index' import { createRepoRowExecutionHostLookup, resolveWorktreeExecutionHost -} from '../../../../shared/execution-host/worktree-execution-host-resolution' -import { automationWorktreesForRepo } from './automation-list-row-identity' +} from '../../../../../shared/execution-host/worktree-execution-host-resolution' +import { automationWorktreesForRepo } from '../listing/automation-list-row-identity' import { getDefaultWorktree } from './automation-draft-model' -import type { AutomationsPageListState } from './use-automations-page-list-state' -import type { AutomationsPageLocalState } from './use-automations-page-local-state' -import type { AutomationsPageStoreState } from './use-automations-page-store-state' +import type { AutomationsPageListState } from '../listing/use-automations-page-list-state' +import type { AutomationsPageLocalState } from '../use-automations-page-local-state' +import type { AutomationsPageStoreState } from '../use-automations-page-store-state' import { useAutomationCreateDestination } from './use-automation-create-destination' -import type { AutomationHostCatalogEntry } from './automation-host-catalog-types' -import type { AutomationAuthorityChangeReason } from './automation-host-invalidation' +import type { AutomationHostCatalogEntry } from '../hosts/automation-host-catalog-types' +import type { AutomationAuthorityChangeReason } from '../hosts/automation-host-invalidation' /** Host destination, owner fencing, and authority-scoped project/workspace choices. */ export function useAutomationsPageDestinationState({ diff --git a/src/renderer/src/components/automations/use-automations-page-setup-state.ts b/src/renderer/src/components/automations/authoring/use-automations-page-setup-state.ts similarity index 91% rename from src/renderer/src/components/automations/use-automations-page-setup-state.ts rename to src/renderer/src/components/automations/authoring/use-automations-page-setup-state.ts index da39b2ebd5f..3165a7fc94c 100644 --- a/src/renderer/src/components/automations/use-automations-page-setup-state.ts +++ b/src/renderer/src/components/automations/authoring/use-automations-page-setup-state.ts @@ -1,14 +1,17 @@ import { useCallback, useMemo } from 'react' -import type { OrcaHooks } from '../../../../shared/orca-yaml-hook-types' +import type { OrcaHooks } from '../../../../../shared/orca-yaml-hook-types' import { checkRuntimeHooks } from '@/runtime/repo-hooks/runtime-hooks-client' import type { AutomationDraft } from './AutomationEditorDialog' -import { getAutomationHostTargetFromKey, type AutomationHostTarget } from './automation-host-client' -import { getRepoExecutionHostId, type ExecutionHostId } from '../../../../shared/execution-host' -import { findAutomationRepo } from '../../../../shared/automations/ownership/automation-repo-target' +import { + getAutomationHostTargetFromKey, + type AutomationHostTarget +} from '../hosts/automation-host-client' +import { getRepoExecutionHostId, type ExecutionHostId } from '../../../../../shared/execution-host' +import { findAutomationRepo } from '../../../../../shared/automations/ownership/automation-repo-target' import { getVisibleAutomationSetupDecision } from './automation-setup-decision' -import type { AutomationsPageListState } from './use-automations-page-list-state' -import type { AutomationsPageLocalState } from './use-automations-page-local-state' -import type { AutomationsPageStoreState } from './use-automations-page-store-state' +import type { AutomationsPageListState } from '../listing/use-automations-page-list-state' +import type { AutomationsPageLocalState } from '../use-automations-page-local-state' +import type { AutomationsPageStoreState } from '../use-automations-page-store-state' /** Draft setup policy, selected history, and the page's legacy host target. */ export function useAutomationsPageSetupState({ diff --git a/src/renderer/src/components/automations/automation-create-destination.test.ts b/src/renderer/src/components/automations/automation-create-destination.test.ts deleted file mode 100644 index 006ce63d56c..00000000000 --- a/src/renderer/src/components/automations/automation-create-destination.test.ts +++ /dev/null @@ -1,48 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { buildAutomationHostCatalog } from './automation-host-catalog' -import type { AutomationCatalogSshMirrorInput } from './automation-host-catalog-types' -import { - automationCreateHostOffered, - preselectAutomationCreateHost -} from './automation-create-destination' - -function mirror( - targets: AutomationCatalogSshMirrorInput['targets'] -): AutomationCatalogSshMirrorInput { - return { - targetsHydrated: true, - targets, - removedTargetLabels: new Map(), - connectionStatusByTargetId: new Map() - } -} - -describe('create destination on a managed SSH host', () => { - it("lists only the host's server and lands its desktop SSH key there", () => { - const { entries } = buildAutomationHostCatalog({ - desktop: { - label: 'Local Mac', - ssh: mirror([{ targetId: 'box', label: 'Build box', generation: 2 }]) - }, - runtimes: [ - { - environmentId: 'env-1', - label: 'Build box', - pairingRevision: 3, - authorityHealth: 'fresh', - querySupport: 'scoped', - ssh: mirror([]), - managedSshTargetId: 'box' - } - ], - runtimeCatalogSettled: true - }) - const desktopSshKey = 'host:desktop:ssh:box' - - const desktopSsh = entries.find((entry) => entry.stableKey === desktopSshKey) - expect(desktopSsh && automationCreateHostOffered(desktopSsh)).toBe(false) - expect(preselectAutomationCreateHost(entries, desktopSshKey, null)?.stableKey).toBe( - 'host:runtime:env-1:self' - ) - }) -}) diff --git a/src/renderer/src/components/automations/automation-create-projects.test.ts b/src/renderer/src/components/automations/automation-create-projects.test.ts deleted file mode 100644 index af5905d7fe1..00000000000 --- a/src/renderer/src/components/automations/automation-create-projects.test.ts +++ /dev/null @@ -1,38 +0,0 @@ -import { describe, expect, it } from 'vitest' -import type { Repo } from '../../../../shared/repo-types' -import { getAutomationCreateRepos } from './automation-create-projects' - -function repo(id: string, executionHostId: Repo['executionHostId']): Repo { - return { - id, - path: `/${id}`, - displayName: id, - badgeColor: '#000000', - addedAt: 1, - executionHostId - } -} - -describe('getAutomationCreateRepos', () => { - const repos = [ - repo('local', 'local'), - repo('remote', 'runtime:env-1'), - repo('ssh', 'ssh:builder') - ] - - it('selects only the destination runtime catalog', () => { - expect( - getAutomationCreateRepos(repos, { kind: 'environment', environmentId: 'env-1' }) - ).toEqual([repos[1]]) - }) - - it('keeps local and direct SSH rows but excludes paired-runtime rows', () => { - expect(getAutomationCreateRepos(repos, { kind: 'local' })).toEqual([repos[0], repos[2]]) - }) - - it('fails closed when the destination runtime has no project', () => { - expect( - getAutomationCreateRepos(repos, { kind: 'environment', environmentId: 'missing' }) - ).toEqual([]) - }) -}) diff --git a/src/renderer/src/components/automations/automation-host-cache-error.test.ts b/src/renderer/src/components/automations/automation-host-cache-error.test.ts deleted file mode 100644 index 6268e693234..00000000000 --- a/src/renderer/src/components/automations/automation-host-cache-error.test.ts +++ /dev/null @@ -1,37 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { RemoteRuntimeClientError } from '../../../../shared/remote-runtime/remote-runtime-client-error' -import { classifyAutomationHostQueryError } from './automation-host-cache-error' - -function classify(error: unknown): { code: string; retryable: boolean } { - const { code, retryable } = classifyAutomationHostQueryError(error, { attempt: 1, now: 0 }) - return { code, retryable } -} - -// Pin RPC failure-code mapping so dropping a classification is deliberate. -describe('classifyAutomationHostQueryError code mapping', () => { - it.each([ - ['runtime_unavailable', 'authority_unavailable', true], - ['remote_runtime_unavailable', 'authority_unavailable', true], - ['relay_quota_exceeded', 'authority_unavailable', true], - ['timeout', 'timeout', true], - ['runtime_timeout', 'timeout', true], - ['permission_denied', 'permission_denied', false], - ['unauthorized', 'permission_denied', false], - ['forbidden', 'permission_denied', false], - ['capability_unsupported', 'incompatible', false], - ['legacy_read_only', 'incompatible', false], - ['invalid_runtime_response', 'invalid_response', false], - ['invalid_argument', 'invalid_response', false], - ['runtime_manually_disconnected', 'unknown', true], - ['runtime_rpc_queue_overloaded', 'unknown', true], - ['remote_runtime_busy', 'unknown', true] - ])('maps %s to %s (retryable: %s)', (rpcCode, code, retryable) => { - expect(classify(new RemoteRuntimeClientError(rpcCode, 'failed'))).toEqual({ code, retryable }) - }) - - it('reads a code-stripped message token', () => { - expect( - classify(new Error("Error invoking remote method 'x': Error: failed: runtime_timeout")) - ).toEqual({ code: 'timeout', retryable: true }) - }) -}) diff --git a/src/renderer/src/components/automations/automation-host-cache-health.test.ts b/src/renderer/src/components/automations/automation-host-cache-health.test.ts deleted file mode 100644 index 2cd2e47cc12..00000000000 --- a/src/renderer/src/components/automations/automation-host-cache-health.test.ts +++ /dev/null @@ -1,58 +0,0 @@ -import { describe, expect, it } from 'vitest' -import type { AutomationHostCacheEntry } from './automation-host-cache-types' -import type { AutomationHostCatalogEntry } from './automation-host-catalog-types' -import { automationHostEntryHealth } from './automation-host-cache-health' - -function entry( - overrides: Partial & Pick -): AutomationHostCatalogEntry { - return { - stableRef: { authority: { kind: 'desktop' }, selector: { kind: 'self' } }, - owner: null, - label: 'This computer', - authorityLabel: 'This computer', - kind: 'self', - catalogState: 'authoritative', - authorityHealth: 'fresh', - executionHealth: 'connected', - querySupport: 'scoped', - ...overrides - } -} - -function cached(overrides: Partial): AutomationHostCacheEntry { - return { - data: [], - fetchedAt: null, - attempt: 0, - requestGeneration: 0, - catalogGeneration: 0, - request: null, - error: null, - orphanCount: null, - ...overrides - } -} - -const SELF = entry({ stableKey: 'host:desktop:self' }) - -describe('automation host cache health', () => { - it('marks a host whose unscoped list failed, so it never reads as empty', () => { - expect( - automationHostEntryHealth(SELF, { - entry: () => null, - failedAuthorityKeys: new Set(['authority:desktop']) - }) - ).toBe('stale-error') - }) - - it('lets a successful host-scoped read outrank the unscoped failure', () => { - // The per-host read is better evidence about this host than the ambient one. - expect( - automationHostEntryHealth(SELF, { - entry: () => cached({ fetchedAt: 5 }), - failedAuthorityKeys: new Set(['authority:desktop']) - }) - ).toBe('fresh') - }) -}) diff --git a/src/renderer/src/components/automations/automation-host-catalog-generation.test.ts b/src/renderer/src/components/automations/automation-host-catalog-generation.test.ts deleted file mode 100644 index 8144378bacc..00000000000 --- a/src/renderer/src/components/automations/automation-host-catalog-generation.test.ts +++ /dev/null @@ -1,166 +0,0 @@ -import { beforeEach, describe, expect, it } from 'vitest' -import type { StableAutomationAuthorityRef } from '../../../../shared/automations/ownership/automation-owner-ref' -import { buildAutomationHostCatalog } from './automation-host-catalog' -import { createAutomationCatalogGenerationRegistry } from './automation-host-catalog-generation' -import type { - AutomationCatalogSshMirrorInput, - AutomationHostCatalogInput, - AutomationRuntimeAuthorityInput -} from './automation-host-catalog-types' - -const DESKTOP: StableAutomationAuthorityRef = { kind: 'desktop' } -const ENV_A: StableAutomationAuthorityRef = { kind: 'runtime', environmentId: 'env-a' } -const ENV_B: StableAutomationAuthorityRef = { kind: 'runtime', environmentId: 'env-b' } - -function mirror( - overrides: Partial = {} -): AutomationCatalogSshMirrorInput { - return { - targetsHydrated: true, - targets: [], - removedTargetLabels: new Map(), - connectionStatusByTargetId: new Map(), - ...overrides - } -} - -function runtime( - environmentId: string, - overrides: Partial = {} -): AutomationRuntimeAuthorityInput { - return { - environmentId, - label: environmentId, - pairingRevision: 1, - authorityHealth: 'fresh', - querySupport: 'scoped', - ssh: mirror(), - ...overrides - } -} - -function input(overrides: Partial = {}): AutomationHostCatalogInput { - return { - desktop: { label: 'Local Mac', ssh: mirror() }, - runtimes: [runtime('env-a'), runtime('env-b')], - runtimeCatalogSettled: true, - ...overrides - } -} - -describe('automation catalog generation', () => { - let registry = createAutomationCatalogGenerationRegistry() - - beforeEach(() => { - registry = createAutomationCatalogGenerationRegistry() - }) - - it('advances only the authority whose target bucket hydrated', () => { - registry.sync( - buildAutomationHostCatalog( - input({ - runtimes: [ - runtime('env-a', { ssh: mirror({ targetsHydrated: false }) }), - runtime('env-b') - ] - }) - ) - ) - const before = { - desktop: registry.get(DESKTOP), - a: registry.get(ENV_A), - b: registry.get(ENV_B) - } - const advanced = registry.sync( - buildAutomationHostCatalog( - input({ - runtimes: [ - runtime('env-a', { - ssh: mirror({ targets: [{ targetId: 't', label: 'T', generation: 2 }] }) - }), - runtime('env-b') - ] - }) - ) - ) - expect(advanced.advancedAuthorityKeys).toEqual(['authority:runtime:env-a']) - expect(registry.get(ENV_A)).toBeGreaterThan(before.a) - expect(registry.get(ENV_B)).toBe(before.b) - expect(registry.get(DESKTOP)).toBe(before.desktop) - }) - - it('does not advance on runtime or SSH connection status changes', () => { - const targets = [{ targetId: 't', label: 'T', generation: 2 }] - registry.sync( - buildAutomationHostCatalog( - input({ - runtimes: [ - runtime('env-a', { - ssh: mirror({ targets, connectionStatusByTargetId: new Map([['t', 'connected']]) }) - }), - runtime('env-b') - ] - }) - ) - ) - const before = registry.get(ENV_A) - const advanced = registry.sync( - buildAutomationHostCatalog( - input({ - runtimes: [ - runtime('env-a', { - authorityHealth: 'stale-error', - ssh: mirror({ targets, connectionStatusByTargetId: new Map([['t', 'reconnecting']]) }) - }), - runtime('env-b') - ] - }) - ) - ) - expect(advanced.advancedAuthorityKeys).toEqual([]) - expect(registry.get(ENV_A)).toBe(before) - }) - - // doc:321 — the entry a same-id re-adoption produces is byte-identical apart - // from this, so the caller has no other way to know its rows are obsolete. - it('reports a same-id SSH re-adoption as a reincarnated host', () => { - const desktopAt = (generation: number, label = 'Box'): AutomationHostCatalogInput => - input({ - desktop: { - label: 'Local Mac', - ssh: mirror({ targets: [{ targetId: 'ssh-1', label, generation }] }) - } - }) - const first = registry.sync(buildAutomationHostCatalog(desktopAt(4))) - expect(first.reincarnatedStableKeys).toEqual([]) - - const renamed = registry.sync(buildAutomationHostCatalog(desktopAt(4, 'Renamed'))) - expect(renamed.reincarnatedStableKeys).toEqual([]) - - const readopted = registry.sync(buildAutomationHostCatalog(desktopAt(5))) - expect(readopted.reincarnatedStableKeys).toEqual(['host:desktop:ssh:ssh-1']) - expect(readopted.advancedAuthorityKeys).toEqual(['authority:desktop']) - }) - - // The generation file's own warning: an offline authority reported as - // legacy-unscoped loses its owner refs, which must not read as a re-adoption. - it('does not report a host whose owner merely went absent', () => { - const withSupport = (querySupport: 'scoped' | 'legacy-unscoped'): AutomationHostCatalogInput => - input({ - runtimes: [ - runtime('env-a', { - querySupport, - // An SSH entry is where the owner ref actually disappears with the support level. - ssh: mirror({ targets: [{ targetId: 't', label: 'T', generation: 3 }] }) - }) - ] - }) - registry.sync(buildAutomationHostCatalog(withSupport('scoped'))) - - const degraded = registry.sync(buildAutomationHostCatalog(withSupport('legacy-unscoped'))) - expect(degraded.reincarnatedStableKeys).toEqual([]) - - const restored = registry.sync(buildAutomationHostCatalog(withSupport('scoped'))) - expect(restored.reincarnatedStableKeys).toEqual([]) - }) -}) diff --git a/src/renderer/src/components/automations/automation-host-client.test.ts b/src/renderer/src/components/automations/automation-host-client.test.ts deleted file mode 100644 index 480c6dcd016..00000000000 --- a/src/renderer/src/components/automations/automation-host-client.test.ts +++ /dev/null @@ -1,118 +0,0 @@ -import { describe, expect, it, vi, beforeEach } from 'vitest' -import type { - Automation, - AutomationCreateInput -} from '../../../../shared/automations/automation-definition' -import { - getAutomationListedTargetFromHostId, - toRuntimeAutomationCreateInput -} from './automation-host-client' - -vi.mock('@/runtime/rpc/calls/runtime-rpc-call', () => ({ - callRuntimeRpc: vi.fn() -})) - -const mockApi = { - automations: { - list: vi.fn(), - listRuns: vi.fn(), - create: vi.fn(), - update: vi.fn(), - delete: vi.fn(), - runNow: vi.fn() - } -} - -// @ts-expect-error test window mock -globalThis.window = { api: mockApi } - -function makeAutomation(overrides: Partial = {}): Automation { - return { - id: 'auto-1', - name: 'Remote check', - prompt: 'Check', - precheck: null, - agentId: 'codex', - projectId: 'repo-1', - executionTargetType: 'local', - executionTargetId: 'local', - schedulerOwner: 'remote_host_service', - workspaceMode: 'new_per_run', - workspaceId: null, - baseBranch: null, - reuseSession: false, - timezone: 'UTC', - rrule: 'FREQ=DAILY;BYHOUR=9;BYMINUTE=0', - dtstart: 1, - enabled: true, - nextRunAt: 2, - missedRunPolicy: 'run_once_within_grace', - missedRunGraceMinutes: 720, - createdAt: 1, - updatedAt: 1, - runContext: { - kind: 'workspace-run', - projectId: 'github:stablyai/orca', - hostId: 'runtime:gpu', - projectHostSetupId: 'setup-gpu', - repoId: 'repo-1', - path: '/srv/orca' - }, - ...overrides - } -} - -describe('automation host client', () => { - beforeEach(() => { - vi.clearAllMocks() - }) - - it('encodes exact machine selectors for the create wire input', () => { - const automation = makeAutomation({ - workspaceMode: 'existing', - workspaceId: 'repo-1::/srv/orca' - }) - const input: AutomationCreateInput = { - name: automation.name, - prompt: automation.prompt, - precheck: null, - agentId: automation.agentId, - runContext: automation.runContext, - projectId: automation.projectId, - workspaceMode: 'existing', - workspaceId: automation.workspaceId, - setupDecision: 'skip', - timezone: automation.timezone, - rrule: automation.rrule, - dtstart: automation.dtstart - } - - expect(toRuntimeAutomationCreateInput(input)).toMatchObject({ - repo: 'id:repo-1', - workspace: 'id:repo-1::/srv/orca' - }) - // A per-run workspace states no workspace selector at all. - expect( - toRuntimeAutomationCreateInput({ ...input, workspaceMode: 'new_per_run', workspaceId: null }) - ).toMatchObject({ repo: 'id:repo-1', workspace: undefined }) - }) -}) - -describe('getAutomationListedTargetFromHostId', () => { - const state = { runtimeEnvironments: [{ id: 'env-1' }] } - - // #32415: a web run link names 'local', but the catalog lists the server only as its runtime. - it('lists a paired web client local and SSH hosts under its server', () => { - Object.assign(globalThis, { __ORCA_WEB_CLIENT__: true }) - try { - for (const hostId of ['local', 'ssh:box', undefined]) { - expect(getAutomationListedTargetFromHostId(hostId, state)).toEqual({ - kind: 'environment', - environmentId: 'env-1' - }) - } - } finally { - Reflect.deleteProperty(globalThis, '__ORCA_WEB_CLIENT__') - } - }) -}) diff --git a/src/renderer/src/components/automations/automation-host-filter-resolution.test.ts b/src/renderer/src/components/automations/automation-host-filter-resolution.test.ts deleted file mode 100644 index f06b11c8f5a..00000000000 --- a/src/renderer/src/components/automations/automation-host-filter-resolution.test.ts +++ /dev/null @@ -1,223 +0,0 @@ -import { describe, expect, it } from 'vitest' -import type { AutomationHostFilter } from '../../../../shared/automations/ownership/automation-host-filter' -import { hostStableKey } from '../../../../shared/automations/ownership/automation-owner-key' -import type { StableAutomationCatalogRef } from '../../../../shared/automations/ownership/automation-owner-ref' -import { buildAutomationHostCatalog } from './automation-host-catalog' -import type { - AutomationCatalogSshMirrorInput, - AutomationHostCatalogInput, - AutomationRuntimeAuthorityInput -} from './automation-host-catalog-types' -import { resolveAutomationHostFilter } from './automation-host-filter-resolution' - -function mirror( - overrides: Partial = {} -): AutomationCatalogSshMirrorInput { - return { - targetsHydrated: true, - targets: [], - removedTargetLabels: new Map(), - connectionStatusByTargetId: new Map(), - ...overrides - } -} - -function runtime( - overrides: Partial = {} -): AutomationRuntimeAuthorityInput { - return { - environmentId: 'env-1', - label: 'Build server', - pairingRevision: 3, - authorityHealth: 'fresh', - querySupport: 'scoped', - ssh: mirror(), - ...overrides - } -} - -function catalogOf(overrides: Partial = {}) { - return buildAutomationHostCatalog({ - desktop: { label: 'Local Mac', ssh: mirror() }, - runtimes: [], - runtimeCatalogSettled: true, - ...overrides - }) -} - -function filterFor(host: StableAutomationCatalogRef): AutomationHostFilter { - return { kind: 'host', host } -} - -const desktopSsh = (targetId: string): StableAutomationCatalogRef => ({ - authority: { kind: 'desktop' }, - selector: { kind: 'ssh', targetId } -}) -const runtimeSelf: StableAutomationCatalogRef = { - authority: { kind: 'runtime', environmentId: 'env-1' }, - selector: { kind: 'self' } -} -const runtimeSsh: StableAutomationCatalogRef = { - authority: { kind: 'runtime', environmentId: 'env-1' }, - selector: { kind: 'ssh', targetId: 'nested' } -} -const desktopOrphan: StableAutomationCatalogRef = { - authority: { kind: 'desktop' }, - selector: { kind: 'orphan' } -} - -describe('resolveAutomationHostFilter', () => { - it('retains a desktop SSH selection until the target list hydrates', () => { - const filter = filterFor(desktopSsh('pending')) - const resolution = resolveAutomationHostFilter({ - filter, - catalog: catalogOf({ - desktop: { label: 'Local Mac', ssh: mirror({ targetsHydrated: false }) } - }) - }) - expect(resolution).toMatchObject({ status: 'loading', announceFallback: false }) - expect(resolution.effective).toBe(filter) - }) - - it('falls back and announces once desktop SSH absence is authoritative', () => { - const resolution = resolveAutomationHostFilter({ - filter: filterFor(desktopSsh('gone')), - catalog: catalogOf() - }) - expect(resolution).toEqual({ - effective: { kind: 'all' }, - entry: null, - status: 'removed', - announceFallback: true - }) - }) - - it('keeps a removed host as a ghost while automations still reference it', () => { - const host = desktopSsh('gone') - const key = hostStableKey(host) - const resolution = resolveAutomationHostFilter({ - filter: filterFor(host), - catalog: catalogOf({ - desktop: { - label: 'Local Mac', - ssh: mirror({ removedTargetLabels: new Map([['gone', 'Old box']]) }) - }, - referencedStableKeys: [key] - }), - referencedStableKeys: new Set([key]) - }) - expect(resolution.status).toBe('ghost') - expect(resolution.announceFallback).toBe(false) - expect(resolution.entry?.label).toBe('Old box') - }) - - it('retains a Runtime Self selection until the saved runtime catalog settles', () => { - const filter = filterFor(runtimeSelf) - expect( - resolveAutomationHostFilter({ filter, catalog: catalogOf({ runtimeCatalogSettled: false }) }) - .status - ).toBe('loading') - expect(resolveAutomationHostFilter({ filter, catalog: catalogOf() })).toMatchObject({ - status: 'removed', - announceFallback: true - }) - }) - - it('retains a Runtime SSH selection until that runtime bucket hydrates', () => { - const filter = filterFor(runtimeSsh) - expect( - resolveAutomationHostFilter({ - filter, - catalog: catalogOf({ runtimes: [runtime({ ssh: mirror({ targetsHydrated: false }) })] }) - }).status - ).toBe('loading') - expect( - resolveAutomationHostFilter({ filter, catalog: catalogOf({ runtimes: [runtime()] }) }) - ).toMatchObject({ status: 'removed', announceFallback: true }) - }) - - it('accepts a removal tombstone as positive evidence for a nested target', () => { - const resolution = resolveAutomationHostFilter({ - filter: filterFor(runtimeSsh), - catalog: catalogOf({ - runtimes: [ - runtime({ - ssh: mirror({ - targetsHydrated: false, - removedTargetLabels: new Map([['nested', 'Nested box']]) - }) - }) - ] - }) - }) - expect(resolution.status).toBe('removed') - expect(resolution.announceFallback).toBe(true) - }) - - it('never claims removal while the owning authority is offline', () => { - const offline = catalogOf({ - runtimes: [ - runtime({ - authorityHealth: 'unavailable', - ssh: mirror({ removedTargetLabels: new Map([['nested', 'Nested box']]) }) - }) - ] - }) - expect( - resolveAutomationHostFilter({ filter: filterFor(runtimeSsh), catalog: offline }) - ).toMatchObject({ status: 'unavailable', announceFallback: false }) - expect( - resolveAutomationHostFilter({ - filter: filterFor({ - authority: { kind: 'runtime', environmentId: 'env-1' }, - selector: { kind: 'ssh', targetId: 'never-seen' } - }), - catalog: offline - }) - ).toMatchObject({ status: 'unavailable', announceFallback: false }) - }) - - it('settles an orphan selection only on an authoritative orphan count', () => { - const filter = filterFor(desktopOrphan) - expect(resolveAutomationHostFilter({ filter, catalog: catalogOf() }).status).toBe('loading') - expect( - resolveAutomationHostFilter({ - filter, - catalog: catalogOf({ desktop: { label: 'Local Mac', ssh: mirror(), orphanCount: 2 } }) - }).status - ).toBe('ready') - expect( - resolveAutomationHostFilter({ - filter, - catalog: catalogOf({ desktop: { label: 'Local Mac', ssh: mirror(), orphanCount: 0 } }) - }) - ).toMatchObject({ status: 'removed', announceFallback: true }) - }) - - it('retains an orphan selection as unavailable while its authority is offline', () => { - const resolution = resolveAutomationHostFilter({ - filter: filterFor({ - authority: { kind: 'runtime', environmentId: 'env-1' }, - selector: { kind: 'orphan' } - }), - catalog: catalogOf({ runtimes: [runtime({ authorityHealth: 'unavailable' })] }) - }) - expect(resolution).toMatchObject({ status: 'unavailable', announceFallback: false }) - }) - - it('retains the display selection through a same-id re-pair', () => { - const filter = filterFor(runtimeSelf) - const before = resolveAutomationHostFilter({ - filter, - catalog: catalogOf({ runtimes: [runtime({ pairingRevision: 3 })] }) - }) - const after = resolveAutomationHostFilter({ - filter, - catalog: catalogOf({ runtimes: [runtime({ pairingRevision: 4 })] }) - }) - expect(after.status).toBe('ready') - expect(after.entry?.stableKey).toBe(before.entry?.stableKey) - // The display slot survives; the captured incarnation does not. - expect(after.entry?.owner).not.toEqual(before.entry?.owner) - }) -}) diff --git a/src/renderer/src/components/automations/automation-host-health.test.ts b/src/renderer/src/components/automations/automation-host-health.test.ts deleted file mode 100644 index ee3aef12e07..00000000000 --- a/src/renderer/src/components/automations/automation-host-health.test.ts +++ /dev/null @@ -1,31 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { - resolveAutomationAuthorityHealth, - resolveSelfExecutionHealth, - resolveSshExecutionHealth -} from './automation-host-health' - -describe('resolveAutomationAuthorityHealth', () => { - it('reports incompatibility ahead of every other signal', () => { - expect( - resolveAutomationAuthorityHealth({ - reachable: false, - compatible: false, - queryState: 'error', - hasData: false - }) - ).toBe('incompatible') - }) -}) - -describe('execution health', () => { - it('never borrows a status for unverified or removed registrations', () => { - expect(resolveSshExecutionHealth('removed', 'connected', 'disconnected')).toBe('unavailable') - expect(resolveSshExecutionHealth('unhydrated', 'connected', 'disconnected')).toBe('unknown') - }) - - it('treats an offline authority as disconnected, not gone', () => { - expect(resolveSelfExecutionHealth('unavailable')).toBe('disconnected') - expect(resolveSelfExecutionHealth('stale-error')).toBe('connected') - }) -}) diff --git a/src/renderer/src/components/automations/automation-host-recovery.test.ts b/src/renderer/src/components/automations/automation-host-recovery.test.ts deleted file mode 100644 index af7de46aaf4..00000000000 --- a/src/renderer/src/components/automations/automation-host-recovery.test.ts +++ /dev/null @@ -1,55 +0,0 @@ -import { describe, expect, it, vi } from 'vitest' -import type { AutomationHostCatalogEntry } from './automation-host-catalog-types' -import { - runAutomationHostRecovery, - type AutomationHostRecoveryDeps -} from './automation-host-recovery' - -function entry( - overrides: Partial & Pick -): AutomationHostCatalogEntry { - return { - owner: null, - stableKey: 'host', - label: 'Host', - authorityLabel: 'Authority', - kind: 'self', - catalogState: 'authoritative', - authorityHealth: 'fresh', - executionHealth: 'connected', - querySupport: 'scoped', - ...overrides - } -} - -function deps() { - return { - retry: vi.fn(), - connectSshTarget: vi.fn(), - connectRuntimeEnvironment: vi.fn(), - openSettings: vi.fn() - } -} - -const RUNTIME_ENVIRONMENT_ID = 'gpu' -const RUNTIME_SSH = entry({ - stableRef: { - authority: { kind: 'runtime', environmentId: RUNTIME_ENVIRONMENT_ID }, - selector: { kind: 'ssh', targetId: 't1' } - }, - kind: 'ssh' -}) - -describe('automation host recovery', () => { - it('dials the runtime first when the server itself is unreachable', () => { - const target = deps() - // Why: an unreachable server cannot be asked to dial its own SSH target. - runAutomationHostRecovery( - 'reconnect', - { ...RUNTIME_SSH, authorityHealth: 'unavailable' }, - target - ) - expect(target.connectRuntimeEnvironment).toHaveBeenCalledWith(RUNTIME_ENVIRONMENT_ID) - expect(target.connectSshTarget).not.toHaveBeenCalled() - }) -}) diff --git a/src/renderer/src/components/automations/automation-list-focus-recovery.test.ts b/src/renderer/src/components/automations/automation-list-focus-recovery.test.ts deleted file mode 100644 index 55411b3cab4..00000000000 --- a/src/renderer/src/components/automations/automation-list-focus-recovery.test.ts +++ /dev/null @@ -1,35 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { resolveAutomationListFocusRecovery } from './automation-list-focus-recovery' - -describe('automation list focus recovery', () => { - it('leaves focus alone when it was never on a row', () => { - expect( - resolveAutomationListFocusRecovery({ - previousRowKeys: ['a'], - nextRowKeys: [], - focusedRowKey: null - }) - ).toBeNull() - }) - - it('moves to the next surviving row', () => { - expect( - resolveAutomationListFocusRecovery({ - previousRowKeys: ['a', 'b', 'c'], - nextRowKeys: ['a', 'c'], - focusedRowKey: 'b' - }) - ).toEqual({ kind: 'row', rowKey: 'c' }) - }) - - it('goes to the picker when the lost row was never in this list', () => { - // A host switch replaces every row, so no neighbor here is the right one. - expect( - resolveAutomationListFocusRecovery({ - previousRowKeys: ['a', 'b'], - nextRowKeys: ['x', 'y'], - focusedRowKey: 'z' - }) - ).toEqual({ kind: 'picker' }) - }) -}) diff --git a/src/renderer/src/components/automations/automation-list-row-identity.test.ts b/src/renderer/src/components/automations/automation-list-row-identity.test.ts deleted file mode 100644 index d276371e712..00000000000 --- a/src/renderer/src/components/automations/automation-list-row-identity.test.ts +++ /dev/null @@ -1,167 +0,0 @@ -/** Follow colliding authority-local IDs from host cache through list/search joins so the last host cannot overwrite another’s row. */ - -import { describe, expect, it } from 'vitest' -import type { Automation } from '../../../../shared/automations/automation-definition' -import type { AutomationHostCacheEntry, AutomationHostRow } from './automation-host-cache-types' -import type { - AutomationHostCatalog, - AutomationHostCatalogEntry -} from './automation-host-catalog-types' -import type { AutomationHostFilterResolution } from './automation-host-filter-resolution' -import type { Repo } from '../../../../shared/repo-types' -import type { Worktree } from '../../../../shared/worktree/types' -import { resolveAutomationHostListRows } from './automation-host-list-rows' - -import { REPO_ID } from './automations-page-fixtures' -import { makeFolderWorkspace } from '../sidebar/workspace-creation/folder/folder-workspace-composer-submit-fixtures' -import { - automationFolderWorktreeForRow, - automationRepoForRow, - automationWorktreeForRow -} from './automation-list-row-identity' - -const repoMap = new Map([ - [REPO_ID, { id: REPO_ID, displayName: 'orca', path: '/src/orca' } as Repo] -]) - -const DESKTOP_SELF: AutomationHostCatalogEntry = { - stableRef: { authority: { kind: 'desktop' }, selector: { kind: 'self' } }, - owner: { authority: { kind: 'desktop' }, selector: { kind: 'self' } }, - stableKey: 'host:desktop:self', - label: 'This computer', - authorityLabel: 'This computer', - kind: 'self', - catalogState: 'authoritative', - authorityHealth: 'fresh', - executionHealth: 'connected', - querySupport: 'scoped' -} - -const RUNTIME_SSH: AutomationHostCatalogEntry = { - ...DESKTOP_SELF, - stableRef: { - authority: { kind: 'runtime', environmentId: 'gpu' }, - selector: { kind: 'ssh', targetId: 'web-01' } - }, - owner: { - authority: { kind: 'runtime', environmentId: 'gpu', pairingRevision: 4 }, - selector: { kind: 'ssh', targetId: 'web-01', targetGeneration: 2 } - }, - stableKey: 'host:runtime:gpu:ssh:web-01', - label: 'web-01', - authorityLabel: 'GPU box', - kind: 'ssh' -} - -const ALL_HOSTS: AutomationHostFilterResolution = { - effective: { kind: 'all' }, - entry: null, - status: 'all', - announceFallback: false -} - -function cached(rows: AutomationHostRow[]): AutomationHostCacheEntry { - return { - data: rows, - fetchedAt: 1, - attempt: 0, - requestGeneration: 0, - catalogGeneration: 0, - request: null, - error: null, - orphanCount: null - } -} - -function hostRow(entry: AutomationHostCatalogEntry, name: string): AutomationHostRow { - return { - automation: { - id: 'a-1', - name, - prompt: 'sweep', - projectId: REPO_ID, - workspaceMode: 'new_per_run', - baseBranch: null, - agentId: 'claude' - } as Automation, - owner: entry.owner, - selector: { kind: 'self' }, - usageSummary: null, - usageKnown: true - } -} - -/** The desktop and a runtime SSH host each holding a record called `a-1`. */ -function collidedListRows(): ReturnType { - const entries = [DESKTOP_SELF, RUNTIME_SSH] - const catalog: AutomationHostCatalog = { - entries, - byStableKey: new Map(entries.map((entry) => [entry.stableKey, entry])), - hydration: { - runtimeCatalogSettled: true, - desktopSshHydrated: true, - runtimeSshHydratedByEnvironmentId: new Map(), - savedRuntimeEnvironmentIds: new Set(), - orphanSettledAuthorityKeys: new Set(), - unavailableAuthorityKeys: new Set() - } - } - return resolveAutomationHostListRows({ - catalog, - resolution: ALL_HOSTS, - entry: (stableKey) => - cached([ - stableKey === DESKTOP_SELF.stableKey - ? hostRow(DESKTOP_SELF, 'Nightly desktop') - : hostRow(RUNTIME_SSH, 'Nightly web-01') - ]) - }) -} - -describe('automation list row identity across hosts', () => { - it('resolves colliding projects and worktrees inside each row authority', () => { - const rows = collidedListRows().rows - const repos = [ - { ...repoMap.get(REPO_ID)!, displayName: 'Desktop repo', executionHostId: 'local' as const }, - { - ...repoMap.get(REPO_ID)!, - displayName: 'Runtime repo', - executionHostId: 'runtime:gpu' as const - } - ] - const worktrees = [ - { id: 'ws-1', repoId: REPO_ID, hostId: 'local', displayName: 'Desktop workspace' }, - { - id: 'ws-1', - repoId: REPO_ID, - hostId: 'runtime:gpu', - displayName: 'Runtime workspace' - } - ] as Worktree[] - - expect(rows.map((row) => automationRepoForRow(row, repos)?.displayName)).toEqual([ - 'Desktop repo', - 'Runtime repo' - ]) - expect( - rows.map((row) => { - const repo = automationRepoForRow(row, repos) - return automationWorktreeForRow(row, { [REPO_ID]: worktrees }, repo, repos, 'ws-1') - ?.displayName - }) - ).toEqual(['Desktop workspace', 'Runtime workspace']) - }) - - it('resolves a folder workspace target inside each row authority', () => { - const rows = collidedListRows().rows - const folders = [ - makeFolderWorkspace({ id: 'fw-1', name: 'Desktop folder' }), - makeFolderWorkspace({ id: 'fw-1', name: 'Runtime folder', executionHostId: 'runtime:gpu' }) - ] - - expect( - rows.map((row) => automationFolderWorktreeForRow(row, folders, 'folder:fw-1')?.displayName) - ).toEqual(['Desktop folder', 'Runtime folder']) - expect(automationFolderWorktreeForRow(rows[0], folders, 'ws-1')).toBeUndefined() - }) -}) diff --git a/src/renderer/src/components/automations/automation-list-search.test.ts b/src/renderer/src/components/automations/automation-list-search.test.ts deleted file mode 100644 index 01550ed7dcd..00000000000 --- a/src/renderer/src/components/automations/automation-list-search.test.ts +++ /dev/null @@ -1,48 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { - AUTOMATION_LIST_SEARCH_PROMPT_MAX_CODE_UNITS, - AUTOMATION_LIST_SEARCH_QUERY_MAX_BYTES, - automationListSearchIndexMatches, - buildAutomationListSearchIndex, - clampAutomationListSearchQueryInput, - isAutomationListSearchQueryTooLarge, - resolveAutomationListSearchQuery, - truncateAutomationListSearchField -} from './automation-list-search' - -describe('automation-list-search', () => { - it('rejects queries over the byte limit but under the code-unit limit', () => { - // 3 UTF-8 bytes per character, so half the cap in code units is over it in bytes. - const multiByte = '한'.repeat(AUTOMATION_LIST_SEARCH_QUERY_MAX_BYTES / 2) - expect(multiByte.length).toBeLessThanOrEqual(AUTOMATION_LIST_SEARCH_QUERY_MAX_BYTES) - expect(isAutomationListSearchQueryTooLarge(multiByte)).toBe(true) - expect(resolveAutomationListSearchQuery(multiByte)).toEqual({ status: 'too_large' }) - }) - - it('clamps stored query input so multi-MB pastes are discarded', () => { - const hugePaste = 'a'.repeat(AUTOMATION_LIST_SEARCH_QUERY_MAX_BYTES * 100) - const clamped = clampAutomationListSearchQueryInput(hugePaste) - expect(clamped.length).toBe(AUTOMATION_LIST_SEARCH_QUERY_MAX_BYTES + 1) - expect(isAutomationListSearchQueryTooLarge(clamped)).toBe(true) - expect(clampAutomationListSearchQueryInput('auto pr')).toBe('auto pr') - }) - - it('caps indexed field length so huge prompts stay bounded', () => { - const prompt = `${'x'.repeat(AUTOMATION_LIST_SEARCH_PROMPT_MAX_CODE_UNITS)}unique-tail-token` - const index = buildAutomationListSearchIndex({ - name: 'Nightly', - project: 'mobile', - prompt - }) - expect(index.prompt.length).toBe(AUTOMATION_LIST_SEARCH_PROMPT_MAX_CODE_UNITS) - expect(automationListSearchIndexMatches(index, 'unique-tail-token')).toBe(false) - expect(automationListSearchIndexMatches(index, 'xxxx')).toBe(true) - }) - - it('does not split surrogate pairs when truncating', () => { - const emoji = '😀' - const value = `${'a'.repeat(7)}${emoji}` - expect(truncateAutomationListSearchField(value, 8)).toBe('a'.repeat(7)) - expect(truncateAutomationListSearchField(value, 9)).toBe(value) - }) -}) diff --git a/src/renderer/src/components/automations/automation-page-parts.tsx b/src/renderer/src/components/automations/automation-page-parts.tsx index 563284ee607..6019c4fe14a 100644 --- a/src/renderer/src/components/automations/automation-page-parts.tsx +++ b/src/renderer/src/components/automations/automation-page-parts.tsx @@ -3,7 +3,7 @@ import type { Badge } from '@/components/ui/badge' import { Button } from '@/components/ui/button' import { cn } from '@/lib/utils' import type { AutomationRun } from '../../../../shared/automations/history/automation-run' -import type { PendingAutomationSetupReview } from './automation-setup-review' +import type { PendingAutomationSetupReview } from './authoring/automation-setup-review' import { translate } from '@/i18n/i18n' import { useTranslate, type Translate } from '@/i18n/use-translate' import { formatUiNarrowRelativeTime } from '@/i18n/relative-time-format' diff --git a/src/renderer/src/components/automations/automation-run-context.test.ts b/src/renderer/src/components/automations/automation-run-context.test.ts deleted file mode 100644 index 32ecbf29012..00000000000 --- a/src/renderer/src/components/automations/automation-run-context.test.ts +++ /dev/null @@ -1,79 +0,0 @@ -import { describe, expect, it } from 'vitest' -import type { ProjectHostSetup } from '../../../../shared/project-types' -import type { Repo } from '../../../../shared/repo-types' -import { buildAutomationRunContextForRepo } from './automation-run-context' - -function repo(id: string, path = `/repos/${id}`, executionHostId?: Repo['executionHostId']): Repo { - return { - id, - path, - displayName: id, - badgeColor: '#000000', - addedAt: 1, - executionHostId - } -} - -function setup(overrides: Partial = {}): ProjectHostSetup { - return { - id: 'setup-builder', - projectId: 'github:stablyai/orca', - hostId: 'ssh:builder', - repoId: 'repo-builder', - path: '/remote/orca', - displayName: 'orca', - setupState: 'ready', - setupMethod: 'cloned', - createdAt: 1, - updatedAt: 1, - ...overrides - } -} - -describe('buildAutomationRunContextForRepo', () => { - it('persists logical project and host setup identity for the selected run repo', () => { - expect( - buildAutomationRunContextForRepo({ - repoId: 'repo-builder', - repos: [ - repo('repo-local', '/local/orca'), - repo('repo-builder', '/remote/orca', 'ssh:builder') - ], - projectHostSetups: [ - setup({ - id: 'setup-local', - hostId: 'local', - repoId: 'repo-local', - path: '/local/orca' - }), - setup() - ] - }) - ).toEqual({ - kind: 'workspace-run', - projectId: 'github:stablyai/orca', - hostId: 'ssh:builder', - projectHostSetupId: 'setup-builder', - repoId: 'repo-builder', - path: '/remote/orca' - }) - }) - - it('does not build a run context for missing or not-ready setups', () => { - expect( - buildAutomationRunContextForRepo({ - repoId: 'repo-builder', - repos: [repo('repo-builder')], - projectHostSetups: [setup({ hostId: 'local', setupState: 'setting-up' })] - }) - ).toBeNull() - - expect( - buildAutomationRunContextForRepo({ - repoId: 'repo-builder', - repos: [], - projectHostSetups: [setup()] - }) - ).toBeNull() - }) -}) diff --git a/src/renderer/src/components/automations/automation-run-open-target.test.ts b/src/renderer/src/components/automations/automation-run-open-target.test.ts deleted file mode 100644 index b55c3c41aa9..00000000000 --- a/src/renderer/src/components/automations/automation-run-open-target.test.ts +++ /dev/null @@ -1,179 +0,0 @@ -import { describe, expect, it } from 'vitest' -import type { AutomationRun } from '../../../../shared/automations/history/automation-run' -import { - buildAutomationRunOpenLayout, - resolveAutomationRunOpenTarget -} from './automation-run-open-target' - -const leafId = '11111111-1111-4111-8111-111111111111' -const otherLeafId = '22222222-2222-4222-8222-222222222222' -const paneKey = `tab-1:${leafId}` - -const runLeafLayout = { - root: { type: 'leaf' as const, leafId }, - activeLeafId: leafId, - expandedLeafId: null -} -const livePtyIds = ['pty-run'] -const canOpen = (args: Parameters[0]): boolean => - resolveAutomationRunOpenTarget(args) !== null - -function run(overrides: Partial = {}): AutomationRun { - return { - id: 'run-1', - automationId: 'automation-1', - title: 'Run 1', - scheduledFor: 1, - status: 'completed', - trigger: 'manual', - workspaceId: 'wt-1', - workspaceDisplayName: 'Workspace', - sessionKind: 'terminal', - chatSessionId: null, - terminalSessionId: 'tab-1', - terminalPaneKey: paneKey, - terminalPtyId: 'pty-run', - outputSnapshot: null, - precheckResult: null, - usage: null, - error: null, - startedAt: 1, - dispatchedAt: 1, - createdAt: 1, - ...overrides - } -} - -describe('automation run open target', () => { - it('rejects a layout whose run leaf is bound to another PTY', () => { - expect( - resolveAutomationRunOpenTarget({ - run: run(), - terminalTabExists: true, - currentLayout: { - ...runLeafLayout, - ptyIdsByLeafId: { [leafId]: 'pty-other' } - }, - livePtyIds - }) - ).toBeNull() - }) - - it('targets the pane a successful run slept in place, before and after it wakes', () => { - // Why: hibernation drops only the run's PTY id; the pane key still names the run's own pane. - const sleptRun = run({ terminalPtyId: null }) - const asleepLayout = { ...runLeafLayout, ptyIdsByLeafId: { [leafId]: 'pty-run' } } - const asleep = resolveAutomationRunOpenTarget({ - run: sleptRun, - terminalTabExists: true, - currentLayout: asleepLayout, - livePtyIds: [] - }) - - expect(asleep).toEqual({ tabId: 'tab-1', paneKey, leafId, ptyId: null }) - if (!asleep) { - throw new Error('Expected target.') - } - expect( - buildAutomationRunOpenLayout({ target: asleep, currentLayout: asleepLayout }).ptyIdsByLeafId - ).toBe(asleepLayout.ptyIdsByLeafId) - expect( - resolveAutomationRunOpenTarget({ - run: sleptRun, - terminalTabExists: true, - currentLayout: { ...runLeafLayout, ptyIdsByLeafId: { [leafId]: 'pty-resumed' } }, - livePtyIds: ['pty-resumed'] - }) - ).toEqual({ tabId: 'tab-1', paneKey, leafId, ptyId: 'pty-resumed' }) - expect( - canOpen({ - run: sleptRun, - terminalTabExists: false, - currentLayout: asleepLayout, - livePtyIds: [] - }) - ).toBe(false) - }) - - it('opens an existing run leaf when the layout has no PTY mapping yet', () => { - const target = resolveAutomationRunOpenTarget({ - run: run(), - terminalTabExists: true, - currentLayout: runLeafLayout, - livePtyIds - }) - - expect(target).not.toBeNull() - if (!target) { - throw new Error('Expected target.') - } - expect(buildAutomationRunOpenLayout({ target, currentLayout: runLeafLayout })).toMatchObject({ - root: { type: 'leaf', leafId }, - activeLeafId: leafId, - ptyIdsByLeafId: { [leafId]: 'pty-run' } - }) - }) - - it('does not rebuild a layout that is missing the run pane', () => { - expect( - resolveAutomationRunOpenTarget({ - run: run(), - terminalTabExists: true, - currentLayout: { - root: { type: 'leaf', leafId: otherLeafId }, - activeLeafId: otherLeafId, - expandedLeafId: null, - ptyIdsByLeafId: { [otherLeafId]: 'pty-empty-shell' } - }, - livePtyIds - }) - ).toBeNull() - }) - - it('does not open when the current tab layout is unavailable', () => { - expect( - resolveAutomationRunOpenTarget({ - run: run(), - terminalTabExists: true, - currentLayout: null, - livePtyIds - }) - ).toBeNull() - }) - - it('keeps an existing split layout when the run leaf is still present', () => { - const currentLayout = { - root: { - type: 'split' as const, - direction: 'horizontal' as const, - first: { type: 'leaf' as const, leafId }, - second: { type: 'leaf' as const, leafId: otherLeafId } - }, - activeLeafId: otherLeafId, - expandedLeafId: otherLeafId, - ptyIdsByLeafId: { [leafId]: 'pty-run', [otherLeafId]: 'pty-other' } - } - const target = resolveAutomationRunOpenTarget({ - run: run(), - terminalTabExists: true, - currentLayout, - livePtyIds - }) - - expect(target).not.toBeNull() - if (!target) { - throw new Error('Expected target.') - } - const layout = buildAutomationRunOpenLayout({ - target, - currentLayout - }) - - expect(layout).toMatchObject({ - root: expect.objectContaining({ type: 'split' }), - activeLeafId: leafId, - expandedLeafId: null, - ptyIdsByLeafId: { [leafId]: 'pty-run', [otherLeafId]: 'pty-other' } - }) - }) -}) diff --git a/src/renderer/src/components/automations/automations-page-action-context.ts b/src/renderer/src/components/automations/automations-page-action-context.ts index 7b2c1b89c0f..27d9ebb5b0d 100644 --- a/src/renderer/src/components/automations/automations-page-action-context.ts +++ b/src/renderer/src/components/automations/automations-page-action-context.ts @@ -1,11 +1,11 @@ -import type { AutomationsPageListState } from './use-automations-page-list-state' +import type { AutomationsPageListState } from './listing/use-automations-page-list-state' import type { AutomationsPageLocalState } from './use-automations-page-local-state' import type { AutomationsPagePresentationState } from './use-automations-page-presentation-state' import type { AutomationsPageRefresh } from './use-automations-page-refresh' -import type { AutomationsPageSetupState } from './use-automations-page-setup-state' +import type { AutomationsPageSetupState } from './authoring/use-automations-page-setup-state' import type { AutomationsPageStoreState } from './use-automations-page-store-state' -import type { AutomationsPageDestinationState } from './use-automations-page-destination-state' -import type { AutomationsPageDestinationFormState } from './use-automations-page-destination-form' +import type { AutomationsPageDestinationState } from './authoring/use-automations-page-destination-state' +import type { AutomationsPageDestinationFormState } from './authoring/use-automations-page-destination-form' export type AutomationsPageActionContext = { store: AutomationsPageStoreState diff --git a/src/renderer/src/components/automations/automations-page-actions-test-harness.ts b/src/renderer/src/components/automations/automations-page-actions-test-harness.ts index 70fe36d8109..cb581cd733e 100644 --- a/src/renderer/src/components/automations/automations-page-actions-test-harness.ts +++ b/src/renderer/src/components/automations/automations-page-actions-test-harness.ts @@ -17,7 +17,7 @@ import { checkRuntimeHooks, type HookCheckResult } from '@/runtime/repo-hooks/ru import { loadHostStructuredAgents } from '@/runtime/native-chat/agent-catalogs/host-structured-agents' import { getDefaultSettings } from '../../../../shared/constants' import type { Automation } from '../../../../shared/automations/automation-definition' -import type { AutomationDraft } from './AutomationEditorDialog' +import type { AutomationDraft } from './authoring/AutomationEditorDialog' import { AUTOMATION_LIST_HOST_SCOPE_RUNTIME_CAPABILITY as LIST_HOST_SCOPE, AUTOMATION_OWNER_FENCING_RUNTIME_CAPABILITY as OWNER_FENCING, diff --git a/src/renderer/src/components/automations/automations-page-child-props.test-fixture.ts b/src/renderer/src/components/automations/automations-page-child-props.test-fixture.ts index 34c91c3fe8a..7852a857b10 100644 --- a/src/renderer/src/components/automations/automations-page-child-props.test-fixture.ts +++ b/src/renderer/src/components/automations/automations-page-child-props.test-fixture.ts @@ -1,12 +1,12 @@ import type { AutomationAuthorityRef } from '../../../../shared/automations/ownership/automation-owner-ref' import type { Automation } from '../../../../shared/automations/automation-definition' import type { Worktree } from '../../../../shared/worktree/types' -import type { AutomationHostCatalogView } from './use-automation-host-catalog' -import type { AutomationCreateDestinationControl } from './use-automation-create-destination' -import type { ExternalAutomationListEntry } from './external-automation-list-entries' -import type { AutomationListRow } from './automation-list-row-identity' -import type { AutomationListViewItem } from './automation-list-view' -import type { AutomationTemplate } from './automation-templates' +import type { AutomationHostCatalogView } from './hosts/use-automation-host-catalog' +import type { AutomationCreateDestinationControl } from './authoring/use-automation-create-destination' +import type { ExternalAutomationListEntry } from './external/external-automation-list-entries' +import type { AutomationListRow } from './listing/automation-list-row-identity' +import type { AutomationListViewItem } from './listing/automation-list-view' +import type { AutomationTemplate } from './authoring/automation-templates' export type ListPanelProps = { sortedListItems: readonly AutomationListViewItem[] diff --git a/src/renderer/src/components/automations/automations-page-fixtures.ts b/src/renderer/src/components/automations/automations-page-fixtures.ts index 0c5daecf279..9b60daacd74 100644 --- a/src/renderer/src/components/automations/automations-page-fixtures.ts +++ b/src/renderer/src/components/automations/automations-page-fixtures.ts @@ -7,15 +7,18 @@ import type { } from '../../../../shared/automations/history/automation-run' import type { ExternalAutomationManager } from '../../../../shared/automations/external/external-automation' import type { ProjectHostSetup } from '../../../../shared/project-types' -import type { AutomationHostCatalogEntry } from './automation-host-catalog-types' +import type { AutomationHostCatalogEntry } from './hosts/automation-host-catalog-types' import type { AppState } from '@/store/types' import type { Repo } from '../../../../shared/repo-types' import type { Worktree } from '../../../../shared/worktree/types' import type { ExternalAutomationScope, ScopedExternalAutomationManager -} from './external-automation-scope-client' -import { automationListRowKey, type AutomationListRow } from './automation-list-row-identity' +} from './external/external-automation-scope-client' +import { + automationListRowKey, + type AutomationListRow +} from './listing/automation-list-row-identity' import { ALL_AUTOMATION_HOSTS_FILTER } from '../../../../shared/automations/ownership/automation-host-filter' import { getDefaultSettings } from '../../../../shared/constants' diff --git a/src/renderer/src/components/automations/automations-page-listed-items.ts b/src/renderer/src/components/automations/automations-page-listed-items.ts index 723d093ef38..2f64eff3037 100644 --- a/src/renderer/src/components/automations/automations-page-listed-items.ts +++ b/src/renderer/src/components/automations/automations-page-listed-items.ts @@ -1,7 +1,7 @@ /** Read authority-qualified row keys and render order from the mocked list panel, matching real clicks rather than synthesizing identity. */ -import type { AutomationListRow } from './automation-list-row-identity' -import type { ExternalAutomationListEntry } from './external-automation-list-entries' +import type { AutomationListRow } from './listing/automation-list-row-identity' +import type { ExternalAutomationListEntry } from './external/external-automation-list-entries' import { mocks } from './automations-page-test-harness' function listedItems() { diff --git a/src/renderer/src/components/automations/automations-page-test-harness.tsx b/src/renderer/src/components/automations/automations-page-test-harness.tsx index d9ee8364a0b..309adc4fed9 100644 --- a/src/renderer/src/components/automations/automations-page-test-harness.tsx +++ b/src/renderer/src/components/automations/automations-page-test-harness.tsx @@ -21,10 +21,10 @@ import { } from '../../../../shared/automations/automation-runtime-capabilities' import type { AppState } from '@/store/types' -import { AutomationDestinationField } from './AutomationDestinationField' +import { AutomationDestinationField } from './authoring/AutomationDestinationField' import { TooltipProvider } from '@/components/ui/tooltip' -import { resetAutomationCapabilityProbes } from './automation-scoped-list-client' +import { resetAutomationCapabilityProbes } from './hosts/automation-capability-probe' import { addRuntimeProject as addRuntimeProjectFixture, selfScopedList @@ -65,7 +65,7 @@ export const mocks: AutomationsPageMocks = { setPendingRunNavigation: vi.fn() } -vi.mock('@/store', () => { +vi.mock('@/store/index', () => { const useAppStore = (selector: (state: Partial) => unknown): unknown => selector(mocks.state as Partial) useAppStore.getState = (): Partial => mocks.state as Partial @@ -122,7 +122,7 @@ vi.mock('@/lib/workspace/activation/worktree-activation', () => ({ activateAndRevealWorktree: vi.fn() })) -vi.mock('./AutomationsListPanel', () => ({ +vi.mock('./listing/AutomationsListPanel', () => ({ AutomationsListPanel: (props: ListPanelProps) => { const selectAutomationRow = (rowKey: string | null): void => { props.selectAutomationRow(rowKey) @@ -164,7 +164,7 @@ vi.mock('./AutomationsListPanel', () => ({ } })) -vi.mock('./AutomationsDetailPane', () => ({ +vi.mock('./details/AutomationsDetailPane', () => ({ AutomationsDetailPane: (props: DetailPaneProps) => { mocks.detailPane = props return ( @@ -176,7 +176,7 @@ vi.mock('./AutomationsDetailPane', () => ({ } })) -vi.mock('./AutomationEditorDialog', () => ({ +vi.mock('./authoring/AutomationEditorDialog', () => ({ AutomationEditorDialog: (props: EditorDialogProps) => { mocks.editorDialog = props return ( @@ -195,7 +195,7 @@ vi.mock('./AutomationEditorDialog', () => ({ } })) -vi.mock('./AutomationDeleteDialogs', () => ({ +vi.mock('./authoring/AutomationDeleteDialogs', () => ({ AutomationDeleteDialog: (props: DeleteDialogProps) => { mocks.deleteDialog = props return null diff --git a/src/renderer/src/components/automations/AutomationDetail.tsx b/src/renderer/src/components/automations/details/AutomationDetail.tsx similarity index 94% rename from src/renderer/src/components/automations/AutomationDetail.tsx rename to src/renderer/src/components/automations/details/AutomationDetail.tsx index cb8f9f992e3..faa95e3070d 100644 --- a/src/renderer/src/components/automations/AutomationDetail.tsx +++ b/src/renderer/src/components/automations/details/AutomationDetail.tsx @@ -5,25 +5,25 @@ import { Badge } from '@/components/ui/badge' import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip' import { getAgentCatalog } from '@/lib/agent-catalog/agent-catalog' import { AgentIcon } from '@/components/agent/icons/AgentIcon' -import type { Automation } from '../../../../shared/automations/automation-definition' -import type { AutomationRun } from '../../../../shared/automations/history/automation-run' +import type { Automation } from '../../../../../shared/automations/automation-definition' +import type { AutomationRun } from '../../../../../shared/automations/history/automation-run' import { formatUiAutomationSchedule } from './automation-schedule-label' import { formatUiNarrowDuration } from '@/i18n/relative-time-format' import { AutomationRunErrorNotice, formatAutomationDateTimeWithRelative -} from './automation-page-parts' -import { indexLatestAutomationRuns } from './automation-list-last-run' -import { formatAutomationCost, formatAutomationTokens } from './automation-usage-model' -import { summarizeAutomationRunUsage } from '../../../../shared/automations/history/automation-usage-summary' -import type { AutomationTargetAvailability } from './automation-target-availability' -import type { AutomationHostCatalogEntry } from './automation-host-catalog-types' -import { getAutomationHostDetailDisplay } from './automation-host-detail-display' +} from '../automation-page-parts' +import { indexLatestAutomationRuns } from '../listing/automation-list-last-run' +import { formatAutomationCost, formatAutomationTokens } from '../runs/automation-usage-model' +import { summarizeAutomationRunUsage } from '../../../../../shared/automations/history/automation-usage-summary' +import type { AutomationTargetAvailability } from '../hosts/automation-target-availability-types' +import type { AutomationHostCatalogEntry } from '../hosts/automation-host-catalog-types' +import { getAutomationHostDetailDisplay } from '../hosts/automation-host-detail-display' import { getAutomationSourceDisplay } from './automation-source-display' import { translate } from '@/i18n/i18n' import { useIntlLocale, useTranslate, type Translate } from '@/i18n/use-translate' import { AutomationPromptDisclosure } from './AutomationPromptDisclosure' -import { automationRunErrorText } from './automation-run-error-copy' +import { automationRunErrorText } from '../runs/automation-run-error-copy' type AutomationDetailProps = { automation: Automation | null diff --git a/src/renderer/src/components/automations/AutomationPromptDisclosure.tsx b/src/renderer/src/components/automations/details/AutomationPromptDisclosure.tsx similarity index 100% rename from src/renderer/src/components/automations/AutomationPromptDisclosure.tsx rename to src/renderer/src/components/automations/details/AutomationPromptDisclosure.tsx diff --git a/src/renderer/src/components/automations/AutomationsDetailPane.tsx b/src/renderer/src/components/automations/details/AutomationsDetailPane.tsx similarity index 87% rename from src/renderer/src/components/automations/AutomationsDetailPane.tsx rename to src/renderer/src/components/automations/details/AutomationsDetailPane.tsx index fb770460a33..41cabc8235d 100644 --- a/src/renderer/src/components/automations/AutomationsDetailPane.tsx +++ b/src/renderer/src/components/automations/details/AutomationsDetailPane.tsx @@ -2,24 +2,24 @@ import React from 'react' import { ArrowLeft } from 'lucide-react' import { Button } from '@/components/ui/button' import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs' -import type { Automation } from '../../../../shared/automations/automation-definition' +import type { Automation } from '../../../../../shared/automations/automation-definition' import type { ExternalAutomationAction, ExternalAutomationJob, ExternalAutomationManager -} from '../../../../shared/automations/external/external-automation' -import type { AutomationRun } from '../../../../shared/automations/history/automation-run' -import type { Worktree } from '../../../../shared/worktree/types' +} from '../../../../../shared/automations/external/external-automation' +import type { AutomationRun } from '../../../../../shared/automations/history/automation-run' +import type { Worktree } from '../../../../../shared/worktree/types' import { AutomationDetail } from './AutomationDetail' -import { AutomationRunHistory } from './AutomationRunHistory' -import { ExternalAutomationManagers } from './ExternalAutomationManagers' -import type { ExternalAutomationListEntry } from './external-automation-list-entries' -import type { ExternalAutomationScope } from './external-automation-scope-client' -import type { AutomationActionNotice } from './automation-row-action-dispatch' -import type { AutomationHostRecoveryAction } from './automation-host-status-descriptors' -import type { AutomationHostCatalogEntry } from './automation-host-catalog-types' -import type { AutomationTargetAvailability } from './automation-target-availability' -import type { AutomationPaneTab } from './automation-page-state' +import { AutomationRunHistory } from '../runs/AutomationRunHistory' +import { ExternalAutomationManagers } from '../external/ExternalAutomationManagers' +import type { ExternalAutomationListEntry } from '../external/external-automation-list-entries' +import type { ExternalAutomationScope } from '../external/external-automation-scope-client' +import type { AutomationActionNotice } from '../hosts/automation-row-action-dispatch' +import type { AutomationHostRecoveryAction } from '../hosts/automation-host-status-descriptors' +import type { AutomationHostCatalogEntry } from '../hosts/automation-host-catalog-types' +import type { AutomationTargetAvailability } from '../hosts/automation-target-availability-types' +import type { AutomationPaneTab } from '../automation-page-state' import { getAutomationDetailNextTab, shouldHandleAutomationDetailEscapeKey, diff --git a/src/renderer/src/components/automations/automation-detail-tab-navigation.ts b/src/renderer/src/components/automations/details/automation-detail-tab-navigation.ts similarity index 97% rename from src/renderer/src/components/automations/automation-detail-tab-navigation.ts rename to src/renderer/src/components/automations/details/automation-detail-tab-navigation.ts index f9bf2c8d239..f4bfa877d43 100644 --- a/src/renderer/src/components/automations/automation-detail-tab-navigation.ts +++ b/src/renderer/src/components/automations/details/automation-detail-tab-navigation.ts @@ -1,4 +1,4 @@ -import type { AutomationPaneTab } from './automation-page-state' +import type { AutomationPaneTab } from '../automation-page-state' export type AutomationDetailTabArrowKey = 'ArrowLeft' | 'ArrowRight' diff --git a/src/renderer/src/components/automations/automation-schedule-label.ts b/src/renderer/src/components/automations/details/automation-schedule-label.ts similarity index 96% rename from src/renderer/src/components/automations/automation-schedule-label.ts rename to src/renderer/src/components/automations/details/automation-schedule-label.ts index b0808cbd018..c39b3f267a4 100644 --- a/src/renderer/src/components/automations/automation-schedule-label.ts +++ b/src/renderer/src/components/automations/details/automation-schedule-label.ts @@ -2,7 +2,7 @@ import { describeAutomationSchedule, formatAutomationScheduleTime, type AutomationScheduleDescriptor -} from '../../../../shared/automations/scheduling/automation-schedules' +} from '../../../../../shared/automations/scheduling/automation-schedules' import { translate } from '@/i18n/i18n' import type { Translate } from '@/i18n/use-translate' import { getUiWeekdayNames } from '@/i18n/weekday-names' diff --git a/src/renderer/src/components/automations/automation-source-display.ts b/src/renderer/src/components/automations/details/automation-source-display.ts similarity index 93% rename from src/renderer/src/components/automations/automation-source-display.ts rename to src/renderer/src/components/automations/details/automation-source-display.ts index b0c62fdd4d6..fdd82e1edc7 100644 --- a/src/renderer/src/components/automations/automation-source-display.ts +++ b/src/renderer/src/components/automations/details/automation-source-display.ts @@ -1,7 +1,7 @@ import { translate } from '@/i18n/i18n' import type { Translate } from '@/i18n/use-translate' -import { getExecutionHostLabel } from '../../../../shared/execution-host' -import type { TaskSourceContext } from '../../../../shared/work-items/task-source-context' +import { getExecutionHostLabel } from '../../../../../shared/execution-host' +import type { TaskSourceContext } from '../../../../../shared/work-items/task-source-context' export type AutomationSourceDisplay = { label: string diff --git a/src/renderer/src/components/automations/ExternalAutomationManagers.tsx b/src/renderer/src/components/automations/external/ExternalAutomationManagers.tsx similarity index 99% rename from src/renderer/src/components/automations/ExternalAutomationManagers.tsx rename to src/renderer/src/components/automations/external/ExternalAutomationManagers.tsx index 16d1f70dab8..9acba22517e 100644 --- a/src/renderer/src/components/automations/ExternalAutomationManagers.tsx +++ b/src/renderer/src/components/automations/external/ExternalAutomationManagers.tsx @@ -8,7 +8,7 @@ import type { ExternalAutomationAction, ExternalAutomationJob, ExternalAutomationManager -} from '../../../../shared/automations/external/external-automation' +} from '../../../../../shared/automations/external/external-automation' import type { ExternalAutomationScope, ScopedExternalAutomationManager diff --git a/src/renderer/src/components/automations/external-automation-display.ts b/src/renderer/src/components/automations/external/external-automation-display.ts similarity index 81% rename from src/renderer/src/components/automations/external-automation-display.ts rename to src/renderer/src/components/automations/external/external-automation-display.ts index 55d73755b68..d28d714f6a3 100644 --- a/src/renderer/src/components/automations/external-automation-display.ts +++ b/src/renderer/src/components/automations/external/external-automation-display.ts @@ -1,10 +1,11 @@ -import type { ExternalAutomationManager } from '../../../../shared/automations/external/external-automation' +// @protected-copy: copy consumed by destructive automation confirmations. +import type { ExternalAutomationManager } from '../../../../../shared/automations/external/external-automation' import { translate } from '@/i18n/i18n' import type { Translate } from '@/i18n/use-translate' import { formatAutomationDateTime, formatAutomationDateTimeWithRelative -} from './automation-page-parts' +} from '../automation-page-parts' export function formatExternalDate( value: string | null, diff --git a/src/renderer/src/components/automations/external-automation-list-entries.ts b/src/renderer/src/components/automations/external/external-automation-list-entries.ts similarity index 93% rename from src/renderer/src/components/automations/external-automation-list-entries.ts rename to src/renderer/src/components/automations/external/external-automation-list-entries.ts index 18100f8a173..1757432c632 100644 --- a/src/renderer/src/components/automations/external-automation-list-entries.ts +++ b/src/renderer/src/components/automations/external/external-automation-list-entries.ts @@ -1,7 +1,7 @@ import type { ExternalAutomationJob, ExternalAutomationManager -} from '../../../../shared/automations/external/external-automation' +} from '../../../../../shared/automations/external/external-automation' import type { ExternalAutomationScope, ScopedExternalAutomationManager diff --git a/src/renderer/src/components/automations/external-automation-schedule-display.ts b/src/renderer/src/components/automations/external/external-automation-schedule-display.ts similarity index 78% rename from src/renderer/src/components/automations/external-automation-schedule-display.ts rename to src/renderer/src/components/automations/external/external-automation-schedule-display.ts index 02f7a79000c..9bef0ebcfd8 100644 --- a/src/renderer/src/components/automations/external-automation-schedule-display.ts +++ b/src/renderer/src/components/automations/external/external-automation-schedule-display.ts @@ -1,9 +1,10 @@ +// @protected-copy: copy consumed by destructive automation confirmations. import type { ExternalAutomationJob, ExternalAutomationManager -} from '../../../../shared/automations/external/external-automation' -import { isRunnableAutomationCronSchedule } from '../../../../shared/automations/scheduling/automation-schedule-parsing' -import { formatUiAutomationSchedule } from './automation-schedule-label' +} from '../../../../../shared/automations/external/external-automation' +import { isRunnableAutomationCronSchedule } from '../../../../../shared/automations/scheduling/automation-schedule-parsing' +import { formatUiAutomationSchedule } from '../details/automation-schedule-label' import { translate } from '@/i18n/i18n' import type { Translate } from '@/i18n/use-translate' diff --git a/src/renderer/src/components/automations/external-automation-scope-client.ts b/src/renderer/src/components/automations/external/external-automation-scope-client.ts similarity index 89% rename from src/renderer/src/components/automations/external-automation-scope-client.ts rename to src/renderer/src/components/automations/external/external-automation-scope-client.ts index d2d3db21c67..b98661be8b2 100644 --- a/src/renderer/src/components/automations/external-automation-scope-client.ts +++ b/src/renderer/src/components/automations/external/external-automation-scope-client.ts @@ -4,10 +4,10 @@ import type { ExternalAutomationAction, ExternalAutomationManager, ExternalAutomationProvider -} from '../../../../shared/automations/external/external-automation' -import type { AutomationOwnerRef } from '../../../../shared/automations/ownership/automation-owner-ref' -import { EXTERNAL_AUTOMATION_PROVIDERS } from '../../../../shared/external-automation-scope' -import type { AutomationHostCatalogEntry } from './automation-host-catalog-types' +} from '../../../../../shared/automations/external/external-automation' +import type { AutomationOwnerRef } from '../../../../../shared/automations/ownership/automation-owner-ref' +import { EXTERNAL_AUTOMATION_PROVIDERS } from '../../../../../shared/external-automation-scope' +import type { AutomationHostCatalogEntry } from '../hosts/automation-host-catalog-types' import { resolveExternalAutomationScopeGate } from './external-automation-scope-gating' export type ExternalAutomationScope = { diff --git a/src/renderer/src/components/automations/external-automation-scope-gating.test.ts b/src/renderer/src/components/automations/external/external-automation-scope-gating.test.ts similarity index 69% rename from src/renderer/src/components/automations/external-automation-scope-gating.test.ts rename to src/renderer/src/components/automations/external/external-automation-scope-gating.test.ts index 6060de28186..dbb45ed5d28 100644 --- a/src/renderer/src/components/automations/external-automation-scope-gating.test.ts +++ b/src/renderer/src/components/automations/external/external-automation-scope-gating.test.ts @@ -1,9 +1,6 @@ import { describe, expect, it } from 'vitest' -import { - EXTERNAL_AUTOMATION_SCOPE_CODES, - ExternalAutomationScopeError -} from '../../../../shared/external-automation-scope' -import type { AutomationHostCatalogEntry } from './automation-host-catalog-types' + +import type { AutomationHostCatalogEntry } from '../hosts/automation-host-catalog-types' import { externalAutomationProbeOwners, externalAutomationScopeGateFromError, @@ -46,19 +43,6 @@ describe('external automation scope gating', () => { }) describe('engine scope errors', () => { - it('reads the code the engine appends to its message', () => { - const hidden = new ExternalAutomationScopeError(EXTERNAL_AUTOMATION_SCOPE_CODES.targetHidden) - expect(parseExternalAutomationScopeCode(hidden)).toBe( - EXTERNAL_AUTOMATION_SCOPE_CODES.targetHidden - ) - // Electron rewraps the message; the trailing token still terminates it. - expect( - parseExternalAutomationScopeCode( - new Error(`Error invoking remote method 'x': ${hidden.message}`) - ) - ).toBe(EXTERNAL_AUTOMATION_SCOPE_CODES.targetHidden) - }) - it('leaves unrelated failures alone so they are not relabelled as scope limits', () => { expect(externalAutomationScopeGateFromError(new Error('socket hang up'))).toBeNull() expect(parseExternalAutomationScopeCode(null)).toBeNull() diff --git a/src/renderer/src/components/automations/external-automation-scope-gating.ts b/src/renderer/src/components/automations/external/external-automation-scope-gating.ts similarity index 89% rename from src/renderer/src/components/automations/external-automation-scope-gating.ts rename to src/renderer/src/components/automations/external/external-automation-scope-gating.ts index 03b747a91d9..300b86aa86a 100644 --- a/src/renderer/src/components/automations/external-automation-scope-gating.ts +++ b/src/renderer/src/components/automations/external/external-automation-scope-gating.ts @@ -3,10 +3,10 @@ import { EXTERNAL_AUTOMATION_SCOPE_CODES, type ExternalAutomationScopeCode -} from '../../../../shared/external-automation-scope' -import type { AutomationOwnerRef } from '../../../../shared/automations/ownership/automation-owner-ref' -import type { AutomationHostCatalogEntry } from './automation-host-catalog-types' -import type { AutomationHostFilterResolution } from './automation-host-filter-resolution' +} from '../../../../../shared/external-automation-scope' +import type { AutomationOwnerRef } from '../../../../../shared/automations/ownership/automation-owner-ref' +import type { AutomationHostCatalogEntry } from '../hosts/automation-host-catalog-types' +import type { AutomationHostFilterResolution } from '../hosts/automation-host-filter-resolution' export type ExternalAutomationScopeStatus = 'listed' | 'not-listed' | 'unknown' diff --git a/src/renderer/src/components/automations/external-automation-scope-keys.ts b/src/renderer/src/components/automations/external/external-automation-scope-keys.ts similarity index 83% rename from src/renderer/src/components/automations/external-automation-scope-keys.ts rename to src/renderer/src/components/automations/external/external-automation-scope-keys.ts index 842cd71e9db..17bb63e3ee7 100644 --- a/src/renderer/src/components/automations/external-automation-scope-keys.ts +++ b/src/renderer/src/components/automations/external/external-automation-scope-keys.ts @@ -1,11 +1,11 @@ /** Qualify external row/job/action keys by kind, captured owner and provider; manager IDs alone collide across hosts. */ -import { ownerKey } from '../../../../shared/automations/ownership/automation-owner-key' -import type { AutomationOwnerRef } from '../../../../shared/automations/ownership/automation-owner-ref' +import { ownerKey } from '../../../../../shared/automations/ownership/automation-owner-key' +import type { AutomationOwnerRef } from '../../../../../shared/automations/ownership/automation-owner-ref' import type { ExternalAutomationAction, ExternalAutomationProvider -} from '../../../../shared/automations/external/external-automation' +} from '../../../../../shared/automations/external/external-automation' const SEPARATOR = '|' diff --git a/src/renderer/src/components/automations/external-automation-source-availability.ts b/src/renderer/src/components/automations/external/external-automation-source-availability.ts similarity index 91% rename from src/renderer/src/components/automations/external-automation-source-availability.ts rename to src/renderer/src/components/automations/external/external-automation-source-availability.ts index 27ea88d0bd3..5fc3717b0f9 100644 --- a/src/renderer/src/components/automations/external-automation-source-availability.ts +++ b/src/renderer/src/components/automations/external/external-automation-source-availability.ts @@ -1,5 +1,5 @@ -import type { ExternalAutomationManager } from '../../../../shared/automations/external/external-automation' -import type { SshConnectionStatus } from '../../../../shared/ssh-types' +import type { ExternalAutomationManager } from '../../../../../shared/automations/external/external-automation' +import type { SshConnectionStatus } from '../../../../../shared/ssh-types' import { isConnectingSshStatus } from '@/ssh/ssh-connection-recoverability' import { translate } from '@/i18n/i18n' import type { Translate } from '@/i18n/use-translate' diff --git a/src/renderer/src/components/automations/external-automation-unchecked-hosts.ts b/src/renderer/src/components/automations/external/external-automation-unchecked-hosts.ts similarity index 91% rename from src/renderer/src/components/automations/external-automation-unchecked-hosts.ts rename to src/renderer/src/components/automations/external/external-automation-unchecked-hosts.ts index a555fbdb0a8..eda7929bd26 100644 --- a/src/renderer/src/components/automations/external-automation-unchecked-hosts.ts +++ b/src/renderer/src/components/automations/external/external-automation-unchecked-hosts.ts @@ -2,8 +2,8 @@ import { translate } from '@/i18n/i18n' import type { Translate } from '@/i18n/use-translate' -import { ownerKey } from '../../../../shared/automations/ownership/automation-owner-key' -import type { AutomationHostCatalogEntry } from './automation-host-catalog-types' +import { ownerKey } from '../../../../../shared/automations/ownership/automation-owner-key' +import type { AutomationHostCatalogEntry } from '../hosts/automation-host-catalog-types' import type { ScopedExternalAutomationFailure } from './external-automation-scope-client' export function externalAutomationUncheckedHostLabels( diff --git a/src/renderer/src/components/automations/use-external-automation-actions.ts b/src/renderer/src/components/automations/external/use-external-automation-actions.ts similarity index 92% rename from src/renderer/src/components/automations/use-external-automation-actions.ts rename to src/renderer/src/components/automations/external/use-external-automation-actions.ts index 1f67bf7d97b..3da957d4bb7 100644 --- a/src/renderer/src/components/automations/use-external-automation-actions.ts +++ b/src/renderer/src/components/automations/external/use-external-automation-actions.ts @@ -1,18 +1,18 @@ import { toast } from 'sonner' -import type { AutomationRun } from '../../../../shared/automations/history/automation-run' +import type { AutomationRun } from '../../../../../shared/automations/history/automation-run' import type { ExternalAutomationAction, ExternalAutomationJob, ExternalAutomationManager -} from '../../../../shared/automations/external/external-automation' +} from '../../../../../shared/automations/external/external-automation' import { translate } from '@/i18n/i18n' -import { useAppStore } from '@/store' +import { useAppStore } from '@/store/index' import { externalAutomationActionKey, externalAutomationJobKey } from './external-automation-scope-keys' import type { ExternalAutomationScope } from './external-automation-scope-client' -import type { AutomationsPageActionContext } from './automations-page-action-context' +import type { AutomationsPageActionContext } from '../automations-page-action-context' /** External manager actions always carry the scope that produced their row. */ export function useExternalAutomationActions({ diff --git a/src/renderer/src/components/automations/use-external-automation-scope-retention.ts b/src/renderer/src/components/automations/external/use-external-automation-scope-retention.ts similarity index 84% rename from src/renderer/src/components/automations/use-external-automation-scope-retention.ts rename to src/renderer/src/components/automations/external/use-external-automation-scope-retention.ts index 22d888f6804..1d2fc4fad82 100644 --- a/src/renderer/src/components/automations/use-external-automation-scope-retention.ts +++ b/src/renderer/src/components/automations/external/use-external-automation-scope-retention.ts @@ -1,7 +1,7 @@ import { useEffect, useMemo, useRef } from 'react' -import { ownerKey } from '../../../../shared/automations/ownership/automation-owner-key' +import { ownerKey } from '../../../../../shared/automations/ownership/automation-owner-key' import { externalAutomationProbeOwners } from './external-automation-scope-gating' -import type { AutomationHostCatalogEntry } from './automation-host-catalog-types' +import type { AutomationHostCatalogEntry } from '../hosts/automation-host-catalog-types' /** Retain probes only for visible hosts; cancel filtered/page-exit work so stale results cannot compete with requested Orca traffic. */ export function useExternalAutomationScopeRetention( diff --git a/src/renderer/src/components/automations/use-scoped-external-automations.ts b/src/renderer/src/components/automations/external/use-scoped-external-automations.ts similarity index 94% rename from src/renderer/src/components/automations/use-scoped-external-automations.ts rename to src/renderer/src/components/automations/external/use-scoped-external-automations.ts index 6cf31a8de2c..4bebb5cfa02 100644 --- a/src/renderer/src/components/automations/use-scoped-external-automations.ts +++ b/src/renderer/src/components/automations/external/use-scoped-external-automations.ts @@ -1,6 +1,6 @@ import { useCallback, useEffect, useMemo, useRef, useState } from 'react' -import type { ExternalAutomationAction } from '../../../../shared/automations/external/external-automation' -import type { AutomationHostCatalogEntry } from './automation-host-catalog-types' +import type { ExternalAutomationAction } from '../../../../../shared/automations/external/external-automation' +import type { AutomationHostCatalogEntry } from '../hosts/automation-host-catalog-types' import { externalAutomationScopes, listScopedExternalAutomationManagers, diff --git a/src/renderer/src/components/automations/AutomationHostBadges.tsx b/src/renderer/src/components/automations/hosts/AutomationHostBadges.tsx similarity index 100% rename from src/renderer/src/components/automations/AutomationHostBadges.tsx rename to src/renderer/src/components/automations/hosts/AutomationHostBadges.tsx diff --git a/src/renderer/src/components/automations/AutomationHostFilterNotice.tsx b/src/renderer/src/components/automations/hosts/AutomationHostFilterNotice.tsx similarity index 100% rename from src/renderer/src/components/automations/AutomationHostFilterNotice.tsx rename to src/renderer/src/components/automations/hosts/AutomationHostFilterNotice.tsx diff --git a/src/renderer/src/components/automations/AutomationOwnerConflictNotice.tsx b/src/renderer/src/components/automations/hosts/AutomationOwnerConflictNotice.tsx similarity index 100% rename from src/renderer/src/components/automations/AutomationOwnerConflictNotice.tsx rename to src/renderer/src/components/automations/hosts/AutomationOwnerConflictNotice.tsx diff --git a/src/renderer/src/components/automations/automation-authority-identity.ts b/src/renderer/src/components/automations/hosts/automation-authority-identity.ts similarity index 91% rename from src/renderer/src/components/automations/automation-authority-identity.ts rename to src/renderer/src/components/automations/hosts/automation-authority-identity.ts index 5453709217a..c6a39690f73 100644 --- a/src/renderer/src/components/automations/automation-authority-identity.ts +++ b/src/renderer/src/components/automations/hosts/automation-authority-identity.ts @@ -1,14 +1,14 @@ /** Read live pairing revisions/repo tables at use time; cached values can fence against a re-paired authority or a project that moved hosts. */ -import type { Repo } from '../../../../shared/repo-types' -import type { LegacyAutomationPartitionContext } from '../../../../shared/automations/ownership/automation-legacy-list-partition' -import type { StableAutomationAuthorityRef } from '../../../../shared/automations/ownership/automation-owner-ref' +import type { Repo } from '../../../../../shared/repo-types' +import type { LegacyAutomationPartitionContext } from '../../../../../shared/automations/ownership/automation-legacy-list-partition' +import type { StableAutomationAuthorityRef } from '../../../../../shared/automations/ownership/automation-owner-ref' import { automationAuthorityCatalogKey } from './automation-host-catalog-types' import { getRepoExecutionHostId, getRepoSshConnectionId, parseExecutionHostId -} from '../../../../shared/execution-host' +} from '../../../../../shared/execution-host' type RepoConnection = Pick diff --git a/src/renderer/src/components/automations/automation-capability-probe.ts b/src/renderer/src/components/automations/hosts/automation-capability-probe.ts similarity index 92% rename from src/renderer/src/components/automations/automation-capability-probe.ts rename to src/renderer/src/components/automations/hosts/automation-capability-probe.ts index 43350f0f710..a2a5c345482 100644 --- a/src/renderer/src/components/automations/automation-capability-probe.ts +++ b/src/renderer/src/components/automations/hosts/automation-capability-probe.ts @@ -1,24 +1,22 @@ import type { AutomationCreateInput, AutomationUpdateInput -} from '../../../../shared/automations/automation-definition' +} from '../../../../../shared/automations/automation-definition' import { AUTOMATION_LAUNCH_SETUP_RUNTIME_CAPABILITY, AUTOMATION_SURFACE_RUNTIME_CAPABILITY, - AUTOMATION_LIST_HOST_SCOPE_RUNTIME_CAPABILITY, - AUTOMATION_LIST_HOST_SCOPE_UPDATE_REQUIRED_MESSAGE, AUTOMATION_OWNER_FENCING_RUNTIME_CAPABILITY, AUTOMATION_OWNER_FENCING_UPDATE_REQUIRED_MESSAGE, AUTOMATION_CREATE_IDEMPOTENCY_RUNTIME_CAPABILITY, AUTOMATION_EXTRA_AGENT_ARGS_RUNTIME_CAPABILITY -} from '../../../../shared/automations/automation-runtime-capabilities' +} from '../../../../../shared/automations/automation-runtime-capabilities' import { getRuntimeEnvironmentStatus } from '@/runtime/rpc/compatibility/runtime-compatibility-probe' -import type { AutomationAuthorityRef } from '../../../../shared/automations/ownership/automation-owner-ref' -import type { RuntimeCapability } from '../../../../shared/protocol-version' +import type { AutomationAuthorityRef } from '../../../../../shared/automations/ownership/automation-owner-ref' +import type { RuntimeCapability } from '../../../../../shared/protocol-version' import { EXTRA_AGENT_ARGS_HOST_UPDATE_REQUIRED, hasExtraAgentArgs -} from '../../../../shared/agent-launch/startup/automation-extra-agent-args' +} from '../../../../../shared/agent-launch/startup/automation-extra-agent-args' import { automationAuthorityCatalogKey } from './automation-host-catalog-types' import { automationHostDiagnostics } from './automation-host-diagnostics' import { translate } from '@/i18n/i18n' @@ -191,12 +189,6 @@ export async function assertEnvironmentSupportsExtraAgentArgs( } } -export { - AUTOMATION_LIST_HOST_SCOPE_RUNTIME_CAPABILITY, - AUTOMATION_LIST_HOST_SCOPE_UPDATE_REQUIRED_MESSAGE, - AUTOMATION_CREATE_IDEMPOTENCY_RUNTIME_CAPABILITY -} - /** Old hosts keep their terminal contract; an explicit chat must refuse before a move creates anything. */ export async function prepareAutomationLaunchSetup< T extends AutomationCreateInput | AutomationUpdateInput diff --git a/src/renderer/src/components/automations/automation-captured-owner.test.ts b/src/renderer/src/components/automations/hosts/automation-captured-owner.test.ts similarity index 100% rename from src/renderer/src/components/automations/automation-captured-owner.test.ts rename to src/renderer/src/components/automations/hosts/automation-captured-owner.test.ts diff --git a/src/renderer/src/components/automations/automation-captured-owner.ts b/src/renderer/src/components/automations/hosts/automation-captured-owner.ts similarity index 92% rename from src/renderer/src/components/automations/automation-captured-owner.ts rename to src/renderer/src/components/automations/hosts/automation-captured-owner.ts index d7de9f229f0..d804dc626ac 100644 --- a/src/renderer/src/components/automations/automation-captured-owner.ts +++ b/src/renderer/src/components/automations/hosts/automation-captured-owner.ts @@ -1,13 +1,13 @@ /** Carry the listed owner into actions so a host move fences against the incarnation the user saw. Owned rows act normally, orphans allow pause/delete/history but cannot execute, and unfenced legacy rows stay view-only. */ -import { AUTOMATION_CAPTURED_HOST_REFUSALS } from '../../../../shared/automations/ownership/automation-owner-conflict' -import { AUTOMATION_ORPHAN_ISSUES } from '../../../../shared/automations/ownership/automation-list-scope' +import { AUTOMATION_CAPTURED_HOST_REFUSALS } from '../../../../../shared/automations/ownership/automation-owner-conflict' +import { AUTOMATION_ORPHAN_ISSUES } from '../../../../../shared/automations/ownership/automation-list-scope' import type { AutomationAuthorityRef, AutomationOwnerRef -} from '../../../../shared/automations/ownership/automation-owner-ref' -import { ownerKey } from '../../../../shared/automations/ownership/automation-owner-key' -import type { AutomationOwnerPrecondition } from '../../../../shared/automations/ownership/automation-owner-precondition' +} from '../../../../../shared/automations/ownership/automation-owner-ref' +import { ownerKey } from '../../../../../shared/automations/ownership/automation-owner-key' +import type { AutomationOwnerPrecondition } from '../../../../../shared/automations/ownership/automation-owner-precondition' import { translate } from '@/i18n/i18n' import type { Translate } from '@/i18n/use-translate' import type { AutomationHostRow, AutomationHostRowSelector } from './automation-host-cache-types' diff --git a/src/renderer/src/components/automations/automation-host-cache-controller.ts b/src/renderer/src/components/automations/hosts/automation-host-cache-controller.ts similarity index 98% rename from src/renderer/src/components/automations/automation-host-cache-controller.ts rename to src/renderer/src/components/automations/hosts/automation-host-cache-controller.ts index 35541c084a1..80d167157bf 100644 --- a/src/renderer/src/components/automations/automation-host-cache-controller.ts +++ b/src/renderer/src/components/automations/hosts/automation-host-cache-controller.ts @@ -1,11 +1,11 @@ /** Apply catalog membership/incarnation generations before fetching, discard stale work and evict missing entries. Background All-hosts refresh preserves unreachable authorities without dialing them. */ import { getRuntimeEnvironmentRevision } from '@/runtime/rpc/environment-revisions/runtime-environment-revision' -import type { LegacyAutomationPartitionContext } from '../../../../shared/automations/ownership/automation-legacy-list-partition' +import type { LegacyAutomationPartitionContext } from '../../../../../shared/automations/ownership/automation-legacy-list-partition' import type { AutomationAuthorityRef, StableAutomationAuthorityRef -} from '../../../../shared/automations/ownership/automation-owner-ref' +} from '../../../../../shared/automations/ownership/automation-owner-ref' import { syncAutomationHostCatalogGenerations } from './automation-host-catalog-generation' import type { AutomationHostCatalog, diff --git a/src/renderer/src/components/automations/automation-host-cache-error.ts b/src/renderer/src/components/automations/hosts/automation-host-cache-error.ts similarity index 90% rename from src/renderer/src/components/automations/automation-host-cache-error.ts rename to src/renderer/src/components/automations/hosts/automation-host-cache-error.ts index c0f0be1a0b2..e4cda8def2a 100644 --- a/src/renderer/src/components/automations/automation-host-cache-error.ts +++ b/src/renderer/src/components/automations/hosts/automation-host-cache-error.ts @@ -1,15 +1,13 @@ /** Classify by error code: contract/owner failures do not spend retry budget; unreachable or slow hosts do. */ -import { hasRuntimeRpcErrorCode } from '../../../../shared/runtime-rpc-error-code' +import { hasRuntimeRpcErrorCode } from '../../../../../shared/runtime-rpc-error-code' import { AUTOMATION_OWNER_CONFLICT_CODES, matchAutomationOwnerConflict, stripAutomationOwnerConflictCode -} from '../../../../shared/automations/ownership/automation-owner-conflict' -import { - AutomationHostScopeUnsupportedError, - AutomationListResponseError -} from './automation-scoped-list-client' +} from '../../../../../shared/automations/ownership/automation-owner-conflict' +import { AutomationHostScopeUnsupportedError } from './automation-capability-probe' +import { AutomationListResponseError } from './automation-scoped-list-client' import type { AutomationHostQueryError, AutomationHostQueryErrorCode diff --git a/src/renderer/src/components/automations/automation-host-cache-health.ts b/src/renderer/src/components/automations/hosts/automation-host-cache-health.ts similarity index 100% rename from src/renderer/src/components/automations/automation-host-cache-health.ts rename to src/renderer/src/components/automations/hosts/automation-host-cache-health.ts diff --git a/src/renderer/src/components/automations/automation-host-cache-rows.ts b/src/renderer/src/components/automations/hosts/automation-host-cache-rows.ts similarity index 89% rename from src/renderer/src/components/automations/automation-host-cache-rows.ts rename to src/renderer/src/components/automations/hosts/automation-host-cache-rows.ts index 643202c371c..f4c63e9273e 100644 --- a/src/renderer/src/components/automations/automation-host-cache-rows.ts +++ b/src/renderer/src/components/automations/hosts/automation-host-cache-rows.ts @@ -1,17 +1,17 @@ /** Scoped rows retain their captured owner for later fences. Legacy responses prove neither owner nor usage; never compensate with run-history downloads. */ -import type { Automation } from '../../../../shared/automations/automation-definition' -import type { AutomationListItem } from '../../../../shared/automations/ownership/automation-list-scope' +import type { Automation } from '../../../../../shared/automations/automation-definition' +import type { AutomationListItem } from '../../../../../shared/automations/ownership/automation-list-scope' import { partitionLegacyAutomationList, type LegacyAutomationPartitionContext, type LegacyAutomationSelector -} from '../../../../shared/automations/ownership/automation-legacy-list-partition' +} from '../../../../../shared/automations/ownership/automation-legacy-list-partition' import type { AutomationAuthorityRef, AutomationOwnerRef, StableAutomationCatalogRef -} from '../../../../shared/automations/ownership/automation-owner-ref' +} from '../../../../../shared/automations/ownership/automation-owner-ref' import type { ScopedAutomationList } from './automation-scoped-list-client' import type { AutomationHostRow } from './automation-host-cache-types' diff --git a/src/renderer/src/components/automations/automation-host-cache-types.ts b/src/renderer/src/components/automations/hosts/automation-host-cache-types.ts similarity index 81% rename from src/renderer/src/components/automations/automation-host-cache-types.ts rename to src/renderer/src/components/automations/hosts/automation-host-cache-types.ts index 2b49f0aa0ad..9acef78e5dd 100644 --- a/src/renderer/src/components/automations/automation-host-cache-types.ts +++ b/src/renderer/src/components/automations/hosts/automation-host-cache-types.ts @@ -1,13 +1,13 @@ /** Rows retain captured owners, null when unqualified; requests retain all three generations required by their commit fence. */ -import type { Automation } from '../../../../shared/automations/automation-definition' -import type { AutomationListItemSelector } from '../../../../shared/automations/ownership/automation-list-scope' -import type { LegacyAutomationSelector } from '../../../../shared/automations/ownership/automation-legacy-list-partition' +import type { Automation } from '../../../../../shared/automations/automation-definition' +import type { AutomationListItemSelector } from '../../../../../shared/automations/ownership/automation-list-scope' +import type { LegacyAutomationSelector } from '../../../../../shared/automations/ownership/automation-legacy-list-partition' import type { AutomationAuthorityRef, AutomationOwnerRef -} from '../../../../shared/automations/ownership/automation-owner-ref' -import type { AutomationUsageSummary } from '../../../../shared/automations/history/automation-usage-summary' +} from '../../../../../shared/automations/ownership/automation-owner-ref' +import type { AutomationUsageSummary } from '../../../../../shared/automations/history/automation-usage-summary' /** A legacy SSH row carries no registration generation, which is why it can never be fenced. */ export type AutomationHostRowSelector = AutomationListItemSelector | LegacyAutomationSelector diff --git a/src/renderer/src/components/automations/automation-host-cache.test.ts b/src/renderer/src/components/automations/hosts/automation-host-cache.test.ts similarity index 94% rename from src/renderer/src/components/automations/automation-host-cache.test.ts rename to src/renderer/src/components/automations/hosts/automation-host-cache.test.ts index fd6870a6d42..5ad2c8280b5 100644 --- a/src/renderer/src/components/automations/automation-host-cache.test.ts +++ b/src/renderer/src/components/automations/hosts/automation-host-cache.test.ts @@ -1,12 +1,12 @@ /** A formerly correct answer can arrive after host replacement; the commit fence must reject it instead of misattributing automations. */ import { describe, expect, it } from 'vitest' -import type { Automation } from '../../../../shared/automations/automation-definition' -import { hostStableKey } from '../../../../shared/automations/ownership/automation-owner-key' +import type { Automation } from '../../../../../shared/automations/automation-definition' +import { hostStableKey } from '../../../../../shared/automations/ownership/automation-owner-key' import type { StableAutomationAuthorityRef, StableAutomationCatalogRef -} from '../../../../shared/automations/ownership/automation-owner-ref' +} from '../../../../../shared/automations/ownership/automation-owner-ref' import { createAutomationHostCache } from './automation-host-cache' import type { AutomationHostRow } from './automation-host-cache-types' diff --git a/src/renderer/src/components/automations/automation-host-cache.ts b/src/renderer/src/components/automations/hosts/automation-host-cache.ts similarity index 98% rename from src/renderer/src/components/automations/automation-host-cache.ts rename to src/renderer/src/components/automations/hosts/automation-host-cache.ts index 80bed279cd2..edf9ff5aafb 100644 --- a/src/renderer/src/components/automations/automation-host-cache.ts +++ b/src/renderer/src/components/automations/hosts/automation-host-cache.ts @@ -1,11 +1,11 @@ /** Commit only while request, authority-catalog and connection generations match. This rejects stale answers after re-pair, re-registration or host changes; removal tombstones advance the same catalog fence. */ import { getRuntimeEnvironmentRevision } from '@/runtime/rpc/environment-revisions/runtime-environment-revision' -import { hostStableKey } from '../../../../shared/automations/ownership/automation-owner-key' +import { hostStableKey } from '../../../../../shared/automations/ownership/automation-owner-key' import type { StableAutomationAuthorityRef, StableAutomationCatalogRef -} from '../../../../shared/automations/ownership/automation-owner-ref' +} from '../../../../../shared/automations/ownership/automation-owner-ref' import { automationAuthorityCatalogKey } from './automation-host-catalog-types' import { getAuthorityCatalogGeneration } from './automation-host-catalog-generation' import { diff --git a/src/renderer/src/components/automations/automation-host-catalog-generation.ts b/src/renderer/src/components/automations/hosts/automation-host-catalog-generation.ts similarity index 96% rename from src/renderer/src/components/automations/automation-host-catalog-generation.ts rename to src/renderer/src/components/automations/hosts/automation-host-catalog-generation.ts index 89dfb296c72..5fb7d46cf54 100644 --- a/src/renderer/src/components/automations/automation-host-catalog-generation.ts +++ b/src/renderer/src/components/automations/hosts/automation-host-catalog-generation.ts @@ -1,5 +1,5 @@ -import { ownerKey } from '../../../../shared/automations/ownership/automation-owner-key' -import type { StableAutomationAuthorityRef } from '../../../../shared/automations/ownership/automation-owner-ref' +import { ownerKey } from '../../../../../shared/automations/ownership/automation-owner-key' +import type { StableAutomationAuthorityRef } from '../../../../../shared/automations/ownership/automation-owner-ref' import { automationAuthorityCatalogKey, type AutomationHostCatalog, diff --git a/src/renderer/src/components/automations/automation-host-catalog-order.ts b/src/renderer/src/components/automations/hosts/automation-host-catalog-order.ts similarity index 100% rename from src/renderer/src/components/automations/automation-host-catalog-order.ts rename to src/renderer/src/components/automations/hosts/automation-host-catalog-order.ts diff --git a/src/renderer/src/components/automations/automation-host-catalog-source.ts b/src/renderer/src/components/automations/hosts/automation-host-catalog-source.ts similarity index 92% rename from src/renderer/src/components/automations/automation-host-catalog-source.ts rename to src/renderer/src/components/automations/hosts/automation-host-catalog-source.ts index 8f551e83044..bfd8fe113a8 100644 --- a/src/renderer/src/components/automations/automation-host-catalog-source.ts +++ b/src/renderer/src/components/automations/hosts/automation-host-catalog-source.ts @@ -1,10 +1,10 @@ /** Build catalog input only from mirrored store state. Fold query results into the separate health projection so cache commits cannot trigger generation changes/cancellation. */ -import { getLocalExecutionHostLabel } from '../../../../shared/execution-host' -import { AUTOMATION_LIST_HOST_SCOPE_RUNTIME_CAPABILITY } from '../../../../shared/automations/automation-runtime-capabilities' -import type { RuntimeStatus } from '../../../../shared/runtime-session-contracts' -import type { SshConnectionStatus } from '../../../../shared/ssh-types' -import type { StableAutomationAuthorityRef } from '../../../../shared/automations/ownership/automation-owner-ref' +import { getLocalExecutionHostLabel } from '../../../../../shared/execution-host' +import { AUTOMATION_LIST_HOST_SCOPE_RUNTIME_CAPABILITY } from '../../../../../shared/automations/automation-runtime-capabilities' +import type { RuntimeStatus } from '../../../../../shared/runtime-session-contracts' +import type { SshConnectionStatus } from '../../../../../shared/ssh-types' +import type { StableAutomationAuthorityRef } from '../../../../../shared/automations/ownership/automation-owner-ref' import type { AutomationAuthorityHealth, AutomationCatalogSshMirrorInput, diff --git a/src/renderer/src/components/automations/automation-host-catalog-types.ts b/src/renderer/src/components/automations/hosts/automation-host-catalog-types.ts similarity index 97% rename from src/renderer/src/components/automations/automation-host-catalog-types.ts rename to src/renderer/src/components/automations/hosts/automation-host-catalog-types.ts index e0d30aef0e4..287be350acc 100644 --- a/src/renderer/src/components/automations/automation-host-catalog-types.ts +++ b/src/renderer/src/components/automations/hosts/automation-host-catalog-types.ts @@ -2,8 +2,8 @@ import type { AutomationOwnerRef, StableAutomationAuthorityRef, StableAutomationCatalogRef -} from '../../../../shared/automations/ownership/automation-owner-ref' -import type { SshConnectionStatus } from '../../../../shared/ssh-types' +} from '../../../../../shared/automations/ownership/automation-owner-ref' +import type { SshConnectionStatus } from '../../../../../shared/ssh-types' /** Authority storage-query health, independent of execution targets; SSH downtime must not prevent listing/editing stored records. */ export type AutomationAuthorityHealth = diff --git a/src/renderer/src/components/automations/automation-host-catalog.ts b/src/renderer/src/components/automations/hosts/automation-host-catalog.ts similarity index 98% rename from src/renderer/src/components/automations/automation-host-catalog.ts rename to src/renderer/src/components/automations/hosts/automation-host-catalog.ts index f70f2c756a9..cc994d823fc 100644 --- a/src/renderer/src/components/automations/automation-host-catalog.ts +++ b/src/renderer/src/components/automations/hosts/automation-host-catalog.ts @@ -1,14 +1,14 @@ import { hostStableKey, parseHostStableKey -} from '../../../../shared/automations/ownership/automation-owner-key' +} from '../../../../../shared/automations/ownership/automation-owner-key' import { translate } from '@/i18n/i18n' import type { AutomationOwnerRef, StableAutomationAuthorityRef, StableAutomationCatalogRef -} from '../../../../shared/automations/ownership/automation-owner-ref' -import { isOwnedSshTargetId } from '../../../../shared/execution-host' +} from '../../../../../shared/automations/ownership/automation-owner-ref' +import { isOwnedSshTargetId } from '../../../../../shared/execution-host' import { automationAuthorityCatalogKey, type AutomationCatalogSshMirrorInput, diff --git a/src/renderer/src/components/automations/automation-host-client.ts b/src/renderer/src/components/automations/hosts/automation-host-client.ts similarity index 93% rename from src/renderer/src/components/automations/automation-host-client.ts rename to src/renderer/src/components/automations/hosts/automation-host-client.ts index 82290fe80db..ccc395d8126 100644 --- a/src/renderer/src/components/automations/automation-host-client.ts +++ b/src/renderer/src/components/automations/hosts/automation-host-client.ts @@ -5,11 +5,11 @@ import type { Automation, AutomationCreateInput, AutomationUpdateInput -} from '../../../../shared/automations/automation-definition' -import type { AutomationRun } from '../../../../shared/automations/history/automation-run' -import type { StableAutomationAuthorityRef } from '../../../../shared/automations/ownership/automation-owner-ref' -import { parseExecutionHostId } from '../../../../shared/execution-host' -import type { GlobalSettings } from '../../../../shared/global-settings-types' +} from '../../../../../shared/automations/automation-definition' +import type { AutomationRun } from '../../../../../shared/automations/history/automation-run' +import type { StableAutomationAuthorityRef } from '../../../../../shared/automations/ownership/automation-owner-ref' +import { parseExecutionHostId } from '../../../../../shared/execution-host' +import type { GlobalSettings } from '../../../../../shared/global-settings-types' type RuntimeAutomationCreateInput = Omit< AutomationCreateInput, diff --git a/src/renderer/src/components/automations/automation-host-detail-display.ts b/src/renderer/src/components/automations/hosts/automation-host-detail-display.ts similarity index 90% rename from src/renderer/src/components/automations/automation-host-detail-display.ts rename to src/renderer/src/components/automations/hosts/automation-host-detail-display.ts index b11110667e5..c9c4eba9114 100644 --- a/src/renderer/src/components/automations/automation-host-detail-display.ts +++ b/src/renderer/src/components/automations/hosts/automation-host-detail-display.ts @@ -1,7 +1,7 @@ // Use the catalog row’s storage host: a record’s local target means local to its server. Fall back to that target only for uncaptured legacy rows. -import type { Automation } from '../../../../shared/automations/automation-definition' -import { getExecutionHostLabel, toSshExecutionHostId } from '../../../../shared/execution-host' +import type { Automation } from '../../../../../shared/automations/automation-definition' +import { getExecutionHostLabel, toSshExecutionHostId } from '../../../../../shared/execution-host' import type { AutomationHostCatalogEntry } from './automation-host-catalog-types' export type AutomationHostDetailDisplay = { diff --git a/src/renderer/src/components/automations/automation-host-diagnostics.ts b/src/renderer/src/components/automations/hosts/automation-host-diagnostics.ts similarity index 100% rename from src/renderer/src/components/automations/automation-host-diagnostics.ts rename to src/renderer/src/components/automations/hosts/automation-host-diagnostics.ts diff --git a/src/renderer/src/components/automations/automation-host-fetch-target.ts b/src/renderer/src/components/automations/hosts/automation-host-fetch-target.ts similarity index 91% rename from src/renderer/src/components/automations/automation-host-fetch-target.ts rename to src/renderer/src/components/automations/hosts/automation-host-fetch-target.ts index 93ba4f68668..012edc35c73 100644 --- a/src/renderer/src/components/automations/automation-host-fetch-target.ts +++ b/src/renderer/src/components/automations/hosts/automation-host-fetch-target.ts @@ -1,6 +1,6 @@ /** Manual Retry carries the same catalog incarnation as scheduled work so its response can pass the commit fence. */ -import type { AutomationAuthorityRef } from '../../../../shared/automations/ownership/automation-owner-ref' +import type { AutomationAuthorityRef } from '../../../../../shared/automations/ownership/automation-owner-ref' import type { AutomationHostCatalogEntry } from './automation-host-catalog-types' import type { AutomationHostFetchTarget } from './automation-host-scheduler' diff --git a/src/renderer/src/components/automations/automation-host-filter-resolution.ts b/src/renderer/src/components/automations/hosts/automation-host-filter-resolution.ts similarity index 96% rename from src/renderer/src/components/automations/automation-host-filter-resolution.ts rename to src/renderer/src/components/automations/hosts/automation-host-filter-resolution.ts index e7a1c3a3298..37c59e1c21a 100644 --- a/src/renderer/src/components/automations/automation-host-filter-resolution.ts +++ b/src/renderer/src/components/automations/hosts/automation-host-filter-resolution.ts @@ -2,8 +2,8 @@ import { ALL_AUTOMATION_HOSTS_FILTER, automationHostFilterStableKey, type AutomationHostFilter -} from '../../../../shared/automations/ownership/automation-host-filter' -import type { StableAutomationCatalogRef } from '../../../../shared/automations/ownership/automation-owner-ref' +} from '../../../../../shared/automations/ownership/automation-host-filter' +import type { StableAutomationCatalogRef } from '../../../../../shared/automations/ownership/automation-owner-ref' import { automationAuthorityCatalogKey, type AutomationCatalogHydrationEvidence, diff --git a/src/renderer/src/components/automations/automation-host-health.ts b/src/renderer/src/components/automations/hosts/automation-host-health.ts similarity index 97% rename from src/renderer/src/components/automations/automation-host-health.ts rename to src/renderer/src/components/automations/hosts/automation-host-health.ts index 3b9ddbe8bdf..4134f7471f7 100644 --- a/src/renderer/src/components/automations/automation-host-health.ts +++ b/src/renderer/src/components/automations/hosts/automation-host-health.ts @@ -1,4 +1,4 @@ -import type { SshConnectionStatus } from '../../../../shared/ssh-types' +import type { SshConnectionStatus } from '../../../../../shared/ssh-types' import type { AutomationAuthorityHealth, AutomationExecutionHealth, diff --git a/src/renderer/src/components/automations/automation-host-invalidation-window-events.ts b/src/renderer/src/components/automations/hosts/automation-host-invalidation-window-events.ts similarity index 91% rename from src/renderer/src/components/automations/automation-host-invalidation-window-events.ts rename to src/renderer/src/components/automations/hosts/automation-host-invalidation-window-events.ts index 5febf048f5f..f56f380c2df 100644 --- a/src/renderer/src/components/automations/automation-host-invalidation-window-events.ts +++ b/src/renderer/src/components/automations/hosts/automation-host-invalidation-window-events.ts @@ -5,7 +5,7 @@ import { automationsChangedWindowDetail, type AutomationsChangedWindowDetail } from '@/lib/automations-changed-window-event' -import type { StableAutomationAuthorityRef } from '../../../../shared/automations/ownership/automation-owner-ref' +import type { StableAutomationAuthorityRef } from '../../../../../shared/automations/ownership/automation-owner-ref' import type { AutomationAuthorityChangeEvent } from './automation-host-invalidation' export function toAutomationAuthorityChangeEvent( diff --git a/src/renderer/src/components/automations/automation-host-invalidation.ts b/src/renderer/src/components/automations/hosts/automation-host-invalidation.ts similarity index 95% rename from src/renderer/src/components/automations/automation-host-invalidation.ts rename to src/renderer/src/components/automations/hosts/automation-host-invalidation.ts index 5975442852b..41cf40b13f9 100644 --- a/src/renderer/src/components/automations/automation-host-invalidation.ts +++ b/src/renderer/src/components/automations/hosts/automation-host-invalidation.ts @@ -1,10 +1,10 @@ /** Invalidate only the scoped entry or unscoped publisher authority. Coalesce event bursts in one microtask so definition/run/usage writes share one refresh and legacy authority request. */ -import { hostStableKey } from '../../../../shared/automations/ownership/automation-owner-key' +import { hostStableKey } from '../../../../../shared/automations/ownership/automation-owner-key' import type { StableAutomationAuthorityRef, StableAutomationCatalogRef -} from '../../../../shared/automations/ownership/automation-owner-ref' +} from '../../../../../shared/automations/ownership/automation-owner-ref' import { automationAuthorityCatalogKey } from './automation-host-catalog-types' import type { AutomationHostCache } from './automation-host-cache' diff --git a/src/renderer/src/components/automations/automation-host-list-rows.test.ts b/src/renderer/src/components/automations/hosts/automation-host-list-rows.test.ts similarity index 98% rename from src/renderer/src/components/automations/automation-host-list-rows.test.ts rename to src/renderer/src/components/automations/hosts/automation-host-list-rows.test.ts index 3ea5c7d8d3a..7c3a41555bf 100644 --- a/src/renderer/src/components/automations/automation-host-list-rows.test.ts +++ b/src/renderer/src/components/automations/hosts/automation-host-list-rows.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it } from 'vitest' -import type { Automation } from '../../../../shared/automations/automation-definition' +import type { Automation } from '../../../../../shared/automations/automation-definition' import type { AutomationHostCacheEntry, AutomationHostRow } from './automation-host-cache-types' import type { AutomationHostCatalog, diff --git a/src/renderer/src/components/automations/automation-host-list-rows.ts b/src/renderer/src/components/automations/hosts/automation-host-list-rows.ts similarity index 97% rename from src/renderer/src/components/automations/automation-host-list-rows.ts rename to src/renderer/src/components/automations/hosts/automation-host-list-rows.ts index 49fff53429c..00f6c079052 100644 --- a/src/renderer/src/components/automations/automation-host-list-rows.ts +++ b/src/renderer/src/components/automations/hosts/automation-host-list-rows.ts @@ -1,6 +1,6 @@ /** Keep host origin on every visible row. Until a host in view commits an answer, preserve the caller’s prior rows instead of claiming an empty result. */ -import type { Automation } from '../../../../shared/automations/automation-definition' +import type { Automation } from '../../../../../shared/automations/automation-definition' import type { AutomationHostCacheEntry } from './automation-host-cache-types' import type { AutomationHostCatalog, @@ -17,7 +17,7 @@ import { automationAuthorityRecordKey, automationListRowKey, type AutomationListRow -} from './automation-list-row-identity' +} from '../listing/automation-list-row-identity' export type AutomationHostGroupHost = { entry: AutomationHostCatalogEntry diff --git a/src/renderer/src/components/automations/automation-host-picker-groups.ts b/src/renderer/src/components/automations/hosts/automation-host-picker-groups.ts similarity index 100% rename from src/renderer/src/components/automations/automation-host-picker-groups.ts rename to src/renderer/src/components/automations/hosts/automation-host-picker-groups.ts diff --git a/src/renderer/src/components/automations/automation-host-recovery.ts b/src/renderer/src/components/automations/hosts/automation-host-recovery.ts similarity index 100% rename from src/renderer/src/components/automations/automation-host-recovery.ts rename to src/renderer/src/components/automations/hosts/automation-host-recovery.ts diff --git a/src/renderer/src/components/automations/automation-host-request-instrumentation.ts b/src/renderer/src/components/automations/hosts/automation-host-request-instrumentation.ts similarity index 94% rename from src/renderer/src/components/automations/automation-host-request-instrumentation.ts rename to src/renderer/src/components/automations/hosts/automation-host-request-instrumentation.ts index ffc9ac610c7..2e3717e8494 100644 --- a/src/renderer/src/components/automations/automation-host-request-instrumentation.ts +++ b/src/renderer/src/components/automations/hosts/automation-host-request-instrumentation.ts @@ -1,7 +1,7 @@ /** Translate scheduler work into counters: legacy requests/dedupe/discards belong to an authority, never one stable host key. */ -import { hostStableKey } from '../../../../shared/automations/ownership/automation-owner-key' -import type { StableAutomationCatalogRef } from '../../../../shared/automations/ownership/automation-owner-ref' +import { hostStableKey } from '../../../../../shared/automations/ownership/automation-owner-key' +import type { StableAutomationCatalogRef } from '../../../../../shared/automations/ownership/automation-owner-ref' import { automationAuthorityCatalogKey, type AutomationHostQuerySupport diff --git a/src/renderer/src/components/automations/automation-host-retry-schedule.ts b/src/renderer/src/components/automations/hosts/automation-host-retry-schedule.ts similarity index 100% rename from src/renderer/src/components/automations/automation-host-retry-schedule.ts rename to src/renderer/src/components/automations/hosts/automation-host-retry-schedule.ts diff --git a/src/renderer/src/components/automations/automation-host-scheduler-plan.ts b/src/renderer/src/components/automations/hosts/automation-host-scheduler-plan.ts similarity index 95% rename from src/renderer/src/components/automations/automation-host-scheduler-plan.ts rename to src/renderer/src/components/automations/hosts/automation-host-scheduler-plan.ts index 3c54f554361..084aa46a14a 100644 --- a/src/renderer/src/components/automations/automation-host-scheduler-plan.ts +++ b/src/renderer/src/components/automations/hosts/automation-host-scheduler-plan.ts @@ -1,6 +1,6 @@ /** Capture fences only for requests that survive dedupe, freshness, in-flight and retry-cooldown checks. */ -import { hostStableKey } from '../../../../shared/automations/ownership/automation-owner-key' +import { hostStableKey } from '../../../../../shared/automations/ownership/automation-owner-key' import type { AutomationHostCache } from './automation-host-cache' import type { AutomationHostRequestFence } from './automation-host-cache-types' import type { AutomationHostFetchTarget } from './automation-host-scheduler' diff --git a/src/renderer/src/components/automations/automation-host-scheduler-queue.ts b/src/renderer/src/components/automations/hosts/automation-host-scheduler-queue.ts similarity index 100% rename from src/renderer/src/components/automations/automation-host-scheduler-queue.ts rename to src/renderer/src/components/automations/hosts/automation-host-scheduler-queue.ts diff --git a/src/renderer/src/components/automations/automation-host-scheduler.test.ts b/src/renderer/src/components/automations/hosts/automation-host-scheduler.test.ts similarity index 97% rename from src/renderer/src/components/automations/automation-host-scheduler.test.ts rename to src/renderer/src/components/automations/hosts/automation-host-scheduler.test.ts index b882f6a87f3..a0856d22542 100644 --- a/src/renderer/src/components/automations/automation-host-scheduler.test.ts +++ b/src/renderer/src/components/automations/hosts/automation-host-scheduler.test.ts @@ -1,13 +1,13 @@ /** Enforce four pooled calls, one legacy authority call per cycle and no run-history fetch to fill missing usage. */ import { describe, expect, it, vi } from 'vitest' -import type { Automation } from '../../../../shared/automations/automation-definition' +import type { Automation } from '../../../../../shared/automations/automation-definition' import type { AutomationAuthorityRef, StableAutomationAuthorityRef, StableAutomationCatalogRef -} from '../../../../shared/automations/ownership/automation-owner-ref' +} from '../../../../../shared/automations/ownership/automation-owner-ref' import { createAutomationHostCache, type AutomationHostCache } from './automation-host-cache' import type { AutomationHostQuerySupport } from './automation-host-catalog-types' import { diff --git a/src/renderer/src/components/automations/automation-host-scheduler.ts b/src/renderer/src/components/automations/hosts/automation-host-scheduler.ts similarity index 95% rename from src/renderer/src/components/automations/automation-host-scheduler.ts rename to src/renderer/src/components/automations/hosts/automation-host-scheduler.ts index 32b0cb5079a..5b0e2574c56 100644 --- a/src/renderer/src/components/automations/automation-host-scheduler.ts +++ b/src/renderer/src/components/automations/hosts/automation-host-scheduler.ts @@ -1,15 +1,15 @@ /** Fetch through four pooled calls, share each legacy authority answer across its entries, and publish only responses that pass the cache fence. */ -import type { Automation } from '../../../../shared/automations/automation-definition' -import type { AutomationListScopeSelector } from '../../../../shared/automations/ownership/automation-list-scope' -import type { LegacyAutomationPartitionContext } from '../../../../shared/automations/ownership/automation-legacy-list-partition' -import { hostStableKey } from '../../../../shared/automations/ownership/automation-owner-key' +import type { Automation } from '../../../../../shared/automations/automation-definition' +import type { AutomationListScopeSelector } from '../../../../../shared/automations/ownership/automation-list-scope' +import type { LegacyAutomationPartitionContext } from '../../../../../shared/automations/ownership/automation-legacy-list-partition' +import { hostStableKey } from '../../../../../shared/automations/ownership/automation-owner-key' import type { AutomationAuthorityRef, AutomationOwnerRef, StableAutomationAuthorityRef, StableAutomationCatalogRef -} from '../../../../shared/automations/ownership/automation-owner-ref' +} from '../../../../../shared/automations/ownership/automation-owner-ref' import { automationAuthorityCatalogKey, type AutomationHostQuerySupport @@ -20,8 +20,8 @@ import { partitionLegacyAutomationHostRows, toScopedAutomationHostRows } from './automation-host-cache-rows' +import { AutomationHostScopeUnsupportedError } from './automation-capability-probe' import { - AutomationHostScopeUnsupportedError, listLegacyAutomations, listScopedAutomations, type ScopedAutomationList diff --git a/src/renderer/src/components/automations/automation-host-scope-descriptors.ts b/src/renderer/src/components/automations/hosts/automation-host-scope-descriptors.ts similarity index 100% rename from src/renderer/src/components/automations/automation-host-scope-descriptors.ts rename to src/renderer/src/components/automations/hosts/automation-host-scope-descriptors.ts diff --git a/src/renderer/src/components/automations/automation-host-status-descriptors.ts b/src/renderer/src/components/automations/hosts/automation-host-status-descriptors.ts similarity index 100% rename from src/renderer/src/components/automations/automation-host-status-descriptors.ts rename to src/renderer/src/components/automations/hosts/automation-host-status-descriptors.ts diff --git a/src/renderer/src/components/automations/automation-notice-recovery-host.ts b/src/renderer/src/components/automations/hosts/automation-notice-recovery-host.ts similarity index 77% rename from src/renderer/src/components/automations/automation-notice-recovery-host.ts rename to src/renderer/src/components/automations/hosts/automation-notice-recovery-host.ts index b16c90ed33d..c17281e0677 100644 --- a/src/renderer/src/components/automations/automation-notice-recovery-host.ts +++ b/src/renderer/src/components/automations/hosts/automation-notice-recovery-host.ts @@ -1,7 +1,7 @@ /** Recover against the refused row’s captured owner or create destination; the list filter may point elsewhere or to All hosts. */ -import { hostStableKey } from '../../../../shared/automations/ownership/automation-owner-key' -import type { AutomationAuthorityRef } from '../../../../shared/automations/ownership/automation-owner-ref' +import { hostStableKey } from '../../../../../shared/automations/ownership/automation-owner-key' +import type { AutomationAuthorityRef } from '../../../../../shared/automations/ownership/automation-owner-ref' import type { AutomationCapturedOwner } from './automation-captured-owner' import type { AutomationHostCatalog, diff --git a/src/renderer/src/components/automations/automation-owner-action-runner.ts b/src/renderer/src/components/automations/hosts/automation-owner-action-runner.ts similarity index 94% rename from src/renderer/src/components/automations/automation-owner-action-runner.ts rename to src/renderer/src/components/automations/hosts/automation-owner-action-runner.ts index 069da14a8f5..e3e5ee0a403 100644 --- a/src/renderer/src/components/automations/automation-owner-action-runner.ts +++ b/src/renderer/src/components/automations/hosts/automation-owner-action-runner.ts @@ -4,30 +4,30 @@ import type { Automation, AutomationCreateInput, AutomationUpdateInput -} from '../../../../shared/automations/automation-definition' +} from '../../../../../shared/automations/automation-definition' import type { AutomationRun, AutomationRunsPage -} from '../../../../shared/automations/history/automation-run' +} from '../../../../../shared/automations/history/automation-run' import { automationOwnerConflictMessage, matchAutomationOwnerConflict, stripAutomationOwnerConflictCode, type AutomationOwnerConflictCode -} from '../../../../shared/automations/ownership/automation-owner-conflict' +} from '../../../../../shared/automations/ownership/automation-owner-conflict' import type { AutomationAuthorityRef, AutomationOwnerRef -} from '../../../../shared/automations/ownership/automation-owner-ref' -import type { AutomationDestination } from '../../../../shared/automations/ownership/automation-owner-precondition' +} from '../../../../../shared/automations/ownership/automation-owner-ref' +import type { AutomationDestination } from '../../../../../shared/automations/ownership/automation-owner-precondition' import { translate } from '@/i18n/i18n' import type { AutomationActionAvailability, AutomationActionBlock } from './automation-captured-owner' import type { AutomationHostRecoveryAction } from './automation-host-status-descriptors' +import { AutomationHostScopeUnsupportedError } from './automation-capability-probe' import { - AutomationHostScopeUnsupportedError, createAutomationForDestination, deleteAutomationForOwner, deleteOrphanAutomation, diff --git a/src/renderer/src/components/automations/automation-row-action-dispatch.ts b/src/renderer/src/components/automations/hosts/automation-row-action-dispatch.ts similarity index 94% rename from src/renderer/src/components/automations/automation-row-action-dispatch.ts rename to src/renderer/src/components/automations/hosts/automation-row-action-dispatch.ts index f42209f22bd..ccffe685eb5 100644 --- a/src/renderer/src/components/automations/automation-row-action-dispatch.ts +++ b/src/renderer/src/components/automations/hosts/automation-row-action-dispatch.ts @@ -3,13 +3,13 @@ import type { Automation, AutomationUpdateInput -} from '../../../../shared/automations/automation-definition' +} from '../../../../../shared/automations/automation-definition' import type { AutomationRun, AutomationRunsPage -} from '../../../../shared/automations/history/automation-run' -import type { AutomationAuthorityRef } from '../../../../shared/automations/ownership/automation-owner-ref' -import type { AutomationDestination } from '../../../../shared/automations/ownership/automation-owner-precondition' +} from '../../../../../shared/automations/history/automation-run' +import type { AutomationAuthorityRef } from '../../../../../shared/automations/ownership/automation-owner-ref' +import type { AutomationDestination } from '../../../../../shared/automations/ownership/automation-owner-precondition' import { automationActionAvailability, capturedAutomationOwner, diff --git a/src/renderer/src/components/automations/automation-run-context-host-match.ts b/src/renderer/src/components/automations/hosts/automation-run-context-host-match.ts similarity index 89% rename from src/renderer/src/components/automations/automation-run-context-host-match.ts rename to src/renderer/src/components/automations/hosts/automation-run-context-host-match.ts index 72eb4951ef4..1508d24cd76 100644 --- a/src/renderer/src/components/automations/automation-run-context-host-match.ts +++ b/src/renderer/src/components/automations/hosts/automation-run-context-host-match.ts @@ -1,11 +1,11 @@ import type { AutomationHostTarget } from './automation-host-client' -import type { ProjectHostSetup } from '../../../../shared/project-types' -import type { Repo } from '../../../../shared/repo-types' +import type { ProjectHostSetup } from '../../../../../shared/project-types' +import type { Repo } from '../../../../../shared/repo-types' import { getRepoExecutionHostId, getRepoSshConnectionId, toSshExecutionHostId -} from '../../../../shared/execution-host' +} from '../../../../../shared/execution-host' function getRuntimeTargetHostId(target: AutomationHostTarget | null | undefined): string | null { return target?.kind === 'environment' diff --git a/src/renderer/src/components/automations/automation-scoped-list-client.ts b/src/renderer/src/components/automations/hosts/automation-scoped-list-client.ts similarity index 93% rename from src/renderer/src/components/automations/automation-scoped-list-client.ts rename to src/renderer/src/components/automations/hosts/automation-scoped-list-client.ts index b8e6ee654f4..7bae5db087d 100644 --- a/src/renderer/src/components/automations/automation-scoped-list-client.ts +++ b/src/renderer/src/components/automations/hosts/automation-scoped-list-client.ts @@ -1,31 +1,31 @@ /** Pin runtime pairing revisions and SSH registration generations to captured owners. Validate responses: an old host may ignore selectors and return other hosts’ rows. */ import { callRuntimeRpc } from '@/runtime/rpc/calls/runtime-rpc-call' -import type { RuntimeClientTarget } from '../../../../shared/runtime-client-target' +import type { RuntimeClientTarget } from '../../../../../shared/runtime-client-target' import type { Automation, AutomationCreateInput, AutomationUpdateInput -} from '../../../../shared/automations/automation-definition' +} from '../../../../../shared/automations/automation-definition' import type { AutomationRun, AutomationRunsPage -} from '../../../../shared/automations/history/automation-run' +} from '../../../../../shared/automations/history/automation-run' import type { AutomationListResult, AutomationListScopeSelector -} from '../../../../shared/automations/ownership/automation-list-scope' -import { validateAutomationListResponse } from '../../../../shared/automations/ownership/automation-list-response' +} from '../../../../../shared/automations/ownership/automation-list-scope' +import { validateAutomationListResponse } from '../../../../../shared/automations/ownership/automation-list-response' import type { AutomationAuthorityRef, AutomationOwnerRef -} from '../../../../shared/automations/ownership/automation-owner-ref' +} from '../../../../../shared/automations/ownership/automation-owner-ref' /** The one classifier every client shares; re-exported so call sites keep importing it from here. */ import type { AutomationDestination, AutomationOwnerPrecondition -} from '../../../../shared/automations/ownership/automation-owner-precondition' +} from '../../../../../shared/automations/ownership/automation-owner-precondition' import { toRuntimeAutomationCreateInput, toRuntimeAutomationUpdateInput @@ -35,18 +35,13 @@ import { prepareAutomationLaunchSetup, assertOwnerFencingSupported, assertAutomationCreateIdempotencySupported, - AUTOMATION_LIST_HOST_SCOPE_RUNTIME_CAPABILITY, - AUTOMATION_LIST_HOST_SCOPE_UPDATE_REQUIRED_MESSAGE, AutomationHostScopeUnsupportedError, REQUEST_TIMEOUT_MS } from './automation-capability-probe' - -export { - AutomationHostScopeUnsupportedError, - AUTHORITY_CAPABILITY_CONFIRMATION_TTL_MS, - AUTHORITY_CAPABILITY_CONFIRMATION_MAX, - resetAutomationCapabilityProbes -} from './automation-capability-probe' +import { + AUTOMATION_LIST_HOST_SCOPE_RUNTIME_CAPABILITY, + AUTOMATION_LIST_HOST_SCOPE_UPDATE_REQUIRED_MESSAGE +} from '../../../../../shared/automations/automation-runtime-capabilities' export class AutomationListResponseError extends Error { readonly code = 'invalid_response' diff --git a/src/renderer/src/components/automations/automation-target-availability-types.ts b/src/renderer/src/components/automations/hosts/automation-target-availability-types.ts similarity index 100% rename from src/renderer/src/components/automations/automation-target-availability-types.ts rename to src/renderer/src/components/automations/hosts/automation-target-availability-types.ts diff --git a/src/renderer/src/components/automations/automation-target-availability.ts b/src/renderer/src/components/automations/hosts/automation-target-availability.ts similarity index 89% rename from src/renderer/src/components/automations/automation-target-availability.ts rename to src/renderer/src/components/automations/hosts/automation-target-availability.ts index 4331ad20838..9834d615ee7 100644 --- a/src/renderer/src/components/automations/automation-target-availability.ts +++ b/src/renderer/src/components/automations/hosts/automation-target-availability.ts @@ -2,30 +2,29 @@ import { automationHostReselectionMessage, type AutomationCapturedOwner } from './automation-captured-owner' -import type { Automation } from '../../../../shared/automations/automation-definition' -import { parseExecutionHostId } from '../../../../shared/execution-host' +import type { Automation } from '../../../../../shared/automations/automation-definition' +import { parseExecutionHostId } from '../../../../../shared/execution-host' import { setupHostMatchesRunContext, repoHostMatchesRunContext } from './automation-run-context-host-match' -import { evaluateRuntimeCompat } from '../../../../shared/protocol-compat' +import { evaluateRuntimeCompat } from '../../../../../shared/protocol-compat' import { describeRuntimeCompatBlock } from '@/lib/runtime-host-copy' import { translate } from '@/i18n/i18n' import type { Translate } from '@/i18n/use-translate' import { MIN_COMPATIBLE_RUNTIME_SERVER_VERSION, RUNTIME_PROTOCOL_VERSION -} from '../../../../shared/protocol-version' +} from '../../../../../shared/protocol-version' import type { AutomationHostTarget } from './automation-host-client' -import type { SshConnectionState } from '../../../../shared/ssh-types' -import type { ProjectHostSetup } from '../../../../shared/project-types' -import type { Repo } from '../../../../shared/repo-types' -import type { RuntimeEnvironmentStatus } from '../../../../shared/remote-runtime/host-status/runtime-host-status' -import type { Worktree } from '../../../../shared/worktree/types' -import type { RuntimeEnvironmentSshBucket } from '../../store/slices/ssh/runtime-environment-ssh' +import type { SshConnectionState } from '../../../../../shared/ssh-types' +import type { ProjectHostSetup } from '../../../../../shared/project-types' +import type { Repo } from '../../../../../shared/repo-types' +import type { RuntimeEnvironmentStatus } from '../../../../../shared/remote-runtime/host-status/runtime-host-status' +import type { Worktree } from '../../../../../shared/worktree/types' +import type { RuntimeEnvironmentSshBucket } from '../../../store/slices/ssh/runtime-environment-ssh' import type { AutomationTargetAvailability } from './automation-target-availability-types' -export type { AutomationTargetAvailability } from './automation-target-availability-types' type AutomationTargetAvailabilityArgs = { automation: Automation diff --git a/src/renderer/src/components/automations/automation-write-invalidation.ts b/src/renderer/src/components/automations/hosts/automation-write-invalidation.ts similarity index 92% rename from src/renderer/src/components/automations/automation-write-invalidation.ts rename to src/renderer/src/components/automations/hosts/automation-write-invalidation.ts index d774e435bf9..012b54ebb9d 100644 --- a/src/renderer/src/components/automations/automation-write-invalidation.ts +++ b/src/renderer/src/components/automations/hosts/automation-write-invalidation.ts @@ -1,11 +1,11 @@ /** Invalidate immediately from the completed write’s known host instead of waiting for a droppable change event. Uncaptured rows invalidate their authority without guessing a selector. */ -import { toStableCatalogRef } from '../../../../shared/automations/ownership/automation-owner-key' +import { toStableCatalogRef } from '../../../../../shared/automations/ownership/automation-owner-key' import type { AutomationAuthorityRef, StableAutomationAuthorityRef, StableAutomationCatalogRef -} from '../../../../shared/automations/ownership/automation-owner-ref' +} from '../../../../../shared/automations/ownership/automation-owner-ref' import type { AutomationCapturedOwner } from './automation-captured-owner' import type { AutomationAuthorityChangeEvent, diff --git a/src/renderer/src/components/automations/use-automation-desktop-ssh-registrations.ts b/src/renderer/src/components/automations/hosts/use-automation-desktop-ssh-registrations.ts similarity index 86% rename from src/renderer/src/components/automations/use-automation-desktop-ssh-registrations.ts rename to src/renderer/src/components/automations/hosts/use-automation-desktop-ssh-registrations.ts index 43995eb14de..5a649d19da2 100644 --- a/src/renderer/src/components/automations/use-automation-desktop-ssh-registrations.ts +++ b/src/renderer/src/components/automations/hosts/use-automation-desktop-ssh-registrations.ts @@ -1,4 +1,4 @@ -import { useAppStore } from '../../store' +import { useAppStore } from '../../../store/index' /** Use the live store’s registration generations instead of per-mount listTargets IPC. Omit unknown generations so only that host stays view-only; never guess a fence. */ export function useAutomationDesktopSshRegistrations(): ReadonlyMap { diff --git a/src/renderer/src/components/automations/use-automation-host-catalog-readoption.test.tsx b/src/renderer/src/components/automations/hosts/use-automation-host-catalog-readoption.test.tsx similarity index 95% rename from src/renderer/src/components/automations/use-automation-host-catalog-readoption.test.tsx rename to src/renderer/src/components/automations/hosts/use-automation-host-catalog-readoption.test.tsx index e94702866d9..ccf2fb37ec7 100644 --- a/src/renderer/src/components/automations/use-automation-host-catalog-readoption.test.tsx +++ b/src/renderer/src/components/automations/hosts/use-automation-host-catalog-readoption.test.tsx @@ -5,15 +5,15 @@ import { act } from 'react' import { createRoot, type Root } from 'react-dom/client' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import type { Automation } from '../../../../shared/automations/automation-definition' -import type { AutomationListScopeSelector } from '../../../../shared/automations/ownership/automation-list-scope' +import type { Automation } from '../../../../../shared/automations/automation-definition' +import type { AutomationListScopeSelector } from '../../../../../shared/automations/ownership/automation-list-scope' import type { AppState } from '@/store/types' import type { AutomationHostCatalogView } from './use-automation-host-catalog' import { resetAutomationHostCatalogGenerationsForTests } from './automation-host-catalog-generation' const mocks = vi.hoisted(() => ({ state: {} as Record })) -vi.mock('@/store', () => { +vi.mock('@/store/index', () => { const useAppStore = (selector: (state: Partial) => unknown): unknown => selector(mocks.state as Partial) useAppStore.getState = (): Partial => mocks.state as Partial diff --git a/src/renderer/src/components/automations/use-automation-host-catalog-source-state.ts b/src/renderer/src/components/automations/hosts/use-automation-host-catalog-source-state.ts similarity index 94% rename from src/renderer/src/components/automations/use-automation-host-catalog-source-state.ts rename to src/renderer/src/components/automations/hosts/use-automation-host-catalog-source-state.ts index a658252b09e..8c7195f1a25 100644 --- a/src/renderer/src/components/automations/use-automation-host-catalog-source-state.ts +++ b/src/renderer/src/components/automations/hosts/use-automation-host-catalog-source-state.ts @@ -1,8 +1,8 @@ import { useMemo } from 'react' -import { useAppStore } from '@/store' +import { useAppStore } from '@/store/index' import { getPairedWebClientEnvironmentId } from '@/lib/paired-web-client-host' -import type { PublicKnownRuntimeEnvironment } from '../../../../shared/remote-runtime/host-catalog/runtime-environments' -import { getManagedOrcadSshTargetId } from '../../../../shared/execution-host/managed-orcad-execution-host' +import type { PublicKnownRuntimeEnvironment } from '../../../../../shared/remote-runtime/host-catalog/runtime-environments' +import { getManagedOrcadSshTargetId } from '../../../../../shared/execution-host/managed-orcad-execution-host' import type { AutomationCatalogRuntimeSource, AutomationCatalogSshSource, diff --git a/src/renderer/src/components/automations/use-automation-host-catalog.test.tsx b/src/renderer/src/components/automations/hosts/use-automation-host-catalog.test.tsx similarity index 97% rename from src/renderer/src/components/automations/use-automation-host-catalog.test.tsx rename to src/renderer/src/components/automations/hosts/use-automation-host-catalog.test.tsx index 66ebd9b17c6..8cecc8d0d16 100644 --- a/src/renderer/src/components/automations/use-automation-host-catalog.test.tsx +++ b/src/renderer/src/components/automations/hosts/use-automation-host-catalog.test.tsx @@ -5,9 +5,9 @@ import { act } from 'react' import { createRoot, type Root } from 'react-dom/client' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import type { Automation } from '../../../../shared/automations/automation-definition' +import type { Automation } from '../../../../../shared/automations/automation-definition' import type { AppState } from '@/store/types' -import type { Repo } from '../../../../shared/repo-types' +import type { Repo } from '../../../../../shared/repo-types' import type { AutomationHostCatalogView } from './use-automation-host-catalog' const mocks = vi.hoisted(() => ({ @@ -16,7 +16,7 @@ const mocks = vi.hoisted(() => ({ getRuntimeEnvironmentStatus: vi.fn() })) -vi.mock('@/store', () => { +vi.mock('@/store/index', () => { const useAppStore = (selector: (state: Partial) => unknown): unknown => selector(mocks.state as Partial) useAppStore.getState = (): Partial => mocks.state as Partial diff --git a/src/renderer/src/components/automations/use-automation-host-catalog.ts b/src/renderer/src/components/automations/hosts/use-automation-host-catalog.ts similarity index 95% rename from src/renderer/src/components/automations/use-automation-host-catalog.ts rename to src/renderer/src/components/automations/hosts/use-automation-host-catalog.ts index 8ed6fbfbb4f..9eb4f38e3d4 100644 --- a/src/renderer/src/components/automations/use-automation-host-catalog.ts +++ b/src/renderer/src/components/automations/hosts/use-automation-host-catalog.ts @@ -1,10 +1,10 @@ import { useCallback, useEffect, useEffectEvent, useMemo, useRef, useState } from 'react' -import { useAppStore } from '@/store' +import { useAppStore } from '@/store/index' import { useUiLanguageRevision } from '@/i18n/use-ui-language-revision' -import { getHostDisplayLabelOverrides } from '../../../../shared/host-setting-overrides' -import { getLocalExecutionHostLabel } from '../../../../shared/execution-host' -import type { AutomationHostFilter } from '../../../../shared/automations/ownership/automation-host-filter' -import type { StableAutomationAuthorityRef } from '../../../../shared/automations/ownership/automation-owner-ref' +import { getHostDisplayLabelOverrides } from '../../../../../shared/host-setting-overrides' +import { getLocalExecutionHostLabel } from '../../../../../shared/execution-host' +import type { AutomationHostFilter } from '../../../../../shared/automations/ownership/automation-host-filter' +import type { StableAutomationAuthorityRef } from '../../../../../shared/automations/ownership/automation-owner-ref' import { buildAutomationHostCatalog } from './automation-host-catalog' import { subscribeAutomationHostInvalidation } from './automation-host-invalidation-window-events' import { buildAutomationHostCatalogSource } from './automation-host-catalog-source' @@ -23,7 +23,7 @@ import type { AutomationHostCatalog, AutomationHostCatalogEntry } from './automation-host-catalog-types' -import { automationHostFilterStableKey } from '../../../../shared/automations/ownership/automation-host-filter' +import { automationHostFilterStableKey } from '../../../../../shared/automations/ownership/automation-host-filter' import { foldDesktopHostFilter, resolveAutomationHostFilter, diff --git a/src/renderer/src/components/automations/AutomationListEmptyView.tsx b/src/renderer/src/components/automations/listing/AutomationListEmptyView.tsx similarity index 96% rename from src/renderer/src/components/automations/AutomationListEmptyView.tsx rename to src/renderer/src/components/automations/listing/AutomationListEmptyView.tsx index cb7d0b1ace5..0b888cb16a7 100644 --- a/src/renderer/src/components/automations/AutomationListEmptyView.tsx +++ b/src/renderer/src/components/automations/listing/AutomationListEmptyView.tsx @@ -8,7 +8,7 @@ import { import { recoveryActionLabel, type AutomationHostRecoveryAction -} from './automation-host-status-descriptors' +} from '../hosts/automation-host-status-descriptors' import { useTranslate } from '@/i18n/use-translate' /** Renders whichever empty/partial/failure state the list is in; nothing when rows exist. */ diff --git a/src/renderer/src/components/automations/AutomationListExternalRow.tsx b/src/renderer/src/components/automations/listing/AutomationListExternalRow.tsx similarity index 93% rename from src/renderer/src/components/automations/AutomationListExternalRow.tsx rename to src/renderer/src/components/automations/listing/AutomationListExternalRow.tsx index 026918baa58..b802be4ba44 100644 --- a/src/renderer/src/components/automations/AutomationListExternalRow.tsx +++ b/src/renderer/src/components/automations/listing/AutomationListExternalRow.tsx @@ -20,17 +20,17 @@ import type { ExternalAutomationAction, ExternalAutomationJob, ExternalAutomationManager -} from '../../../../shared/automations/external/external-automation' -import type { SshConnectionState } from '../../../../shared/ssh-types' -import type { ExternalAutomationListEntry } from './external-automation-list-entries' -import type { ExternalAutomationScope } from './external-automation-scope-client' +} from '../../../../../shared/automations/external/external-automation' +import type { SshConnectionState } from '../../../../../shared/ssh-types' +import type { ExternalAutomationListEntry } from '../external/external-automation-list-entries' +import type { ExternalAutomationScope } from '../external/external-automation-scope-client' import { formatExternalDate, getExternalProviderLabel, getExternalTargetKindLabel -} from './external-automation-display' -import { getExternalAutomationScheduleDisplay } from './external-automation-schedule-display' -import { getExternalAutomationActionDisabledMessage } from './external-automation-source-availability' +} from '../external/external-automation-display' +import { getExternalAutomationScheduleDisplay } from '../external/external-automation-schedule-display' +import { getExternalAutomationActionDisabledMessage } from '../external/external-automation-source-availability' import { AUTOMATIONS_TABLE_GRID_CLASS } from './automations-table-layout' import { LIST_TABLE_ROW_CLASS, diff --git a/src/renderer/src/components/automations/AutomationListExternalRows.tsx b/src/renderer/src/components/automations/listing/AutomationListExternalRows.tsx similarity index 85% rename from src/renderer/src/components/automations/AutomationListExternalRows.tsx rename to src/renderer/src/components/automations/listing/AutomationListExternalRows.tsx index 3ed78fc2a69..c3e802ea80a 100644 --- a/src/renderer/src/components/automations/AutomationListExternalRows.tsx +++ b/src/renderer/src/components/automations/listing/AutomationListExternalRows.tsx @@ -1,5 +1,5 @@ import React from 'react' -import type { ExternalAutomationListEntry } from './external-automation-list-entries' +import type { ExternalAutomationListEntry } from '../external/external-automation-list-entries' import { AutomationListExternalRow, type AutomationListExternalRowProps diff --git a/src/renderer/src/components/automations/AutomationListFilterMenu.tsx b/src/renderer/src/components/automations/listing/AutomationListFilterMenu.tsx similarity index 99% rename from src/renderer/src/components/automations/AutomationListFilterMenu.tsx rename to src/renderer/src/components/automations/listing/AutomationListFilterMenu.tsx index cc11fbcad2f..80099a50dc5 100644 --- a/src/renderer/src/components/automations/AutomationListFilterMenu.tsx +++ b/src/renderer/src/components/automations/listing/AutomationListFilterMenu.tsx @@ -23,7 +23,7 @@ import { useTranslate } from '@/i18n/use-translate' import { useBoundedHostRows } from '@/components/host-picker/use-bounded-host-rows' import { HostListSearchField } from '@/components/host-picker/HostListSearchField' import { HostListOverflowNote } from '@/components/host-picker/HostListOverflowNote' -import type { AutomationHostCatalogEntry } from './automation-host-catalog-types' +import type { AutomationHostCatalogEntry } from '../hosts/automation-host-catalog-types' import { countAutomationListFilters, EMPTY_AUTOMATION_LIST_FILTER, diff --git a/src/renderer/src/components/automations/AutomationListHostGroups.tsx b/src/renderer/src/components/automations/listing/AutomationListHostGroups.tsx similarity index 93% rename from src/renderer/src/components/automations/AutomationListHostGroups.tsx rename to src/renderer/src/components/automations/listing/AutomationListHostGroups.tsx index 86e5ad77ff2..3047805434d 100644 --- a/src/renderer/src/components/automations/AutomationListHostGroups.tsx +++ b/src/renderer/src/components/automations/listing/AutomationListHostGroups.tsx @@ -1,11 +1,11 @@ import React from 'react' import { Button } from '@/components/ui/button' -import { AutomationHostLabel, AutomationHostStatusBadges } from './AutomationHostBadges' +import { AutomationHostLabel, AutomationHostStatusBadges } from '../hosts/AutomationHostBadges' import { AutomationListLocalRows, type AutomationListLocalRowsProps } from './AutomationListLocalRows' -import type { AutomationHostVisibleGroup } from './automation-host-list-rows' +import type { AutomationHostVisibleGroup } from '../hosts/automation-host-list-rows' import { resolveAutomationHostGroupEmptyState, type AutomationListEmptyState @@ -14,8 +14,8 @@ import { automationHostRecoveryActions, recoveryActionLabel, type AutomationHostRecoveryAction -} from './automation-host-status-descriptors' -import type { AutomationHostCatalogEntry } from './automation-host-catalog-types' +} from '../hosts/automation-host-status-descriptors' +import type { AutomationHostCatalogEntry } from '../hosts/automation-host-catalog-types' import { useTranslate } from '@/i18n/use-translate' /** Keep status on each host header, including hosts with no rows; unreachable must never read as an empty schedule. */ diff --git a/src/renderer/src/components/automations/AutomationListLastRunCell.tsx b/src/renderer/src/components/automations/listing/AutomationListLastRunCell.tsx similarity index 100% rename from src/renderer/src/components/automations/AutomationListLastRunCell.tsx rename to src/renderer/src/components/automations/listing/AutomationListLastRunCell.tsx diff --git a/src/renderer/src/components/automations/AutomationListLocalRow.tsx b/src/renderer/src/components/automations/listing/AutomationListLocalRow.tsx similarity index 89% rename from src/renderer/src/components/automations/AutomationListLocalRow.tsx rename to src/renderer/src/components/automations/listing/AutomationListLocalRow.tsx index 8c0bd693100..85c2ec0f2b3 100644 --- a/src/renderer/src/components/automations/AutomationListLocalRow.tsx +++ b/src/renderer/src/components/automations/listing/AutomationListLocalRow.tsx @@ -2,14 +2,14 @@ import { capturedAutomationOwner, type AutomationCapturedOwner, type AutomationRowAction -} from './automation-captured-owner' -import type { RuntimeEnvironmentSshBucket } from '../../store/slices/ssh/runtime-environment-ssh' +} from '../hosts/automation-captured-owner' +import type { RuntimeEnvironmentSshBucket } from '../../../store/slices/ssh/runtime-environment-ssh' import React from 'react' import { MoreHorizontal, Pause, Pencil, Play, ShieldCheck, Trash2 } from 'lucide-react' import { ContextMenu, ContextMenuContent, ContextMenuTrigger } from '@/components/ui/context-menu' import { MenuItem, MenuRunItem, MenuSeparator } from './AutomationListRowContextMenuItems' -import { pendingAutomationSetupReviewFromSummary } from './automation-setup-review' -import type { SetupTrustMismatch } from '../../../../shared/worktree/create-types' +import { pendingAutomationSetupReviewFromSummary } from '../authoring/automation-setup-review' +import type { SetupTrustMismatch } from '../../../../../shared/worktree/create-types' import { DropdownMenu, DropdownMenuContent, @@ -21,30 +21,30 @@ import { Button } from '@/components/ui/button' import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip' import { AgentIcon } from '@/components/agent/icons/AgentIcon' import { cn } from '@/lib/utils' -import type { AutomationRun } from '../../../../shared/automations/history/automation-run' -import { getAutomationRunRepoId } from '../../../../shared/automations/history/automation-run-identity' -import { formatUiAutomationSchedule } from './automation-schedule-label' +import type { AutomationRun } from '../../../../../shared/automations/history/automation-run' +import { getAutomationRunRepoId } from '../../../../../shared/automations/history/automation-run-identity' +import { formatUiAutomationSchedule } from '../details/automation-schedule-label' import { getExecutionHostLabel, getLocalExecutionHostLabel, getRepoExecutionHostId -} from '../../../../shared/execution-host' -import type { SshConnectionState } from '../../../../shared/ssh-types' -import type { ProjectHostSetup } from '../../../../shared/project-types' -import type { Repo } from '../../../../shared/repo-types' -import type { Worktree } from '../../../../shared/worktree/types' -import type { RuntimeEnvironmentStatus } from '../../../../shared/remote-runtime/host-status/runtime-host-status' -import type { AutomationHostTarget } from './automation-host-client' +} from '../../../../../shared/execution-host' +import type { SshConnectionState } from '../../../../../shared/ssh-types' +import type { ProjectHostSetup } from '../../../../../shared/project-types' +import type { Repo } from '../../../../../shared/repo-types' +import type { Worktree } from '../../../../../shared/worktree/types' +import type { RuntimeEnvironmentStatus } from '../../../../../shared/remote-runtime/host-status/runtime-host-status' +import type { AutomationHostTarget } from '../hosts/automation-host-client' import { getAutomationRowLastRunSnapshot, getLocalAutomationLastRunSnapshot } from './automation-list-last-run' import { AutomationListLastRunCell } from './AutomationListLastRunCell' -import { formatAutomationDateTimeWithRelative } from './automation-page-parts' -import { getAutomationTargetAvailability } from './automation-target-availability' -import { getAgentLabel } from './automation-draft-model' +import { formatAutomationDateTimeWithRelative } from '../automation-page-parts' +import { getAutomationTargetAvailability } from '../hosts/automation-target-availability' +import { getAgentLabel } from '../authoring/automation-draft-model' import { automationProjectName, type AutomationListRow } from './automation-list-row-identity' -import { formatAutomationUsageSummary } from './automation-usage-model' +import { formatAutomationUsageSummary } from '../runs/automation-usage-model' import { AUTOMATIONS_TABLE_GRID_CLASS } from './automations-table-layout' import { LIST_TABLE_ROW_CLASS, @@ -54,7 +54,7 @@ import { import { isPortaledRowMenuClick, isRowActivationKey } from '@/lib/list-row-interaction' import { AutomationListStatusCell } from './AutomationListStatusCell' import { useIntlLocale, useTranslate } from '@/i18n/use-translate' -import { useAppStore } from '@/store' +import { useAppStore } from '@/store/index' import { wslMovedProjectForAutomation } from '@/store/repos/wsl-moved-projects' export type AutomationListLocalRowProps = { diff --git a/src/renderer/src/components/automations/AutomationListLocalRows.tsx b/src/renderer/src/components/automations/listing/AutomationListLocalRows.tsx similarity index 100% rename from src/renderer/src/components/automations/AutomationListLocalRows.tsx rename to src/renderer/src/components/automations/listing/AutomationListLocalRows.tsx diff --git a/src/renderer/src/components/automations/AutomationListRowContextMenuItems.tsx b/src/renderer/src/components/automations/listing/AutomationListRowContextMenuItems.tsx similarity index 100% rename from src/renderer/src/components/automations/AutomationListRowContextMenuItems.tsx rename to src/renderer/src/components/automations/listing/AutomationListRowContextMenuItems.tsx diff --git a/src/renderer/src/components/automations/AutomationListSearchField.tsx b/src/renderer/src/components/automations/listing/AutomationListSearchField.tsx similarity index 100% rename from src/renderer/src/components/automations/AutomationListSearchField.tsx rename to src/renderer/src/components/automations/listing/AutomationListSearchField.tsx diff --git a/src/renderer/src/components/automations/AutomationListSortHeader.tsx b/src/renderer/src/components/automations/listing/AutomationListSortHeader.tsx similarity index 100% rename from src/renderer/src/components/automations/AutomationListSortHeader.tsx rename to src/renderer/src/components/automations/listing/AutomationListSortHeader.tsx diff --git a/src/renderer/src/components/automations/AutomationListStatusCell.tsx b/src/renderer/src/components/automations/listing/AutomationListStatusCell.tsx similarity index 100% rename from src/renderer/src/components/automations/AutomationListStatusCell.tsx rename to src/renderer/src/components/automations/listing/AutomationListStatusCell.tsx diff --git a/src/renderer/src/components/automations/AutomationListTableHeader.tsx b/src/renderer/src/components/automations/listing/AutomationListTableHeader.tsx similarity index 100% rename from src/renderer/src/components/automations/AutomationListTableHeader.tsx rename to src/renderer/src/components/automations/listing/AutomationListTableHeader.tsx diff --git a/src/renderer/src/components/automations/AutomationListToolbar.tsx b/src/renderer/src/components/automations/listing/AutomationListToolbar.tsx similarity index 95% rename from src/renderer/src/components/automations/AutomationListToolbar.tsx rename to src/renderer/src/components/automations/listing/AutomationListToolbar.tsx index 312c5e0a669..bbe24069a21 100644 --- a/src/renderer/src/components/automations/AutomationListToolbar.tsx +++ b/src/renderer/src/components/automations/listing/AutomationListToolbar.tsx @@ -4,13 +4,13 @@ import { Button } from '@/components/ui/button' import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip' import { useTranslate } from '@/i18n/use-translate' import { cn } from '@/lib/utils' -import type { AutomationHostCatalogEntry } from './automation-host-catalog-types' +import type { AutomationHostCatalogEntry } from '../hosts/automation-host-catalog-types' import type { AutomationListArrowKey } from './automation-list-keyboard-navigation' -import { clampAutomationListSearchQueryInput } from './automation-list-search' +import { clampAutomationListSearchQueryInput } from './automation-list-search-query' import type { AutomationListFilter } from './automation-list-view' import { AutomationListSearchField } from './AutomationListSearchField' import { AutomationListFilterMenu } from './AutomationListFilterMenu' -import type { AutomationTemplate } from './automation-templates' +import type { AutomationTemplate } from '../authoring/automation-templates' type AutomationListToolbarProps = { /** Focus fallback for the list: the controls that produced the rows. */ diff --git a/src/renderer/src/components/automations/AutomationsListPanel.tsx b/src/renderer/src/components/automations/listing/AutomationsListPanel.tsx similarity index 87% rename from src/renderer/src/components/automations/AutomationsListPanel.tsx rename to src/renderer/src/components/automations/listing/AutomationsListPanel.tsx index f468f5a79fa..ac96f41f002 100644 --- a/src/renderer/src/components/automations/AutomationsListPanel.tsx +++ b/src/renderer/src/components/automations/listing/AutomationsListPanel.tsx @@ -1,28 +1,28 @@ -import type { SetupTrustMismatch } from '../../../../shared/worktree/create-types' -import type { RuntimeEnvironmentSshBucket } from '../../store/slices/ssh/runtime-environment-ssh' +import type { SetupTrustMismatch } from '../../../../../shared/worktree/create-types' +import type { RuntimeEnvironmentSshBucket } from '../../../store/slices/ssh/runtime-environment-ssh' import React, { useRef } from 'react' import { cn } from '@/lib/utils' -import type { AutomationRun } from '../../../../shared/automations/history/automation-run' +import type { AutomationRun } from '../../../../../shared/automations/history/automation-run' import type { ExternalAutomationAction, ExternalAutomationJob, ExternalAutomationManager -} from '../../../../shared/automations/external/external-automation' +} from '../../../../../shared/automations/external/external-automation' -import type { SshConnectionState } from '../../../../shared/ssh-types' -import type { ProjectHostSetup } from '../../../../shared/project-types' -import type { Repo } from '../../../../shared/repo-types' -import type { Worktree } from '../../../../shared/worktree/types' -import type { RuntimeEnvironmentStatus } from '../../../../shared/remote-runtime/host-status/runtime-host-status' -import type { AutomationRowAction } from './automation-captured-owner' -import type { AutomationHostTarget } from './automation-host-client' +import type { SshConnectionState } from '../../../../../shared/ssh-types' +import type { ProjectHostSetup } from '../../../../../shared/project-types' +import type { Repo } from '../../../../../shared/repo-types' +import type { Worktree } from '../../../../../shared/worktree/types' +import type { RuntimeEnvironmentStatus } from '../../../../../shared/remote-runtime/host-status/runtime-host-status' +import type { AutomationRowAction } from '../hosts/automation-captured-owner' +import type { AutomationHostTarget } from '../hosts/automation-host-client' import { createAutomationListEnterHandler, getAutomationListArrowNavigationTarget, type AutomationListArrowKey } from './automation-list-keyboard-navigation' import type { AutomationListRow } from './automation-list-row-identity' -import type { AutomationPaneTab } from './automation-page-state' +import type { AutomationPaneTab } from '../automation-page-state' import { AutomationListFilterPills } from './AutomationListFilterMenu' import { isAutomationListFilterActive, @@ -34,23 +34,26 @@ import { import { type AutomationHostFilter, automationHostFilterStableKey -} from '../../../../shared/automations/ownership/automation-host-filter' -import type { AutomationTemplate } from './automation-templates' -import type { ExternalAutomationListEntry } from './external-automation-list-entries' -import type { ExternalAutomationScope } from './external-automation-scope-client' +} from '../../../../../shared/automations/ownership/automation-host-filter' +import type { AutomationTemplate } from '../authoring/automation-templates' +import type { ExternalAutomationListEntry } from '../external/external-automation-list-entries' +import type { ExternalAutomationScope } from '../external/external-automation-scope-client' import { AutomationListLocalRow } from './AutomationListLocalRow' import { AutomationListExternalRow } from './AutomationListExternalRow' -import { AutomationHostFilterNotice, AutomationHostLoadSummary } from './AutomationHostFilterNotice' +import { + AutomationHostFilterNotice, + AutomationHostLoadSummary +} from '../hosts/AutomationHostFilterNotice' import { AutomationListEmptyView } from './AutomationListEmptyView' import { resolveAutomationListEmptyState } from './automation-list-empty-state' import type { AutomationListSearchCounts } from './use-automation-list-search' -import type { AutomationHostCatalogView } from './use-automation-host-catalog' -import type { AutomationHostRecoveryAction } from './automation-host-status-descriptors' -import type { AutomationHostCatalogEntry } from './automation-host-catalog-types' +import type { AutomationHostCatalogView } from '../hosts/use-automation-host-catalog' +import type { AutomationHostRecoveryAction } from '../hosts/automation-host-status-descriptors' +import type { AutomationHostCatalogEntry } from '../hosts/automation-host-catalog-types' import { useAutomationListFocusRecovery } from './use-automation-list-focus-recovery' import { LIST_TABLE_CONTAINER_CLASS } from '@/lib/list-table-layout' import { useTranslate } from '@/i18n/use-translate' -import { AutomationTemplateEmptyState } from './AutomationTemplateEmptyState' +import { AutomationTemplateEmptyState } from '../authoring/AutomationTemplateEmptyState' import { AutomationListTableHeader } from './AutomationListTableHeader' import { AutomationListToolbar } from './AutomationListToolbar' diff --git a/src/renderer/src/components/automations/automation-list-empty-state.ts b/src/renderer/src/components/automations/listing/automation-list-empty-state.ts similarity index 97% rename from src/renderer/src/components/automations/automation-list-empty-state.ts rename to src/renderer/src/components/automations/listing/automation-list-empty-state.ts index b996b136af3..4348ed2ed5e 100644 --- a/src/renderer/src/components/automations/automation-list-empty-state.ts +++ b/src/renderer/src/components/automations/listing/automation-list-empty-state.ts @@ -1,14 +1,14 @@ import { translate } from '@/i18n/i18n' import type { Translate } from '@/i18n/use-translate' -import type { AutomationHostCatalogEntry } from './automation-host-catalog-types' +import type { AutomationHostCatalogEntry } from '../hosts/automation-host-catalog-types' import type { AutomationHostFilterResolution, AutomationHostFilterStatus -} from './automation-host-filter-resolution' +} from '../hosts/automation-host-filter-resolution' import { automationHostRecoveryActions, type AutomationHostRecoveryAction -} from './automation-host-status-descriptors' +} from '../hosts/automation-host-status-descriptors' /** Describe disconnected, unreachable or unhydrated hosts as unknown, never empty; no storage read established that claim. */ diff --git a/src/renderer/src/components/automations/automation-list-focus-recovery.ts b/src/renderer/src/components/automations/listing/automation-list-focus-recovery.ts similarity index 100% rename from src/renderer/src/components/automations/automation-list-focus-recovery.ts rename to src/renderer/src/components/automations/listing/automation-list-focus-recovery.ts diff --git a/src/renderer/src/components/automations/automation-list-keyboard-navigation.ts b/src/renderer/src/components/automations/listing/automation-list-keyboard-navigation.ts similarity index 98% rename from src/renderer/src/components/automations/automation-list-keyboard-navigation.ts rename to src/renderer/src/components/automations/listing/automation-list-keyboard-navigation.ts index 3e364851b74..f210f4cd596 100644 --- a/src/renderer/src/components/automations/automation-list-keyboard-navigation.ts +++ b/src/renderer/src/components/automations/listing/automation-list-keyboard-navigation.ts @@ -1,5 +1,5 @@ import type { AutomationListViewItem } from './automation-list-view' -import type { AutomationPaneTab } from './automation-page-state' +import type { AutomationPaneTab } from '../automation-page-state' export type AutomationListArrowKey = 'ArrowUp' | 'ArrowDown' diff --git a/src/renderer/src/components/automations/automation-list-last-run.ts b/src/renderer/src/components/automations/listing/automation-list-last-run.ts similarity index 94% rename from src/renderer/src/components/automations/automation-list-last-run.ts rename to src/renderer/src/components/automations/listing/automation-list-last-run.ts index 6e484d826d1..717a1765cf0 100644 --- a/src/renderer/src/components/automations/automation-list-last-run.ts +++ b/src/renderer/src/components/automations/listing/automation-list-last-run.ts @@ -1,16 +1,16 @@ import { translate } from '@/i18n/i18n' import type { Translate } from '@/i18n/use-translate' -import type { Automation } from '../../../../shared/automations/automation-definition' +import type { Automation } from '../../../../../shared/automations/automation-definition' import type { AutomationRun, AutomationRunStatus -} from '../../../../shared/automations/history/automation-run' -import type { ExternalAutomationJob } from '../../../../shared/automations/external/external-automation' +} from '../../../../../shared/automations/history/automation-run' +import type { ExternalAutomationJob } from '../../../../../shared/automations/external/external-automation' import { formatAutomationDateTime, formatAutomationRelativeTime, getAutomationRunStatusLabel -} from './automation-page-parts' +} from '../automation-page-parts' export type AutomationLastRunTone = | 'failed' diff --git a/src/renderer/src/components/automations/automation-list-row-identity.ts b/src/renderer/src/components/automations/listing/automation-list-row-identity.ts similarity index 85% rename from src/renderer/src/components/automations/automation-list-row-identity.ts rename to src/renderer/src/components/automations/listing/automation-list-row-identity.ts index e58792a7c9c..63ac6231ddc 100644 --- a/src/renderer/src/components/automations/automation-list-row-identity.ts +++ b/src/renderer/src/components/automations/listing/automation-list-row-identity.ts @@ -1,10 +1,10 @@ /** Qualify row IDs by incarnation-free host stableKey so colliding authorities stay distinct and re-pairs preserve React identity/selection. Freshness uses incarnation-bearing ownerKey separately. */ -import type { Automation } from '../../../../shared/automations/automation-definition' -import type { AutomationUsageSummary } from '../../../../shared/automations/history/automation-usage-summary' -import { findAutomationRepo } from '../../../../shared/automations/ownership/automation-repo-target' -import { getAutomationRunRepoId } from '../../../../shared/automations/history/automation-run-identity' -import type { StableAutomationCatalogRef } from '../../../../shared/automations/ownership/automation-owner-ref' +import type { Automation } from '../../../../../shared/automations/automation-definition' +import type { AutomationUsageSummary } from '../../../../../shared/automations/history/automation-usage-summary' +import { findAutomationRepo } from '../../../../../shared/automations/ownership/automation-repo-target' +import { getAutomationRunRepoId } from '../../../../../shared/automations/history/automation-run-identity' +import type { StableAutomationCatalogRef } from '../../../../../shared/automations/ownership/automation-owner-ref' import { getRepoExecutionHostId, getConnectionExecutionHostId, @@ -12,21 +12,21 @@ import { toSshExecutionHostId, parseExecutionHostId, toRuntimeExecutionHostId -} from '../../../../shared/execution-host' +} from '../../../../../shared/execution-host' import { resolveQualifiedFolderWorkspaceResult, type QualifiedFolderHostState -} from '../../../../shared/folder-workspaces/folder-workspace-execution-host' +} from '../../../../../shared/folder-workspaces/folder-workspace-execution-host' import { createRepoRowExecutionHostLookup, resolveWorktreeExecutionHost -} from '../../../../shared/execution-host/worktree-execution-host-resolution' -import type { FolderWorkspace } from '../../../../shared/folder-workspaces/folder-workspace-types' -import type { Repo } from '../../../../shared/repo-types' -import type { Worktree } from '../../../../shared/worktree/types' -import { parseWorkspaceKey } from '../../../../shared/workspace-scope' +} from '../../../../../shared/execution-host/worktree-execution-host-resolution' +import type { FolderWorkspace } from '../../../../../shared/folder-workspaces/folder-workspace-types' +import type { Repo } from '../../../../../shared/repo-types' +import type { Worktree } from '../../../../../shared/worktree/types' +import { parseWorkspaceKey } from '../../../../../shared/workspace-scope' -import { getFolderWorkspaceWorktree } from '../../../../shared/folder-workspaces/folder-workspace-worktree' +import { getFolderWorkspaceWorktree } from '../../../../../shared/folder-workspaces/folder-workspace-worktree' export type AutomationListRow = { /** Authority-qualified and incarnation-free; see the module note. */ diff --git a/src/renderer/src/components/automations/automation-list-search-query.ts b/src/renderer/src/components/automations/listing/automation-list-search-query.ts similarity index 98% rename from src/renderer/src/components/automations/automation-list-search-query.ts rename to src/renderer/src/components/automations/listing/automation-list-search-query.ts index fec6b0f17b8..e2d93ccf61d 100644 --- a/src/renderer/src/components/automations/automation-list-search-query.ts +++ b/src/renderer/src/components/automations/listing/automation-list-search-query.ts @@ -1,4 +1,4 @@ -import { isClipboardTextByteLengthOverLimit } from '../../../../shared/clipboard-text' +import { isClipboardTextByteLengthOverLimit } from '../../../../../shared/clipboard-text' /** Pasted queries above this are rejected so filtering never runs on unbounded input. */ export const AUTOMATION_LIST_SEARCH_QUERY_MAX_BYTES = 2 * 1024 diff --git a/src/renderer/src/components/automations/automation-list-search-rows.ts b/src/renderer/src/components/automations/listing/automation-list-search-rows.ts similarity index 89% rename from src/renderer/src/components/automations/automation-list-search-rows.ts rename to src/renderer/src/components/automations/listing/automation-list-search-rows.ts index 8ebb6566b70..38fbb317321 100644 --- a/src/renderer/src/components/automations/automation-list-search-rows.ts +++ b/src/renderer/src/components/automations/listing/automation-list-search-rows.ts @@ -1,8 +1,8 @@ -import { getAutomationRunRepoId } from '../../../../shared/automations/history/automation-run-identity' -import type { Automation } from '../../../../shared/automations/automation-definition' -import type { Repo } from '../../../../shared/repo-types' +import { getAutomationRunRepoId } from '../../../../../shared/automations/history/automation-run-identity' +import type { Automation } from '../../../../../shared/automations/automation-definition' +import type { Repo } from '../../../../../shared/repo-types' import type { AutomationListRow } from './automation-list-row-identity' -import { getAgentLabel } from './automation-draft-model' +import { getAgentLabel } from '../authoring/automation-draft-model' import { automationListSearchIndexMatches, buildAutomationListSearchFingerprint, @@ -11,8 +11,8 @@ import { type AutomationListSearchFields, type AutomationListSearchIndex } from './automation-list-search' -import { getExternalProviderLabel } from './external-automation-display' -import type { ExternalAutomationListEntry } from './external-automation-list-entries' +import { getExternalProviderLabel } from '../external/external-automation-display' +import type { ExternalAutomationListEntry } from '../external/external-automation-list-entries' /** Row identity is the authority-qualified row key / external key, so reorders invalidate the index. */ export type AutomationListSearchRowSource = { diff --git a/src/renderer/src/components/automations/automation-list-search.ts b/src/renderer/src/components/automations/listing/automation-list-search.ts similarity index 93% rename from src/renderer/src/components/automations/automation-list-search.ts rename to src/renderer/src/components/automations/listing/automation-list-search.ts index f1d3a9926fd..d6836798abd 100644 --- a/src/renderer/src/components/automations/automation-list-search.ts +++ b/src/renderer/src/components/automations/listing/automation-list-search.ts @@ -1,12 +1,3 @@ -export { - AUTOMATION_LIST_SEARCH_QUERY_MAX_BYTES, - clampAutomationListSearchQueryInput, - getActiveAutomationListSearchQuery, - isAutomationListSearchQueryTooLarge, - resolveAutomationListSearchQuery, - type AutomationListSearchQueryResolution -} from './automation-list-search-query' - // Bound indexed fields so lowercasing/includes cannot scale with multi-MB prompts. export const AUTOMATION_LIST_SEARCH_NAME_MAX_CODE_UNITS = 512 export const AUTOMATION_LIST_SEARCH_PROJECT_MAX_CODE_UNITS = 1_024 diff --git a/src/renderer/src/components/automations/automation-list-view.ts b/src/renderer/src/components/automations/listing/automation-list-view.ts similarity index 95% rename from src/renderer/src/components/automations/automation-list-view.ts rename to src/renderer/src/components/automations/listing/automation-list-view.ts index a7090e71d8d..9d41813ad86 100644 --- a/src/renderer/src/components/automations/automation-list-view.ts +++ b/src/renderer/src/components/automations/listing/automation-list-view.ts @@ -1,13 +1,13 @@ -import type { TuiAgent } from '../../../../shared/agent-launch/catalog/tui-agent' -import { hostStableKey } from '../../../../shared/automations/ownership/automation-owner-key' +import type { TuiAgent } from '../../../../../shared/agent-launch/catalog/tui-agent' +import { hostStableKey } from '../../../../../shared/automations/ownership/automation-owner-key' import type { AutomationListRow } from './automation-list-row-identity' -import type { ExternalAutomationListEntry } from './external-automation-list-entries' +import type { ExternalAutomationListEntry } from '../external/external-automation-list-entries' import { getAutomationRowLastRunSnapshot, getExternalAutomationLastRunSnapshot, type AutomationLastRunSnapshot } from './automation-list-last-run' -import type { Translate } from '../../i18n/use-translate' +import type { Translate } from '../../../i18n/use-translate' export type AutomationListStatusFilter = 'all' | 'enabled' | 'paused' export type AutomationListLastRunFilter = 'all' | 'failed' | 'succeeded' | 'never' diff --git a/src/renderer/src/components/automations/automations-table-layout.ts b/src/renderer/src/components/automations/listing/automations-table-layout.ts similarity index 100% rename from src/renderer/src/components/automations/automations-table-layout.ts rename to src/renderer/src/components/automations/listing/automations-table-layout.ts diff --git a/src/renderer/src/components/automations/use-automation-list-focus-recovery.ts b/src/renderer/src/components/automations/listing/use-automation-list-focus-recovery.ts similarity index 100% rename from src/renderer/src/components/automations/use-automation-list-focus-recovery.ts rename to src/renderer/src/components/automations/listing/use-automation-list-focus-recovery.ts diff --git a/src/renderer/src/components/automations/use-automation-list-search.test.tsx b/src/renderer/src/components/automations/listing/use-automation-list-search.test.tsx similarity index 96% rename from src/renderer/src/components/automations/use-automation-list-search.test.tsx rename to src/renderer/src/components/automations/listing/use-automation-list-search.test.tsx index 08bc7892067..bdee9b8dac2 100644 --- a/src/renderer/src/components/automations/use-automation-list-search.test.tsx +++ b/src/renderer/src/components/automations/listing/use-automation-list-search.test.tsx @@ -3,8 +3,8 @@ import { act } from 'react' import { createRoot, type Root } from 'react-dom/client' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import type { Repo } from '../../../../shared/repo-types' -import { makeAutomation, makeAutomationListRow, REPO_ID } from './automations-page-fixtures' +import type { Repo } from '../../../../../shared/repo-types' +import { makeAutomation, makeAutomationListRow, REPO_ID } from '../automations-page-fixtures' import type { AutomationListRow } from './automation-list-row-identity' import * as searchRows from './automation-list-search-rows' diff --git a/src/renderer/src/components/automations/use-automation-list-search.ts b/src/renderer/src/components/automations/listing/use-automation-list-search.ts similarity index 97% rename from src/renderer/src/components/automations/use-automation-list-search.ts rename to src/renderer/src/components/automations/listing/use-automation-list-search.ts index 207cb9bddb7..06938727b8b 100644 --- a/src/renderer/src/components/automations/use-automation-list-search.ts +++ b/src/renderer/src/components/automations/listing/use-automation-list-search.ts @@ -1,6 +1,6 @@ import { useDeferredValue, useEffect, useMemo, useRef } from 'react' -import type { Repo } from '../../../../shared/repo-types' -import { resolveAutomationListSearchQuery } from './automation-list-search' +import type { Repo } from '../../../../../shared/repo-types' +import { resolveAutomationListSearchQuery } from './automation-list-search-query' import type { AutomationListRow } from './automation-list-row-identity' import { buildAutomationListSearchRowFingerprint, @@ -12,7 +12,7 @@ import { type AutomationListSearchRowSource, type AutomationWorkspaceNameLookup } from './automation-list-search-rows' -import type { ExternalAutomationListEntry } from './external-automation-list-entries' +import type { ExternalAutomationListEntry } from '../external/external-automation-list-entries' /** Counts the empty-state view consumes, so it never recomputes what search already knows. */ export type AutomationListSearchCounts = { diff --git a/src/renderer/src/components/automations/use-automations-page-list-state.ts b/src/renderer/src/components/automations/listing/use-automations-page-list-state.ts similarity index 87% rename from src/renderer/src/components/automations/use-automations-page-list-state.ts rename to src/renderer/src/components/automations/listing/use-automations-page-list-state.ts index bbcf82d7e50..6e59091092c 100644 --- a/src/renderer/src/components/automations/use-automations-page-list-state.ts +++ b/src/renderer/src/components/automations/listing/use-automations-page-list-state.ts @@ -1,17 +1,20 @@ import { useCallback, useMemo } from 'react' -import { useAppStore } from '@/store' +import { useAppStore } from '@/store/index' import { hostStableKey, ownerKey, toStableCatalogRef -} from '../../../../shared/automations/ownership/automation-owner-key' -import { resolveAutomationRunTarget } from './automation-run-open-target' -import { capturedAutomationOwner, capturedAutomationOwnerKey } from './automation-captured-owner' -import type { AutomationRun } from '../../../../shared/automations/history/automation-run' -import { getWorktreePathBasenameFromId } from '../../../../shared/worktree/id' -import { buildExternalAutomationListEntries } from './external-automation-list-entries' -import { externalAutomationScopeEntries } from './external-automation-scope-gating' -import { externalAutomationUncheckedNotice } from './external-automation-unchecked-hosts' +} from '../../../../../shared/automations/ownership/automation-owner-key' +import { resolveAutomationRunTarget } from '../runs/automation-run-open-target' +import { + capturedAutomationOwner, + capturedAutomationOwnerKey +} from '../hosts/automation-captured-owner' +import type { AutomationRun } from '../../../../../shared/automations/history/automation-run' +import { getWorktreePathBasenameFromId } from '../../../../../shared/worktree/id' +import { buildExternalAutomationListEntries } from '../external/external-automation-list-entries' +import { externalAutomationScopeEntries } from '../external/external-automation-scope-gating' +import { externalAutomationUncheckedNotice } from '../external/external-automation-unchecked-hosts' import { buildAutomationListViewItems, filterAutomationListRows, @@ -20,11 +23,11 @@ import { } from './automation-list-view' import { useIntlLocale } from '@/i18n/use-translate' import { unscopedAutomationListRows } from './automation-list-row-identity' -import { useAutomationHostCatalog } from './use-automation-host-catalog' +import { useAutomationHostCatalog } from '../hosts/use-automation-host-catalog' import { useAutomationListSearch } from './use-automation-list-search' -import { useScopedExternalAutomations } from './use-scoped-external-automations' -import type { AutomationsPageLocalState } from './use-automations-page-local-state' -import type { AutomationsPageStoreState } from './use-automations-page-store-state' +import { useScopedExternalAutomations } from '../external/use-scoped-external-automations' +import type { AutomationsPageLocalState } from '../use-automations-page-local-state' +import type { AutomationsPageStoreState } from '../use-automations-page-store-state' /** Host-qualified rows, external scopes, selection, and list-search projection. */ export function useAutomationsPageListState({ diff --git a/src/renderer/src/components/automations/AutomationRunDetailsPage.tsx b/src/renderer/src/components/automations/runs/AutomationRunDetailsPage.tsx similarity index 93% rename from src/renderer/src/components/automations/AutomationRunDetailsPage.tsx rename to src/renderer/src/components/automations/runs/AutomationRunDetailsPage.tsx index b252a7beef8..c393904acd9 100644 --- a/src/renderer/src/components/automations/AutomationRunDetailsPage.tsx +++ b/src/renderer/src/components/automations/runs/AutomationRunDetailsPage.tsx @@ -4,16 +4,16 @@ import { Button } from '@/components/ui/button' import CommentMarkdown from '@/components/sidebar/CommentMarkdown' import { cn } from '@/lib/utils' import { useIntlLocale, useTranslate } from '@/i18n/use-translate' -import type { Automation } from '../../../../shared/automations/automation-definition' -import type { AutomationRun } from '../../../../shared/automations/history/automation-run' +import type { Automation } from '../../../../../shared/automations/automation-definition' +import type { AutomationRun } from '../../../../../shared/automations/history/automation-run' import { AutomationRunPageFrame } from './AutomationRunPageFrame' import { getAutomationRunContent } from './automation-run-content' import { automationRunErrorText } from './automation-run-error-copy' import type { AutomationRunViewState } from './automation-run-view-state' import type { AutomationRunWorkspaceDisplay } from './automation-run-workspace-display' import { useFullAutomationRun } from './use-full-automation-run' -import { pendingAutomationSetupReview } from './automation-setup-review' -import type { SetupTrustMismatch } from '../../../../shared/worktree/create-types' +import { pendingAutomationSetupReview } from '../authoring/automation-setup-review' +import type { SetupTrustMismatch } from '../../../../../shared/worktree/create-types' import type { SelectedAutomationRunHistoryOutcome } from './use-selected-automation-run-history' import { AutomationRunErrorNotice, @@ -21,7 +21,7 @@ import { formatAutomationDateTimeWithRelative, getAutomationRunStatusLabel, getAutomationRunStatusVariant -} from './automation-page-parts' +} from '../automation-page-parts' export function AutomationRunDetailsPage({ automation, diff --git a/src/renderer/src/components/automations/AutomationRunHistory.tsx b/src/renderer/src/components/automations/runs/AutomationRunHistory.tsx similarity index 96% rename from src/renderer/src/components/automations/AutomationRunHistory.tsx rename to src/renderer/src/components/automations/runs/AutomationRunHistory.tsx index 2a5170c22b9..6fe9129addd 100644 --- a/src/renderer/src/components/automations/AutomationRunHistory.tsx +++ b/src/renderer/src/components/automations/runs/AutomationRunHistory.tsx @@ -2,13 +2,13 @@ import React, { useCallback, useLayoutEffect, useMemo, useRef, useState } from ' import { useVirtualizer } from '@tanstack/react-virtual' import { Badge } from '@/components/ui/badge' import { cn } from '@/lib/utils' -import type { AutomationRun } from '../../../../shared/automations/history/automation-run' -import type { Worktree } from '../../../../shared/worktree/types' +import type { AutomationRun } from '../../../../../shared/automations/history/automation-run' +import type { Worktree } from '../../../../../shared/worktree/types' import { formatAutomationDateTime, getAutomationRunStatusLabel, getAutomationRunStatusVariant -} from './automation-page-parts' +} from '../automation-page-parts' import { formatAutomationCost, formatAutomationTokens, @@ -16,9 +16,9 @@ import { } from './automation-usage-model' import { automationRunOccurrenceLabel, isAutomationRunFolded } from './automation-run-occurrences' import { getAutomationRunWorkspaceDisplay } from './automation-run-workspace-display' -import { AutomationOwnerConflictNotice } from './AutomationOwnerConflictNotice' -import type { AutomationActionNotice } from './automation-row-action-dispatch' -import type { AutomationHostRecoveryAction } from './automation-host-status-descriptors' +import { AutomationOwnerConflictNotice } from '../hosts/AutomationOwnerConflictNotice' +import type { AutomationActionNotice } from '../hosts/automation-row-action-dispatch' +import type { AutomationHostRecoveryAction } from '../hosts/automation-host-status-descriptors' import { getAutomationRunHistoryArrowTarget, isAutomationRunHistoryArrowKey, diff --git a/src/renderer/src/components/automations/AutomationRunPageFrame.tsx b/src/renderer/src/components/automations/runs/AutomationRunPageFrame.tsx similarity index 100% rename from src/renderer/src/components/automations/AutomationRunPageFrame.tsx rename to src/renderer/src/components/automations/runs/AutomationRunPageFrame.tsx diff --git a/src/renderer/src/components/automations/AutomationRunsDashboard.tsx b/src/renderer/src/components/automations/runs/AutomationRunsDashboard.tsx similarity index 99% rename from src/renderer/src/components/automations/AutomationRunsDashboard.tsx rename to src/renderer/src/components/automations/runs/AutomationRunsDashboard.tsx index 121d4eab838..ada20eae61e 100644 --- a/src/renderer/src/components/automations/AutomationRunsDashboard.tsx +++ b/src/renderer/src/components/automations/runs/AutomationRunsDashboard.tsx @@ -17,7 +17,7 @@ import { Input } from '@/components/ui/input' import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip' import { useTranslate } from '@/i18n/use-translate' import { useUiLanguageRevision } from '@/i18n/use-ui-language-revision' -import type { AutomationListRow } from './automation-list-row-identity' +import type { AutomationListRow } from '../listing/automation-list-row-identity' import { countAutomationRunOutcomes, filterAutomationRunsDashboardEntries, diff --git a/src/renderer/src/components/automations/AutomationRunsDashboardSurface.tsx b/src/renderer/src/components/automations/runs/AutomationRunsDashboardSurface.tsx similarity index 87% rename from src/renderer/src/components/automations/AutomationRunsDashboardSurface.tsx rename to src/renderer/src/components/automations/runs/AutomationRunsDashboardSurface.tsx index 2cfe6edc2a9..2a8b8aa6209 100644 --- a/src/renderer/src/components/automations/AutomationRunsDashboardSurface.tsx +++ b/src/renderer/src/components/automations/runs/AutomationRunsDashboardSurface.tsx @@ -1,12 +1,15 @@ import React from 'react' -import { toRuntimeExecutionHostId, type ExecutionHostId } from '../../../../shared/execution-host' -import type { AutomationListRow } from './automation-list-row-identity' +import { + toRuntimeExecutionHostId, + type ExecutionHostId +} from '../../../../../shared/execution-host' +import type { AutomationListRow } from '../listing/automation-list-row-identity' import type { AutomationRunsDashboardEntry, AutomationRunsDashboardFailure } from './automation-runs-dashboard-model' import { AutomationRunsDashboard } from './AutomationRunsDashboard' -import type { AutomationsPageView } from './automation-page-state' +import type { AutomationsPageView } from '../automation-page-state' export function AutomationRunsDashboardSurface({ rows, diff --git a/src/renderer/src/components/automations/AutomationRunsTable.tsx b/src/renderer/src/components/automations/runs/AutomationRunsTable.tsx similarity index 99% rename from src/renderer/src/components/automations/AutomationRunsTable.tsx rename to src/renderer/src/components/automations/runs/AutomationRunsTable.tsx index 07e7ffacdb8..622ac1e51e5 100644 --- a/src/renderer/src/components/automations/AutomationRunsTable.tsx +++ b/src/renderer/src/components/automations/runs/AutomationRunsTable.tsx @@ -8,7 +8,7 @@ import { formatAutomationDateTimeWithRelative, getAutomationRunStatusLabel, getAutomationRunStatusVariant -} from './automation-page-parts' +} from '../automation-page-parts' const RUN_ROW_HEIGHT_PX = 59 const RUN_ROW_OVERSCAN = 10 diff --git a/src/renderer/src/components/automations/automation-run-actions.ts b/src/renderer/src/components/automations/runs/automation-run-actions.ts similarity index 87% rename from src/renderer/src/components/automations/automation-run-actions.ts rename to src/renderer/src/components/automations/runs/automation-run-actions.ts index 349375c18bb..ec1546678c5 100644 --- a/src/renderer/src/components/automations/automation-run-actions.ts +++ b/src/renderer/src/components/automations/runs/automation-run-actions.ts @@ -1,14 +1,14 @@ -import { capturedAutomationOwner } from './automation-captured-owner' +import { capturedAutomationOwner } from '../hosts/automation-captured-owner' import { toast } from 'sonner' -import type { AutomationRun } from '../../../../shared/automations/history/automation-run' +import type { AutomationRun } from '../../../../../shared/automations/history/automation-run' import { translate } from '@/i18n/i18n' -import { useAppStore } from '@/store' -import { getAutomationTargetAvailability } from './automation-target-availability' -import { runAutomationNowForTarget } from './automation-host-client' -import { dispatchAutomationRunNow } from './automation-row-action-dispatch' +import { useAppStore } from '@/store/index' +import { getAutomationTargetAvailability } from '../hosts/automation-target-availability' +import { runAutomationNowForTarget } from '../hosts/automation-host-client' +import { dispatchAutomationRunNow } from '../hosts/automation-row-action-dispatch' import { waitForAutomationRerunPendingVisibility } from './automation-run-view-state' -import type { AutomationListRow } from './automation-list-row-identity' -import type { AutomationsPageActionContext } from './automations-page-action-context' +import type { AutomationListRow } from '../listing/automation-list-row-identity' +import type { AutomationsPageActionContext } from '../automations-page-action-context' /** Run-now/rerun handlers keyed by the selected row's captured host. */ export function createAutomationRunActions({ diff --git a/src/renderer/src/components/automations/automation-run-completion-evidence.ts b/src/renderer/src/components/automations/runs/automation-run-completion-evidence.ts similarity index 85% rename from src/renderer/src/components/automations/automation-run-completion-evidence.ts rename to src/renderer/src/components/automations/runs/automation-run-completion-evidence.ts index 0e17d6a4dbb..7e9278b9d5f 100644 --- a/src/renderer/src/components/automations/automation-run-completion-evidence.ts +++ b/src/renderer/src/components/automations/runs/automation-run-completion-evidence.ts @@ -1,5 +1,5 @@ -import type { AutomationRun } from '../../../../shared/automations/history/automation-run' -import type { AgentStatusEntry } from '../../../../shared/agent-status/contracts/agent-status-types' +import type { AutomationRun } from '../../../../../shared/automations/history/automation-run' +import type { AgentStatusEntry } from '../../../../../shared/agent-status/contracts/agent-status-types' import type { RetainedAgentEntry } from '@/store/slices/agent-status/agent-status-contract' import { automationRunMatchesPaneKey } from './automation-run-open-target' diff --git a/src/renderer/src/components/automations/automation-run-content.ts b/src/renderer/src/components/automations/runs/automation-run-content.ts similarity index 75% rename from src/renderer/src/components/automations/automation-run-content.ts rename to src/renderer/src/components/automations/runs/automation-run-content.ts index 1e60554de81..dc56d6957d0 100644 --- a/src/renderer/src/components/automations/automation-run-content.ts +++ b/src/renderer/src/components/automations/runs/automation-run-content.ts @@ -1,5 +1,5 @@ -import type { AutomationRun } from '../../../../shared/automations/history/automation-run' -import { getAutomationRunContent as getSharedAutomationRunContent } from '../../../../shared/automations/history/automation-run-content' +import type { AutomationRun } from '../../../../../shared/automations/history/automation-run' +import { getAutomationRunContent as getSharedAutomationRunContent } from '../../../../../shared/automations/history/automation-run-content' import { translate } from '@/i18n/i18n' import type { Translate } from '@/i18n/use-translate' import { automationRunErrorText } from './automation-run-error-copy' diff --git a/src/renderer/src/components/automations/automation-run-error-copy.ts b/src/renderer/src/components/automations/runs/automation-run-error-copy.ts similarity index 96% rename from src/renderer/src/components/automations/automation-run-error-copy.ts rename to src/renderer/src/components/automations/runs/automation-run-error-copy.ts index 0656d23b19e..c7480ce7376 100644 --- a/src/renderer/src/components/automations/automation-run-error-copy.ts +++ b/src/renderer/src/components/automations/runs/automation-run-error-copy.ts @@ -2,8 +2,8 @@ import { translate } from '@/i18n/i18n' import { AUTOMATION_RUN_FAILURE_COPY as EN, type AutomationRunFailureCode -} from '../../../../shared/automations/history/automation-run-failure-copy' -import type { AutomationRun } from '../../../../shared/automations/history/automation-run' +} from '../../../../../shared/automations/history/automation-run-failure-copy' +import type { AutomationRun } from '../../../../../shared/automations/history/automation-run' // One whole sentence per non-ready setup state; unknown states keep the stored English. const SETUP_STATE_COPY: Record string> = { diff --git a/src/renderer/src/components/automations/automation-run-history-keyboard-navigation.test.ts b/src/renderer/src/components/automations/runs/automation-run-history-keyboard-navigation.test.ts similarity index 100% rename from src/renderer/src/components/automations/automation-run-history-keyboard-navigation.test.ts rename to src/renderer/src/components/automations/runs/automation-run-history-keyboard-navigation.test.ts diff --git a/src/renderer/src/components/automations/automation-run-history-keyboard-navigation.ts b/src/renderer/src/components/automations/runs/automation-run-history-keyboard-navigation.ts similarity index 96% rename from src/renderer/src/components/automations/automation-run-history-keyboard-navigation.ts rename to src/renderer/src/components/automations/runs/automation-run-history-keyboard-navigation.ts index 5b61eab7ff0..147d5bcbb00 100644 --- a/src/renderer/src/components/automations/automation-run-history-keyboard-navigation.ts +++ b/src/renderer/src/components/automations/runs/automation-run-history-keyboard-navigation.ts @@ -1,4 +1,4 @@ -import type { AutomationRun } from '../../../../shared/automations/history/automation-run' +import type { AutomationRun } from '../../../../../shared/automations/history/automation-run' import { isImeOwnedKeyboardEvent } from '@/lib/text-input/ime/ime-composition-keyboard-event' export type AutomationRunHistoryArrowKey = 'ArrowUp' | 'ArrowDown' diff --git a/src/renderer/src/components/automations/automation-run-occurrences.ts b/src/renderer/src/components/automations/runs/automation-run-occurrences.ts similarity index 90% rename from src/renderer/src/components/automations/automation-run-occurrences.ts rename to src/renderer/src/components/automations/runs/automation-run-occurrences.ts index c4b148f40cb..09011a19fe4 100644 --- a/src/renderer/src/components/automations/automation-run-occurrences.ts +++ b/src/renderer/src/components/automations/runs/automation-run-occurrences.ts @@ -1,7 +1,7 @@ /** Folded rows retain the first occurrence date; count/latest occurrence must expose continuing failures rather than suggesting one old event. */ -import type { AutomationRun } from '../../../../shared/automations/history/automation-run' -import { formatAutomationDateTime } from './automation-page-parts' +import type { AutomationRun } from '../../../../../shared/automations/history/automation-run' +import { formatAutomationDateTime } from '../automation-page-parts' import { translate } from '@/i18n/i18n' import type { Translate } from '@/i18n/use-translate' diff --git a/src/renderer/src/components/automations/runs/automation-run-open-target.test.ts b/src/renderer/src/components/automations/runs/automation-run-open-target.test.ts new file mode 100644 index 00000000000..52c986924ae --- /dev/null +++ b/src/renderer/src/components/automations/runs/automation-run-open-target.test.ts @@ -0,0 +1,84 @@ +import { describe, expect, it } from 'vitest' +import type { AutomationRun } from '../../../../../shared/automations/history/automation-run' + +import { resolveAutomationRunOpenTarget } from './automation-run-open-target' + +const leafId = '11111111-1111-4111-8111-111111111111' +const otherLeafId = '22222222-2222-4222-8222-222222222222' +const paneKey = `tab-1:${leafId}` + +const runLeafLayout = { + root: { type: 'leaf' as const, leafId }, + activeLeafId: leafId, + expandedLeafId: null +} +const livePtyIds = ['pty-run'] + +function run(overrides: Partial = {}): AutomationRun { + return { + id: 'run-1', + automationId: 'automation-1', + title: 'Run 1', + scheduledFor: 1, + status: 'completed', + trigger: 'manual', + workspaceId: 'wt-1', + workspaceDisplayName: 'Workspace', + sessionKind: 'terminal', + chatSessionId: null, + terminalSessionId: 'tab-1', + terminalPaneKey: paneKey, + terminalPtyId: 'pty-run', + outputSnapshot: null, + precheckResult: null, + usage: null, + error: null, + startedAt: 1, + dispatchedAt: 1, + createdAt: 1, + ...overrides + } +} + +describe('automation run open target', () => { + it('rejects a layout whose run leaf is bound to another PTY', () => { + expect( + resolveAutomationRunOpenTarget({ + run: run(), + terminalTabExists: true, + currentLayout: { + ...runLeafLayout, + ptyIdsByLeafId: { [leafId]: 'pty-other' } + }, + livePtyIds + }) + ).toBeNull() + }) + + it('does not rebuild a layout that is missing the run pane', () => { + expect( + resolveAutomationRunOpenTarget({ + run: run(), + terminalTabExists: true, + currentLayout: { + root: { type: 'leaf', leafId: otherLeafId }, + activeLeafId: otherLeafId, + expandedLeafId: null, + ptyIdsByLeafId: { [otherLeafId]: 'pty-empty-shell' } + }, + livePtyIds + }) + ).toBeNull() + }) + + it('does not open when the current tab layout is unavailable', () => { + expect( + resolveAutomationRunOpenTarget({ + run: run(), + terminalTabExists: true, + currentLayout: null, + livePtyIds + }) + ).toBeNull() + }) +}) diff --git a/src/renderer/src/components/automations/automation-run-open-target.ts b/src/renderer/src/components/automations/runs/automation-run-open-target.ts similarity index 91% rename from src/renderer/src/components/automations/automation-run-open-target.ts rename to src/renderer/src/components/automations/runs/automation-run-open-target.ts index 3ba854dd0a4..8fd6a1d96ef 100644 --- a/src/renderer/src/components/automations/automation-run-open-target.ts +++ b/src/renderer/src/components/automations/runs/automation-run-open-target.ts @@ -1,34 +1,34 @@ -import type { AutomationRun } from '../../../../shared/automations/history/automation-run' -import { makePaneKey, parsePaneKey } from '../../../../shared/workspace-layout/stable-pane-id' +import type { AutomationRun } from '../../../../../shared/automations/history/automation-run' +import { makePaneKey, parsePaneKey } from '../../../../../shared/workspace-layout/stable-pane-id' import { parseRemoteRuntimePtyId, isRemoteRuntimePtyId -} from '../../../../shared/remote-runtime/remote-runtime-pty-id' +} from '../../../../../shared/remote-runtime/remote-runtime-pty-id' import { isWebTerminalSurfaceTabId, toWebTerminalSurfaceTabId -} from '../../../../shared/workspace-layout/terminal-surface-id' -import type { TerminalLayoutSnapshot } from '../../../../shared/workspace-layout/terminal-tab-types' -import { terminalLayoutContainsLeaf } from '../../../../shared/workspace-session/workspace-session-pane-ownership' +} from '../../../../../shared/workspace-layout/terminal-surface-id' +import type { TerminalLayoutSnapshot } from '../../../../../shared/workspace-layout/terminal-tab-types' +import { terminalLayoutContainsLeaf } from '../../../../../shared/workspace-session/workspace-session-pane-ownership' import { getRepoExecutionHostId, parseExecutionHostId, toRuntimeExecutionHostId, type ExecutionHostId -} from '../../../../shared/execution-host' -import type { AutomationAuthorityRef } from '../../../../shared/automations/ownership/automation-owner-ref' +} from '../../../../../shared/execution-host' +import type { AutomationAuthorityRef } from '../../../../../shared/automations/ownership/automation-owner-ref' import type { AppState } from '@/store/types' import { selectFolderWorkspaces, selectWorktreesByRepo } from '@/store/workspaces/catalog/workspace-record-fields' -import { getFolderWorkspaceWorktree } from '../../../../shared/folder-workspaces/folder-workspace-worktree' +import { getFolderWorkspaceWorktree } from '../../../../../shared/folder-workspaces/folder-workspace-worktree' import { resolveExactWorktreeRoute } from '@/lib/workspace/ownership/worktree-owner-route' -import { parseWorkspaceKey } from '../../../../shared/workspace-scope' +import { parseWorkspaceKey } from '../../../../../shared/workspace-scope' import { getAutomationRunViewState } from './automation-run-view-state' import { resolveOwner } from '@/lib/workspace/ownership/resolve-owner' import type { WorktreeOperationRouteState } from '@/lib/workspace/ownership/worktree-operation-route' -import { resolveQualifiedFolderWorkspaceResult } from '../../../../shared/folder-workspaces/folder-workspace-execution-host' +import { resolveQualifiedFolderWorkspaceResult } from '../../../../../shared/folder-workspaces/folder-workspace-execution-host' import { getRuntimeEnvironmentIdForFolderWorkspace } from '@/lib/workspace/ownership/folder-workspace-runtime-owner' export type AutomationRunPaneTarget = { @@ -141,8 +141,6 @@ export function resolveAutomationRunTerminalTarget( } } -export { buildAutomationRunOpenLayout } from './automation-run-pane-layout' - /** The paired server that owns the run's workspace, or null when this client runs it itself. */ export function getAutomationRunOwnerEnvironmentId( state: WorktreeOperationRouteState, diff --git a/src/renderer/src/components/automations/automation-run-pane-layout.ts b/src/renderer/src/components/automations/runs/automation-run-pane-layout.ts similarity index 84% rename from src/renderer/src/components/automations/automation-run-pane-layout.ts rename to src/renderer/src/components/automations/runs/automation-run-pane-layout.ts index 5cf655364a1..516f05afc07 100644 --- a/src/renderer/src/components/automations/automation-run-pane-layout.ts +++ b/src/renderer/src/components/automations/runs/automation-run-pane-layout.ts @@ -1,4 +1,4 @@ -import type { TerminalLayoutSnapshot } from '../../../../shared/workspace-layout/terminal-tab-types' +import type { TerminalLayoutSnapshot } from '../../../../../shared/workspace-layout/terminal-tab-types' import type { AutomationRunPaneTarget } from './automation-run-open-target' export function buildAutomationRunOpenLayout({ diff --git a/src/renderer/src/components/automations/automation-run-view-state.ts b/src/renderer/src/components/automations/runs/automation-run-view-state.ts similarity index 96% rename from src/renderer/src/components/automations/automation-run-view-state.ts rename to src/renderer/src/components/automations/runs/automation-run-view-state.ts index a05ea7e6a4e..9e784026851 100644 --- a/src/renderer/src/components/automations/automation-run-view-state.ts +++ b/src/renderer/src/components/automations/runs/automation-run-view-state.ts @@ -1,5 +1,5 @@ -import type { Automation } from '../../../../shared/automations/automation-definition' -import type { AutomationRun } from '../../../../shared/automations/history/automation-run' +import type { Automation } from '../../../../../shared/automations/automation-definition' +import type { AutomationRun } from '../../../../../shared/automations/history/automation-run' import { translate } from '@/i18n/i18n' export type AutomationRunViewAvailability = diff --git a/src/renderer/src/components/automations/automation-run-workspace-action.ts b/src/renderer/src/components/automations/runs/automation-run-workspace-action.ts similarity index 92% rename from src/renderer/src/components/automations/automation-run-workspace-action.ts rename to src/renderer/src/components/automations/runs/automation-run-workspace-action.ts index 7606afe8169..82764baa8bd 100644 --- a/src/renderer/src/components/automations/automation-run-workspace-action.ts +++ b/src/renderer/src/components/automations/runs/automation-run-workspace-action.ts @@ -1,7 +1,7 @@ import { openExistingStructuredSession } from '@/lib/open-existing-structured-session' -import { ALL_TUI_AGENTS } from '../../../../shared/agent-launch/catalog/tui-agent-display-names' -import { isStructuredAgentSessionIdFor } from '../../../../shared/agent-session/structured-agent-session-create' -import type { AutomationRun } from '../../../../shared/automations/history/automation-run' +import { ALL_TUI_AGENTS } from '../../../../../shared/agent-launch/catalog/tui-agent-display-names' +import { isStructuredAgentSessionIdFor } from '../../../../../shared/agent-session/structured-agent-session-create' +import type { AutomationRun } from '../../../../../shared/automations/history/automation-run' import { toast } from 'sonner' import { translate } from '@/i18n/i18n' import { @@ -10,14 +10,14 @@ import { } from '@/lib/workspace/activation/worktree-activation' import type { ActivateAndRevealResult } from '@/lib/workspace/activation/worktree-activation-outcome' import { activateWslMovedWorkspace } from '@/lib/workspace/activation/wsl-moved-chat-activation' -import { useAppStore } from '@/store' +import { useAppStore } from '@/store/index' import { activateTerminalTabOnOwner } from '@/lib/workspace/tabs/terminal-tab-owner-activation' import { activateWebRuntimeSessionTab } from '@/runtime/web-session-tabs-sync/actions/web-runtime-session-tab-lifecycle' import { resolveWebSessionVisibleTabId } from '@/runtime/web-session-tabs-sync/navigation/web-session-focus-intent' -import { parsePaneKey } from '../../../../shared/workspace-layout/stable-pane-id' -import { parseWorkspaceKey } from '../../../../shared/workspace-scope' -import { buildAutomationRunOpenLayout } from './automation-run-open-target' -import type { AutomationsPageActionContext } from './automations-page-action-context' +import { parsePaneKey } from '../../../../../shared/workspace-layout/stable-pane-id' +import { parseWorkspaceKey } from '../../../../../shared/workspace-scope' +import { buildAutomationRunOpenLayout } from './automation-run-pane-layout' +import type { AutomationsPageActionContext } from '../automations-page-action-context' let cancelPendingReveal: (() => void) | undefined diff --git a/src/renderer/src/components/automations/automation-run-workspace-display.ts b/src/renderer/src/components/automations/runs/automation-run-workspace-display.ts similarity index 90% rename from src/renderer/src/components/automations/automation-run-workspace-display.ts rename to src/renderer/src/components/automations/runs/automation-run-workspace-display.ts index 7726dd6677a..80023bd47ba 100644 --- a/src/renderer/src/components/automations/automation-run-workspace-display.ts +++ b/src/renderer/src/components/automations/runs/automation-run-workspace-display.ts @@ -1,7 +1,7 @@ import { translate } from '@/i18n/i18n' import type { Translate } from '@/i18n/use-translate' -import type { AutomationRun } from '../../../../shared/automations/history/automation-run' -import type { Worktree } from '../../../../shared/worktree/types' +import type { AutomationRun } from '../../../../../shared/automations/history/automation-run' +import type { Worktree } from '../../../../../shared/worktree/types' export type AutomationRunWorkspaceDisplay = { rowLabel: string diff --git a/src/renderer/src/components/automations/automation-runs-dashboard-model.ts b/src/renderer/src/components/automations/runs/automation-runs-dashboard-model.ts similarity index 93% rename from src/renderer/src/components/automations/automation-runs-dashboard-model.ts rename to src/renderer/src/components/automations/runs/automation-runs-dashboard-model.ts index d575f271feb..cef4501da04 100644 --- a/src/renderer/src/components/automations/automation-runs-dashboard-model.ts +++ b/src/renderer/src/components/automations/runs/automation-runs-dashboard-model.ts @@ -1,10 +1,10 @@ import type { AutomationRun, AutomationRunStatus -} from '../../../../shared/automations/history/automation-run' -import { parseExecutionHostId } from '../../../../shared/execution-host' -import type { AutomationActionNotice } from './automation-row-action-dispatch' -import type { AutomationListRow } from './automation-list-row-identity' +} from '../../../../../shared/automations/history/automation-run' +import { parseExecutionHostId } from '../../../../../shared/execution-host' +import type { AutomationActionNotice } from '../hosts/automation-row-action-dispatch' +import type { AutomationListRow } from '../listing/automation-list-row-identity' export type AutomationRunsDashboardRun = Pick< AutomationRun, diff --git a/src/renderer/src/components/automations/automation-usage-model.ts b/src/renderer/src/components/automations/runs/automation-usage-model.ts similarity index 92% rename from src/renderer/src/components/automations/automation-usage-model.ts rename to src/renderer/src/components/automations/runs/automation-usage-model.ts index a43b4a13ea8..03449a6643a 100644 --- a/src/renderer/src/components/automations/automation-usage-model.ts +++ b/src/renderer/src/components/automations/runs/automation-usage-model.ts @@ -1,7 +1,7 @@ import { getIntlLocale, translate } from '@/i18n/i18n' import type { Translate } from '@/i18n/use-translate' -import type { AutomationUsageSummary } from '../../../../shared/automations/history/automation-usage-summary' -import type { AutomationRunUsage } from '../../../../shared/automations/history/automation-run' +import type { AutomationUsageSummary } from '../../../../../shared/automations/history/automation-usage-summary' +import type { AutomationRunUsage } from '../../../../../shared/automations/history/automation-run' // Keep retained-run summaries shared across owning authorities; only display formatting belongs to the renderer. diff --git a/src/renderer/src/components/automations/use-automation-run-page-state.ts b/src/renderer/src/components/automations/runs/use-automation-run-page-state.ts similarity index 93% rename from src/renderer/src/components/automations/use-automation-run-page-state.ts rename to src/renderer/src/components/automations/runs/use-automation-run-page-state.ts index e35bd264191..dedf4911686 100644 --- a/src/renderer/src/components/automations/use-automation-run-page-state.ts +++ b/src/renderer/src/components/automations/runs/use-automation-run-page-state.ts @@ -6,14 +6,14 @@ import { getAutomationAuthorityTarget, getAutomationHostTargetKey, getAutomationListedTargetFromHostId -} from './automation-host-client' -import { ALL_AUTOMATION_HOSTS_FILTER } from '../../../../shared/automations/ownership/automation-host-filter' +} from '../hosts/automation-host-client' +import { ALL_AUTOMATION_HOSTS_FILTER } from '../../../../../shared/automations/ownership/automation-host-filter' import { canRerunAutomationRun } from './automation-run-view-state' import { getAutomationRunWorkspaceDisplay } from './automation-run-workspace-display' -import type { AutomationsPageListState } from './use-automations-page-list-state' -import type { AutomationsPageLocalState } from './use-automations-page-local-state' -import type { AutomationsPageSetupState } from './use-automations-page-setup-state' -import type { AutomationsPageStoreState } from './use-automations-page-store-state' +import type { AutomationsPageListState } from '../listing/use-automations-page-list-state' +import type { AutomationsPageLocalState } from '../use-automations-page-local-state' +import type { AutomationsPageSetupState } from '../authoring/use-automations-page-setup-state' +import type { AutomationsPageStoreState } from '../use-automations-page-store-state' /** Navigation and terminal affordances for the selected automation run. */ export function useAutomationRunPageState({ diff --git a/src/renderer/src/components/automations/use-automation-runs-dashboard-payload.test.tsx b/src/renderer/src/components/automations/runs/use-automation-runs-dashboard-payload.test.tsx similarity index 92% rename from src/renderer/src/components/automations/use-automation-runs-dashboard-payload.test.tsx rename to src/renderer/src/components/automations/runs/use-automation-runs-dashboard-payload.test.tsx index 63fdfa53b87..bd2e16684ec 100644 --- a/src/renderer/src/components/automations/use-automation-runs-dashboard-payload.test.tsx +++ b/src/renderer/src/components/automations/runs/use-automation-runs-dashboard-payload.test.tsx @@ -3,12 +3,12 @@ import { act } from 'react' import { createRoot, type Root } from 'react-dom/client' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import type { AutomationRun } from '../../../../shared/automations/history/automation-run' -import { makeAutomationListRow, makeRun } from './automations-page-fixtures' -import * as dispatch from './automation-row-action-dispatch' +import type { AutomationRun } from '../../../../../shared/automations/history/automation-run' +import { makeAutomationListRow, makeRun } from '../automations-page-fixtures' +import * as dispatch from '../hosts/automation-row-action-dispatch' import { useAutomationRunsDashboard } from './use-automation-runs-dashboard' -vi.mock('./automation-row-action-dispatch', async (importOriginal) => ({ +vi.mock('../hosts/automation-row-action-dispatch', async (importOriginal) => ({ ...(await importOriginal()), dispatchAutomationRunHistoryPage: vi.fn(), dispatchAutomationRunHistory: vi.fn() diff --git a/src/renderer/src/components/automations/use-automation-runs-dashboard.test.tsx b/src/renderer/src/components/automations/runs/use-automation-runs-dashboard.test.tsx similarity index 88% rename from src/renderer/src/components/automations/use-automation-runs-dashboard.test.tsx rename to src/renderer/src/components/automations/runs/use-automation-runs-dashboard.test.tsx index e3dbd5c929c..1a4f97193e3 100644 --- a/src/renderer/src/components/automations/use-automation-runs-dashboard.test.tsx +++ b/src/renderer/src/components/automations/runs/use-automation-runs-dashboard.test.tsx @@ -3,14 +3,14 @@ import { act, useCallback } from 'react' import { createRoot, type Root } from 'react-dom/client' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import type { AutomationAuthorityRef } from '../../../../shared/automations/ownership/automation-owner-ref' -import type { AutomationRunsPage } from '../../../../shared/automations/history/automation-run' -import type { AutomationHostTarget } from './automation-host-client' -import { makeAutomationListRow, makeRun } from './automations-page-fixtures' -import * as dispatch from './automation-row-action-dispatch' +import type { AutomationAuthorityRef } from '../../../../../shared/automations/ownership/automation-owner-ref' +import type { AutomationRunsPage } from '../../../../../shared/automations/history/automation-run' +import type { AutomationHostTarget } from '../hosts/automation-host-client' +import { makeAutomationListRow, makeRun } from '../automations-page-fixtures' +import * as dispatch from '../hosts/automation-row-action-dispatch' import { useAutomationRunsDashboard } from './use-automation-runs-dashboard' -vi.mock('./automation-row-action-dispatch', async (importOriginal) => ({ +vi.mock('../hosts/automation-row-action-dispatch', async (importOriginal) => ({ ...(await importOriginal()), dispatchAutomationRunHistoryPage: vi.fn() })) diff --git a/src/renderer/src/components/automations/use-automation-runs-dashboard.ts b/src/renderer/src/components/automations/runs/use-automation-runs-dashboard.ts similarity index 92% rename from src/renderer/src/components/automations/use-automation-runs-dashboard.ts rename to src/renderer/src/components/automations/runs/use-automation-runs-dashboard.ts index 58d4fcbfdfb..9379449c671 100644 --- a/src/renderer/src/components/automations/use-automation-runs-dashboard.ts +++ b/src/renderer/src/components/automations/runs/use-automation-runs-dashboard.ts @@ -1,17 +1,20 @@ import { useCallback, useEffect, useMemo, useRef, useState } from 'react' -import type { AutomationAuthorityRef } from '../../../../shared/automations/ownership/automation-owner-ref' -import { ownerKey } from '../../../../shared/automations/ownership/automation-owner-key' -import { capturedAutomationOwner, capturedAutomationOwnerKey } from './automation-captured-owner' +import type { AutomationAuthorityRef } from '../../../../../shared/automations/ownership/automation-owner-ref' +import { ownerKey } from '../../../../../shared/automations/ownership/automation-owner-key' +import { + capturedAutomationOwner, + capturedAutomationOwnerKey +} from '../hosts/automation-captured-owner' import { getAutomationHostTargetKey, listAutomationRunsForTarget, type AutomationHostTarget -} from './automation-host-client' -import type { AutomationListRow } from './automation-list-row-identity' +} from '../hosts/automation-host-client' +import type { AutomationListRow } from '../listing/automation-list-row-identity' import { dispatchAutomationRunHistoryPage, type AutomationDispatchContext -} from './automation-row-action-dispatch' +} from '../hosts/automation-row-action-dispatch' import { buildAutomationRunsDashboardEntries, getAutomationRunsScope, diff --git a/src/renderer/src/components/automations/use-full-automation-run.ts b/src/renderer/src/components/automations/runs/use-full-automation-run.ts similarity index 89% rename from src/renderer/src/components/automations/use-full-automation-run.ts rename to src/renderer/src/components/automations/runs/use-full-automation-run.ts index caf6856dd6d..f534ec145fe 100644 --- a/src/renderer/src/components/automations/use-full-automation-run.ts +++ b/src/renderer/src/components/automations/runs/use-full-automation-run.ts @@ -1,9 +1,9 @@ import { useEffect, useLayoutEffect, useRef, useState } from 'react' -import type { AutomationRun } from '../../../../shared/automations/history/automation-run' -import { automationActionAvailability } from './automation-captured-owner' -import { readFullAutomationRun } from './automation-scoped-list-client' +import type { AutomationRun } from '../../../../../shared/automations/history/automation-run' +import { automationActionAvailability } from '../hosts/automation-captured-owner' +import { readFullAutomationRun } from '../hosts/automation-scoped-list-client' import type { SelectedAutomationRunHistoryOutcome } from './use-selected-automation-run-history' -import { useTranslate } from '../../i18n/use-translate' +import { useTranslate } from '../../../i18n/use-translate' export type FullAutomationRun = { run: AutomationRun diff --git a/src/renderer/src/components/automations/use-selected-automation-run-history.ts b/src/renderer/src/components/automations/runs/use-selected-automation-run-history.ts similarity index 90% rename from src/renderer/src/components/automations/use-selected-automation-run-history.ts rename to src/renderer/src/components/automations/runs/use-selected-automation-run-history.ts index 6f9a96436c2..0bb044be483 100644 --- a/src/renderer/src/components/automations/use-selected-automation-run-history.ts +++ b/src/renderer/src/components/automations/runs/use-selected-automation-run-history.ts @@ -9,30 +9,30 @@ */ import { useEffect, useLayoutEffect, useRef } from 'react' -import type { AutomationRun } from '../../../../shared/automations/history/automation-run' -import type { AutomationAuthorityRef } from '../../../../shared/automations/ownership/automation-owner-ref' +import type { AutomationRun } from '../../../../../shared/automations/history/automation-run' +import type { AutomationAuthorityRef } from '../../../../../shared/automations/ownership/automation-owner-ref' import { capturedAutomationOwner, capturedAutomationOwnerKey, type AutomationCapturedOwner -} from './automation-captured-owner' -import type { AutomationListRow } from './automation-list-row-identity' +} from '../hosts/automation-captured-owner' +import type { AutomationListRow } from '../listing/automation-list-row-identity' import { type AutomationActionNotice, type AutomationDispatchContext, dispatchAutomationRunHistory -} from './automation-row-action-dispatch' +} from '../hosts/automation-row-action-dispatch' import { getAutomationAuthorityTarget, getAutomationTargetFromHostId, listAutomationRunsForTarget, type AutomationHostTarget -} from './automation-host-client' -import { useAppStore } from '@/store' -import { automationRuntimePairingRevision } from './automation-authority-identity' -import { automationAuthorityCatalogKey } from './automation-host-catalog-types' -import { isSameStableAutomationHost } from '../../../../shared/automations/ownership/automation-owner-key' -import { subscribeAutomationHostInvalidation } from './automation-host-invalidation-window-events' +} from '../hosts/automation-host-client' +import { useAppStore } from '@/store/index' +import { automationRuntimePairingRevision } from '../hosts/automation-authority-identity' +import { automationAuthorityCatalogKey } from '../hosts/automation-host-catalog-types' +import { isSameStableAutomationHost } from '../../../../../shared/automations/ownership/automation-owner-key' +import { subscribeAutomationHostInvalidation } from '../hosts/automation-host-invalidation-window-events' export type SelectedAutomationRunNavigation = { automationId: string diff --git a/src/renderer/src/components/automations/use-automation-list-focus-recovery.test.tsx b/src/renderer/src/components/automations/use-automation-list-focus-recovery.test.tsx deleted file mode 100644 index 6dcb1383fec..00000000000 --- a/src/renderer/src/components/automations/use-automation-list-focus-recovery.test.tsx +++ /dev/null @@ -1,88 +0,0 @@ -// @vitest-environment happy-dom - -/** Exercise real DOM focus: the hook must distinguish lost row focus from a user who moved elsewhere. */ - -import { act, useRef } from 'react' -import { createRoot, type Root } from 'react-dom/client' -import { afterEach, beforeEach, describe, expect, it } from 'vitest' -import { useAutomationListFocusRecovery } from './use-automation-list-focus-recovery' - -let container: HTMLDivElement -let root: Root - -beforeEach(() => { - globalThis.IS_REACT_ACT_ENVIRONMENT = true - container = document.createElement('div') - document.body.appendChild(container) - root = createRoot(container) -}) - -afterEach(() => { - act(() => root.unmount()) - container.remove() -}) - -function Harness({ rowKeys }: { rowKeys: readonly string[] }): React.JSX.Element { - const listRef = useRef(null) - const pickerRef = useRef(null) - useAutomationListFocusRecovery({ rowKeys, containerRef: listRef, fallbackRef: pickerRef }) - return ( -
- {/* The header: outside the list container, exactly as the panel lays it out. */} -
-
- -
- {rowKeys.map((rowKey) => ( -
- ))} -
-
- ) -} - -function render(rowKeys: readonly string[]): void { - act(() => { - root.render() - }) -} - -function node(testId: string): HTMLElement { - const found = container.querySelector(`[data-testid="${testId}"]`) - if (!found) { - throw new Error(`no node for ${testId}`) - } - return found -} - -function focus(testId: string): void { - act(() => { - node(testId).focus() - }) -} - -describe('useAutomationListFocusRecovery', () => { - it('leaves focus in the search field when filtering removes the row it was on', () => { - render(['r1', 'r2', 'r3']) - focus('r2') - focus('search') - const search = node('search') - - render(['r1', 'r3']) - - expect(document.activeElement).toBe(search) - }) - - it('still repairs focus lost from the list itself', () => { - render(['r1', 'r2', 'r3']) - focus('r2') - act(() => { - node('r2').blur() - }) - - render(['r1', 'r3']) - - expect(document.activeElement).toBe(node('r3')) - }) -}) diff --git a/src/renderer/src/components/automations/use-automations-page-controller.ts b/src/renderer/src/components/automations/use-automations-page-controller.ts index a31c26e0bf6..132eb3135bb 100644 --- a/src/renderer/src/components/automations/use-automations-page-controller.ts +++ b/src/renderer/src/components/automations/use-automations-page-controller.ts @@ -1,22 +1,22 @@ -import { createAutomationManagementActions } from './automation-management-actions' -import { createAutomationRunActions } from './automation-run-actions' -import { createAutomationRunWorkspaceAction } from './automation-run-workspace-action' -import { createAutomationSaveAction } from './automation-save-action' -import { useAutomationDraftEffects } from './use-automation-draft-effects' -import { useAutomationEditorActions } from './use-automation-editor-actions' -import { useAutomationMigrateAction } from './use-automation-migrate-action' -import { useAutomationRunPageState } from './use-automation-run-page-state' +import { createAutomationManagementActions } from './authoring/automation-management-actions' +import { createAutomationRunActions } from './runs/automation-run-actions' +import { createAutomationRunWorkspaceAction } from './runs/automation-run-workspace-action' +import { createAutomationSaveAction } from './authoring/automation-save-action' +import { useAutomationDraftEffects } from './authoring/use-automation-draft-effects' +import { useAutomationEditorActions } from './authoring/use-automation-editor-actions' +import { useAutomationMigrateAction } from './authoring/use-automation-migrate-action' +import { useAutomationRunPageState } from './runs/use-automation-run-page-state' import { useAutomationsPageEscape } from './use-automations-page-escape' -import { useAutomationsPageListState } from './use-automations-page-list-state' +import { useAutomationsPageListState } from './listing/use-automations-page-list-state' import { useAutomationsPageLocalState } from './use-automations-page-local-state' -import { useAutomationsPageDestinationState } from './use-automations-page-destination-state' -import { useAutomationsPageDestinationForm } from './use-automations-page-destination-form' +import { useAutomationsPageDestinationState } from './authoring/use-automations-page-destination-state' +import { useAutomationsPageDestinationForm } from './authoring/use-automations-page-destination-form' import { useAutomationsPagePresentationState } from './use-automations-page-presentation-state' import { useAutomationsPageRefresh } from './use-automations-page-refresh' -import { useAutomationsPageSetupState } from './use-automations-page-setup-state' +import { useAutomationsPageSetupState } from './authoring/use-automations-page-setup-state' import { useAutomationsPageStoreState } from './use-automations-page-store-state' -import { useExternalAutomationActions } from './use-external-automation-actions' -import { useAutomationRunsDashboard } from './use-automation-runs-dashboard' +import { useExternalAutomationActions } from './external/use-external-automation-actions' +import { useAutomationRunsDashboard } from './runs/use-automation-runs-dashboard' export function useAutomationsPageController() { const store = useAutomationsPageStoreState() diff --git a/src/renderer/src/components/automations/use-automations-page-local-state.ts b/src/renderer/src/components/automations/use-automations-page-local-state.ts index 7589076e4fe..87d4438d963 100644 --- a/src/renderer/src/components/automations/use-automations-page-local-state.ts +++ b/src/renderer/src/components/automations/use-automations-page-local-state.ts @@ -6,24 +6,24 @@ import type { } from '../../../../shared/automations/external/external-automation' import type { OrcaHooks } from '../../../../shared/orca-yaml-hook-types' import { useContextualTour } from '@/components/contextual-tours/use-contextual-tour' -import type { AutomationDraft } from './AutomationEditorDialog' -import { AUTOMATION_DEFAULT_TIME } from './automation-draft-model' -import type { AutomationActionNotice } from './automation-row-action-dispatch' -import type { AutomationHostCatalogEntry } from './automation-host-catalog-types' -import type { AutomationCreateDestination } from './automation-create-destination' -import type { AutomationListRow } from './automation-list-row-identity' +import type { AutomationDraft } from './authoring/AutomationEditorDialog' +import { AUTOMATION_DEFAULT_TIME } from './authoring/automation-draft-model' +import type { AutomationActionNotice } from './hosts/automation-row-action-dispatch' +import type { AutomationHostCatalogEntry } from './hosts/automation-host-catalog-types' +import type { AutomationCreateDestination } from './authoring/automation-create-destination' +import type { AutomationListRow } from './listing/automation-list-row-identity' import { EMPTY_AUTOMATION_LIST_FILTER, type AutomationListFilter, type AutomationListSort -} from './automation-list-view' +} from './listing/automation-list-view' import type { AutomationPaneTab, AutomationRunPageOrigin, AutomationsPageView } from './automation-page-state' -import type { ExternalAutomationScope } from './external-automation-scope-client' -import type { SelectedAutomationRunHistoryOutcome } from './use-selected-automation-run-history' +import type { ExternalAutomationScope } from './external/external-automation-scope-client' +import type { SelectedAutomationRunHistoryOutcome } from './runs/use-selected-automation-run-history' import type { AutomationsPageStoreState } from './use-automations-page-store-state' /** React-owned values for the page; host/catalog state remains in dedicated hooks. */ diff --git a/src/renderer/src/components/automations/use-automations-page-presentation-state.ts b/src/renderer/src/components/automations/use-automations-page-presentation-state.ts index eb694afb229..964f9f783c1 100644 --- a/src/renderer/src/components/automations/use-automations-page-presentation-state.ts +++ b/src/renderer/src/components/automations/use-automations-page-presentation-state.ts @@ -1,4 +1,4 @@ -import { capturedAutomationOwner } from './automation-captured-owner' +import { capturedAutomationOwner } from './hosts/automation-captured-owner' import { useCallback, useEffect, useMemo } from 'react' import { getLocalExecutionHostLabel, @@ -7,10 +7,10 @@ import { } from '../../../../shared/execution-host' import { getHostDisplayLabelOverrides } from '../../../../shared/host-setting-overrides' import type { Repo } from '../../../../shared/repo-types' -import { getAutomationTargetAvailability } from './automation-target-availability' -import type { AutomationsPageDestinationState } from './use-automations-page-destination-state' -import type { AutomationsPageDestinationFormState } from './use-automations-page-destination-form' -import type { AutomationsPageListState } from './use-automations-page-list-state' +import { getAutomationTargetAvailability } from './hosts/automation-target-availability' +import type { AutomationsPageDestinationState } from './authoring/use-automations-page-destination-state' +import type { AutomationsPageDestinationFormState } from './authoring/use-automations-page-destination-form' +import type { AutomationsPageListState } from './listing/use-automations-page-list-state' import type { AutomationsPageLocalState } from './use-automations-page-local-state' import type { AutomationsPageStoreState } from './use-automations-page-store-state' import { useTranslate } from '../../i18n/use-translate' diff --git a/src/renderer/src/components/automations/use-automations-page-refresh.ts b/src/renderer/src/components/automations/use-automations-page-refresh.ts index a0db0e2e6ad..d79192d22aa 100644 --- a/src/renderer/src/components/automations/use-automations-page-refresh.ts +++ b/src/renderer/src/components/automations/use-automations-page-refresh.ts @@ -1,16 +1,16 @@ import { useCallback, useEffect, useRef } from 'react' import { installWindowVisibilityInterval } from '@/lib/window-visibility-interval' -import { useAppStore } from '@/store' +import { useAppStore } from '@/store/index' import { AUTOMATIONS_CHANGED_EVENT } from '@/lib/automations-changed-window-event' import { getAutomationHostTargetKey, getAutomationListedTargetFromHostId, listAutomationsForTarget -} from './automation-host-client' -import { automationAuthorityCatalogKey } from './automation-host-catalog-types' -import { useSelectedAutomationRunHistory } from './use-selected-automation-run-history' -import type { AutomationsPageDestinationState } from './use-automations-page-destination-state' -import type { AutomationsPageListState } from './use-automations-page-list-state' +} from './hosts/automation-host-client' +import { automationAuthorityCatalogKey } from './hosts/automation-host-catalog-types' +import { useSelectedAutomationRunHistory } from './runs/use-selected-automation-run-history' +import type { AutomationsPageDestinationState } from './authoring/use-automations-page-destination-state' +import type { AutomationsPageListState } from './listing/use-automations-page-list-state' import type { AutomationsPageLocalState } from './use-automations-page-local-state' import type { AutomationsPageStoreState } from './use-automations-page-store-state' diff --git a/src/renderer/src/components/automations/use-automations-page-store-state.ts b/src/renderer/src/components/automations/use-automations-page-store-state.ts index 4528ee6ea98..84d48ee7467 100644 --- a/src/renderer/src/components/automations/use-automations-page-store-state.ts +++ b/src/renderer/src/components/automations/use-automations-page-store-state.ts @@ -6,7 +6,7 @@ import { import type { Repo } from '../../../../shared/repo-types' import type { Worktree } from '../../../../shared/worktree/types' import { getAgentCatalog } from '@/lib/agent-catalog/agent-catalog' -import { useAppStore } from '@/store' +import { useAppStore } from '@/store/index' import { useRepoMap } from '@/store/repos/use-repository-catalog' import { useWorktreeMap } from '@/store/slices/worktrees/listing/use-worktree-catalog' import { @@ -14,7 +14,7 @@ import { automationRepoForRow, automationWorktreeForRow, type AutomationListRow -} from './automation-list-row-identity' +} from './listing/automation-list-row-identity' import { selectFolderWorkspaces, selectWorktreesByRepo diff --git a/src/renderer/src/components/cmd-j/palette-extra-results.ts b/src/renderer/src/components/cmd-j/palette-extra-results.ts new file mode 100644 index 00000000000..974e1da88fe --- /dev/null +++ b/src/renderer/src/components/cmd-j/palette-extra-results.ts @@ -0,0 +1,81 @@ +import type React from 'react' +import type { Translate } from '@/i18n/use-translate' +import type { Worktree } from '../../../../shared/worktree/types' +import type { MatchRange } from '../../../../shared/palette-match/normalized-text' +import type { PaletteResultQualityClass } from '../../../../shared/palette-match/match-quality' +import { + buildPaletteDocument, + type PaletteDocumentRank +} from '../../../../shared/palette-match/palette-document' +import { matchPaletteDocument } from '../../../../shared/palette-match/match-document' +import { preparePaletteQuery } from '../../../../shared/palette-match/palette-query' + +/** One row a non-workspace source contributes to Cmd+J. */ +export type PaletteExtraResult = { + id: string + title: string + titleRanges: readonly MatchRange[] + /** null in the empty query, where rows are listed without a match. */ + rank: PaletteDocumentRank | null + qualityClass: PaletteResultQualityClass | null + lastActiveAt: number | null + /** Source-defined order: empty-query order, and the typed tie-break after rank and activity. */ + order: number + dimmed?: boolean + leading?: React.ReactNode + line?: React.ReactNode + trailing?: React.ReactNode + onSelect: () => void +} + +/** One section a source contributes, with its rows for the current query. */ +export type PaletteExtraSource = { + id: string + sectionLabel: (t: Translate) => string + emptyQueryCap: number + /** Typed queries: where the section sits when it does not lead the list. */ + typedPlacement: 'before-workspaces' | 'after-workspaces' + /** Lead the list when its best match equals the best workspace or tab match, not only when it beats it. */ + leadsOnTie: boolean + /** Typed: matching rows only. Empty query: every row, unranked. */ + results: readonly PaletteExtraResult[] + /** Workspaces the source represents itself; their tabs stay in Open Tabs and recents. */ + hidesWorkspace?: (worktree: Worktree) => boolean +} + +export type PaletteExtraMatch = { + rank: PaletteDocumentRank + qualityClass: PaletteResultQualityClass + rangesByField: ReadonlyMap +} + +/** Ranks a source's row with the same engine as workspaces, so qualities compare across sections. */ +export function matchPaletteExtraFields( + id: string, + fields: readonly { id: string; text: string; role: 'primary' | 'secondary' }[], + query: string +): PaletteExtraMatch | null { + const prepared = preparePaletteQuery(query) + if (prepared.state !== 'ready') { + return null + } + const match = matchPaletteDocument({ + document: buildPaletteDocument({ + id, + visibleFields: fields.map((field) => ({ + id: field.id, + profile: field.role === 'primary' ? 'structured-label' : 'prose', + text: field.text, + role: field.role, + destinationEligible: field.role === 'primary' + })), + evidence: [] + }), + tokens: prepared.tokens, + normalizedQuery: prepared.normalized, + tokenCountBeforeDeduplication: prepared.tokenCountBeforeDeduplication + }) + return match + ? { rank: match.rank, qualityClass: match.qualityClass, rangesByField: match.rangesByField } + : null +} diff --git a/src/renderer/src/components/cmd-j/palette-extra-sources.ts b/src/renderer/src/components/cmd-j/palette-extra-sources.ts new file mode 100644 index 00000000000..48066d300a7 --- /dev/null +++ b/src/renderer/src/components/cmd-j/palette-extra-sources.ts @@ -0,0 +1,11 @@ +import type { PaletteExtraSource } from './palette-extra-results' + +const NO_SOURCES: readonly PaletteExtraSource[] = [] + +/** Each source registers here with its own hook; return a memoized list. */ +export function usePaletteExtraSources(_args: { + query: string + visible: boolean +}): readonly PaletteExtraSource[] { + return NO_SOURCES +} diff --git a/src/renderer/src/components/dictation/DictationController.tsx b/src/renderer/src/components/dictation/DictationController.tsx index 9c4957044bc..e664085388d 100644 --- a/src/renderer/src/components/dictation/DictationController.tsx +++ b/src/renderer/src/components/dictation/DictationController.tsx @@ -30,6 +30,7 @@ import { import { useHoldDictationGesture } from './use-hold-dictation-gesture' import { publishDictationMeter } from './dictation-meter-store' import { useDictationSilenceStop } from './use-dictation-silence-stop' +import { stopAfterSilenceSeconds } from '../../../../shared/dictation-silence-stop' import { useDictationSpeechEvents } from './use-dictation-speech-events' import { NO_DICTATION_LIVE_TEXT } from '@/store/slices/dictation/dictation' import { @@ -364,14 +365,7 @@ export function DictationController() { isDictationUnderway(sessionRef.current.phase) || sessionRef.current.phase === 'stopping' }) - useDictationSilenceStop( - dictationState === 'listening', - settings?.voice?.dictationMode, - getLastSpeechAt, - () => void stopDictation() - ) - - useHoldDictationGesture({ + const { isHolding } = useHoldDictationGesture({ canStartDictation: () => canStartDictation(sessionRef.current.phase), isDictationUnderway: () => isDictationUnderway(sessionRef.current.phase), keybindings, @@ -380,6 +374,15 @@ export function DictationController() { stopDictation }) + useDictationSilenceStop( + dictationState === 'listening', + settings?.voice?.dictationMode, + stopAfterSilenceSeconds(settings?.voice), + getLastSpeechAt, + isHolding, + () => void stopDictation() + ) + useDictationSpeechEvents({ currentSessionId: () => sessionRef.current.sessionId, onLiveText: setLiveText, diff --git a/src/renderer/src/components/dictation/use-dictation-silence-stop.ts b/src/renderer/src/components/dictation/use-dictation-silence-stop.ts index 06389b2fc8f..588e1eb0fb7 100644 --- a/src/renderer/src/components/dictation/use-dictation-silence-stop.ts +++ b/src/renderer/src/components/dictation/use-dictation-silence-stop.ts @@ -1,34 +1,42 @@ import { useEffect, useEffectEvent } from 'react' import { toast } from 'sonner' import { translate } from '@/i18n/i18n' -import { watchDictationSilence } from '../../../../shared/dictation-silence-stop' +import { + watchDictationSilence, + type StopAfterSilenceSeconds +} from '../../../../shared/dictation-silence-stop' // A forgotten toggle mic stays open; a held push-to-talk key or button ends the session on release. export function useDictationSilenceStop( listening: boolean, dictationMode: string | undefined, + silenceSeconds: StopAfterSilenceSeconds, getLastSpeechAt: () => number, + /** A held shortcut counts as speech: Auto mode records until release, however quiet. */ + isHolding: () => boolean, stopDictation: () => void ): void { - const watching = listening && dictationMode !== 'hold' + const watching = listening && dictationMode !== 'hold' && silenceSeconds !== null const stopForSilence = useEffectEvent(() => { toast.message( translate( - 'auto.components.dictation.DictationController.stoppedAfterSilence', - 'Stopped after a minute of silence' + 'components.dictation.stoppedAfterSilenceSeconds', + 'Stopped after {{seconds}} seconds of silence', + { seconds: silenceSeconds } ) ) stopDictation() }) useEffect(() => { - if (!watching) { + if (!watching || silenceSeconds === null) { return } return watchDictationSilence( - getLastSpeechAt, + () => (isHolding() ? performance.now() : getLastSpeechAt()), () => performance.now(), + silenceSeconds * 1000, () => stopForSilence() ) - }, [watching, getLastSpeechAt]) + }, [watching, silenceSeconds, getLastSpeechAt, isHolding]) } diff --git a/src/renderer/src/components/dictation/use-hold-dictation-gesture.ts b/src/renderer/src/components/dictation/use-hold-dictation-gesture.ts index 5186b7ba380..2f47c5aa009 100644 --- a/src/renderer/src/components/dictation/use-hold-dictation-gesture.ts +++ b/src/renderer/src/components/dictation/use-hold-dictation-gesture.ts @@ -1,4 +1,4 @@ -import { useEffect, useEffectEvent, useRef } from 'react' +import { useCallback, useEffect, useEffectEvent, useRef } from 'react' import { getShortcutPlatform } from '@/lib/keyboard/shortcut-platform' import { keybindingMatchesAction, @@ -124,7 +124,7 @@ export function useHoldDictationGesture({ settings, startDictation, stopDictation -}: HoldDictationGestureOptions): void { +}: HoldDictationGestureOptions): { isHolding: () => boolean } { const activeHoldRef = useRef(null) const mode = dictationShortcutMode(settings?.voice) const enabled = settings?.voice?.enabled === true @@ -236,4 +236,8 @@ export function useHoldDictationGesture({ document.removeEventListener('visibilitychange', handleVisibilityChange) } }, [mode, enabled]) + + // True while a held shortcut press is the one recording. + const isHolding = useCallback(() => activeHoldRef.current?.startedDictation === true, []) + return { isHolding } } diff --git a/src/renderer/src/components/emulator-pane/use-mobile-emulator-agent-setup-state.ts b/src/renderer/src/components/emulator-pane/use-mobile-emulator-agent-setup-state.ts index 35d7b3e1e7c..3cb21bdb569 100644 --- a/src/renderer/src/components/emulator-pane/use-mobile-emulator-agent-setup-state.ts +++ b/src/renderer/src/components/emulator-pane/use-mobile-emulator-agent-setup-state.ts @@ -1,11 +1,11 @@ -import { useActiveProjectSkillRuntime } from '@/hooks/useActiveProjectSkillRuntime' +import { useActiveProjectSkillRuntime } from '@/hooks/skills/runtime/useActiveProjectSkillRuntime' import { useCallback, useEffect, useState } from 'react' import { toast } from 'sonner' import { ORCA_CLI_SKILL_NAME } from '@/lib/skills/installation/agent-feature-skill-names' import { GLOBAL_AGENT_SKILL_SOURCE_KINDS, useInstalledAgentSkill -} from '@/hooks/useInstalledAgentSkills' +} from '@/hooks/skills/discovery/useInstalledAgentSkills' import { useMountedRef } from '@/hooks/useMountedRef' import { translate } from '@/i18n/i18n' diff --git a/src/renderer/src/components/feature-tips/CliSkillSetupPanel.tsx b/src/renderer/src/components/feature-tips/CliSkillSetupPanel.tsx index 29e6bc84d87..2e0fd6ef742 100644 --- a/src/renderer/src/components/feature-tips/CliSkillSetupPanel.tsx +++ b/src/renderer/src/components/feature-tips/CliSkillSetupPanel.tsx @@ -4,12 +4,12 @@ import { ORCA_CLI_SKILL_NAME, ORCHESTRATION_SKILL_NAME } from '@/lib/skills/installation/agent-feature-skill-names' -import { useActiveProjectSkillRuntime } from '@/hooks/useActiveProjectSkillRuntime' +import { useActiveProjectSkillRuntime } from '@/hooks/skills/runtime/useActiveProjectSkillRuntime' import { GLOBAL_AGENT_SKILL_SOURCE_KINDS, hasInstalledAgentSkill, useInstalledAgentSkillNames -} from '@/hooks/useInstalledAgentSkills' +} from '@/hooks/skills/discovery/useInstalledAgentSkills' import { useTranslate } from '@/i18n/use-translate' const CLI_TIP_SKILL_NAMES = [ORCA_CLI_SKILL_NAME, ORCHESTRATION_SKILL_NAME] as const diff --git a/src/renderer/src/components/feature-tips/CliSkillSetupTerminal.tsx b/src/renderer/src/components/feature-tips/CliSkillSetupTerminal.tsx index 66dba756e26..e4e86d5554e 100644 --- a/src/renderer/src/components/feature-tips/CliSkillSetupTerminal.tsx +++ b/src/renderer/src/components/feature-tips/CliSkillSetupTerminal.tsx @@ -7,9 +7,9 @@ import { OnboardingInlineCommandTerminal } from '@/components/onboarding/Onboard import { buildSkillCommandForRuntime, buildSkillSetupTerminalCommand -} from '@/lib/skill-runtime-command' +} from '@/lib/skills/runtime/skill-runtime-command' import { ORCA_CLI_ORCHESTRATION_SKILL_INSTALL_COMMAND } from '@/lib/skills/installation/agent-feature-install-commands' -import { useActiveProjectSkillRuntime } from '@/hooks/useActiveProjectSkillRuntime' +import { useActiveProjectSkillRuntime } from '@/hooks/skills/runtime/useActiveProjectSkillRuntime' import { useTranslate } from '@/i18n/use-translate' export function CliSkillSetupTerminal(): React.JSX.Element { diff --git a/src/renderer/src/components/feature-wall/AgentCapabilitiesSetupAction.tsx b/src/renderer/src/components/feature-wall/AgentCapabilitiesSetupAction.tsx index d9c96a59896..2f18904b175 100644 --- a/src/renderer/src/components/feature-wall/AgentCapabilitiesSetupAction.tsx +++ b/src/renderer/src/components/feature-wall/AgentCapabilitiesSetupAction.tsx @@ -1,12 +1,12 @@ import { useBundledSkillInstallAction, type BundledSkillInstallActionState -} from '@/hooks/use-bundled-skill-install-action' +} from '@/hooks/skills/installation/use-bundled-skill-install-action' import { bundledSkillSetupActionLabel } from '../skills/setup/bundled-skill-setup-copy' -import { useOnboardingSkillRuntime } from '@/hooks/use-onboarding-skill-runtime' +import { useOnboardingSkillRuntime } from '@/hooks/skills/runtime/use-onboarding-skill-runtime' import { FeatureSetupInlineTerminal } from '../onboarding/FeatureSetupInlineTerminal' import { buildAgentFeatureSkillInstallCommand } from '@/lib/skills/installation/agent-feature-install-commands' -import { buildSkillCommandForRuntime } from '../../lib/skill-runtime-command' +import { buildSkillCommandForRuntime } from '../../lib/skills/runtime/skill-runtime-command' import type { OnboardingFeatureSetupRuntimeContext } from '../onboarding/onboarding-feature-setup-runtime' import { useCallback, useEffect, useRef, useState } from 'react' import { Check, Download, Loader2 } from 'lucide-react' @@ -19,7 +19,7 @@ import { bundledSkillInstallNeedsAttention, useBundledSkillInstall, type BundledSkillInstall -} from '@/hooks/use-bundled-skill-install' +} from '@/hooks/skills/installation/use-bundled-skill-install' import { BundledSkillInstallStatus } from '../skills/setup/BundledSkillInstallStatus' import { DEFAULT_ONBOARDING_FEATURE_SETUP_SELECTION, diff --git a/src/renderer/src/components/feature-wall/BrowserUseSkillSetupCard.tsx b/src/renderer/src/components/feature-wall/BrowserUseSkillSetupCard.tsx index 50ba20b0691..c99a6b0ed1a 100644 --- a/src/renderer/src/components/feature-wall/BrowserUseSkillSetupCard.tsx +++ b/src/renderer/src/components/feature-wall/BrowserUseSkillSetupCard.tsx @@ -1,8 +1,8 @@ import type { JSX } from 'react' import { ORCA_CLI_SKILL_NAME } from '@/lib/skills/installation/agent-feature-skill-names' import { BROWSER_USE_ENABLED_STORAGE_KEY } from '@/lib/browser/browser-use-setup-state' -import type { InstalledAgentSkillState } from '@/hooks/useInstalledAgentSkills' -import { useActiveProjectSkillRuntime } from '@/hooks/useActiveProjectSkillRuntime' +import type { InstalledAgentSkillState } from '@/hooks/skills/discovery/useInstalledAgentSkills' +import { useActiveProjectSkillRuntime } from '@/hooks/skills/runtime/useActiveProjectSkillRuntime' import { AgentSkillSetupPanel } from '@/components/skills/setup/AgentSkillSetupPanel' import { useAppStore } from '@/store' import { useTranslate } from '@/i18n/use-translate' diff --git a/src/renderer/src/components/feature-wall/FeatureWallBody.tsx b/src/renderer/src/components/feature-wall/FeatureWallBody.tsx index d8654ef82da..366de782b95 100644 --- a/src/renderer/src/components/feature-wall/FeatureWallBody.tsx +++ b/src/renderer/src/components/feature-wall/FeatureWallBody.tsx @@ -5,7 +5,7 @@ import type { AgentsStep } from '../../../../shared/agents-orchestration-steps' import type { WorkbenchStep } from '../../../../shared/workbench-steps' import type { ReviewStep } from '../../../../shared/review-steps' import type { GlobalSettings } from '../../../../shared/global-settings-types' -import type { InstalledAgentSkillState } from '@/hooks/useInstalledAgentSkills' +import type { InstalledAgentSkillState } from '@/hooks/skills/discovery/useInstalledAgentSkills' import { cn } from '@/lib/utils' import { PreviewMedia, RelatedFeatures } from './FeatureWallPreview' import { getLocalizedFeatureWallWorkflowCopy } from './feature-wall-tour-localized-copy' diff --git a/src/renderer/src/components/feature-wall/FeatureWallBrowserAction.tsx b/src/renderer/src/components/feature-wall/FeatureWallBrowserAction.tsx index c75a4e6cde8..971e9e8ebb4 100644 --- a/src/renderer/src/components/feature-wall/FeatureWallBrowserAction.tsx +++ b/src/renderer/src/components/feature-wall/FeatureWallBrowserAction.tsx @@ -1,10 +1,10 @@ -import { useBundledSkillInstallAction } from '@/hooks/use-bundled-skill-install-action' +import { useBundledSkillInstallAction } from '@/hooks/skills/installation/use-bundled-skill-install-action' import { bundledSkillSetupActionLabel } from '../skills/setup/bundled-skill-setup-copy' import { ORCA_CLI_SKILL_NAME } from '@/lib/skills/installation/agent-feature-skill-names' -import { useOnboardingSkillRuntime } from '@/hooks/use-onboarding-skill-runtime' +import { useOnboardingSkillRuntime } from '@/hooks/skills/runtime/use-onboarding-skill-runtime' import { FeatureSetupInlineTerminal } from '../onboarding/FeatureSetupInlineTerminal' import { buildAgentFeatureSkillInstallCommand } from '@/lib/skills/installation/agent-feature-install-commands' -import { buildSkillCommandForRuntime } from '../../lib/skill-runtime-command' +import { buildSkillCommandForRuntime } from '../../lib/skills/runtime/skill-runtime-command' import type { OnboardingFeatureSetupRuntimeContext } from '../onboarding/onboarding-feature-setup-runtime' import { useCallback, useState } from 'react' import { ArrowUpRight, Download, Loader2 } from 'lucide-react' @@ -18,7 +18,7 @@ import { useAppStore } from '@/store' import { bundledSkillInstallNeedsAttention, useBundledSkillInstall -} from '@/hooks/use-bundled-skill-install' +} from '@/hooks/skills/installation/use-bundled-skill-install' import { BundledSkillInstallStatus } from '../skills/setup/BundledSkillInstallStatus' import { onboardingFeatureSetupRunTelemetry, diff --git a/src/renderer/src/components/feature-wall/FeatureWallTourPanel.tsx b/src/renderer/src/components/feature-wall/FeatureWallTourPanel.tsx index dbb89938624..85eff9e9bf7 100644 --- a/src/renderer/src/components/feature-wall/FeatureWallTourPanel.tsx +++ b/src/renderer/src/components/feature-wall/FeatureWallTourPanel.tsx @@ -8,7 +8,7 @@ import type { ReviewStep, ReviewStepId } from '../../../../shared/review-steps' import type { FeatureWallOpenSourceTelemetry } from '../../../../shared/telemetry-events' import type { GlobalSettings } from '../../../../shared/global-settings-types' import type { WorkbenchStep, WorkbenchStepId } from '../../../../shared/workbench-steps' -import type { InstalledAgentSkillState } from '@/hooks/useInstalledAgentSkills' +import type { InstalledAgentSkillState } from '@/hooks/skills/discovery/useInstalledAgentSkills' import { cn } from '@/lib/utils' import type { FeatureWallCompletionState } from './use-feature-wall-completion' import { FeatureWallBody } from './FeatureWallBody' diff --git a/src/renderer/src/components/feature-wall/FeatureWallTourSurface.tsx b/src/renderer/src/components/feature-wall/FeatureWallTourSurface.tsx index 091a6ef6175..a3e87c37a9f 100644 --- a/src/renderer/src/components/feature-wall/FeatureWallTourSurface.tsx +++ b/src/renderer/src/components/feature-wall/FeatureWallTourSurface.tsx @@ -16,7 +16,7 @@ import type { FeatureWallTourDepthSummary } from '../../../../shared/feature-wal import { track } from '@/lib/telemetry' import { useAppStore } from '@/store' import { useFeatureWallTourSkills } from './use-feature-wall-tour-skills' -import { useActiveProjectSkillRuntime } from '@/hooks/useActiveProjectSkillRuntime' +import { useActiveProjectSkillRuntime } from '@/hooks/skills/runtime/useActiveProjectSkillRuntime' import { usePrefersReducedMotion } from './feature-wall-modal-helpers' import { toFeatureWallAssetUrl, useFeatureWallAssetBaseUrl } from './feature-wall-assets' import { useFeatureWallTaskSourcePresentation } from './use-feature-wall-task-source-presentation' diff --git a/src/renderer/src/components/feature-wall/OrchestrationSetupCard.tsx b/src/renderer/src/components/feature-wall/OrchestrationSetupCard.tsx index b4414b55fd4..6cb204bd76d 100644 --- a/src/renderer/src/components/feature-wall/OrchestrationSetupCard.tsx +++ b/src/renderer/src/components/feature-wall/OrchestrationSetupCard.tsx @@ -1,7 +1,7 @@ import type { JSX } from 'react' import { ORCHESTRATION_SKILL_NAME } from '@/lib/skills/installation/agent-feature-skill-names' -import type { InstalledAgentSkillState } from '@/hooks/useInstalledAgentSkills' -import { useActiveProjectSkillRuntime } from '@/hooks/useActiveProjectSkillRuntime' +import type { InstalledAgentSkillState } from '@/hooks/skills/discovery/useInstalledAgentSkills' +import { useActiveProjectSkillRuntime } from '@/hooks/skills/runtime/useActiveProjectSkillRuntime' import { AgentSkillSetupPanel } from '../skills/setup/AgentSkillSetupPanel' import { useAppStore } from '@/store/index' import { useTranslate } from '@/i18n/use-translate' diff --git a/src/renderer/src/components/feature-wall/agent-capability-setup-status.ts b/src/renderer/src/components/feature-wall/agent-capability-setup-status.ts index 102ccf8ac71..56e1f593498 100644 --- a/src/renderer/src/components/feature-wall/agent-capability-setup-status.ts +++ b/src/renderer/src/components/feature-wall/agent-capability-setup-status.ts @@ -11,8 +11,8 @@ import { import { GLOBAL_AGENT_SKILL_SOURCE_KINDS, useInstalledAgentSkill -} from '@/hooks/useInstalledAgentSkills' -import { useOnboardingSkillRuntime } from '@/hooks/use-onboarding-skill-runtime' +} from '@/hooks/skills/discovery/useInstalledAgentSkills' +import { useOnboardingSkillRuntime } from '@/hooks/skills/runtime/use-onboarding-skill-runtime' import { translate } from '@/i18n/i18n' import type { Translate } from '@/i18n/use-translate' import { isAgentCapabilitiesDone } from './feature-wall-setup-progress' diff --git a/src/renderer/src/components/feature-wall/use-feature-wall-tour-skills.ts b/src/renderer/src/components/feature-wall/use-feature-wall-tour-skills.ts index 1185bf0b6cf..187615ff5f9 100644 --- a/src/renderer/src/components/feature-wall/use-feature-wall-tour-skills.ts +++ b/src/renderer/src/components/feature-wall/use-feature-wall-tour-skills.ts @@ -5,7 +5,7 @@ import { import { GLOBAL_AGENT_SKILL_SOURCE_KINDS, useInstalledAgentSkill -} from '@/hooks/useInstalledAgentSkills' +} from '@/hooks/skills/discovery/useInstalledAgentSkills' type DiscoveryTarget = NonNullable[1]>['discoveryTarget'] diff --git a/src/renderer/src/components/floating-terminal/FloatingTerminalOrchestrationDialog.tsx b/src/renderer/src/components/floating-terminal/FloatingTerminalOrchestrationDialog.tsx index 39bc18b48cf..f715b7f5f02 100644 --- a/src/renderer/src/components/floating-terminal/FloatingTerminalOrchestrationDialog.tsx +++ b/src/renderer/src/components/floating-terminal/FloatingTerminalOrchestrationDialog.tsx @@ -8,14 +8,14 @@ import { } from '@/components/ui/dialog' import { AgentSkillSetupPanel } from '@/components/skills/setup/AgentSkillSetupPanel' import { IntegrationStatusPill } from '@/components/integration-status-pill' -import { SkillFreshnessStatusPill } from '@/components/skills/SkillFreshnessStatusPill' +import { SkillFreshnessStatusPill } from '@/components/skills/freshness/SkillFreshnessStatusPill' import { ORCHESTRATION_SKILL_NAME } from '@/lib/skills/installation/agent-feature-skill-names' import { GLOBAL_AGENT_SKILL_SOURCE_KINDS, useInstalledAgentSkill -} from '@/hooks/useInstalledAgentSkills' -import { useActiveProjectSkillRuntime } from '@/hooks/useActiveProjectSkillRuntime' -import { refreshSkillFreshness } from '@/hooks/useSkillFreshness' +} from '@/hooks/skills/discovery/useInstalledAgentSkills' +import { useActiveProjectSkillRuntime } from '@/hooks/skills/runtime/useActiveProjectSkillRuntime' +import { refreshSkillFreshness } from '@/hooks/skills/freshness/useSkillFreshness' import { useAppStore } from '@/store' import { useTranslate } from '@/i18n/use-translate' diff --git a/src/renderer/src/components/native-chat-launch-resume-decision.test.tsx b/src/renderer/src/components/native-chat-launch-resume-decision.test.tsx deleted file mode 100644 index 5946eb95798..00000000000 --- a/src/renderer/src/components/native-chat-launch-resume-decision.test.tsx +++ /dev/null @@ -1,97 +0,0 @@ -// @vitest-environment happy-dom -// Suppress other continuation offers until the launch decides and publishes the chats it will resume atomically. - -import { act } from 'react' -import { createRoot, type Root } from 'react-dom/client' -import { afterEach, beforeEach, expect, it, vi } from 'vitest' -import { useAppStore } from '../store' -import { getDefaultSettings } from '../../../shared/constants' -import type { ResumeCandidate } from './native-chat-resume-on-restart-grouping' -import { - _resetNativeChatRestartOffer, - useNativeChatRestartOffer, - useNativeChatRestartResuming -} from './native-chat-resume-on-restart-store' -import { - _resetNativeChatLaunchResumeDecision, - useNativeChatLaunchResumePending -} from './native-chat-launch-resume-decision' - -const rpc = vi.hoisted(() => vi.fn()) -vi.mock('../runtime/native-chat/requests/structured-agent-session-call', () => ({ - callStructuredAgentSession: rpc -})) - -vi.mock('../runtime/native-chat/requests/structured-agent-session-subscriptions', () => ({ - subscribeStructuredAgentSessionStatus: () => new Promise(() => {}) -})) -vi.mock('sonner', async () => - (await import('./native-chat-resume-sonner-mock.test-support')).resumeSonnerMock() -) - -globalThis.IS_REACT_ACT_ENVIRONMENT = true -let root: Root -let container: HTMLDivElement -const offered: ResumeCandidate[] = ['a', 'b'].map((sessionId) => ({ - sessionId, - workspaceId: 'workspace', - agent: 'codex', - trigger: 'quit', - latestPrompt: `Prompt ${sessionId}`, - recordedAt: 1_800_000_000_000, - executionHostId: 'local', - workspaceKind: 'git-worktree' -})) - -const seen: { pending: boolean; resuming: readonly string[] }[] = [] -function Probe({ launch }: { launch: boolean }): null { - useNativeChatRestartOffer(launch) - seen.push({ - pending: useNativeChatLaunchResumePending(), - resuming: useNativeChatRestartResuming() - }) - return null -} - -function settings(autoResume: boolean | undefined): void { - useAppStore.setState({ - settings: { - ...getDefaultSettings(''), - ...(autoResume === undefined ? {} : { nativeChatResumeWorkOnRestart: autoResume }) - } - }) -} - -beforeEach(() => { - rpc.mockReset() - _resetNativeChatRestartOffer() - _resetNativeChatLaunchResumeDecision() - useAppStore.setState(useAppStore.getInitialState(), true) - seen.length = 0 - container = document.createElement('div') - document.body.appendChild(container) - root = createRoot(container) -}) - -afterEach(async () => { - await act(async () => root.unmount()) - container.remove() -}) - -it('holds Continue back from the settings wait until the opted-in launch names its chats', async () => { - const read = Promise.withResolvers() - rpc.mockImplementation((_target, method) => - method === 'agentSession.restartResumable' ? read.promise : new Promise(() => {}) - ) - await act(async () => root.render()) - expect(seen.at(-1)).toEqual({ pending: true, resuming: [] }) - - settings(true) - await act(async () => root.render()) - expect(seen.at(-1)).toEqual({ pending: true, resuming: [] }) - - await act(async () => read.resolve({ sessions: offered })) - - expect(seen.at(-1)).toEqual({ pending: false, resuming: ['a', 'b'] }) - expect(seen.some((entry) => !entry.pending && entry.resuming.length === 0)).toBe(false) -}) diff --git a/src/renderer/src/components/NativeChatResumeOnRestartModal.tsx b/src/renderer/src/components/native-chat-recovery/NativeChatResumeOnRestartModal.tsx similarity index 93% rename from src/renderer/src/components/NativeChatResumeOnRestartModal.tsx rename to src/renderer/src/components/native-chat-recovery/NativeChatResumeOnRestartModal.tsx index 2ee9c4ee7cd..569fbb2d98e 100644 --- a/src/renderer/src/components/NativeChatResumeOnRestartModal.tsx +++ b/src/renderer/src/components/native-chat-recovery/NativeChatResumeOnRestartModal.tsx @@ -1,35 +1,35 @@ -import { NativeChatResumeDialogHeader } from './NativeChatResumeDialogHeader' +import { NativeChatResumeDialogHeader } from './dialogs/NativeChatResumeDialogHeader' import { useCallback, useEffect, useMemo, useRef, useState, useSyncExternalStore } from 'react' -import { Button } from './ui/button' -import { Checkbox } from './ui/checkbox' -import { Dialog, DialogContent, DialogFooter } from './ui/dialog' -import { useAppStore } from '../store' +import { Button } from '../ui/button' +import { Checkbox } from '../ui/checkbox' +import { Dialog, DialogContent, DialogFooter } from '../ui/dialog' +import { useAppStore } from '../../store/index' import { useTranslate, type Translate } from '@/i18n/use-translate' import { activateAiVaultStructuredSession } from '@/lib/activate-ai-vault-structured-session' -import { ResumeOnRestartGroups } from './NativeChatResumeOnRestartGroups' -import { ResumeTreeRow } from './NativeChatResumeTreeRow' +import { ResumeOnRestartGroups } from './tree/NativeChatResumeOnRestartGroups' +import { ResumeTreeRow } from './tree/NativeChatResumeTreeRow' import { resumeFailureGuidance, resumeFailureSelectable, type ResumeFailureAction -} from './native-chat-resume-failure-guidance' +} from './failures/native-chat-resume-failure-guidance' import { resumeSelectionState, toggleResumeSelection, type ResumeCandidate, type ResumeFailure -} from './native-chat-resume-on-restart-grouping' +} from './tree/native-chat-resume-on-restart-grouping' import { useNativeChatRestartOffer, useNativeChatRestartResuming, - useNativeChatRestartRun, - type NativeChatRestartStore -} from './native-chat-resume-on-restart-store' -import { useResumeRunPanel } from './NativeChatResumeRunPanel' -import { resumeRunFailures } from './native-chat-resume-run-view' -import { NativeChatResumeAutoNote } from './NativeChatResumeAutoNote' -import { NativeChatRemoteResumeActions } from './NativeChatRemoteResumeActions' -import { moveInTree } from './native-chat-resume-tree-keys' + useNativeChatRestartRun +} from './offers/native-chat-resume-on-restart-store' +import type { NativeChatRestartStore } from './offers/native-chat-restart-runtime-store' +import { useResumeRunPanel } from './runs/NativeChatResumeRunPanel' +import { resumeRunFailures } from './runs/native-chat-resume-run-view' +import { NativeChatResumeAutoNote } from './dialogs/NativeChatResumeAutoNote' +import { NativeChatRemoteResumeActions } from './dialogs/NativeChatRemoteResumeActions' +import { moveInTree } from './tree/native-chat-resume-tree-keys' /** Resume reattaches and sends a continuation, never the original user prompt; disclose this before sending. Automatic preference skips the prompt but uses the same host safety checks. * The store owns runs across dialog closes. Closing snoozes; Dismiss all deletes durable offers. Row Retry/Dismiss keep the dialog open, and settled runs cannot close a user-reopened dialog. Unretryable failures stay outside Resume. */ diff --git a/src/renderer/src/components/NativeChatResumeRuntimeModal.tsx b/src/renderer/src/components/native-chat-recovery/NativeChatResumeRuntimeModal.tsx similarity index 72% rename from src/renderer/src/components/NativeChatResumeRuntimeModal.tsx rename to src/renderer/src/components/native-chat-recovery/NativeChatResumeRuntimeModal.tsx index 373a69643f5..61ad4fed54e 100644 --- a/src/renderer/src/components/NativeChatResumeRuntimeModal.tsx +++ b/src/renderer/src/components/native-chat-recovery/NativeChatResumeRuntimeModal.tsx @@ -1,14 +1,12 @@ import { useSyncExternalStore } from 'react' -import { - localNativeChatRestartStore, - type NativeChatRestartStore -} from './native-chat-resume-on-restart-store' +import { localNativeChatRestartStore } from './offers/native-chat-resume-on-restart-store' +import type { NativeChatRestartStore } from './offers/native-chat-restart-runtime-store' import { NativeChatResumeOccurrenceModal } from './NativeChatResumeOnRestartModal' -import { useNativeChatRestartOfferEnabled } from './native-chat-restart-offer-gate' -import { useNativeChatRestartRuntimes } from './native-chat-restart-runtimes' +import { useLocalStructuredChatsInUse } from '../../runtime/native-chat/local-sessions/local-structured-chats' +import { useNativeChatRestartRuntimes } from './offers/native-chat-restart-runtimes' export function NativeChatResumeOnRestartModal(): React.JSX.Element { - const enabled = useNativeChatRestartOfferEnabled() + const enabled = useLocalStructuredChatsInUse() const runtimes = useNativeChatRestartRuntimes() return ( <> diff --git a/src/renderer/src/components/NativeChatRemoteResumeActions.tsx b/src/renderer/src/components/native-chat-recovery/dialogs/NativeChatRemoteResumeActions.tsx similarity index 92% rename from src/renderer/src/components/NativeChatRemoteResumeActions.tsx rename to src/renderer/src/components/native-chat-recovery/dialogs/NativeChatRemoteResumeActions.tsx index f5b4b6b1963..6562bc8e3b9 100644 --- a/src/renderer/src/components/NativeChatRemoteResumeActions.tsx +++ b/src/renderer/src/components/native-chat-recovery/dialogs/NativeChatRemoteResumeActions.tsx @@ -1,6 +1,6 @@ -import { Button } from './ui/button' +import { Button } from '../../ui/button' import { useTranslate } from '@/i18n/use-translate' -import type { NativeChatRestartStore } from './native-chat-resume-on-restart-store' +import type { NativeChatRestartStore } from '../offers/native-chat-restart-runtime-store' export function NativeChatRemoteResumeActions({ store, diff --git a/src/renderer/src/components/NativeChatResumeAutoNote.tsx b/src/renderer/src/components/native-chat-recovery/dialogs/NativeChatResumeAutoNote.tsx similarity index 88% rename from src/renderer/src/components/NativeChatResumeAutoNote.tsx rename to src/renderer/src/components/native-chat-recovery/dialogs/NativeChatResumeAutoNote.tsx index ccbe1f20d24..3d0e6e77d32 100644 --- a/src/renderer/src/components/NativeChatResumeAutoNote.tsx +++ b/src/renderer/src/components/native-chat-recovery/dialogs/NativeChatResumeAutoNote.tsx @@ -1,7 +1,7 @@ import { useTranslate } from '@/i18n/use-translate' -import { useAppStore } from '../store' -import { Button } from './ui/button' -import { NATIVE_CHAT_RESUME_SETTING_SECTION_ID } from './settings/chat/native-chat-resume-setting-target' +import { useAppStore } from '../../../store/index' +import { Button } from '../../ui/button' +import { NATIVE_CHAT_RESUME_SETTING_SECTION_ID } from '../../settings/chat/native-chat-resume-setting-target' /** Explain automatic resume only for runs started by this launch’s saved preference, with its settings link. */ export function NativeChatResumeAutoNote({ diff --git a/src/renderer/src/components/NativeChatResumeDialogHeader.tsx b/src/renderer/src/components/native-chat-recovery/dialogs/NativeChatResumeDialogHeader.tsx similarity index 94% rename from src/renderer/src/components/NativeChatResumeDialogHeader.tsx rename to src/renderer/src/components/native-chat-recovery/dialogs/NativeChatResumeDialogHeader.tsx index 2e7045fb15b..8dabbb04f46 100644 --- a/src/renderer/src/components/NativeChatResumeDialogHeader.tsx +++ b/src/renderer/src/components/native-chat-recovery/dialogs/NativeChatResumeDialogHeader.tsx @@ -1,7 +1,7 @@ import { RotateCcw } from 'lucide-react' import { useTranslate } from '@/i18n/use-translate' -import { DialogHeader, DialogTitle, DialogDescription } from './ui/dialog' -import type { ResumeRunPanel } from './NativeChatResumeRunPanel' +import { DialogHeader, DialogTitle, DialogDescription } from '../../ui/dialog' +import type { ResumeRunPanel } from '../runs/NativeChatResumeRunPanel' export function NativeChatResumeDialogHeader({ runPanel, diff --git a/src/renderer/src/components/native-chat-resume-on-restart-dialog.ts b/src/renderer/src/components/native-chat-recovery/dialogs/native-chat-resume-on-restart-dialog.ts similarity index 100% rename from src/renderer/src/components/native-chat-resume-on-restart-dialog.ts rename to src/renderer/src/components/native-chat-recovery/dialogs/native-chat-resume-on-restart-dialog.ts diff --git a/src/renderer/src/components/NativeChatResumeFailureDetails.tsx b/src/renderer/src/components/native-chat-recovery/failures/NativeChatResumeFailureDetails.tsx similarity index 95% rename from src/renderer/src/components/NativeChatResumeFailureDetails.tsx rename to src/renderer/src/components/native-chat-recovery/failures/NativeChatResumeFailureDetails.tsx index 2aa5e92575a..3a53d0ce3c8 100644 --- a/src/renderer/src/components/NativeChatResumeFailureDetails.tsx +++ b/src/renderer/src/components/native-chat-recovery/failures/NativeChatResumeFailureDetails.tsx @@ -1,13 +1,13 @@ import { AlertCircle, Clock, X } from 'lucide-react' -import { Button } from './ui/button' -import { Tooltip, TooltipContent, TooltipTrigger } from './ui/tooltip' +import { Button } from '../../ui/button' +import { Tooltip, TooltipContent, TooltipTrigger } from '../../ui/tooltip' import { translate } from '@/i18n/i18n' import { useTranslate, type Translate } from '@/i18n/use-translate' import { resumeFailureGuidance, type ResumeFailureAction } from './native-chat-resume-failure-guidance' -import type { ResumeFailure } from './native-chat-resume-on-restart-grouping' +import type { ResumeFailure } from '../tree/native-chat-resume-on-restart-grouping' /** Keep unconfirmed outcomes distinct from refusals; offer Retry only where it can succeed. */ diff --git a/src/renderer/src/components/native-chat-resume-failure-guidance.ts b/src/renderer/src/components/native-chat-recovery/failures/native-chat-resume-failure-guidance.ts similarity index 97% rename from src/renderer/src/components/native-chat-resume-failure-guidance.ts rename to src/renderer/src/components/native-chat-recovery/failures/native-chat-resume-failure-guidance.ts index a51552c1ea9..b79d1360561 100644 --- a/src/renderer/src/components/native-chat-resume-failure-guidance.ts +++ b/src/renderer/src/components/native-chat-recovery/failures/native-chat-resume-failure-guidance.ts @@ -1,6 +1,6 @@ import { translate } from '@/i18n/i18n' import type { Translate } from '@/i18n/use-translate' -import type { ResumeFailure } from './native-chat-resume-on-restart-grouping' +import type { ResumeFailure } from '../tree/native-chat-resume-on-restart-grouping' /** Offer retry only for recoverable refusals; newer chat work or a standing provider refusal requires continuing in the chat. */ diff --git a/src/renderer/src/components/native-chat-recovery/integration/native-chat-resume-bulk-progress.test.tsx b/src/renderer/src/components/native-chat-recovery/integration/native-chat-resume-bulk-progress.test.tsx new file mode 100644 index 00000000000..577e63211ee --- /dev/null +++ b/src/renderer/src/components/native-chat-recovery/integration/native-chat-resume-bulk-progress.test.tsx @@ -0,0 +1,150 @@ +// @vitest-environment happy-dom +import { + createResumeModalFixture, + offered, + failure, + type RestartRpc, + type ResumeStatusStream +} from './native-chat-resume-modal.test-support' +import { act } from 'react' +import { expect, it, vi, type Mock } from 'vitest' +import { NativeChatResumeOnRestartModal } from '../NativeChatResumeRuntimeModal' + +import { NativeChatResumeStatusSegment } from '../../status-bar/NativeChatResumeStatusSegment' +import type { ResumeCandidate, ResumeFailure } from '../tree/native-chat-resume-on-restart-grouping' +import type { AgentSessionStatusSummary } from '../../../../../shared/agent-session/agent-session-wire' + +const rpc: Mock = vi.hoisted(() => vi.fn()) +const statusStream: ResumeStatusStream = vi.hoisted(() => ({ + emit: (_event: Parameters[0]) => {}, + snapshot: new Map() +})) +vi.mock('../../../runtime/native-chat/requests/structured-agent-session-call', () => ({ + callStructuredAgentSession: rpc +})) + +vi.mock('../../../runtime/native-chat/requests/structured-agent-session-subscriptions', () => ({ + subscribeStructuredAgentSessionStatus: async ( + _target: unknown, + emit: (event: Parameters[0]) => void + ) => { + statusStream.emit = emit + emit({ type: 'snapshot', sessions: [...statusStream.snapshot.values()] }) + return { unsubscribe: () => {} } + } +})) +vi.mock('@/lib/activate-ai-vault-structured-session', () => ({ + activateAiVaultStructuredSession: vi.fn(async () => true) +})) +vi.mock('sonner', async () => + (await import('./native-chat-resume-sonner-mock.test-support')).resumeSonnerMock() +) + +const { mount, button, offerIds, runStatus } = createResumeModalFixture(rpc, statusStream) + +function emitPhase( + sessionId: string, + phase?: NonNullable['phase'] +): void { + statusStream.emit({ + type: 'status', + session: { + sessionId, + workspaceId: 'workspace', + agent: 'codex', + status: 'idle', + latestPrompt: '', + updatedAt: 1, + ...(phase ? { restartResume: { phase } } : {}) + } + }) +} + +it('keeps the run in flight after every feed verdict until the fallback list is published', async () => { + const answer = Promise.withResolvers<{ + continued: { sessionId: string; outcome: 'continued' }[] + }>() + const listing = Promise.withResolvers<{ sessions: ResumeCandidate[]; failed: ResumeFailure[] }>() + let reads = 0 + rpc.mockImplementation(async (_target, method) => + method === 'agentSession.restartContinue' + ? answer.promise + : reads++ === 0 + ? { sessions: offered, failed: [] } + : listing.promise + ) + await mount( + <> + + + + ) + await act(async () => button('Resume 2 chats').click()) + await act(async () => button('Resuming chats 0/2').click()) + await act(async () => { + for (const { sessionId } of offered) { + statusStream.emit({ + type: 'status', + session: { + sessionId, + workspaceId: 'workspace', + agent: 'codex', + status: 'idle', + latestPrompt: '', + updatedAt: 1, + restartResume: { phase: 'continued' } + } + }) + } + answer.resolve({ + continued: offered.map(({ sessionId }) => ({ sessionId, outcome: 'continued' })) + }) + }) + expect(button('Resuming chats 2/2')).toBeTruthy() + await act(async () => offered.forEach(({ sessionId }) => emitPhase(sessionId))) + expect(button('Resuming chats 2/2')).toBeTruthy() + expect(runStatus('Prompt a')).toBe('Prompt a: Resumed') + expect(button('Resuming…').disabled).toBe(true) + expect(document.body.textContent).not.toContain('chats to resume') + await act(async () => listing.resolve({ sessions: [], failed: [] })) + expect(offerIds()).toEqual([]) + expect(button('Done').disabled).toBe(false) + expect(document.body.textContent).not.toContain('Resuming chats') +}) + +it('retains success and refusal frames through cleanup before a delayed bulk reply', async () => { + const reply = Promise.withResolvers() + rpc.mockImplementation(async (_target, method) => + method === 'agentSession.restartResumable' ? { sessions: offered, failed: [] } : reply.promise + ) + await mount( + <> + + + + ) + await act(async () => button('Resume 2 chats').click()) + // Verdicts and cleanup can arrive together before React gets a render. + await act(async () => { + emitPhase('a', 'continued') + emitPhase('b', 'refused') + emitPhase('a') + emitPhase('b') + }) + expect(button('Resuming chats 2/2')).toBeTruthy() + await act(async () => button('Resuming chats 2/2').click()) + expect(runStatus('Prompt a')).toBe('Prompt a: Resumed') + expect(runStatus('Prompt b')).toBe('Prompt b: Couldn’t resume') + expect(document.querySelector('[role="dialog"]')?.textContent).toContain('Need you1') + await act(async () => + reply.resolve({ + sessions: [], + failed: [failure('b')], + continued: [ + { sessionId: 'a', outcome: 'continued' }, + { sessionId: 'b', outcome: 'refused' } + ] + }) + ) + expect(document.querySelector('[role="dialog"]')?.textContent).toContain('Resumed 1 of 2 chats') +}) diff --git a/src/renderer/src/components/native-chat-recovery/integration/native-chat-resume-finished-run.test.tsx b/src/renderer/src/components/native-chat-recovery/integration/native-chat-resume-finished-run.test.tsx new file mode 100644 index 00000000000..64c64c135ad --- /dev/null +++ b/src/renderer/src/components/native-chat-recovery/integration/native-chat-resume-finished-run.test.tsx @@ -0,0 +1,65 @@ +// @vitest-environment happy-dom +import { act } from 'react' +import { expect, it, vi, type Mock } from 'vitest' +import { NativeChatResumeOnRestartModal } from '../NativeChatResumeRuntimeModal' +import { NativeChatResumeStatusSegment } from '../../status-bar/NativeChatResumeStatusSegment' +import { + createResumeModalFixture, + type RestartRpc, + type ResumeStatusStream +} from './native-chat-resume-modal.test-support' +import { lastToastShow } from './native-chat-resume-toast.test-support' +import { releaseFinishedNativeChatRestartRun } from '../offers/native-chat-resume-on-restart-store' +import { + consumeNativeChatResumeOnRestartDialogRequest, + requestNativeChatResumeOnRestartDialog +} from '../dialogs/native-chat-resume-on-restart-dialog' + +const rpc: Mock = vi.hoisted(() => vi.fn()) +const statusStream: ResumeStatusStream = vi.hoisted(() => ({ + emit: (_event: Parameters[0]) => {}, + snapshot: new Map() +})) +vi.mock('../../../runtime/native-chat/requests/structured-agent-session-call', () => ({ + callStructuredAgentSession: rpc +})) + +vi.mock('../../../runtime/native-chat/requests/structured-agent-session-subscriptions', () => ({ + subscribeStructuredAgentSessionStatus: async ( + _target: unknown, + emit: ResumeStatusStream['emit'] + ) => { + statusStream.emit = emit + emit({ type: 'snapshot', sessions: [...statusStream.snapshot.values()] }) + return { unsubscribe: () => {} } + } +})) +vi.mock('sonner', async () => + (await import('./native-chat-resume-sonner-mock.test-support')).resumeSonnerMock() +) + +const { mount, button, fakeHost } = createResumeModalFixture(rpc, statusStream) +const dialog = () => document.querySelector('[role="dialog"]')?.textContent + +async function mountSurfaces(): Promise { + await mount( + <> + + + + ) +} + +it('does not consume a finished run if its requested view never rendered', async () => { + fakeHost() + await mountSurfaces() + await act(async () => button('Resume 2 chats').click()) + await act(async () => { + requestNativeChatResumeOnRestartDialog() + consumeNativeChatResumeOnRestartDialogRequest() + releaseFinishedNativeChatRestartRun() + }) + expect(dialog()).toBeUndefined() + await act(async () => lastToastShow()?.()) + expect(dialog()).toContain('Resumed 2 of 2 chats') +}) diff --git a/src/renderer/src/components/native-chat-resume-modal.test-support.tsx b/src/renderer/src/components/native-chat-recovery/integration/native-chat-resume-modal.test-support.tsx similarity index 93% rename from src/renderer/src/components/native-chat-resume-modal.test-support.tsx rename to src/renderer/src/components/native-chat-recovery/integration/native-chat-resume-modal.test-support.tsx index 017d2793a2d..583cc5cd4d9 100644 --- a/src/renderer/src/components/native-chat-resume-modal.test-support.tsx +++ b/src/renderer/src/components/native-chat-recovery/integration/native-chat-resume-modal.test-support.tsx @@ -1,22 +1,22 @@ -import { EVERY_AGENT_CHAT } from '../../../shared/native-chat/every-agent-chat.test-fixture' +import { EVERY_AGENT_CHAT } from '../../../../../shared/native-chat/every-agent-chat.test-fixture' import { act } from 'react' import { toast } from 'sonner' import { createRoot, type Root } from 'react-dom/client' import { afterEach, beforeEach, vi, type Mock } from 'vitest' -import { useAppStore } from '../store' -import { getDefaultSettings } from '../../../shared/constants' +import { useAppStore } from '../../../store/index' +import { getDefaultSettings } from '../../../../../shared/constants' import type { AgentSessionStatusEvent, AgentSessionStatusSummary -} from '../../../shared/agent-session/agent-session-wire' +} from '../../../../../shared/agent-session/agent-session-wire' import { resetStructuredAgentSessionStatusFeedsForTests } from '@/runtime/native-chat/status/structured-agent-session-status-feed' -import { TooltipProvider } from './ui/tooltip' -import type { ResumeCandidate, ResumeFailure } from './native-chat-resume-on-restart-grouping' -import { consumeNativeChatResumeOnRestartDialogRequest } from './native-chat-resume-on-restart-dialog' +import { TooltipProvider } from '../../ui/tooltip' +import type { ResumeCandidate, ResumeFailure } from '../tree/native-chat-resume-on-restart-grouping' +import { consumeNativeChatResumeOnRestartDialogRequest } from '../dialogs/native-chat-resume-on-restart-dialog' import { _resetNativeChatRestartOffer, getNativeChatRestartOffer -} from './native-chat-resume-on-restart-store' +} from '../offers/native-chat-resume-on-restart-store' export const offered: ResumeCandidate[] = ['a', 'b'].map((sessionId) => ({ sessionId, diff --git a/src/renderer/src/components/native-chat-resume-on-restart-modal.test-support.ts b/src/renderer/src/components/native-chat-recovery/integration/native-chat-resume-on-restart-modal.test-support.ts similarity index 95% rename from src/renderer/src/components/native-chat-resume-on-restart-modal.test-support.ts rename to src/renderer/src/components/native-chat-recovery/integration/native-chat-resume-on-restart-modal.test-support.ts index b95ce31631a..ceda69d133b 100644 --- a/src/renderer/src/components/native-chat-resume-on-restart-modal.test-support.ts +++ b/src/renderer/src/components/native-chat-recovery/integration/native-chat-resume-on-restart-modal.test-support.ts @@ -1,4 +1,4 @@ -import type { ResumeCandidate } from './native-chat-resume-on-restart-grouping' +import type { ResumeCandidate } from '../tree/native-chat-resume-on-restart-grouping' export const offered: ResumeCandidate[] = ['a', 'b'].map((sessionId) => ({ sessionId, diff --git a/src/renderer/src/components/native-chat-resume-sonner-mock.test-support.ts b/src/renderer/src/components/native-chat-recovery/integration/native-chat-resume-sonner-mock.test-support.ts similarity index 100% rename from src/renderer/src/components/native-chat-resume-sonner-mock.test-support.ts rename to src/renderer/src/components/native-chat-recovery/integration/native-chat-resume-sonner-mock.test-support.ts diff --git a/src/renderer/src/components/native-chat-resume-toast.test-support.ts b/src/renderer/src/components/native-chat-recovery/integration/native-chat-resume-toast.test-support.ts similarity index 100% rename from src/renderer/src/components/native-chat-resume-toast.test-support.ts rename to src/renderer/src/components/native-chat-recovery/integration/native-chat-resume-toast.test-support.ts diff --git a/src/renderer/src/components/native-chat-launch-resume-decision.ts b/src/renderer/src/components/native-chat-recovery/offers/native-chat-launch-resume-decision.ts similarity index 95% rename from src/renderer/src/components/native-chat-launch-resume-decision.ts rename to src/renderer/src/components/native-chat-recovery/offers/native-chat-launch-resume-decision.ts index e3676dce4e2..44013231996 100644 --- a/src/renderer/src/components/native-chat-launch-resume-decision.ts +++ b/src/renderer/src/components/native-chat-recovery/offers/native-chat-launch-resume-decision.ts @@ -1,7 +1,7 @@ // Suppress competing continuation offers until the launch makes its resume decision and publishes resuming ids. import { useSyncExternalStore } from 'react' -import { useAppStore } from '../store' +import { useAppStore } from '../../../store/index' let decided = false const listeners = new Set<() => void>() diff --git a/src/renderer/src/components/native-chat-remote-restart-offer.ts b/src/renderer/src/components/native-chat-recovery/offers/native-chat-remote-restart-offer.ts similarity index 92% rename from src/renderer/src/components/native-chat-remote-restart-offer.ts rename to src/renderer/src/components/native-chat-recovery/offers/native-chat-remote-restart-offer.ts index 63cf2e1179e..e66c769e09c 100644 --- a/src/renderer/src/components/native-chat-remote-restart-offer.ts +++ b/src/renderer/src/components/native-chat-recovery/offers/native-chat-remote-restart-offer.ts @@ -1,5 +1,5 @@ -import type { RuntimeEnvironmentStatus } from '../../../shared/remote-runtime/host-status/runtime-host-status' -import type { RuntimeClientTarget } from '../../../shared/runtime-client-target' +import type { RuntimeEnvironmentStatus } from '../../../../../shared/remote-runtime/host-status/runtime-host-status' +import type { RuntimeClientTarget } from '../../../../../shared/runtime-client-target' import type { HostOfferRead } from './native-chat-restart-host-offer' export const RESTART_READ_RETRY_DELAYS_MS = [100, 250, 500] as const diff --git a/src/renderer/src/components/native-chat-restart-host-offer.ts b/src/renderer/src/components/native-chat-recovery/offers/native-chat-restart-host-offer.ts similarity index 94% rename from src/renderer/src/components/native-chat-restart-host-offer.ts rename to src/renderer/src/components/native-chat-recovery/offers/native-chat-restart-host-offer.ts index 2bea9f74f46..134278b8693 100644 --- a/src/renderer/src/components/native-chat-restart-host-offer.ts +++ b/src/renderer/src/components/native-chat-recovery/offers/native-chat-restart-host-offer.ts @@ -1,8 +1,8 @@ import { callStructuredAgentSession } from '@/runtime/native-chat/requests/structured-agent-session-call' import { RuntimeRpcCallError } from '@/runtime/rpc/calls/runtime-rpc-result' -import type { RuntimeClientTarget } from '../../../shared/runtime-client-target' +import type { RuntimeClientTarget } from '../../../../../shared/runtime-client-target' import { executionHostIdForStructuredTarget } from '@/runtime/native-chat/session-ownership/structured-agent-session-owner' -import type { ResumeCandidate, ResumeFailure } from './native-chat-resume-on-restart-grouping' +import type { ResumeCandidate, ResumeFailure } from '../tree/native-chat-resume-on-restart-grouping' export type HostOfferRead = { candidates: readonly ResumeCandidate[] failed: readonly ResumeFailure[] diff --git a/src/renderer/src/components/native-chat-restart-occurrence.ts b/src/renderer/src/components/native-chat-recovery/offers/native-chat-restart-occurrence.ts similarity index 96% rename from src/renderer/src/components/native-chat-restart-occurrence.ts rename to src/renderer/src/components/native-chat-recovery/offers/native-chat-restart-occurrence.ts index 0c79ce5007d..dda74a426f0 100644 --- a/src/renderer/src/components/native-chat-restart-occurrence.ts +++ b/src/renderer/src/components/native-chat-recovery/offers/native-chat-restart-occurrence.ts @@ -6,19 +6,19 @@ import { type NativeChatRestartOffer, type HostOfferRead } from './native-chat-restart-host-offer' -import type { RuntimeClientTarget } from '../../../shared/runtime-client-target' +import type { RuntimeClientTarget } from '../../../../../shared/runtime-client-target' import { getStructuredAgentSessionStatusFeed } from '@/runtime/native-chat/status/structured-agent-session-status-feed' import { markNativeChatLaunchResumeDecided } from './native-chat-launch-resume-decision' -import { announceRestartResults } from './native-chat-restart-action-notifications' +import { announceRestartResults } from '../runs/native-chat-restart-action-notifications' import { beginResumeRun, resumeRunInFlight, resumeRunPendingIds, type ResumeRun, type ResumeRunStarter -} from './native-chat-resume-run' +} from '../runs/native-chat-resume-run' import { createUnsentResumes } from './native-chat-resume-unsent-requests' -import * as dialog from './native-chat-resume-on-restart-dialog' +import * as dialog from '../dialogs/native-chat-resume-on-restart-dialog' import { createOfferedChatWatch } from './native-chat-resume-offered-chat-watch' import { createRemoteRestartOfferLifecycle, @@ -27,8 +27,8 @@ import { import { continueRestartChunks, type RestartContinuationBatchResult -} from './native-chat-restart-continuation-chunks' -import { watchResumeRunStatus } from './native-chat-resume-run-status-watch' +} from '../runs/native-chat-restart-continuation-chunks' +import { watchResumeRunStatus } from '../runs/native-chat-resume-run-status-watch' let nextOccurrence = 0 diff --git a/src/renderer/src/components/native-chat-restart-runtime-store.ts b/src/renderer/src/components/native-chat-recovery/offers/native-chat-restart-runtime-store.ts similarity index 89% rename from src/renderer/src/components/native-chat-restart-runtime-store.ts rename to src/renderer/src/components/native-chat-recovery/offers/native-chat-restart-runtime-store.ts index bac2a11ae96..a92727cf52e 100644 --- a/src/renderer/src/components/native-chat-restart-runtime-store.ts +++ b/src/renderer/src/components/native-chat-recovery/offers/native-chat-restart-runtime-store.ts @@ -1,5 +1,5 @@ -import type { RuntimeClientTarget } from '../../../shared/runtime-client-target' -import type { RuntimeEnvironmentStatus } from '../../../shared/remote-runtime/host-status/runtime-host-status' +import type { RuntimeClientTarget } from '../../../../../shared/runtime-client-target' +import type { RuntimeEnvironmentStatus } from '../../../../../shared/remote-runtime/host-status/runtime-host-status' import { remoteRestartRuntimeId } from './native-chat-remote-restart-offer' import { createNativeChatRestartOccurrence } from './native-chat-restart-occurrence' import { EMPTY } from './native-chat-restart-host-offer' @@ -7,8 +7,8 @@ import { resumeRunPendingIds, type ResumeRun, type ResumeRunStarter -} from './native-chat-resume-run' -import * as dialog from './native-chat-resume-on-restart-dialog' +} from '../runs/native-chat-resume-run' +import * as dialog from '../dialogs/native-chat-resume-on-restart-dialog' const NO_RESUMING = resumeRunPendingIds(null) @@ -84,3 +84,5 @@ export function createNativeChatRestartStore(target: RuntimeClientTarget) { } } } + +export type NativeChatRestartStore = ReturnType diff --git a/src/renderer/src/components/native-chat-restart-runtimes.ts b/src/renderer/src/components/native-chat-recovery/offers/native-chat-restart-runtimes.ts similarity index 88% rename from src/renderer/src/components/native-chat-restart-runtimes.ts rename to src/renderer/src/components/native-chat-recovery/offers/native-chat-restart-runtimes.ts index acd6b38f44c..cecb9cd55a9 100644 --- a/src/renderer/src/components/native-chat-restart-runtimes.ts +++ b/src/renderer/src/components/native-chat-recovery/offers/native-chat-restart-runtimes.ts @@ -1,11 +1,11 @@ import { useEffect, useSyncExternalStore } from 'react' -import { useAppStore } from '../store' -import type { RuntimeClientTarget } from '../../../shared/runtime-client-target' +import { useAppStore } from '../../../store/index' +import type { RuntimeClientTarget } from '../../../../../shared/runtime-client-target' import { createNativeChatRestartStore, - localNativeChatRestartStore, type NativeChatRestartStore -} from './native-chat-resume-on-restart-store' +} from './native-chat-restart-runtime-store' +import { localNativeChatRestartStore } from './native-chat-resume-on-restart-store' const stores = new Map() const listeners = new Set<() => void>() diff --git a/src/renderer/src/components/native-chat-resume-failed-chat-watch.test.ts b/src/renderer/src/components/native-chat-recovery/offers/native-chat-resume-failed-chat-watch.test.ts similarity index 64% rename from src/renderer/src/components/native-chat-resume-failed-chat-watch.test.ts rename to src/renderer/src/components/native-chat-recovery/offers/native-chat-resume-failed-chat-watch.test.ts index 699a08de4be..d8f8aa50ee0 100644 --- a/src/renderer/src/components/native-chat-resume-failed-chat-watch.test.ts +++ b/src/renderer/src/components/native-chat-recovery/offers/native-chat-resume-failed-chat-watch.test.ts @@ -4,11 +4,10 @@ import { afterEach, beforeEach, expect, it, vi } from 'vitest' import type { AgentSessionStatusEvent, AgentSessionStatusSummary -} from '../../../shared/agent-session/agent-session-wire' +} from '../../../../../shared/agent-session/agent-session-wire' import { resetStructuredAgentSessionStatusFeedsForTests } from '@/runtime/native-chat/status/structured-agent-session-status-feed' import { _resetNativeChatRestartOffer, - continueNativeChatRestartOffer, dismissNativeChatRestartOffer, getNativeChatRestartOffer, refreshNativeChatRestartOffer @@ -19,11 +18,11 @@ const mocks = vi.hoisted(() => ({ subscribeStatus: vi.fn(), unsubscribe: vi.fn() })) -vi.mock('../runtime/native-chat/requests/structured-agent-session-call', () => ({ +vi.mock('../../../runtime/native-chat/requests/structured-agent-session-call', () => ({ callStructuredAgentSession: mocks.rpc })) -vi.mock('../runtime/native-chat/requests/structured-agent-session-subscriptions', () => ({ +vi.mock('../../../runtime/native-chat/requests/structured-agent-session-subscriptions', () => ({ subscribeStructuredAgentSessionStatus: mocks.subscribeStatus })) @@ -89,16 +88,6 @@ afterEach(() => { vi.useRealTimers() }) -// Known chat changes are news despite older host timestamps because list and status delivery can race. -it('re-reads for a known failed chat that changes even when its stamp predates the list', async () => { - await listFailure() - hostEmit()({ type: 'snapshot', sessions: [summary('idle', 'Fix it', 1)] }) - hostEmit()({ type: 'status', session: summary('working', 'Carry on please', 2) }) - await vi.advanceTimersByTimeAsync(500) - expect(offerReads()).toBe(2) - expect(getNativeChatRestartOffer().failed).toEqual([]) -}) - it('never lets a re-read that was already in flight bring back a dismissed failure', async () => { await listFailure({ failed: [failure] }) const stale = Promise.withResolvers() @@ -118,28 +107,3 @@ it('never lets a re-read that was already in flight bring back a dismissed failu expect(getNativeChatRestartOffer().failed).toEqual([]) }) - -it('waits for a resume in flight instead of re-reading under it', async () => { - await listFailure({ failed: [failure] }) - const acting = Promise.withResolvers() - let failed: unknown[] = [failure] - mocks.rpc.mockImplementation((_target: unknown, method: string) => - method === 'agentSession.restartContinue' - ? acting.promise - : Promise.resolve({ sessions: [], failed }) - ) - const retry = continueNativeChatRestartOffer(['a']) - hostEmit()({ type: 'status', session: summary('working', 'Carry on please', Date.now() + 1) }) - await vi.advanceTimersByTimeAsync(500) - expect(offerReads()).toBe(1) - - failed = [] - acting.resolve({ - sessions: [], - failed: [], - continued: [{ sessionId: 'a', outcome: 'continued' }] - }) - await retry - expect(offerReads()).toBe(1) - expect(getNativeChatRestartOffer().failed).toEqual([]) -}) diff --git a/src/renderer/src/components/native-chat-resume-offered-chat-watch.ts b/src/renderer/src/components/native-chat-recovery/offers/native-chat-resume-offered-chat-watch.ts similarity index 96% rename from src/renderer/src/components/native-chat-resume-offered-chat-watch.ts rename to src/renderer/src/components/native-chat-recovery/offers/native-chat-resume-offered-chat-watch.ts index e0d3cf11a37..c482b1cc046 100644 --- a/src/renderer/src/components/native-chat-resume-offered-chat-watch.ts +++ b/src/renderer/src/components/native-chat-recovery/offers/native-chat-resume-offered-chat-watch.ts @@ -1,6 +1,6 @@ import type { StructuredAgentSessionStatusChange } from '@/runtime/native-chat/status/structured-agent-session-status-dispatch' import type { StructuredAgentSessionStatusFeedOwner } from '@/runtime/native-chat/status/structured-agent-session-status-feed' -import type { AgentSessionStatusSummary } from '../../../shared/agent-session/agent-session-wire' +import type { AgentSessionStatusSummary } from '../../../../../shared/agent-session/agent-session-wire' /** Watch offered/failed chats only; debounce status/prompt changes into host rereads without one request per streamed summary. */ diff --git a/src/renderer/src/components/native-chat-resume-on-restart-store.ts b/src/renderer/src/components/native-chat-recovery/offers/native-chat-resume-on-restart-store.ts similarity index 86% rename from src/renderer/src/components/native-chat-resume-on-restart-store.ts rename to src/renderer/src/components/native-chat-recovery/offers/native-chat-resume-on-restart-store.ts index e7b8081c747..acff6a88abf 100644 --- a/src/renderer/src/components/native-chat-resume-on-restart-store.ts +++ b/src/renderer/src/components/native-chat-recovery/offers/native-chat-resume-on-restart-store.ts @@ -1,13 +1,12 @@ +import type { NativeChatRestartStore } from './native-chat-restart-runtime-store' import { RESTART_READ_RETRY_DELAYS_MS } from './native-chat-remote-restart-offer' -import { requestNativeChatResumeOnRestartDialog } from './native-chat-resume-on-restart-dialog' -import { useAppStore } from '../store' +import { requestNativeChatResumeOnRestartDialog } from '../dialogs/native-chat-resume-on-restart-dialog' +import { useAppStore } from '../../../store/index' import { markNativeChatLaunchResumeDecided } from './native-chat-launch-resume-decision' -import { allResumeSessionIds } from './native-chat-resume-on-restart-grouping' +import { allResumeSessionIds } from '../tree/native-chat-resume-on-restart-grouping' import { useEffect, useSyncExternalStore } from 'react' import { createNativeChatRestartStore } from './native-chat-restart-runtime-store' -export type { NativeChatRestartOffer } from './native-chat-restart-host-offer' -export { createNativeChatRestartStore } from './native-chat-restart-runtime-store' -export type NativeChatRestartStore = ReturnType + export const localNativeChatRestartStore = createNativeChatRestartStore({ kind: 'local' }) export const { getNativeChatRestartOffer, diff --git a/src/renderer/src/components/native-chat-resume-unsent-requests.ts b/src/renderer/src/components/native-chat-recovery/offers/native-chat-resume-unsent-requests.ts similarity index 95% rename from src/renderer/src/components/native-chat-resume-unsent-requests.ts rename to src/renderer/src/components/native-chat-recovery/offers/native-chat-resume-unsent-requests.ts index b5be6b0ff24..fb03ac2b99e 100644 --- a/src/renderer/src/components/native-chat-resume-unsent-requests.ts +++ b/src/renderer/src/components/native-chat-recovery/offers/native-chat-resume-unsent-requests.ts @@ -1,4 +1,4 @@ -import type { ResumeCandidate, ResumeFailure } from './native-chat-resume-on-restart-grouping' +import type { ResumeCandidate, ResumeFailure } from '../tree/native-chat-resume-on-restart-grouping' // A lost reply is not a delivery receipt; retain uncertainty until the host supplies current facts. diff --git a/src/renderer/src/components/NativeChatResumeRunPanel.tsx b/src/renderer/src/components/native-chat-recovery/runs/NativeChatResumeRunPanel.tsx similarity index 98% rename from src/renderer/src/components/NativeChatResumeRunPanel.tsx rename to src/renderer/src/components/native-chat-recovery/runs/NativeChatResumeRunPanel.tsx index 6af112638e5..f7e29653a5c 100644 --- a/src/renderer/src/components/NativeChatResumeRunPanel.tsx +++ b/src/renderer/src/components/native-chat-recovery/runs/NativeChatResumeRunPanel.tsx @@ -3,7 +3,7 @@ import { Loader2 } from 'lucide-react' import { translate } from '@/i18n/i18n' import { useTranslate, type Translate } from '@/i18n/use-translate' import { useNow } from '@/hooks/use-now' -import type { ResumeCandidate, ResumeFailure } from './native-chat-resume-on-restart-grouping' +import type { ResumeCandidate, ResumeFailure } from '../tree/native-chat-resume-on-restart-grouping' import { resumeRunInFlight, type ResumeRun, type ResumeRunStarter } from './native-chat-resume-run' import { resumeRunView, type ResumeRunFilter } from './native-chat-resume-run-view' import { ResumeRunStatusIcon } from './NativeChatResumeRunStatusIcon' diff --git a/src/renderer/src/components/NativeChatResumeRunStatusIcon.tsx b/src/renderer/src/components/native-chat-recovery/runs/NativeChatResumeRunStatusIcon.tsx similarity index 94% rename from src/renderer/src/components/NativeChatResumeRunStatusIcon.tsx rename to src/renderer/src/components/native-chat-recovery/runs/NativeChatResumeRunStatusIcon.tsx index 7a3ae94902b..6439650f307 100644 --- a/src/renderer/src/components/NativeChatResumeRunStatusIcon.tsx +++ b/src/renderer/src/components/native-chat-recovery/runs/NativeChatResumeRunStatusIcon.tsx @@ -1,8 +1,8 @@ import { AlertCircle, Check, Clock, Loader2 } from 'lucide-react' -import { Tooltip, TooltipContent, TooltipTrigger } from './ui/tooltip' +import { Tooltip, TooltipContent, TooltipTrigger } from '../../ui/tooltip' import { translate } from '@/i18n/i18n' import { useTranslate, type Translate } from '@/i18n/use-translate' -import { formatNativeChatDuration } from '../../../shared/native-chat/transcript/native-chat-turn-status' +import { formatNativeChatDuration } from '../../../../../shared/native-chat/transcript/native-chat-turn-status' import type { ResumeRunRowStatus } from './native-chat-resume-run-view' export type ResumeRunStartPhase = 'starting' | 'ready' | null diff --git a/src/renderer/src/components/NativeChatResumeRunSummary.tsx b/src/renderer/src/components/native-chat-recovery/runs/NativeChatResumeRunSummary.tsx similarity index 95% rename from src/renderer/src/components/NativeChatResumeRunSummary.tsx rename to src/renderer/src/components/native-chat-recovery/runs/NativeChatResumeRunSummary.tsx index 46b4ec1defa..4732c8e3cd4 100644 --- a/src/renderer/src/components/NativeChatResumeRunSummary.tsx +++ b/src/renderer/src/components/native-chat-recovery/runs/NativeChatResumeRunSummary.tsx @@ -1,7 +1,7 @@ -import { ToggleGroup, ToggleGroupItem } from './ui/toggle-group' +import { ToggleGroup, ToggleGroupItem } from '../../ui/toggle-group' import { translate } from '@/i18n/i18n' import { useTranslate, type Translate } from '@/i18n/use-translate' -import { formatNativeChatDuration } from '../../../shared/native-chat/transcript/native-chat-turn-status' +import { formatNativeChatDuration } from '../../../../../shared/native-chat/transcript/native-chat-turn-status' import type { ResumeRunFilter, ResumeRunView } from './native-chat-resume-run-view' import type { ResumeRunStartPhase } from './NativeChatResumeRunStatusIcon' diff --git a/src/renderer/src/components/native-chat-restart-action-notifications.ts b/src/renderer/src/components/native-chat-recovery/runs/native-chat-restart-action-notifications.ts similarity index 97% rename from src/renderer/src/components/native-chat-restart-action-notifications.ts rename to src/renderer/src/components/native-chat-recovery/runs/native-chat-restart-action-notifications.ts index 5172fb204f5..a3768dd72b4 100644 --- a/src/renderer/src/components/native-chat-restart-action-notifications.ts +++ b/src/renderer/src/components/native-chat-recovery/runs/native-chat-restart-action-notifications.ts @@ -1,8 +1,8 @@ import { createElement, Fragment, type ReactNode } from 'react' import { toast } from 'sonner' import { translate } from '@/i18n/i18n' -import type { ResumeFailure } from './native-chat-resume-on-restart-grouping' -import { INLINE_ACTION_CLASS_NAMES } from './ui/sonner' +import type { ResumeFailure } from '../tree/native-chat-resume-on-restart-grouping' +import { INLINE_ACTION_CLASS_NAMES } from '../../ui/sonner' export type RestartContinuationOutcome = { sessionId: string diff --git a/src/renderer/src/components/native-chat-restart-continuation-chunks.ts b/src/renderer/src/components/native-chat-recovery/runs/native-chat-restart-continuation-chunks.ts similarity index 93% rename from src/renderer/src/components/native-chat-restart-continuation-chunks.ts rename to src/renderer/src/components/native-chat-recovery/runs/native-chat-restart-continuation-chunks.ts index 0b6d1a89468..42ad4d2741f 100644 --- a/src/renderer/src/components/native-chat-restart-continuation-chunks.ts +++ b/src/renderer/src/components/native-chat-recovery/runs/native-chat-restart-continuation-chunks.ts @@ -1,5 +1,5 @@ -import type { ResumeFailure } from './native-chat-resume-on-restart-grouping' -import type { RuntimeClientTarget } from '../../../shared/runtime-client-target' +import type { ResumeFailure } from '../tree/native-chat-resume-on-restart-grouping' +import type { RuntimeClientTarget } from '../../../../../shared/runtime-client-target' import { callStructuredAgentSession } from '@/runtime/native-chat/requests/structured-agent-session-call' import { createRuntimeRpcAbortError } from '@/runtime/rpc/calls/abortable-runtime-environment-call' import { @@ -7,7 +7,7 @@ import { type HostOfferRead, type HostOfferPayload, type NativeChatRestartOffer -} from './native-chat-restart-host-offer' +} from '../offers/native-chat-restart-host-offer' import { restartContinuationHistory, type RestartContinuationOutcome diff --git a/src/renderer/src/components/native-chat-resume-run-status-watch.ts b/src/renderer/src/components/native-chat-recovery/runs/native-chat-resume-run-status-watch.ts similarity index 95% rename from src/renderer/src/components/native-chat-resume-run-status-watch.ts rename to src/renderer/src/components/native-chat-recovery/runs/native-chat-resume-run-status-watch.ts index 879956e64ca..a3ee47c0b69 100644 --- a/src/renderer/src/components/native-chat-resume-run-status-watch.ts +++ b/src/renderer/src/components/native-chat-recovery/runs/native-chat-resume-run-status-watch.ts @@ -1,4 +1,4 @@ -import type { RuntimeClientTarget } from '../../../shared/runtime-client-target' +import type { RuntimeClientTarget } from '../../../../../shared/runtime-client-target' import { getStructuredAgentSessionStatusFeed } from '@/runtime/native-chat/status/structured-agent-session-status-feed' import type { StructuredAgentSessionStatusChange } from '@/runtime/native-chat/status/structured-agent-session-status-dispatch' import { observeResumeRun, type ResumeRun } from './native-chat-resume-run' diff --git a/src/renderer/src/components/native-chat-resume-run-view.ts b/src/renderer/src/components/native-chat-recovery/runs/native-chat-resume-run-view.ts similarity index 98% rename from src/renderer/src/components/native-chat-resume-run-view.ts rename to src/renderer/src/components/native-chat-recovery/runs/native-chat-resume-run-view.ts index 4bfb6a5e0f6..fa3f7056f2e 100644 --- a/src/renderer/src/components/native-chat-resume-run-view.ts +++ b/src/renderer/src/components/native-chat-recovery/runs/native-chat-resume-run-view.ts @@ -1,4 +1,4 @@ -import type { ResumeCandidate, ResumeFailure } from './native-chat-resume-on-restart-grouping' +import type { ResumeCandidate, ResumeFailure } from '../tree/native-chat-resume-on-restart-grouping' import type { ResumeRun, ResumeRunHostStatus } from './native-chat-resume-run' export type ResumeRunRowStatus = diff --git a/src/renderer/src/components/native-chat-resume-run.ts b/src/renderer/src/components/native-chat-recovery/runs/native-chat-resume-run.ts similarity index 93% rename from src/renderer/src/components/native-chat-resume-run.ts rename to src/renderer/src/components/native-chat-recovery/runs/native-chat-resume-run.ts index d7ba6975573..e15748ad3cd 100644 --- a/src/renderer/src/components/native-chat-resume-run.ts +++ b/src/renderer/src/components/native-chat-recovery/runs/native-chat-resume-run.ts @@ -1,6 +1,6 @@ -import type { ResumeCandidate } from './native-chat-resume-on-restart-grouping' +import type { ResumeCandidate } from '../tree/native-chat-resume-on-restart-grouping' import type { RestartContinuationOutcome } from './native-chat-restart-action-notifications' -import type { AgentSessionStatusSummary } from '../../../shared/agent-session/agent-session-wire' +import type { AgentSessionStatusSummary } from '../../../../../shared/agent-session/agent-session-wire' export type ResumeRunHostStatus = Pick< AgentSessionStatusSummary, diff --git a/src/renderer/src/components/NativeChatResumeGroupNode.tsx b/src/renderer/src/components/native-chat-recovery/tree/NativeChatResumeGroupNode.tsx similarity index 100% rename from src/renderer/src/components/NativeChatResumeGroupNode.tsx rename to src/renderer/src/components/native-chat-recovery/tree/NativeChatResumeGroupNode.tsx diff --git a/src/renderer/src/components/NativeChatResumeOnRestartAgentRow.tsx b/src/renderer/src/components/native-chat-recovery/tree/NativeChatResumeOnRestartAgentRow.tsx similarity index 91% rename from src/renderer/src/components/NativeChatResumeOnRestartAgentRow.tsx rename to src/renderer/src/components/native-chat-recovery/tree/NativeChatResumeOnRestartAgentRow.tsx index b1ebf752d87..f7ca3dd3493 100644 --- a/src/renderer/src/components/NativeChatResumeOnRestartAgentRow.tsx +++ b/src/renderer/src/components/native-chat-recovery/tree/NativeChatResumeOnRestartAgentRow.tsx @@ -1,15 +1,18 @@ import { useContext } from 'react' import { AgentIcon } from '@/components/agent/icons/AgentIcon' -import { agentTypeToIconAgent } from '../../../shared/agent-status/presentation/agent-type-icon-agent' -import { formatAgentTypeLabel } from '../../../shared/agent-status/presentation/agent-type-label' +import { agentTypeToIconAgent } from '../../../../../shared/agent-status/presentation/agent-type-icon-agent' +import { formatAgentTypeLabel } from '../../../../../shared/agent-status/presentation/agent-type-label' import { formatShortTimeAgo } from '@/lib/short-time-ago' import { useTranslate } from '@/i18n/use-translate' import type { ResumeCandidate, ResumeFailure } from './native-chat-resume-on-restart-grouping' import { resumeFailureSelectable, type ResumeFailureAction -} from './native-chat-resume-failure-guidance' -import { ResumeFailureGuidanceLine, ResumeFailureStatus } from './NativeChatResumeFailureDetails' +} from '../failures/native-chat-resume-failure-guidance' +import { + ResumeFailureGuidanceLine, + ResumeFailureStatus +} from '../failures/NativeChatResumeFailureDetails' import { resumeActivityLabel } from './native-chat-resume-activity-label' import { ResumeTreeRow } from './NativeChatResumeTreeRow' import { ResumeTreeDepthContext } from './native-chat-resume-tree-state' diff --git a/src/renderer/src/components/NativeChatResumeOnRestartGroups.tsx b/src/renderer/src/components/native-chat-recovery/tree/NativeChatResumeOnRestartGroups.tsx similarity index 97% rename from src/renderer/src/components/NativeChatResumeOnRestartGroups.tsx rename to src/renderer/src/components/native-chat-recovery/tree/NativeChatResumeOnRestartGroups.tsx index 7f8857632b5..a83ecedd4ed 100644 --- a/src/renderer/src/components/NativeChatResumeOnRestartGroups.tsx +++ b/src/renderer/src/components/native-chat-recovery/tree/NativeChatResumeOnRestartGroups.tsx @@ -6,13 +6,13 @@ import { WorktreeHostContextBadge } from '@/components/sidebar/workspace-card/ho import { useSidebarHostScopeOptions } from '@/components/sidebar/worktree-list/controls/use-sidebar-host-scope-options' import { useTranslate } from '@/i18n/use-translate' import { resolveWorktreeBranchLabel } from '@/lib/worktree-default-display-name' -import { getHostContextLabel } from '../../../shared/worktree/host-context-labels' +import { getHostContextLabel } from '../../../../../shared/worktree/host-context-labels' import { LOCAL_EXECUTION_HOST_ID, parseExecutionHostId, type ExecutionHostId -} from '../../../shared/execution-host' -import { useAppStore } from '../store' +} from '../../../../../shared/execution-host' +import { useAppStore } from '../../../store/index' import * as workspaceDisplay from './native-chat-resume-workspace-display' import { useLineageAncestors, @@ -43,8 +43,6 @@ import { type ResumeWorkspaceNode } from './native-chat-resume-on-restart-grouping' -export type { ResumeCandidate } from './native-chat-resume-on-restart-grouping' - /** Group by machine/project/workspace/chat, nesting child workspaces after parent chats. Show machine nodes for remote/multiple hosts; name unknown workspaces by their encoded folder. */ function WorkspaceNode({ diff --git a/src/renderer/src/components/NativeChatResumeTreeRow.tsx b/src/renderer/src/components/native-chat-recovery/tree/NativeChatResumeTreeRow.tsx similarity index 99% rename from src/renderer/src/components/NativeChatResumeTreeRow.tsx rename to src/renderer/src/components/native-chat-recovery/tree/NativeChatResumeTreeRow.tsx index 036e99dc88b..67b126c3bd9 100644 --- a/src/renderer/src/components/NativeChatResumeTreeRow.tsx +++ b/src/renderer/src/components/native-chat-recovery/tree/NativeChatResumeTreeRow.tsx @@ -1,7 +1,7 @@ import { useContext } from 'react' import { ChevronRight } from 'lucide-react' import { useTranslate } from '@/i18n/use-translate' -import { Checkbox } from './ui/checkbox' +import { Checkbox } from '../../ui/checkbox' import { ResumeTreeSelectingContext } from './native-chat-resume-tree-state' /** Indent per tree level, right of the shared checkbox column. */ diff --git a/src/renderer/src/components/native-chat-resume-activity-label.ts b/src/renderer/src/components/native-chat-recovery/tree/native-chat-resume-activity-label.ts similarity index 96% rename from src/renderer/src/components/native-chat-resume-activity-label.ts rename to src/renderer/src/components/native-chat-recovery/tree/native-chat-resume-activity-label.ts index b6d60a5a408..4a2d3a8582d 100644 --- a/src/renderer/src/components/native-chat-resume-activity-label.ts +++ b/src/renderer/src/components/native-chat-recovery/tree/native-chat-resume-activity-label.ts @@ -1,6 +1,6 @@ import { translate } from '@/i18n/i18n' import type { Translate } from '@/i18n/use-translate' -import type { AgentSessionRestartActivity } from '../../../shared/agent-session/lifecycle/agent-session-restart-activity' +import type { AgentSessionRestartActivity } from '../../../../../shared/agent-session/lifecycle/agent-session-restart-activity' export type ResumeActivityLabel = { /** One line naming what the chat was doing, in the sidebar's own vocabulary. */ diff --git a/src/renderer/src/components/native-chat-resume-on-restart-grouping.ts b/src/renderer/src/components/native-chat-recovery/tree/native-chat-resume-on-restart-grouping.ts similarity index 91% rename from src/renderer/src/components/native-chat-resume-on-restart-grouping.ts rename to src/renderer/src/components/native-chat-recovery/tree/native-chat-resume-on-restart-grouping.ts index c89cf443bc4..3464918edad 100644 --- a/src/renderer/src/components/native-chat-resume-on-restart-grouping.ts +++ b/src/renderer/src/components/native-chat-recovery/tree/native-chat-resume-on-restart-grouping.ts @@ -1,10 +1,10 @@ -import { parseWorkspaceKey } from '../../../shared/workspace-scope' -import type { AgentSessionWorkspaceKind } from '../../../shared/agent-session/lifecycle/agent-session-record' -import { LOCAL_EXECUTION_HOST_ID, type ExecutionHostId } from '../../../shared/execution-host' -import { projectGroupIdFromRepoId } from '../../../shared/folder-workspaces/folder-workspace-worktree' -import type { RepoIcon } from '../../../shared/repo-icon' -import type { AgentSessionRestartActivity } from '../../../shared/agent-session/lifecycle/agent-session-restart-activity' -import type { StructuredAgentId } from '../../../shared/agent-session/lifecycle/agent-session-provider-handle' +import { parseWorkspaceKey } from '../../../../../shared/workspace-scope' +import type { AgentSessionWorkspaceKind } from '../../../../../shared/agent-session/lifecycle/agent-session-record' +import { LOCAL_EXECUTION_HOST_ID, type ExecutionHostId } from '../../../../../shared/execution-host' +import { projectGroupIdFromRepoId } from '../../../../../shared/folder-workspaces/folder-workspace-worktree' +import type { RepoIcon } from '../../../../../shared/repo-icon' +import type { AgentSessionRestartActivity } from '../../../../../shared/agent-session/lifecycle/agent-session-restart-activity' +import type { StructuredAgentId } from '../../../../../shared/agent-session/lifecycle/agent-session-provider-handle' export type ResumeCandidate = { sessionId: string diff --git a/src/renderer/src/components/native-chat-resume-tree-keys.ts b/src/renderer/src/components/native-chat-recovery/tree/native-chat-resume-tree-keys.ts similarity index 100% rename from src/renderer/src/components/native-chat-resume-tree-keys.ts rename to src/renderer/src/components/native-chat-recovery/tree/native-chat-resume-tree-keys.ts diff --git a/src/renderer/src/components/native-chat-resume-tree-state.ts b/src/renderer/src/components/native-chat-recovery/tree/native-chat-resume-tree-state.ts similarity index 98% rename from src/renderer/src/components/native-chat-resume-tree-state.ts rename to src/renderer/src/components/native-chat-recovery/tree/native-chat-resume-tree-state.ts index a748c9f05c8..ac106c831d2 100644 --- a/src/renderer/src/components/native-chat-resume-tree-state.ts +++ b/src/renderer/src/components/native-chat-recovery/tree/native-chat-resume-tree-state.ts @@ -7,7 +7,7 @@ import type { import { resumeFailureSelectable, type ResumeFailureAction -} from './native-chat-resume-failure-guidance' +} from '../failures/native-chat-resume-failure-guidance' /** Start expanded per mount; closing/unmounting resets the tree rather than persisting expansion. */ export function useResumeTreeExpansion(): { diff --git a/src/renderer/src/components/native-chat-resume-workspace-display.ts b/src/renderer/src/components/native-chat-recovery/tree/native-chat-resume-workspace-display.ts similarity index 97% rename from src/renderer/src/components/native-chat-resume-workspace-display.ts rename to src/renderer/src/components/native-chat-recovery/tree/native-chat-resume-workspace-display.ts index ec3b1f776dd..961053d856e 100644 --- a/src/renderer/src/components/native-chat-resume-workspace-display.ts +++ b/src/renderer/src/components/native-chat-recovery/tree/native-chat-resume-workspace-display.ts @@ -3,7 +3,7 @@ import { resolveWorktreeDisplayName } from '@/lib/worktree-default-display-name' import { getWorktreePathBasenameFromId, splitWorktreeIdForFilesystem -} from '../../../shared/worktree/id' +} from '../../../../../shared/worktree/id' import type { ResumeRepoGroup, ResumeWorkspaceGroup diff --git a/src/renderer/src/components/native-chat-resume-workspace-lookups.ts b/src/renderer/src/components/native-chat-recovery/tree/native-chat-resume-workspace-lookups.ts similarity index 92% rename from src/renderer/src/components/native-chat-resume-workspace-lookups.ts rename to src/renderer/src/components/native-chat-recovery/tree/native-chat-resume-workspace-lookups.ts index 7e18c1f61ec..9de3a406497 100644 --- a/src/renderer/src/components/native-chat-resume-workspace-lookups.ts +++ b/src/renderer/src/components/native-chat-recovery/tree/native-chat-resume-workspace-lookups.ts @@ -2,7 +2,7 @@ import { useMemo } from 'react' import { getCyclicProjectedWorktreeLineageIds, getSidebarLineageAncestors -} from '../../../shared/sidebar-list/worktree-lineage-projection' +} from '../../../../../shared/sidebar-list/worktree-lineage-projection' import { getIndexedAllWorktrees, getIndexedWorktreeMap @@ -11,9 +11,9 @@ import { getWorktreeOnHostFromState } from '@/store/workspaces/selection/worktre import { composeWorktreeHostIdentity, getWorktreeHostIdentity -} from '../../../shared/worktree/host-qualified-identity' -import type { ExecutionHostId } from '../../../shared/execution-host' -import { useAppStore } from '../store' +} from '../../../../../shared/worktree/host-qualified-identity' +import type { ExecutionHostId } from '../../../../../shared/execution-host' +import { useAppStore } from '../../../store/index' import type { ResumeWorkspaceGroup } from './native-chat-resume-on-restart-grouping' import { selectWorktreesByRepo } from '@/store/workspaces/catalog/workspace-record-fields' diff --git a/src/renderer/src/components/native-chat-restart-offer-gate.ts b/src/renderer/src/components/native-chat-restart-offer-gate.ts deleted file mode 100644 index 3c890d7ce65..00000000000 --- a/src/renderer/src/components/native-chat-restart-offer-gate.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { useLocalStructuredChatsInUse } from '@/runtime/native-chat/local-sessions/local-structured-chats' - -/** Ask only when local structured chats are enabled or present; unused installations must not start a host for an empty offer. */ -export function useNativeChatRestartOfferEnabled(): boolean { - return useLocalStructuredChatsInUse() -} diff --git a/src/renderer/src/components/native-chat-resume-bulk-progress.test.tsx b/src/renderer/src/components/native-chat-resume-bulk-progress.test.tsx deleted file mode 100644 index a0dd4c3961f..00000000000 --- a/src/renderer/src/components/native-chat-resume-bulk-progress.test.tsx +++ /dev/null @@ -1,300 +0,0 @@ -// @vitest-environment happy-dom -import { - createResumeModalFixture, - offered, - failure, - type RestartRpc, - type ResumeStatusStream -} from './native-chat-resume-modal.test-support' -import { act } from 'react' -import { expect, it, vi, type Mock } from 'vitest' -import { NativeChatResumeOnRestartModal } from './NativeChatResumeRuntimeModal' - -import { NativeChatResumeStatusSegment } from './status-bar/NativeChatResumeStatusSegment' -import type { ResumeCandidate, ResumeFailure } from './native-chat-resume-on-restart-grouping' -import type { AgentSessionStatusSummary } from '../../../shared/agent-session/agent-session-wire' -import { requestNativeChatResumeOnRestartDialog } from './native-chat-resume-on-restart-dialog' -import { - continueNativeChatRestartOffer, - getNativeChatRestartOffer, - refreshNativeChatRestartOffer -} from './native-chat-resume-on-restart-store' - -const rpc: Mock = vi.hoisted(() => vi.fn()) -const statusStream: ResumeStatusStream = vi.hoisted(() => ({ - emit: (_event: Parameters[0]) => {}, - snapshot: new Map() -})) -vi.mock('../runtime/native-chat/requests/structured-agent-session-call', () => ({ - callStructuredAgentSession: rpc -})) - -vi.mock('../runtime/native-chat/requests/structured-agent-session-subscriptions', () => ({ - subscribeStructuredAgentSessionStatus: async ( - _target: unknown, - emit: (event: Parameters[0]) => void - ) => { - statusStream.emit = emit - emit({ type: 'snapshot', sessions: [...statusStream.snapshot.values()] }) - return { unsubscribe: () => {} } - } -})) -vi.mock('@/lib/activate-ai-vault-structured-session', () => ({ - activateAiVaultStructuredSession: vi.fn(async () => true) -})) -vi.mock('sonner', async () => - (await import('./native-chat-resume-sonner-mock.test-support')).resumeSonnerMock() -) - -const { mount, button, offerIds, toasts, fakeHost, runStatus } = createResumeModalFixture( - rpc, - statusStream -) - -function emitPhase( - sessionId: string, - phase?: NonNullable['phase'] -): void { - statusStream.emit({ - type: 'status', - session: { - sessionId, - workspaceId: 'workspace', - agent: 'codex', - status: 'idle', - latestPrompt: '', - updatedAt: 1, - ...(phase ? { restartResume: { phase } } : {}) - } - }) -} - -it('uses the host unconfirmed result after a lost bulk reply without reporting a failure', async () => { - const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) - let reads = 0 - rpc.mockImplementation(async (_target, method) => { - if (method === 'agentSession.restartContinue') { - throw new Error('reply lost') - } - return reads++ === 0 - ? { sessions: offered, failed: [] } - : { - sessions: [], - failed: [ - { ...failure('a'), outcome: 'unconfirmed' }, - { ...failure('b'), outcome: 'unconfirmed' } - ] - } - }) - try { - await refreshNativeChatRestartOffer() - await continueNativeChatRestartOffer(['a', 'b']) - expect(toasts()).toEqual([['Couldn’t confirm 2 chats were resumed']]) - expect(getNativeChatRestartOffer().failed.map((row) => row.outcome)).toEqual([ - 'unconfirmed', - 'unconfirmed' - ]) - } finally { - warn.mockRestore() - } -}) - -it('keeps the run in flight after every feed verdict until the fallback list is published', async () => { - const answer = Promise.withResolvers<{ - continued: { sessionId: string; outcome: 'continued' }[] - }>() - const listing = Promise.withResolvers<{ sessions: ResumeCandidate[]; failed: ResumeFailure[] }>() - let reads = 0 - rpc.mockImplementation(async (_target, method) => - method === 'agentSession.restartContinue' - ? answer.promise - : reads++ === 0 - ? { sessions: offered, failed: [] } - : listing.promise - ) - await mount( - <> - - - - ) - await act(async () => button('Resume 2 chats').click()) - await act(async () => button('Resuming chats 0/2').click()) - await act(async () => { - for (const { sessionId } of offered) { - statusStream.emit({ - type: 'status', - session: { - sessionId, - workspaceId: 'workspace', - agent: 'codex', - status: 'idle', - latestPrompt: '', - updatedAt: 1, - restartResume: { phase: 'continued' } - } - }) - } - answer.resolve({ - continued: offered.map(({ sessionId }) => ({ sessionId, outcome: 'continued' })) - }) - }) - expect(button('Resuming chats 2/2')).toBeTruthy() - await act(async () => offered.forEach(({ sessionId }) => emitPhase(sessionId))) - expect(button('Resuming chats 2/2')).toBeTruthy() - expect(runStatus('Prompt a')).toBe('Prompt a: Resumed') - expect(button('Resuming…').disabled).toBe(true) - expect(document.body.textContent).not.toContain('chats to resume') - await act(async () => listing.resolve({ sessions: [], failed: [] })) - expect(offerIds()).toEqual([]) - expect(button('Done').disabled).toBe(false) - expect(document.body.textContent).not.toContain('Resuming chats') -}) - -it('retains success and refusal frames through cleanup before a delayed bulk reply', async () => { - const reply = Promise.withResolvers() - rpc.mockImplementation(async (_target, method) => - method === 'agentSession.restartResumable' ? { sessions: offered, failed: [] } : reply.promise - ) - await mount( - <> - - - - ) - await act(async () => button('Resume 2 chats').click()) - // Verdicts and cleanup can arrive together before React gets a render. - await act(async () => { - emitPhase('a', 'continued') - emitPhase('b', 'refused') - emitPhase('a') - emitPhase('b') - }) - expect(button('Resuming chats 2/2')).toBeTruthy() - await act(async () => button('Resuming chats 2/2').click()) - expect(runStatus('Prompt a')).toBe('Prompt a: Resumed') - expect(runStatus('Prompt b')).toBe('Prompt b: Couldn’t resume') - expect(document.querySelector('[role="dialog"]')?.textContent).toContain('Need you1') - await act(async () => - reply.resolve({ - sessions: [], - failed: [failure('b')], - continued: [ - { sessionId: 'a', outcome: 'continued' }, - { sessionId: 'b', outcome: 'refused' } - ] - }) - ) - expect(document.querySelector('[role="dialog"]')?.textContent).toContain('Resumed 1 of 2 chats') -}) - -it('removes a skipped selection from pending rows and all progress counts', async () => { - const host = fakeHost({}, (sessionId) => (sessionId === 'a' ? 'skipped' : 'continued')) - host.hold('b') - await mount( - <> - - - - ) - host.state.sessions = host.state.sessions.filter((row) => row.sessionId !== 'a') - await act(async () => button('Resume 2 chats').click()) - await act(async () => button('Resuming chats 0/1').click()) - const dialog = () => document.querySelector('[role="dialog"]')?.textContent - expect(dialog()).not.toContain('Prompt a') - expect(dialog()).toContain('All1') - expect(dialog()).toContain('0 of 1 done') - expect(dialog()).toContain('In progress1') - await host.release('b') - expect(dialog()).toContain('Resumed 1 of 1 chat') - expect(dialog()).toContain('1 of 1 done') - expect(dialog()).toContain('All1') - expect(dialog()).toContain('In progress0') - expect(runStatus('Prompt b')).toBe('Prompt b: Resumed') - expect(toasts()).toEqual([['Resumed 1 chat']]) -}) - -it('uses reply skipped ids even when the skip frame was missed', async () => { - rpc.mockImplementation(async (_target, method) => - method === 'agentSession.restartResumable' - ? { sessions: offered, failed: [] } - : { - sessions: [], - failed: [], - skipped: ['b'], - continued: [{ sessionId: 'a', outcome: 'continued' }] - } - ) - await mount() - await act(async () => continueNativeChatRestartOffer(['a', 'b'])) - expect(document.querySelector('[role="dialog"]')?.textContent).toContain('Resumed 1 of 1 chat') - expect(document.querySelector('[role="dialog"]')?.textContent).toContain('All1') - expect(runStatus('Prompt b')).toBeNull() -}) - -it.each(['unknown', 'pending'] as const)( - 'reconciles %s with the reply failure list for both dialog and toast', - async (outcome) => { - rpc.mockImplementation(async (_target, method) => - method === 'agentSession.restartResumable' - ? { sessions: [offered[0]], failed: [] } - : { sessions: [], failed: [], continued: [{ sessionId: 'a', outcome }] } - ) - await mount() - await act(async () => continueNativeChatRestartOffer(['a'])) - expect(document.querySelector('[role="dialog"]')?.textContent).toContain('Resumed 1 of 1 chat') - expect(runStatus('Prompt a')).toBe('Prompt a: Resumed') - expect(toasts()).toEqual([['Resumed 1 chat']]) - } -) - -it('dismissing a host failure preserves the uncertain action history', async () => { - fakeHost({ sessions: [offered[0]!] }, () => 'unknown') - await mount() - await act(async () => continueNativeChatRestartOffer(['a'])) - expect(document.querySelector('[role="dialog"]')?.textContent).toContain('Resumed 0 of 1 chat') - const dismiss = document.querySelector('button[aria-label^="Dismiss"]') - expect(dismiss).not.toBeNull() - await act(async () => dismiss?.click()) - expect(document.querySelector('[role="dialog"]')?.textContent).toContain('Resumed 0 of 1 chat') - expect(getNativeChatRestartOffer().failed).toEqual([]) - expect(document.querySelector('[role="dialog"]')?.textContent).toContain('Need you1') - expect(runStatus('Prompt a')).toBe('Prompt a: Couldn’t confirm the chat was resumed') - expect(toasts()).toEqual([['Couldn’t confirm 1 chat was resumed']]) -}) - -it('keeps an unknown reply unconfirmed when it carries no confirmed failure list', async () => { - rpc.mockImplementation(async (_target, method) => - method === 'agentSession.restartResumable' - ? { sessions: [offered[0]], failed: [] } - : { sessions: [], continued: [{ sessionId: 'a', outcome: 'unknown' }] } - ) - await mount() - await act(async () => continueNativeChatRestartOffer(['a'])) - expect(document.querySelector('[role="dialog"]')?.textContent).toContain('Resumed 0 of 1 chat') - expect(runStatus('Prompt a')).toBe('Prompt a: Couldn’t confirm the chat was resumed') - expect(toasts()).toEqual([['Couldn’t confirm 1 chat was resumed']]) -}) - -it('a retry hides its old failure, then a dismissed final failure leaves Need you', async () => { - const host = fakeHost( - { sessions: [], failed: [failure('b', 'agent_session_conflict')] }, - () => 'refused', - 'agent_session_conflict' - ) - host.hold('b') - await mount() - await act(async () => requestNativeChatResumeOnRestartDialog()) - await act(async () => button('Retry').click()) - expect(runStatus('Prompt b')).toMatch(/Waiting to start/) - expect(document.querySelector('[role="dialog"]')?.textContent).not.toContain('Another Orca') - expect(document.querySelector('[aria-label*="Couldn’t resume"]')).toBeNull() - await host.release('b') - expect(document.querySelector('[role="dialog"]')?.textContent).toContain('Need you1') - const dismiss = document.querySelector('button[aria-label^="Dismiss"]') - expect(dismiss).not.toBeNull() - await act(async () => dismiss?.click()) - expect(getNativeChatRestartOffer().failed).toEqual([]) - expect(document.querySelector('[role="dialog"]')?.textContent).toContain('Need you0') - expect(runStatus('Prompt b')).toBeNull() -}) diff --git a/src/renderer/src/components/native-chat-resume-failure-guidance.test.ts b/src/renderer/src/components/native-chat-resume-failure-guidance.test.ts deleted file mode 100644 index ebb9b42ce82..00000000000 --- a/src/renderer/src/components/native-chat-resume-failure-guidance.test.ts +++ /dev/null @@ -1,23 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { resumeFailureGuidance } from './native-chat-resume-failure-guidance' - -describe('resumeFailureGuidance', () => { - // Provider refusals already live in the chat; respect the host’s non-retryable verdict. - it.each(['codex said no', 'agent_session_conflict'])( - 'offers no retry for %s once the host says a retry would not run', - (reason) => { - expect(resumeFailureGuidance({ outcome: 'refused', reason, retryable: false })).toMatchObject( - { primary: 'open', secondary: 'dismiss' } - ) - expect(resumeFailureGuidance({ outcome: 'refused', reason, retryable: true })).toMatchObject( - resumeFailureGuidance({ outcome: 'refused', reason }) - ) - } - ) - - it('never offers a retry for a delivery nobody could confirm', () => { - expect( - resumeFailureGuidance({ outcome: 'unconfirmed', reason: 'agent_session_conflict' }) - ).toMatchObject({ primary: 'open', secondary: null }) - }) -}) diff --git a/src/renderer/src/components/native-chat-resume-finished-run.test.tsx b/src/renderer/src/components/native-chat-resume-finished-run.test.tsx deleted file mode 100644 index 7edb9efda76..00000000000 --- a/src/renderer/src/components/native-chat-resume-finished-run.test.tsx +++ /dev/null @@ -1,255 +0,0 @@ -// @vitest-environment happy-dom -import { act } from 'react' -import { expect, it, vi, type Mock } from 'vitest' -import { NativeChatResumeOnRestartModal } from './NativeChatResumeRuntimeModal' -import { NativeChatResumeStatusSegment } from './status-bar/NativeChatResumeStatusSegment' -import { - createResumeModalFixture, - failure, - offered, - type RestartRpc, - type ResumeStatusStream -} from './native-chat-resume-modal.test-support' -import { lastToastShow } from './native-chat-resume-toast.test-support' -import { - getNativeChatRestartRun, - refreshNativeChatRestartOffer, - releaseFinishedNativeChatRestartRun -} from './native-chat-resume-on-restart-store' -import { - consumeNativeChatResumeOnRestartDialogRequest, - requestNativeChatResumeOnRestartDialog -} from './native-chat-resume-on-restart-dialog' - -import { chatBox, namedBox } from './native-chat-resume-on-restart-modal.test-support' - -const rpc: Mock = vi.hoisted(() => vi.fn()) -const statusStream: ResumeStatusStream = vi.hoisted(() => ({ - emit: (_event: Parameters[0]) => {}, - snapshot: new Map() -})) -vi.mock('../runtime/native-chat/requests/structured-agent-session-call', () => ({ - callStructuredAgentSession: rpc -})) - -vi.mock('../runtime/native-chat/requests/structured-agent-session-subscriptions', () => ({ - subscribeStructuredAgentSessionStatus: async ( - _target: unknown, - emit: ResumeStatusStream['emit'] - ) => { - statusStream.emit = emit - emit({ type: 'snapshot', sessions: [...statusStream.snapshot.values()] }) - return { unsubscribe: () => {} } - } -})) -vi.mock('sonner', async () => - (await import('./native-chat-resume-sonner-mock.test-support')).resumeSonnerMock() -) - -const { mount, button, fakeHost, runStatus, toasts } = createResumeModalFixture(rpc, statusStream) -const dialog = () => document.querySelector('[role="dialog"]')?.textContent - -async function mountSurfaces(): Promise { - await mount( - <> - - - - ) -} - -it.each(['status entry', 'toast Show'] as const)( - 'opens every finished result from %s after Resume closed the dialog', - async (source) => { - fakeHost({}, (sessionId) => (sessionId === 'a' ? 'continued' : 'refused'), 'unknown') - await mountSurfaces() - await act(async () => button('Resume 2 chats').click()) - expect(dialog()).toBeUndefined() - await act(async () => - source === 'status entry' ? button('1 chat failed to resume').click() : lastToastShow()?.() - ) - expect(dialog()).toContain('Resumed 1 of 2 chats') - expect(dialog()).toContain('All2') - expect(dialog()).toContain('Need you1') - expect(runStatus('Prompt a')).toBe('Prompt a: Resumed') - expect(runStatus('Prompt b')).toBe('Prompt b: Couldn’t resume') - expect(button('Retry')).toBeTruthy() - expect(button('Open chat')).toBeTruthy() - expect(button('Dismiss "Prompt b" in workspace')).toBeTruthy() - expect(toasts()).toEqual([['1 chat couldn’t be resumed', 'Resumed 1 chat']]) - } -) - -it.each(['status entry', 'toast Show'] as const)( - 'returns to the host failure offer from %s after the finished view is closed', - async (source) => { - fakeHost({}, (sessionId) => (sessionId === 'a' ? 'continued' : 'refused')) - await mountSurfaces() - await act(async () => button('Resume 2 chats').click()) - await act(async () => button('1 chat failed to resume').click()) - expect(dialog()).toContain('Resumed 1 of 2 chats') - await act(async () => button('Close').click()) - await act(async () => - source === 'status entry' ? button('1 chat failed to resume').click() : lastToastShow()?.() - ) - expect(dialog()).toContain('Resume interrupted chats?') - expect(dialog()).toContain('Prompt b') - expect(dialog()).not.toContain('Prompt a') - } -) - -it('keeps the unseen summary when a view was opened and closed only during the run', async () => { - const host = fakeHost({}, (sessionId) => (sessionId === 'a' ? 'continued' : 'unknown')) - host.hold('a', 'b') - await mountSurfaces() - await act(async () => button('Resume 2 chats').click()) - await act(async () => button('Resuming chats 0/2').click()) - expect(dialog()).toContain('Resuming 2 chats') - await act(async () => button('Close').click()) - await host.release('a', 'b') - await act(async () => button('1 chat to check').click()) - expect(dialog()).toContain('Resumed 1 of 2 chats') - expect(runStatus('Prompt a')).toBe('Prompt a: Resumed') - expect(runStatus('Prompt b')).toBe('Prompt b: Couldn’t confirm the chat was resumed') -}) - -it.each(['status entry', 'toast Show'] as const)( - 'keeps a resumed entry until the all-success summary is seen from %s', - async (source) => { - fakeHost() - await mountSurfaces() - await act(async () => button('Resume 2 chats').click()) - expect(dialog()).toBeUndefined() - expect(button('2 chats resumed. Click to see them.').textContent).toBe('2 chats resumed') - await act(async () => - source === 'status entry' ? button('2 chats resumed').click() : lastToastShow()?.() - ) - expect(dialog()).toContain('Resumed 2 of 2 chats') - expect(runStatus('Prompt a')).toBe('Prompt a: Resumed') - expect(runStatus('Prompt b')).toBe('Prompt b: Resumed') - await act(async () => button('Done').click()) - expect(document.body.textContent).not.toContain('chat') - await act(async () => lastToastShow()?.()) - expect(dialog()).toBeUndefined() - } -) - -it('adds no resumed entry for a run watched to the end in the dialog', async () => { - const host = fakeHost() - host.hold('a', 'b') - await mountSurfaces() - await act(async () => button('Resume 2 chats').click()) - await act(async () => button('Resuming chats 0/2').click()) - await host.release('a', 'b') - expect(dialog()).toContain('Resumed 2 of 2 chats') - await act(async () => button('Done').click()) - expect(document.body.textContent).not.toContain('chat') -}) - -it('keeps a new successful run visible beside an older host failure', async () => { - fakeHost({ sessions: [offered[0]!], failed: [failure('b')] }) - await mountSurfaces() - await act(async () => button('Resume 1 chat').click()) - expect(button('1 chat failed to resume')).toBeTruthy() - expect(button('1 chat resumed')).toBeTruthy() - await act(async () => button('1 chat resumed').click()) - expect(dialog()).toContain('Resumed 1 of 1 chat') - expect(runStatus('Prompt a')).toBe('Prompt a: Resumed') -}) - -it('does not claim a mixed run succeeded when a host reread fails', async () => { - fakeHost({}, (sessionId) => (sessionId === 'a' ? 'continued' : 'refused')) - await mountSurfaces() - await act(async () => button('Resume 2 chats').click()) - rpc.mockImplementationOnce(async () => { - throw new Error('host unavailable') - }) - await act(async () => refreshNativeChatRestartOffer()) - expect(getNativeChatRestartRun()?.entries).toHaveLength(2) - expect(document.body.textContent).not.toContain('chat resumed') - await act(async () => lastToastShow()?.()) - expect(dialog()).toContain('Resumed 1 of 2 chats') -}) - -it('shows finished rows after resetting an in-flight filter and keeps later filter actions', async () => { - const host = fakeHost() - host.hold('a', 'b') - await mountSurfaces() - await act(async () => button('Resume 2 chats').click()) - await act(async () => button('Resuming chats 0/2').click()) - await act(async () => button('In progress2').click()) - await host.release('a', 'b') - expect(dialog()).toContain('Resumed 2 of 2 chats') - expect(runStatus('Prompt a')).toBe('Prompt a: Resumed') - expect(runStatus('Prompt b')).toBe('Prompt b: Resumed') - await act(async () => button('In progress0').click()) - expect(runStatus('Prompt a')).toBeNull() - await act(async () => button('All2').click()) - expect(runStatus('Prompt a')).toBe('Prompt a: Resumed') - await act(async () => button('Done').click()) - expect(getNativeChatRestartRun()).toBeNull() -}) - -it('expands a group collapsed during a run before retiring the finished result', async () => { - const host = fakeHost() - host.hold('a', 'b') - await mountSurfaces() - await act(async () => button('Resume 2 chats').click()) - await act(async () => button('Resuming chats 0/2').click()) - await act(async () => button('Collapse workspace').click()) - expect(runStatus('Prompt a')).toBeNull() - expect(runStatus('Prompt b')).toBeNull() - await host.release('a', 'b') - expect(dialog()).toContain('Resumed 2 of 2 chats') - expect(runStatus('Prompt a')).toBe('Prompt a: Resumed') - expect(runStatus('Prompt b')).toBe('Prompt b: Resumed') - await act(async () => button('Done').click()) - expect(getNativeChatRestartRun()).toBeNull() - expect(document.body.textContent).not.toContain('chat resumed') -}) - -it('replaces the finished summary when Retry starts a new run', async () => { - const host = fakeHost({}, (sessionId) => (sessionId === 'a' ? 'continued' : 'refused'), 'unknown') - await mountSurfaces() - await act(async () => button('Resume 2 chats').click()) - await act(async () => button('1 chat failed to resume').click()) - host.hold('b') - await act(async () => button('Retry').click()) - expect(dialog()).toContain('Resuming 1 chat') - expect(dialog()).not.toContain('Prompt a') - await host.release('b') - expect(dialog()).toContain('Resumed 0 of 1 chat') -}) - -it('selects only current offers from a workspace that also contains finished run history', async () => { - const host = fakeHost() - await mountSurfaces() - await act(async () => chatBox('b').click()) - await act(async () => button('Resume 1 chat').click()) - await act(async () => lastToastShow()?.()) - const workspace = namedBox('Select all chats in workspace') - expect(workspace.closest('label')?.textContent).toContain('1 of 1') - expect(runStatus('Prompt a')).toBe('Prompt a: Resumed') - await act(async () => workspace.click()) - expect(chatBox('b').getAttribute('aria-checked')).toBe('false') - await act(async () => workspace.click()) - expect(button('Resume 1 chat').disabled).toBe(false) - host.hold('b') - await act(async () => button('Resume 1 chat').click()) - expect(rpc.mock.calls.at(-1)?.[2]).toEqual({ sessionIds: ['b'] }) - await host.release('b') -}) - -it('does not consume a finished run if its requested view never rendered', async () => { - fakeHost() - await mountSurfaces() - await act(async () => button('Resume 2 chats').click()) - await act(async () => { - requestNativeChatResumeOnRestartDialog() - consumeNativeChatResumeOnRestartDialogRequest() - releaseFinishedNativeChatRestartRun() - }) - expect(dialog()).toBeUndefined() - await act(async () => lastToastShow()?.()) - expect(dialog()).toContain('Resumed 2 of 2 chats') -}) diff --git a/src/renderer/src/components/native-chat-resume-on-restart-grouping.test.ts b/src/renderer/src/components/native-chat-resume-on-restart-grouping.test.ts deleted file mode 100644 index 4743e6b9d85..00000000000 --- a/src/renderer/src/components/native-chat-resume-on-restart-grouping.test.ts +++ /dev/null @@ -1,99 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { - groupResumeCandidatesByHost, - nestResumeWorkspaces, - resumeWorkspaceCandidates, - type ResumeCandidate -} from './native-chat-resume-on-restart-grouping' - -const NOW = 1_700_000_000_000 - -function candidate(overrides: Partial = {}): ResumeCandidate { - return { - sessionId: 'session-1', - workspaceId: 'repo-1::/w/one', - agent: 'codex', - trigger: 'quit', - latestPrompt: 'fix the auth bug', - recordedAt: NOW, - executionHostId: 'local', - workspaceKind: 'git-worktree', - ...overrides - } -} - -describe('nesting child workspaces', () => { - const group = (workspaceId: string) => ({ workspaceId, candidates: [] }) - const nestedWorkspaceIds = (nodes: ReturnType): unknown => - nodes.map((node) => [node.group.workspaceId, nestedWorkspaceIds(node.children)]) - - it('puts a child under its nearest listed ancestor, skipping one with nothing to resume', () => { - const ancestors: Record = { grandchild: ['child', 'parent'], parent: [] } - const nested = nestResumeWorkspaces( - [group('grandchild'), group('other'), group('parent')], - (id) => ancestors[id] ?? [] - ) - - expect(nestedWorkspaceIds(nested)).toEqual([ - ['other', []], - ['parent', [['grandchild', []]]] - ]) - }) - - it('places every workspace when ancestors loop', () => { - const ancestors: Record = { a: ['b'], b: ['a'], c: ['a'] } - const nested = nestResumeWorkspaces( - [group('a'), group('b'), group('c'), group('d')], - (id) => ancestors[id] ?? [] - ) - - expect(nestedWorkspaceIds(nested)).toEqual([ - [ - 'a', - [ - ['b', []], - ['c', []] - ] - ], - ['d', []] - ]) - }) -}) - -describe('group checkboxes', () => { - it('covers a workspace and every workspace nested under it', () => { - const chats = (workspaceId: string, ...sessionIds: string[]) => ({ - workspaceId, - candidates: sessionIds.map((sessionId) => candidate({ sessionId, workspaceId })) - }) - const [root] = nestResumeWorkspaces( - [chats('parent', 'p1'), chats('child', 'c1', 'c2'), chats('grandchild', 'g1')], - (id) => ({ child: ['parent'], grandchild: ['child', 'parent'] })[id] ?? [] - ) - - expect(resumeWorkspaceCandidates(root!).map((entry) => entry.sessionId)).toEqual([ - 'p1', - 'c1', - 'c2', - 'g1' - ]) - }) -}) - -describe('grouping by machine', () => { - it('groups by host in first-seen order, a missing host id counting as this machine', () => { - const groups = groupResumeCandidatesByHost([ - candidate({ sessionId: 'a', executionHostId: 'ssh:box' }), - candidate({ sessionId: 'b', executionHostId: undefined }), - candidate({ sessionId: 'c', executionHostId: 'ssh:box' }), - candidate({ sessionId: 'd', executionHostId: 'local' }) - ]) - - expect( - groups.map((group) => [group.hostId, group.candidates.map((entry) => entry.sessionId)]) - ).toEqual([ - ['ssh:box', ['a', 'c']], - ['local', ['b', 'd']] - ]) - }) -}) diff --git a/src/renderer/src/components/native-chat-resume-result-view.test.tsx b/src/renderer/src/components/native-chat-resume-result-view.test.tsx deleted file mode 100644 index b2d2773611b..00000000000 --- a/src/renderer/src/components/native-chat-resume-result-view.test.tsx +++ /dev/null @@ -1,127 +0,0 @@ -// @vitest-environment happy-dom -import { act } from 'react' -import { expect, it, vi, type Mock } from 'vitest' -import { NativeChatResumeOnRestartModal } from './NativeChatResumeRuntimeModal' -import { NativeChatResumeStatusSegment } from './status-bar/NativeChatResumeStatusSegment' -import { - createResumeModalFixture, - type RestartRpc, - type ResumeStatusStream -} from './native-chat-resume-modal.test-support' - -import { lastToastShow } from './native-chat-resume-toast.test-support' -import { chatBox, dontAskAgain } from './native-chat-resume-on-restart-modal.test-support' -import { useAppStore } from '../store' - -const rpc: Mock = vi.hoisted(() => vi.fn()) -const statusStream: ResumeStatusStream = vi.hoisted(() => ({ - emit: (_event: Parameters[0]) => {}, - snapshot: new Map() -})) -vi.mock('../runtime/native-chat/requests/structured-agent-session-call', () => ({ - callStructuredAgentSession: rpc -})) - -vi.mock('../runtime/native-chat/requests/structured-agent-session-subscriptions', () => ({ - subscribeStructuredAgentSessionStatus: async ( - _target: unknown, - emit: ResumeStatusStream['emit'] - ) => { - statusStream.emit = emit - emit({ type: 'snapshot', sessions: [...statusStream.snapshot.values()] }) - return { unsubscribe: () => {} } - } -})) -vi.mock('sonner', async () => - (await import('./native-chat-resume-sonner-mock.test-support')).resumeSonnerMock() -) - -const { mount, button, fakeHost } = createResumeModalFixture(rpc, statusStream) -const dialog = () => document.querySelector('[role="dialog"]') -const tree = () => document.querySelector('[role="tree"]') - -async function mountSurfaces(): Promise { - await mount( - <> - - - - ) -} - -it('does not restore a hidden picker preference when closing a run', async () => { - const host = fakeHost() - host.hold('a', 'b') - await mountSurfaces() - await act(async () => dontAskAgain().click()) - await act(async () => button('Resume 2 chats').click()) - expect(useAppStore.getState().settings?.nativeChatResumeWorkOnRestart).toBe(true) - - await act(async () => button('Resuming chats 0/2').click()) - expect(dialog()?.textContent).not.toContain("Don't ask again") - await act(async () => - useAppStore.getState().updateSettings({ nativeChatResumeWorkOnRestart: false }) - ) - await act(async () => button('Close').click()) - const afterInFlightClose = useAppStore.getState().settings?.nativeChatResumeWorkOnRestart - - await host.release('a', 'b') - await act(async () => lastToastShow()?.()) - expect(dialog()?.textContent).toContain('Resumed 2 of 2 chats') - expect(dontAskAgain().getAttribute('data-state')).toBe('unchecked') - await act(async () => - useAppStore.getState().updateSettings({ nativeChatResumeWorkOnRestart: false }) - ) - await act(async () => button('Done').click()) - expect([ - afterInFlightClose, - useAppStore.getState().settings?.nativeChatResumeWorkOnRestart - ]).toEqual([false, false]) -}) - -it('starts a remaining-offer picker without the preference consumed by the previous resume', async () => { - fakeHost() - await mountSurfaces() - await act(async () => chatBox('b').click()) - await act(async () => dontAskAgain().click()) - await act(async () => button('Resume 1 chat').click()) - expect(useAppStore.getState().settings?.nativeChatResumeWorkOnRestart).toBe(true) - - await act(async () => button('1 chat to resume').click()) - expect(dialog()?.textContent).toContain('Resumed 1 of 1 chat') - await act(async () => button('Close').click()) - await act(async () => - useAppStore.getState().updateSettings({ nativeChatResumeWorkOnRestart: false }) - ) - - await act(async () => button('1 chat to resume').click()) - const pickerCheckbox = dontAskAgain().getAttribute('data-state') - await act(async () => button('Close').click()) - expect([pickerCheckbox, useAppStore.getState().settings?.nativeChatResumeWorkOnRestart]).toEqual([ - 'unchecked', - false - ]) -}) - -it('reopens a collapsed result group with tree keys', async () => { - fakeHost() - await mountSurfaces() - expect(button('Collapse workspace').tabIndex).toBe(-1) - await act(async () => button('Resume 2 chats').click()) - await act(async () => lastToastShow()?.()) - const disclosure = button('Collapse workspace') - const press = async (key: string) => - act(async () => { - document.activeElement?.dispatchEvent(new KeyboardEvent('keydown', { key, bubbles: true })) - }) - expect(disclosure.tabIndex).toBe(0) - tree()?.focus() - await press('ArrowDown') - expect(document.activeElement).toBe(disclosure) - await press('ArrowLeft') - expect(disclosure.getAttribute('aria-expanded')).toBe('false') - expect(document.activeElement).toBe(disclosure) - await press('ArrowRight') - expect(disclosure.getAttribute('aria-expanded')).toBe('true') - expect(document.activeElement).toBe(disclosure) -}) diff --git a/src/renderer/src/components/native-chat-resume-run.test.ts b/src/renderer/src/components/native-chat-resume-run.test.ts deleted file mode 100644 index b30612f11c1..00000000000 --- a/src/renderer/src/components/native-chat-resume-run.test.ts +++ /dev/null @@ -1,179 +0,0 @@ -import { describe, expect, it } from 'vitest' -import type { ResumeCandidate } from './native-chat-resume-on-restart-grouping' -import { - beginResumeRun, - observeResumeRun, - resumeRunInFlight, - resumeRunPendingIds, - type ResumeRunHostStatus -} from './native-chat-resume-run' -import { resumeRunView } from './native-chat-resume-run-view' - -const row = (sessionId: string): ResumeCandidate => ({ - sessionId, - workspaceId: 'folder', - agent: 'codex', - trigger: 'quit', - latestPrompt: `Prompt ${sessionId}`, - recordedAt: 1 -}) -const failure = { ...row('a'), failedAt: 2, outcome: 'unconfirmed' as const, reason: 'pending' } -const run = beginResumeRun([row('a'), row('b')], 10, 'user') - -describe('the dialog over a bulk action', () => { - it('never regresses a seen phase or verdict when live progress clears', () => { - let observed = run - for (const phase of ['queued', 'starting', 'continued'] as const) { - observed = observeResumeRun(observed, () => ({ restartResume: { phase } })) - const before = resumeRunView(observed, [], () => undefined, 'all') - expect(observeResumeRun(observed, () => undefined)).toBe(observed) - expect(observeResumeRun(observed, () => ({ restartResume: { phase: 'queued' } }))).toBe( - observed - ) - expect(resumeRunView(observed, [], () => undefined, 'all')).toEqual(before) - } - expect(resumeRunView(observed, [], () => undefined, 'all').counts.done).toBe(2) - expect(observeResumeRun(observed, () => ({ restartResume: { phase: 'refused' } }))).toBe( - observed - ) - expect(observeResumeRun({ ...observed, inFlight: false }, () => undefined).inFlight).toBe(false) - }) - - it('remembers readiness and excludes skipped chats from rows and the denominator', () => { - const observed = observeResumeRun(run, (id) => ({ - restartResume: { phase: id === 'a' ? 'skipped' : 'starting' }, - hostExecutionPhase: 'ready' - })) - const view = resumeRunView(observed, [row('a')], () => undefined, 'all') - expect(view.rows).toEqual([row('b')]) - expect(view.counts).toMatchObject({ all: 1, total: 1, done: 0, inProgress: 1 }) - expect(view.statusBySession.get('b')).toEqual({ - kind: 'in-flight', - phase: 'ready', - startedAt: 10 - }) - const admitted = observeResumeRun(observed, () => ({ restartResume: { phase: 'starting' } })) - expect(admitted.entries[1]).toBe(observed.entries[1]) - expect(resumeRunView(admitted, [], () => undefined, 'all').counts.total).toBe(2) - }) - - it("real action progress supersedes another request's provisional skip", () => { - let observed = observeResumeRun(run, () => ({ restartResume: { phase: 'skipped' } })) - for (const phase of ['queued', 'starting', 'continued'] as const) { - observed = observeResumeRun(observed, () => ({ restartResume: { phase } })) - expect(observed.entries[0]?.observedStatus?.restartResume?.phase).toBe(phase) - expect(observeResumeRun(observed, () => ({ restartResume: { phase: 'skipped' } }))).toBe( - observed - ) - } - expect(resumeRunView(observed, [], () => undefined, 'all').counts).toMatchObject({ - total: 2, - resumed: 2 - }) - }) - it('settles a chat from its host verdict while the request remains in flight', () => { - const statusFor = (id: string): ResumeRunHostStatus => ({ - restartResume: { phase: id === 'a' ? 'continued' : 'queued' } - }) - const view = resumeRunView(run, [], () => undefined, 'all', statusFor) - expect(view.rows.map((entry) => entry.sessionId)).toEqual(['b', 'a']) - expect(view.statusBySession.get('a')).toEqual({ kind: 'resumed' }) - expect(view.counts).toMatchObject({ total: 2, done: 1, resumed: 1, inProgress: 1 }) - expect(resumeRunInFlight(run)).toBe(true) - expect(resumeRunPendingIds(run)).toEqual(['a', 'b']) - }) - - it('degrades an older host to waiting until the reply, even if its ordinary status is ready', () => { - const view = resumeRunView( - run, - [], - () => undefined, - 'all', - () => ({ hostExecutionPhase: 'ready' }) - ) - expect(view.counts.inProgress).toBe(2) - expect(view.statusBySession.get('a')).toEqual({ kind: 'in-flight', phase: null, startedAt: 10 }) - }) - - it('distinguishes waiting for a start slot from holding one and waiting for delivery', () => { - for (const hostExecutionPhase of ['starting', 'ready'] as const) { - const view = resumeRunView( - run, - [], - () => undefined, - 'all', - () => ({ restartResume: { phase: 'starting' }, hostExecutionPhase }) - ) - expect(view.statusBySession.get('a')).toEqual({ - kind: 'in-flight', - phase: hostExecutionPhase, - startedAt: 10 - }) - } - }) - - it('a retry shows its current progress over the previous failure', () => { - const view = resumeRunView(run, [failure], () => failure, 'all') - expect(view.counts.attention).toBe(0) - expect(view.statusBySession.get('a')?.kind).toBe('in-flight') - }) - - it('keeps an unknown action in Need you after its host failure is withdrawn', () => { - const finished = { - ...run, - inFlight: false, - continued: [{ sessionId: 'a', outcome: 'unknown' as const }] - } - const failed = resumeRunView( - finished, - [failure], - (id) => (id === 'a' ? failure : undefined), - 'attention' - ) - expect(failed.rows).toEqual([failure]) - const withdrawn = resumeRunView(finished, [], () => undefined, 'attention') - expect(withdrawn.rows).toEqual([row('a')]) - expect(withdrawn.counts.attention).toBe(1) - expect(withdrawn.statusBySession.get('a')).toEqual({ kind: 'unconfirmed' }) - const refused = resumeRunView( - { ...finished, continued: [{ sessionId: 'a', outcome: 'refused' }] }, - [], - () => undefined, - 'attention' - ) - expect(refused.rows).toEqual([]) - expect(refused.counts.attention).toBe(0) - }) - - it('retains successful history but always shows current host failures', () => { - const finished = { - ...run, - inFlight: false, - continued: [{ sessionId: 'a', outcome: 'continued' as const }] - } - expect(resumeRunView(finished, [], () => undefined, 'resumed').rows).toEqual([row('a')]) - const failed = resumeRunView( - finished, - [failure], - (id) => (id === 'a' ? failure : undefined), - 'attention' - ) - expect(failed.rows).toEqual([failure]) - expect(failed.statusBySession.has('a')).toBe(false) - expect(resumeRunPendingIds(finished)).toBe(resumeRunPendingIds(null)) - }) - - it('shows final per-chat failures from the feed before the batch returns', () => { - for (const phase of ['refused', 'unconfirmed'] as const) { - const view = resumeRunView( - run, - [], - () => undefined, - 'attention', - () => ({ restartResume: { phase } }) - ) - expect(view.counts.attention).toBe(2) - expect(view.statusBySession.get('a')).toEqual({ kind: phase }) - } - }) -}) diff --git a/src/renderer/src/components/native-chat-resume-skipped-progress.test.tsx b/src/renderer/src/components/native-chat-resume-skipped-progress.test.tsx deleted file mode 100644 index 0207dd7c5f8..00000000000 --- a/src/renderer/src/components/native-chat-resume-skipped-progress.test.tsx +++ /dev/null @@ -1,65 +0,0 @@ -// @vitest-environment happy-dom -import { act } from 'react' -import { expect, it, vi, type Mock } from 'vitest' -import { - createResumeModalFixture, - failure, - type RestartRpc, - type ResumeStatusStream -} from './native-chat-resume-modal.test-support' -import { NativeChatResumeOnRestartModal } from './NativeChatResumeRuntimeModal' -import { NativeChatResumeStatusSegment } from './status-bar/NativeChatResumeStatusSegment' -import { requestNativeChatResumeOnRestartDialog } from './native-chat-resume-on-restart-dialog' -import { getNativeChatRestartRun } from './native-chat-resume-on-restart-store' - -const rpc: Mock = vi.hoisted(() => vi.fn()) -const statusStream: ResumeStatusStream = vi.hoisted(() => ({ - emit: (_event: Parameters[0]) => {}, - snapshot: new Map() -})) -vi.mock('../runtime/native-chat/requests/structured-agent-session-call', () => ({ - callStructuredAgentSession: rpc -})) - -vi.mock('../runtime/native-chat/requests/structured-agent-session-subscriptions', () => ({ - subscribeStructuredAgentSessionStatus: async ( - _target: unknown, - emit: ResumeStatusStream['emit'] - ) => { - statusStream.emit = emit - emit({ type: 'snapshot', sessions: [...statusStream.snapshot.values()] }) - return { unsubscribe: () => {} } - } -})) -vi.mock('@/lib/activate-ai-vault-structured-session', () => ({ - activateAiVaultStructuredSession: vi.fn(async () => true) -})) -vi.mock('sonner', async () => - (await import('./native-chat-resume-sonner-mock.test-support')).resumeSonnerMock() -) - -const { mount, button, fakeHost } = createResumeModalFixture(rpc, statusStream) -const dialog = () => document.querySelector('[role="dialog"]')?.textContent - -it('retires an all-skipped retry after its open result is closed', async () => { - fakeHost( - { sessions: [], failed: [{ ...failure('a', 'agent_session_conflict'), retryable: true }] }, - () => 'skipped' - ) - await mount( - <> - - - - ) - await act(async () => requestNativeChatResumeOnRestartDialog()) - await act(async () => button('Retry').click()) - expect(dialog()).toContain('Resumed 0 of 0 chats') - expect(getNativeChatRestartRun()?.entries).toHaveLength(0) - await act(async () => button('Close').click()) - expect(getNativeChatRestartRun()).toBeNull() - await act(async () => button('1 chat failed to resume').click()) - expect(dialog()).toContain('Resume interrupted chats?') - expect(dialog()).toContain('Prompt a') - expect(dialog()).not.toContain('Resumed 0 of 0 chats') -}) diff --git a/src/renderer/src/components/native-chat-resume-tree.test-support.ts b/src/renderer/src/components/native-chat-resume-tree.test-support.ts deleted file mode 100644 index 70f030f2570..00000000000 --- a/src/renderer/src/components/native-chat-resume-tree.test-support.ts +++ /dev/null @@ -1,146 +0,0 @@ -import { vi, type Mock } from 'vitest' -import { useAppStore } from '../store' -import { getDefaultSettings } from '../../../shared/constants' -import type { ExecutionHostId } from '../../../shared/execution-host' -import type { WorktreeLineage } from '../../../shared/worktree/lineage-types' -import type { Worktree } from '../../../shared/worktree/types' -import type { ResumeCandidate, ResumeFailure } from './native-chat-resume-on-restart-grouping' - -export function worktree(name: string, overrides: Partial = {}): Worktree { - return { - id: `repo-1::/repo/${name}`, - instanceId: `instance-${name}`, - repoId: 'repo-1', - path: `/repo/${name}`, - displayName: name, - branch: `refs/heads/${name}-branch`, - head: 'abc123', - isBare: false, - isMainWorktree: false, - comment: '', - linkedIssue: null, - linkedPR: null, - linkedLinearIssue: null, - isArchived: false, - isUnread: false, - isPinned: false, - sortOrder: 0, - lastActivityAt: 1, - ...overrides - } -} - -export function candidate(sessionId: string, workspace: Worktree): ResumeCandidate { - return { - sessionId, - workspaceId: workspace.id, - agent: 'codex', - trigger: 'quit', - latestPrompt: `Prompt ${sessionId}`, - recordedAt: 1_800_000_000_000, - executionHostId: workspace.hostId ?? 'local', - workspaceKind: 'git-worktree' - } -} - -export function lineage(child: Worktree, parent: Worktree): WorktreeLineage { - return { - worktreeId: child.id, - worktreeInstanceId: child.instanceId!, - parentWorktreeId: parent.id, - parentWorktreeInstanceId: parent.instanceId!, - origin: 'cli', - capture: { source: 'explicit-cli-flag', confidence: 'explicit' }, - createdAt: 1 - } -} - -export function unretryable(entry: ResumeCandidate): ResumeFailure { - return { - ...entry, - failedAt: 1_800_000_030_000, - outcome: 'refused', - reason: 'agent_session_restart_work_superseded', - retryable: false - } -} - -/** Repo "orca": parent (1 chat) > child (2 chats), plus an unrelated root workspace "other". */ -export function seedTree(hosts: { parent?: ExecutionHostId; child?: ExecutionHostId } = {}) { - // An explicit undefined is a row with no host id (older metadata). - const parentHost = 'parent' in hosts ? hosts.parent : 'local' - const parent = worktree('parent', { hostId: parentHost }) - const child = worktree('child', { hostId: 'child' in hosts ? hosts.child : 'local' }) - const other = worktree('other', { hostId: parentHost }) - useAppStore.setState({ - settings: getDefaultSettings(''), - repos: [ - { id: 'repo-1', path: '/repo', displayName: 'orca', badgeColor: '#999999', addedAt: 1 } - ], - worktreesByRepo: { 'repo-1': [parent, child, other] }, - worktreeLineageById: { [child.id]: lineage(child, parent) } - }) - return [ - candidate('in-child', child), - candidate('in-parent', parent), - candidate('also-in-child', child), - candidate('in-other', other) - ] -} - -export const onToggleSpy: Mock<(sessionId: string, checked: boolean) => void> = vi.fn() - -export function nodeBox(name: string): HTMLElement { - const box = document.querySelector( - `[role="checkbox"][aria-label="Select all chats in ${name}"], [role="checkbox"][aria-label="Select all chats on ${name}"]` - ) - if (!box) { - throw new Error(`Missing node checkbox: ${name}`) - } - return box -} - -export function chatBox(sessionId: string): HTMLElement { - const box = document.querySelector( - `[role="checkbox"][aria-label*="Prompt ${sessionId}"]` - ) - if (!box) { - throw new Error(`Missing chat checkbox: ${sessionId}`) - } - return box -} - -export function queryChatBox(sessionId: string): HTMLElement | null { - return document.querySelector(`[role="checkbox"][aria-label*="Prompt ${sessionId}"]`) -} - -export function itemOf(box: HTMLElement): HTMLElement { - return box.closest('[role="treeitem"]')! -} - -export function countOf(name: string): string | undefined { - return itemOf(nodeBox(name)).querySelector('.tabular-nums')?.textContent ?? undefined -} - -export function disclosureOf(name: string): HTMLButtonElement { - return itemOf(nodeBox(name)).querySelector('button[aria-expanded]')! -} - -/** Each tree row in order, as level:kind:name, kind read off the name's weight. */ -export function treeOutline(): string[] { - return [...document.querySelectorAll('[role="treeitem"]')].map((item) => { - const level = item.getAttribute('aria-level') - const label = item.querySelector('[role="checkbox"]')?.getAttribute('aria-label') ?? '' - const chat = /Prompt ([\w-]+)/.exec(label)?.[1] - if (chat) { - return `${level}:chat:${chat}` - } - const name = /^Select all chats (?:in|on) (.+)$/.exec(label)?.[1] - const kind = item.querySelector('.font-bold') - ? 'machine' - : item.querySelector('.font-semibold') - ? 'project' - : 'workspace' - return `${level}:${kind}:${name}` - }) -} diff --git a/src/renderer/src/components/native-chat/attachments/chips/native-chat-pending-attachment-cache.ts b/src/renderer/src/components/native-chat/attachments/chips/native-chat-pending-attachment-cache.ts index 19969a5efc5..4be8893b156 100644 --- a/src/renderer/src/components/native-chat/attachments/chips/native-chat-pending-attachment-cache.ts +++ b/src/renderer/src/components/native-chat/attachments/chips/native-chat-pending-attachment-cache.ts @@ -22,12 +22,9 @@ import { import { resolveNativeChatComposerDraftOwner } from '../../drafts/native-chat-composer-draft-memory' import { chipScopes, - hasNativeChatPendingAttachment, nativeChatPendingAttachmentScope } from './native-chat-pending-attachment-scopes' -export { hasNativeChatPendingAttachment, nativeChatPendingAttachmentScope } - const EMPTY: readonly NativeChatComposerImageAttachment[] = Object.freeze([]) const pendingCache = new Map() const pendingOwners = new Map() @@ -116,7 +113,7 @@ export function takeNativeChatPendingAttachment( scopeKey: string, id: string ): NativeChatComposerImageAttachment | undefined { - scopeKey = pendingDestination(scopeKey, id) + scopeKey = nativeChatPendingAttachmentScope(scopeKey, id) const current = nativeChatPendingAttachmentSnapshot(scopeKey) const taken = current.find((attachment) => attachment.id === id && attachment.pending) if (taken) { @@ -187,10 +184,6 @@ export function moveLaunchPendingAttachmentListeners(from: string, to: string): listeners.set(to, target) } -function pendingDestination(scope: string, id: string): string { - return currentDraftScope(chipScopes.get(id) ?? scope) -} - /** Persist completed images in attachment order; return false if already removed. */ export function settleNativeChatPendingAttachment( scopeKey: string, @@ -198,7 +191,7 @@ export function settleNativeChatPendingAttachment( path: string, connectionId?: string | null ): boolean { - scopeKey = pendingDestination(scopeKey, id) + scopeKey = nativeChatPendingAttachmentScope(scopeKey, id) const current = nativeChatPendingAttachmentSnapshot(scopeKey) const index = current.findIndex((chip) => chip.id === id && chip.pending) if (index === -1) { @@ -238,7 +231,9 @@ export function settleNativeChatPendingAttachmentReferences( insertAtCaret?: (paths: string[]) => void ): boolean { const originalScope = currentDraftScope(scopeKey) - scopeKey = references.length ? pendingDestination(scopeKey, references[0].id) : scopeKey + scopeKey = references.length + ? nativeChatPendingAttachmentScope(scopeKey, references[0].id) + : scopeKey const owner = pendingOwners.get(scopeKey) const paths = references.flatMap(({ id, path }) => takeNativeChatPendingAttachment(scopeKey, id) ? [path] : [] diff --git a/src/renderer/src/components/native-chat/attachments/chips/use-native-chat-composer-attachments.ts b/src/renderer/src/components/native-chat/attachments/chips/use-native-chat-composer-attachments.ts index ead5779b555..ac55d01b4e9 100644 --- a/src/renderer/src/components/native-chat/attachments/chips/use-native-chat-composer-attachments.ts +++ b/src/renderer/src/components/native-chat/attachments/chips/use-native-chat-composer-attachments.ts @@ -20,9 +20,9 @@ import { clearNativeChatPendingAttachments, settleNativeChatPendingAttachment, settleNativeChatPendingAttachmentReferences, - nativeChatPendingAttachmentSnapshot, - nativeChatPendingAttachmentScope + nativeChatPendingAttachmentSnapshot } from './native-chat-pending-attachment-cache' +import { nativeChatPendingAttachmentScope } from './native-chat-pending-attachment-scopes' import { useNativeChatComposerImageChips } from './use-native-chat-composer-image-chips' import { createNonSecureContextUuid as createUuidV4 } from '../../../../../../shared/non-secure-context-uuid' import { diff --git a/src/renderer/src/components/native-chat/attachments/intake/native-chat-element-file-drop.test.tsx b/src/renderer/src/components/native-chat/attachments/intake/native-chat-element-file-drop.test.tsx deleted file mode 100644 index 323d9b7bcf3..00000000000 --- a/src/renderer/src/components/native-chat/attachments/intake/native-chat-element-file-drop.test.tsx +++ /dev/null @@ -1,165 +0,0 @@ -// @vitest-environment happy-dom -import { act, cleanup, fireEvent, render } from '@testing-library/react' -import { useRef, useState } from 'react' -import { createPortal } from 'react-dom' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import type { NativeChatComposerInput } from '../../composer/editor/native-chat-composer-input' -import { - NativeChatPaneFileDropSurface, - useNativeChatPaneFileDropClaim -} from './NativeChatPaneFileDropSurface' -import { NativeChatPromptEditor } from '../../composer/editor/NativeChatPromptEditor' - -const electron = vi.hoisted(() => ({ - on: vi.fn(), - removeListener: vi.fn(), - send: vi.fn(), - getPathForFile: vi.fn((file: File) => `/drop/${file.name}`) -})) -vi.mock('electron', () => ({ - ipcRenderer: electron, - webUtils: { getPathForFile: electron.getPathForFile } -})) -vi.mock('sonner', () => ({ toast: { error: vi.fn() } })) -vi.mock('@/i18n/i18n', () => ({ translate: (_key: string, fallback: string) => fallback })) - -const prepare = vi.fn(async ({ paths }: { paths: string[] }) => ({ paths, failures: [] })) -function Composer({ - attach, - disabled = false -}: { - attach: (paths: string[]) => void - disabled?: boolean -}) { - const input = useRef(null) - useNativeChatPaneFileDropClaim({ - destinationKey: 'draft', - disabled, - onDragOverCapture: () => {}, - onDropCapture: () => {}, - captureExternalDrop: () => async (paths) => attach(paths) - }) - return ( - {}} - onSelect={() => {}} - /> - ) -} -function Chat({ - attach, - hidden = false, - disabled = false -}: { - attach: (paths: string[]) => void - hidden?: boolean - disabled?: boolean -}) { - return ( - - ) -} -async function drop(target: Element, types = ['Files']) { - const event = new Event('drop', { bubbles: true, cancelable: true, composed: true }) - Object.defineProperty(event, 'isTrusted', { value: true }) - Object.defineProperty(event, 'dataTransfer', { - value: { - types, - files: [new File(['x'], 'a.png')], - getData: (type: string) => (type === 'text/html' ? 'Injected' : '') - } - }) - await act(async () => { - target.dispatchEvent(event) - }) - return event -} -function dragEvent(target: Element, type: string, transfer: { dropEffect: string }): Event { - const event = new Event(type, { bubbles: true, cancelable: true, composed: true }) - Object.defineProperty(event, 'isTrusted', { value: true }) - Object.defineProperty(event, 'dataTransfer', { value: transfer }) - target.dispatchEvent(event) - return event -} -function negotiateAndRelease(target: Element) { - const transfer = { types: ['Files'], files: [new File(['x'], 'a.png')], dropEffect: 'move' } - const hover = dragEvent(target, 'dragover', transfer) - const release = dragEvent(target, transfer.dropEffect === 'none' ? 'dragleave' : 'drop', transfer) - return { hover, release, transfer } -} -function AvailabilityComposer({ attach }: { attach: (paths: string[]) => void }) { - const [disabled, setDisabled] = useState(true) - return ( - <> - - - - ) -} - -beforeEach(() => { - vi.clearAllMocks() - vi.stubGlobal('api', { - fs: { getPathForFile: electron.getPathForFile, prepareDroppedPaths: prepare } - }) -}) -afterEach(() => { - cleanup() - vi.unstubAllGlobals() -}) - -describe('element-owned native chat drops', () => { - it('claims a portaled chat while refusing the unowned container around it', async () => { - const attach = vi.fn() - const terminal = document.createElement('div') - document.body.append(terminal) - const terminalDrop = vi.fn() - terminal.addEventListener('drop', terminalDrop) - try { - render(createPortal(, terminal)) - await drop(terminal.querySelector('.ProseMirror')!) - expect(attach).toHaveBeenCalledExactlyOnceWith(['/drop/a.png']) - expect(terminalDrop).not.toHaveBeenCalled() - expect(electron.send).not.toHaveBeenCalled() - await drop(terminal) - expect(electron.send).not.toHaveBeenCalled() - expect(attach).toHaveBeenCalledOnce() - } finally { - terminal.remove() - } - }) - it('reads child-only availability changes on the immediate dragover and drop', async () => { - const attach = vi.fn() - const view = render( - - - - ) - const target = view.container.querySelector('.ProseMirror')! - const refused = negotiateAndRelease(target) - expect(refused.transfer.dropEffect).toBe('none') - expect(prepare).not.toHaveBeenCalled() - fireEvent.click(view.getByText('Toggle availability')) - let accepted: ReturnType | undefined - await act(async () => { - accepted = negotiateAndRelease(target) - }) - expect(accepted?.transfer.dropEffect).toBe('copy') - expect(accepted?.release.type).toBe('drop') - expect(attach).toHaveBeenCalledExactlyOnceWith(['/drop/a.png']) - fireEvent.click(view.getByText('Toggle availability')) - await drop(target) - expect(attach).toHaveBeenCalledOnce() - expect(prepare).toHaveBeenCalledOnce() - expect(electron.send).not.toHaveBeenCalled() - }) -}) diff --git a/src/renderer/src/components/native-chat/attachments/intake/native-chat-local-attachment-drop.ts b/src/renderer/src/components/native-chat/attachments/intake/native-chat-local-attachment-drop.ts index afd7dd0780c..0944765bb72 100644 --- a/src/renderer/src/components/native-chat/attachments/intake/native-chat-local-attachment-drop.ts +++ b/src/renderer/src/components/native-chat/attachments/intake/native-chat-local-attachment-drop.ts @@ -10,7 +10,7 @@ import { import type { NativeChatAttachmentOwner } from '../uploads/native-chat-attachment-owner' import { stageNativeChatDraftFile } from '../../drafts/native-chat-draft-attachment-staging' import { isImageDropPath } from '../../../../../../shared/image-path-paste' -import { nativeChatPendingAttachmentScope } from '../chips/native-chat-pending-attachment-cache' +import { nativeChatPendingAttachmentScope } from '../chips/native-chat-pending-attachment-scopes' import type { NativeChatAttachmentFocusOptions, NativeChatResolvedPathOptions diff --git a/src/renderer/src/components/native-chat/attachments/intake/native-chat-pane-file-drop.test.tsx b/src/renderer/src/components/native-chat/attachments/intake/native-chat-pane-file-drop.test.tsx deleted file mode 100644 index 78b1fdc9376..00000000000 --- a/src/renderer/src/components/native-chat/attachments/intake/native-chat-pane-file-drop.test.tsx +++ /dev/null @@ -1,121 +0,0 @@ -// @vitest-environment happy-dom - -import type * as AttachmentOwnerModule from '../uploads/native-chat-attachment-owner' -import { useState } from 'react' -import { afterEach, expect, it, vi } from 'vitest' -import { act, cleanup, fireEvent, render } from '@testing-library/react' - -import { WORKSPACE_FILE_PATH_MIME } from '@/lib/workspace-file-drag' -import { - NativeChatPaneFileDropSurface, - useNativeChatPaneFileDropClaim -} from './NativeChatPaneFileDropSurface' - -vi.mock('@/i18n/i18n', () => ({ translate: (_key: string, fallback: string) => fallback })) -vi.mock('../../../../store/index', () => ({ useAppStore: { getState: () => ({}) } })) -vi.mock('../uploads/native-chat-attachment-owner', async (original) => ({ - ...(await original()), - resolveNativeChatAttachmentOwnerForWorktree: () => ({ kind: 'local' }) -})) - -class DropDataTransfer { - dropEffect = 'none' - effectAllowed = 'all' - private readonly data = new Map() - get types(): string[] { - return [...this.data.keys()] - } - setData(type: string, value: string): void { - this.data.set(type, value) - } - getData(type: string): string { - return this.data.get(type) ?? '' - } -} - -function workspaceDrag(): DropDataTransfer { - const transfer = new DropDataTransfer() - transfer.setData(WORKSPACE_FILE_PATH_MIME, '/repo/a.ts') - return transfer -} - -function fireDrag( - target: HTMLElement, - type: 'dragenter' | 'dragover' | 'dragleave' | 'drop', - dataTransfer: DropDataTransfer, - relatedTarget: EventTarget | null = null -): void { - const event = new Event(type, { bubbles: true, cancelable: true }) - Object.defineProperty(event, 'dataTransfer', { value: dataTransfer }) - Object.defineProperty(event, 'relatedTarget', { value: relatedTarget }) - act(() => { - target.dispatchEvent(event) - }) -} - -afterEach(cleanup) - -it('direct drops override last focus; background keeps stable focus through disable and remount, with questions independent', () => { - function Composer({ scope, disabled = false }: { scope: string; disabled?: boolean }) { - const [value, setValue] = useState('') - useNativeChatPaneFileDropClaim({ - destinationKey: scope, - focusScopeKey: scope, - disabled, - captureExternalDrop: () => async () => {}, - onDragOverCapture: (event) => { - if (!disabled) { - event.preventDefault() - } - }, - onDropCapture: (event) => { - if (!disabled) { - setValue((previous) => previous + event.dataTransfer.getData(WORKSPACE_FILE_PATH_MIME)) - } - } - }) - return ( -
-