From a9401b7766272e0ac5c77ed6a7d6df51110d3e6d Mon Sep 17 00:00:00 2001 From: Jinwoo-H Date: Tue, 8 Sep 2026 22:16:35 -0400 Subject: [PATCH 01/40] refactor(mobile): add host operation interfaces and native adapters Six operations interfaces the mobile screens will be handed instead of an RpcClient: HostSessionOperations, HostTaskOperations, HostWorkspaceOperations, HostFileOperations, HostAccountOperations and DeviceOperations. Each host domain groups its per-concern contracts as namespaces so a screen takes one prop while every sub-adapter keeps its own file, and each has one native factory built over the socket RpcClient. No screen is wired yet, so this carries no behavior change. Claude-Session: https://claude.ai/code/session_01JNnE9qzUZMMnqpZWCqM3nb --- .../default-host-account-operations.ts | 10 + .../src/accounts/host-account-operations.ts | 22 ++ .../native-host-account-operations.ts | 77 +++++++ .../src/device/default-device-operations.ts | 6 + mobile/src/device/device-operations.ts | 22 ++ mobile/src/device/native-device-operations.ts | 48 ++++ .../default-host-file-explorer-operations.ts | 10 + .../src/files/default-host-file-operations.ts | 10 + .../default-host-file-preview-operations.ts | 10 + .../files/host-file-explorer-operations.ts | 19 ++ mobile/src/files/host-file-operations.ts | 9 + .../src/files/host-file-preview-operations.ts | 27 +++ .../native-host-file-explorer-operations.ts | 55 +++++ .../src/files/native-host-file-operations.ts | 14 ++ .../native-host-file-preview-operations.ts | 25 ++ ...default-host-session-browser-operations.ts | 9 + .../default-host-session-file-operations.ts | 7 + ...efault-host-session-markdown-operations.ts | 9 + ...ult-host-session-native-chat-operations.ts | 9 + .../default-host-session-operations.ts | 7 + ...t-host-session-quick-command-operations.ts | 9 + .../default-host-session-tab-operations.ts | 7 + ...t-host-session-terminal-file-operations.ts | 9 + ...efault-host-session-terminal-operations.ts | 9 + mobile/src/session/github-pr-mutations.ts | 71 +++--- .../host-session-browser-operations.ts | 77 +++++++ .../session/host-session-file-operations.ts | 5 + .../host-session-markdown-operations.ts | 26 +++ .../host-session-native-chat-operations.ts | 79 +++++++ mobile/src/session/host-session-operations.ts | 21 ++ .../host-session-quick-command-operations.ts | 25 ++ .../host-session-runtime-capabilities.ts | 17 ++ .../session/host-session-tab-operations.ts | 37 +++ .../host-session-terminal-file-operations.ts | 41 ++++ .../host-session-terminal-operations.ts | 81 +++++++ .../session/mobile-native-chat-open-file.ts | 49 ++++ mobile/src/session/mobile-native-chat-send.ts | 6 +- .../native-host-session-browser-operations.ts | 178 ++++++++++++++ .../native-host-session-file-operations.ts | 11 + ...native-host-session-markdown-operations.ts | 79 +++++++ ...ost-session-native-chat-operations.test.ts | 66 ++++++ ...ive-host-session-native-chat-operations.ts | 197 ++++++++++++++++ .../session/native-host-session-operations.ts | 23 ++ ...e-host-session-quick-command-operations.ts | 85 +++++++ ...native-host-session-tab-operations.test.ts | 217 ++++++++++++++++++ .../native-host-session-tab-operations.ts | 147 ++++++++++++ ...e-host-session-terminal-file-operations.ts | 79 +++++++ ...e-host-session-terminal-operations.test.ts | 110 +++++++++ ...native-host-session-terminal-operations.ts | 83 +++++++ .../src/tasks/composer-source-base-resolve.ts | 22 +- .../default-host-task-detail-operations.ts | 7 + .../default-host-task-item-file-operations.ts | 7 + ...ault-host-task-item-mutation-operations.ts | 9 + ...efault-host-task-item-review-operations.ts | 9 + .../default-host-task-linear-operations.ts | 7 + .../default-host-task-list-operations.ts | 7 + .../src/tasks/default-host-task-operations.ts | 7 + ...default-host-task-preference-operations.ts | 9 + ...fault-host-task-project-file-operations.ts | 9 + ...t-host-task-project-mutation-operations.ts | 9 + ...fault-host-task-project-read-operations.ts | 9 + ...ult-host-task-provider-write-operations.ts | 9 + .../default-host-task-read-operations.ts | 7 + .../tasks/github-task-detail-projection.ts | 32 +++ .../src/tasks/host-task-detail-operations.ts | 27 +++ .../tasks/host-task-item-file-operations.ts | 43 ++++ .../host-task-item-mutation-operations.ts | 33 +++ .../tasks/host-task-item-review-operations.ts | 24 ++ .../src/tasks/host-task-linear-operations.ts | 25 ++ mobile/src/tasks/host-task-list-operations.ts | 17 ++ mobile/src/tasks/host-task-operations.ts | 29 +++ .../tasks/host-task-preference-operations.ts | 15 ++ .../host-task-project-file-operations.ts | 33 +++ .../host-task-project-mutation-operations.ts | 81 +++++++ .../src/tasks/host-task-project-payloads.ts | 48 ++++ .../host-task-project-read-operations.ts | 27 +++ .../src/tasks/host-task-provider-payloads.ts | 105 +++++++++ .../host-task-provider-write-operations.ts | 9 + mobile/src/tasks/host-task-read-operations.ts | 15 ++ .../src/tasks/host-task-runtime-payloads.ts | 39 ++++ .../native-host-task-detail-operations.ts | 114 +++++++++ .../native-host-task-item-file-operations.ts | 85 +++++++ ...tive-host-task-item-mutation-operations.ts | 135 +++++++++++ ...native-host-task-item-review-operations.ts | 148 ++++++++++++ .../native-host-task-linear-operations.ts | 115 ++++++++++ .../tasks/native-host-task-list-operations.ts | 76 ++++++ ...tive-host-task-operation-contracts.test.ts | 57 +++++ .../src/tasks/native-host-task-operations.ts | 31 +++ .../native-host-task-preference-operations.ts | 23 ++ ...ative-host-task-project-file-operations.ts | 72 ++++++ ...e-host-task-project-mutation-operations.ts | 187 +++++++++++++++ ...ative-host-task-project-read-operations.ts | 113 +++++++++ ...ive-host-task-provider-write-operations.ts | 48 ++++ .../tasks/native-host-task-read-operations.ts | 124 ++++++++++ ...ost-task-review-comment-addressing.test.ts | 78 +++++++ mobile/src/tasks/setup-hook-trust.ts | 6 +- .../src/tasks/smart-source-search-requests.ts | 10 +- mobile/src/tasks/source-workspace-create.ts | 7 +- .../src/tasks/worktree-create-capability.ts | 4 +- mobile/src/tasks/worktree-create-retry.ts | 8 +- mobile/src/transport/rpc-client.ts | 4 + ...fault-host-workspace-catalog-operations.ts | 9 + ...ault-host-workspace-creation-operations.ts | 9 + .../default-host-workspace-operations.ts | 7 + .../host-workspace-catalog-operations.ts | 39 ++++ .../host-workspace-creation-operations.ts | 132 +++++++++++ .../worktree/host-workspace-host-context.ts | 32 +++ .../src/worktree/host-workspace-operations.ts | 9 + ...-host-workspace-catalog-operations.test.ts | 171 ++++++++++++++ ...ative-host-workspace-catalog-operations.ts | 135 +++++++++++ ...host-workspace-creation-operations.test.ts | 142 ++++++++++++ ...tive-host-workspace-creation-operations.ts | 27 +++ ...host-workspace-creation-read-operations.ts | 116 ++++++++++ ...st-workspace-creation-source-operations.ts | 91 ++++++++ .../native-host-workspace-operations.ts | 11 + .../rpc-workspace-creation-operations.ts | 54 +++++ 116 files changed, 5358 insertions(+), 49 deletions(-) create mode 100644 mobile/src/accounts/default-host-account-operations.ts create mode 100644 mobile/src/accounts/host-account-operations.ts create mode 100644 mobile/src/accounts/native-host-account-operations.ts create mode 100644 mobile/src/device/default-device-operations.ts create mode 100644 mobile/src/device/device-operations.ts create mode 100644 mobile/src/device/native-device-operations.ts create mode 100644 mobile/src/files/default-host-file-explorer-operations.ts create mode 100644 mobile/src/files/default-host-file-operations.ts create mode 100644 mobile/src/files/default-host-file-preview-operations.ts create mode 100644 mobile/src/files/host-file-explorer-operations.ts create mode 100644 mobile/src/files/host-file-operations.ts create mode 100644 mobile/src/files/host-file-preview-operations.ts create mode 100644 mobile/src/files/native-host-file-explorer-operations.ts create mode 100644 mobile/src/files/native-host-file-operations.ts create mode 100644 mobile/src/files/native-host-file-preview-operations.ts create mode 100644 mobile/src/session/default-host-session-browser-operations.ts create mode 100644 mobile/src/session/default-host-session-file-operations.ts create mode 100644 mobile/src/session/default-host-session-markdown-operations.ts create mode 100644 mobile/src/session/default-host-session-native-chat-operations.ts create mode 100644 mobile/src/session/default-host-session-operations.ts create mode 100644 mobile/src/session/default-host-session-quick-command-operations.ts create mode 100644 mobile/src/session/default-host-session-tab-operations.ts create mode 100644 mobile/src/session/default-host-session-terminal-file-operations.ts create mode 100644 mobile/src/session/default-host-session-terminal-operations.ts create mode 100644 mobile/src/session/host-session-browser-operations.ts create mode 100644 mobile/src/session/host-session-file-operations.ts create mode 100644 mobile/src/session/host-session-markdown-operations.ts create mode 100644 mobile/src/session/host-session-native-chat-operations.ts create mode 100644 mobile/src/session/host-session-operations.ts create mode 100644 mobile/src/session/host-session-quick-command-operations.ts create mode 100644 mobile/src/session/host-session-runtime-capabilities.ts create mode 100644 mobile/src/session/host-session-tab-operations.ts create mode 100644 mobile/src/session/host-session-terminal-file-operations.ts create mode 100644 mobile/src/session/host-session-terminal-operations.ts create mode 100644 mobile/src/session/native-host-session-browser-operations.ts create mode 100644 mobile/src/session/native-host-session-file-operations.ts create mode 100644 mobile/src/session/native-host-session-markdown-operations.ts create mode 100644 mobile/src/session/native-host-session-native-chat-operations.test.ts create mode 100644 mobile/src/session/native-host-session-native-chat-operations.ts create mode 100644 mobile/src/session/native-host-session-operations.ts create mode 100644 mobile/src/session/native-host-session-quick-command-operations.ts create mode 100644 mobile/src/session/native-host-session-tab-operations.test.ts create mode 100644 mobile/src/session/native-host-session-tab-operations.ts create mode 100644 mobile/src/session/native-host-session-terminal-file-operations.ts create mode 100644 mobile/src/session/native-host-session-terminal-operations.test.ts create mode 100644 mobile/src/session/native-host-session-terminal-operations.ts create mode 100644 mobile/src/tasks/default-host-task-detail-operations.ts create mode 100644 mobile/src/tasks/default-host-task-item-file-operations.ts create mode 100644 mobile/src/tasks/default-host-task-item-mutation-operations.ts create mode 100644 mobile/src/tasks/default-host-task-item-review-operations.ts create mode 100644 mobile/src/tasks/default-host-task-linear-operations.ts create mode 100644 mobile/src/tasks/default-host-task-list-operations.ts create mode 100644 mobile/src/tasks/default-host-task-operations.ts create mode 100644 mobile/src/tasks/default-host-task-preference-operations.ts create mode 100644 mobile/src/tasks/default-host-task-project-file-operations.ts create mode 100644 mobile/src/tasks/default-host-task-project-mutation-operations.ts create mode 100644 mobile/src/tasks/default-host-task-project-read-operations.ts create mode 100644 mobile/src/tasks/default-host-task-provider-write-operations.ts create mode 100644 mobile/src/tasks/default-host-task-read-operations.ts create mode 100644 mobile/src/tasks/github-task-detail-projection.ts create mode 100644 mobile/src/tasks/host-task-detail-operations.ts create mode 100644 mobile/src/tasks/host-task-item-file-operations.ts create mode 100644 mobile/src/tasks/host-task-item-mutation-operations.ts create mode 100644 mobile/src/tasks/host-task-item-review-operations.ts create mode 100644 mobile/src/tasks/host-task-linear-operations.ts create mode 100644 mobile/src/tasks/host-task-list-operations.ts create mode 100644 mobile/src/tasks/host-task-operations.ts create mode 100644 mobile/src/tasks/host-task-preference-operations.ts create mode 100644 mobile/src/tasks/host-task-project-file-operations.ts create mode 100644 mobile/src/tasks/host-task-project-mutation-operations.ts create mode 100644 mobile/src/tasks/host-task-project-payloads.ts create mode 100644 mobile/src/tasks/host-task-project-read-operations.ts create mode 100644 mobile/src/tasks/host-task-provider-payloads.ts create mode 100644 mobile/src/tasks/host-task-provider-write-operations.ts create mode 100644 mobile/src/tasks/host-task-read-operations.ts create mode 100644 mobile/src/tasks/host-task-runtime-payloads.ts create mode 100644 mobile/src/tasks/native-host-task-detail-operations.ts create mode 100644 mobile/src/tasks/native-host-task-item-file-operations.ts create mode 100644 mobile/src/tasks/native-host-task-item-mutation-operations.ts create mode 100644 mobile/src/tasks/native-host-task-item-review-operations.ts create mode 100644 mobile/src/tasks/native-host-task-linear-operations.ts create mode 100644 mobile/src/tasks/native-host-task-list-operations.ts create mode 100644 mobile/src/tasks/native-host-task-operation-contracts.test.ts create mode 100644 mobile/src/tasks/native-host-task-operations.ts create mode 100644 mobile/src/tasks/native-host-task-preference-operations.ts create mode 100644 mobile/src/tasks/native-host-task-project-file-operations.ts create mode 100644 mobile/src/tasks/native-host-task-project-mutation-operations.ts create mode 100644 mobile/src/tasks/native-host-task-project-read-operations.ts create mode 100644 mobile/src/tasks/native-host-task-provider-write-operations.ts create mode 100644 mobile/src/tasks/native-host-task-read-operations.ts create mode 100644 mobile/src/tasks/native-host-task-review-comment-addressing.test.ts create mode 100644 mobile/src/worktree/default-host-workspace-catalog-operations.ts create mode 100644 mobile/src/worktree/default-host-workspace-creation-operations.ts create mode 100644 mobile/src/worktree/default-host-workspace-operations.ts create mode 100644 mobile/src/worktree/host-workspace-catalog-operations.ts create mode 100644 mobile/src/worktree/host-workspace-creation-operations.ts create mode 100644 mobile/src/worktree/host-workspace-host-context.ts create mode 100644 mobile/src/worktree/host-workspace-operations.ts create mode 100644 mobile/src/worktree/native-host-workspace-catalog-operations.test.ts create mode 100644 mobile/src/worktree/native-host-workspace-catalog-operations.ts create mode 100644 mobile/src/worktree/native-host-workspace-creation-operations.test.ts create mode 100644 mobile/src/worktree/native-host-workspace-creation-operations.ts create mode 100644 mobile/src/worktree/native-host-workspace-creation-read-operations.ts create mode 100644 mobile/src/worktree/native-host-workspace-creation-source-operations.ts create mode 100644 mobile/src/worktree/native-host-workspace-operations.ts create mode 100644 mobile/src/worktree/rpc-workspace-creation-operations.ts diff --git a/mobile/src/accounts/default-host-account-operations.ts b/mobile/src/accounts/default-host-account-operations.ts new file mode 100644 index 000000000000..88e6e7684fa3 --- /dev/null +++ b/mobile/src/accounts/default-host-account-operations.ts @@ -0,0 +1,10 @@ +import type { RpcClient } from '../transport/rpc-client' +import type { HostAccountOperations } from './host-account-operations' +import { nativeHostAccountOperations } from './native-host-account-operations' + +export function defaultHostAccountOperations( + client: RpcClient, + hostId: string +): HostAccountOperations { + return nativeHostAccountOperations(client, hostId) +} diff --git a/mobile/src/accounts/host-account-operations.ts b/mobile/src/accounts/host-account-operations.ts new file mode 100644 index 000000000000..626b54814693 --- /dev/null +++ b/mobile/src/accounts/host-account-operations.ts @@ -0,0 +1,22 @@ +import type { + AccountsSnapshot, + ProviderKey, + RateLimitRuntimeTarget +} from '../components/account-usage-state' +import type { CodexResetCreditRequestResult } from '../components/codex-reset-credit' +import type { CodexResetCreditExpectedScope } from '../../../src/shared/codex-reset-credit-scope' + +export type HostAccountOperations = { + loadHostName(hostId: string): Promise + snapshot(): Promise + select( + provider: ProviderKey, + accountId: string | null, + codexTarget?: RateLimitRuntimeTarget | null + ): Promise + readCodexResetCreditCapability(): Promise + consumeCodexResetCredit( + expectedScope: CodexResetCreditExpectedScope + ): Promise + subscribe(listener: (snapshot: AccountsSnapshot) => void, onInvalid?: () => void): () => void +} diff --git a/mobile/src/accounts/native-host-account-operations.ts b/mobile/src/accounts/native-host-account-operations.ts new file mode 100644 index 000000000000..76b41ee55ea2 --- /dev/null +++ b/mobile/src/accounts/native-host-account-operations.ts @@ -0,0 +1,77 @@ +import { + decodeAccountsSnapshot, + type ProviderKey, + type RateLimitRuntimeTarget +} from '../components/account-usage-state' +import { requestCodexResetCredit } from '../components/codex-reset-credit' +import { readCodexResetCreditCapability } from '../components/codex-reset-credit-capability' +import { nativeDeviceOperations } from '../device/native-device-operations' +import { loadHosts } from '../transport/host-store' +import type { RpcClient } from '../transport/rpc-client' +import type { RpcSuccess } from '../transport/types' +import type { HostAccountOperations } from './host-account-operations' + +export function nativeHostAccountOperations( + client: RpcClient, + hostId: string +): HostAccountOperations { + return { + async loadHostName(hostId) { + return (await loadHosts()).find((host) => host.id === hostId)?.name ?? null + }, + async snapshot() { + const response = await client.sendRequest('accounts.list') + requireSuccess(response) + return decodeAccountsSnapshot((response as RpcSuccess).result) + }, + async select(provider, accountId, codexTarget) { + const method = selectionMethod(provider, codexTarget) + const params = + provider === 'codex' && codexTarget?.runtime === 'wsl' + ? { accountId, target: codexTarget } + : { accountId } + requireSuccess(await client.sendRequest(method, params)) + }, + readCodexResetCreditCapability() { + return readCodexResetCreditCapability(client) + }, + consumeCodexResetCredit(expectedScope) { + return requestCodexResetCredit(client, { + hostId, + expectedScope, + createIdempotencyKey: () => nativeDeviceOperations.randomNonce() + }) + }, + subscribe(listener, onInvalid) { + return client.subscribe('accounts.subscribe', null, (payload) => { + if (!payload || typeof payload !== 'object') { + return + } + const event = payload as { type?: string; snapshot?: unknown } + if (event.type === 'ready' || event.type === 'snapshot') { + try { + listener(decodeAccountsSnapshot(event.snapshot)) + } catch { + onInvalid?.() + } + } + }) + } + } +} + +function selectionMethod( + provider: ProviderKey, + target?: RateLimitRuntimeTarget | null +): 'accounts.selectClaude' | 'accounts.selectCodex' | 'accounts.selectCodexForTarget' { + if (provider === 'claude') { + return 'accounts.selectClaude' + } + return target?.runtime === 'wsl' ? 'accounts.selectCodexForTarget' : 'accounts.selectCodex' +} + +function requireSuccess(response: { ok: boolean; error?: { message?: string } }): void { + if (!response.ok) { + throw new Error(response.error?.message ?? 'Account operation failed') + } +} diff --git a/mobile/src/device/default-device-operations.ts b/mobile/src/device/default-device-operations.ts new file mode 100644 index 000000000000..6940fb09285c --- /dev/null +++ b/mobile/src/device/default-device-operations.ts @@ -0,0 +1,6 @@ +import type { DeviceOperations } from './device-operations' +import { nativeDeviceOperations } from './native-device-operations' + +export function defaultDeviceOperations(): DeviceOperations { + return nativeDeviceOperations +} diff --git a/mobile/src/device/device-operations.ts b/mobile/src/device/device-operations.ts new file mode 100644 index 000000000000..8b20b73fe16e --- /dev/null +++ b/mobile/src/device/device-operations.ts @@ -0,0 +1,22 @@ +/** Device capabilities a screen reaches through its host binding instead of importing a native + * module directly, so the same screen runs against a non-native provider later. */ +export type DeviceHapticKind = 'selection' | 'success' | 'error' | 'edge-bump' | 'medium-impact' + +export type DeviceClipboardAvailability = { + hasText: boolean + hasImage: boolean +} + +/** iOS shows its own paste banner; every other platform needs the app to confirm. */ +export type DeviceClipboardWriteResult = { + confirmation: 'in-app' | 'system' +} + +export type DeviceOperations = { + hapticFeedback(kind: DeviceHapticKind): void + clipboardAvailability(): Promise + copyText(text: string): Promise + openExternalUrl(url: string): Promise + openTerminalSettings(): void + randomNonce(): string +} diff --git a/mobile/src/device/native-device-operations.ts b/mobile/src/device/native-device-operations.ts new file mode 100644 index 000000000000..94e4cee777b1 --- /dev/null +++ b/mobile/src/device/native-device-operations.ts @@ -0,0 +1,48 @@ +import * as Clipboard from 'expo-clipboard' +import * as ExpoCrypto from 'expo-crypto' +import { router } from 'expo-router' +import { Linking, Platform } from 'react-native' +import { + triggerEdgeBump, + triggerError, + triggerMediumImpact, + triggerSelection, + triggerSuccess +} from '../platform/haptics' +import type { DeviceOperations } from './device-operations' + +export const nativeDeviceOperations: DeviceOperations = { + hapticFeedback(kind) { + if (kind === 'selection') { + triggerSelection() + } else if (kind === 'success') { + triggerSuccess() + } else if (kind === 'error') { + triggerError() + } else if (kind === 'edge-bump') { + triggerEdgeBump() + } else { + triggerMediumImpact() + } + }, + async clipboardAvailability() { + const [hasText, hasImage] = await Promise.all([ + Clipboard.hasStringAsync().catch(() => false), + Clipboard.hasImageAsync().catch(() => false) + ]) + return { hasText, hasImage } + }, + async copyText(text) { + await Clipboard.setStringAsync(text) + return { confirmation: Platform.OS === 'ios' ? 'in-app' : 'system' } + }, + async openExternalUrl(url) { + await Linking.openURL(url) + }, + openTerminalSettings() { + router.push('/terminal-settings') + }, + randomNonce() { + return ExpoCrypto.randomUUID() + } +} diff --git a/mobile/src/files/default-host-file-explorer-operations.ts b/mobile/src/files/default-host-file-explorer-operations.ts new file mode 100644 index 000000000000..ca9a1cb0005a --- /dev/null +++ b/mobile/src/files/default-host-file-explorer-operations.ts @@ -0,0 +1,10 @@ +import type { RpcClient } from '../transport/rpc-client' +import type { HostFileExplorerOperations } from './host-file-explorer-operations' +import { nativeHostFileExplorerOperations } from './native-host-file-explorer-operations' + +export function defaultHostFileExplorerOperations( + client: RpcClient, + reconnect: () => Promise +): HostFileExplorerOperations { + return nativeHostFileExplorerOperations(client, reconnect) +} diff --git a/mobile/src/files/default-host-file-operations.ts b/mobile/src/files/default-host-file-operations.ts new file mode 100644 index 000000000000..d5a916a69681 --- /dev/null +++ b/mobile/src/files/default-host-file-operations.ts @@ -0,0 +1,10 @@ +import type { RpcClient } from '../transport/rpc-client' +import type { HostFileOperations } from './host-file-operations' +import { nativeHostFileOperations } from './native-host-file-operations' + +export function defaultHostFileOperations( + client: RpcClient, + reconnect: () => Promise +): HostFileOperations { + return nativeHostFileOperations(client, reconnect) +} diff --git a/mobile/src/files/default-host-file-preview-operations.ts b/mobile/src/files/default-host-file-preview-operations.ts new file mode 100644 index 000000000000..23c5783fd5af --- /dev/null +++ b/mobile/src/files/default-host-file-preview-operations.ts @@ -0,0 +1,10 @@ +import type { RpcClient } from '../transport/rpc-client' +import type { HostFilePreviewOperations } from './host-file-preview-operations' +import { nativeHostFilePreviewOperations } from './native-host-file-preview-operations' + +export function defaultHostFilePreviewOperations( + client: RpcClient, + reconnect: () => Promise +): HostFilePreviewOperations { + return nativeHostFilePreviewOperations(client, reconnect) +} diff --git a/mobile/src/files/host-file-explorer-operations.ts b/mobile/src/files/host-file-explorer-operations.ts new file mode 100644 index 000000000000..8144d4ca4697 --- /dev/null +++ b/mobile/src/files/host-file-explorer-operations.ts @@ -0,0 +1,19 @@ +import type { LegacyMobileFileEntry } from './file-list-fallback' +import type { MobileDirEntry } from './file-tree' + +export type HostFileExplorerDirectoryResult = + | { + kind: 'directory' + entries: MobileDirEntry[] + truncated: boolean + } + | { + kind: 'legacy-list' + files: LegacyMobileFileEntry[] + truncated: boolean + } + +export type HostFileExplorerOperations = { + readDirectory(workspaceId: string, relativePath: string): Promise + reconnect(): Promise +} diff --git a/mobile/src/files/host-file-operations.ts b/mobile/src/files/host-file-operations.ts new file mode 100644 index 000000000000..ec42f47539ce --- /dev/null +++ b/mobile/src/files/host-file-operations.ts @@ -0,0 +1,9 @@ +import type { HostFileExplorerOperations } from './host-file-explorer-operations' +import type { HostFilePreviewOperations } from './host-file-preview-operations' + +/** Everything the file screens ask a host for, grouped by concern so a screen takes one prop and + * a provider is built once. Each namespace keeps its own contract file. */ +export type HostFileOperations = { + explorer: HostFileExplorerOperations + preview: HostFilePreviewOperations +} diff --git a/mobile/src/files/host-file-preview-operations.ts b/mobile/src/files/host-file-preview-operations.ts new file mode 100644 index 000000000000..930afb3bdb34 --- /dev/null +++ b/mobile/src/files/host-file-preview-operations.ts @@ -0,0 +1,27 @@ +import type { + MobileFilePreviewResult, + MobileFilePreviewSource +} from './mobile-file-preview-request' +import type { MobileTerminalArtifactPreviewSource } from './mobile-terminal-artifact-grant-refresh' + +export type HostFilePreviewLoadOptions = { + onTerminalArtifactSourceRefreshed?: (source: MobileTerminalArtifactPreviewSource) => void +} + +export type HostFilePreviewSaveOptions = HostFilePreviewLoadOptions & { + baseContent?: string +} + +export type HostFilePreviewOperations = { + load( + source: MobileFilePreviewSource, + options?: HostFilePreviewLoadOptions + ): Promise + saveTerminalArtifact( + source: MobileTerminalArtifactPreviewSource, + content: string, + options?: HostFilePreviewSaveOptions + ): Promise + reconnect(): Promise + openExternalUrl(url: string): Promise +} diff --git a/mobile/src/files/native-host-file-explorer-operations.ts b/mobile/src/files/native-host-file-explorer-operations.ts new file mode 100644 index 000000000000..50b74b37f74f --- /dev/null +++ b/mobile/src/files/native-host-file-explorer-operations.ts @@ -0,0 +1,55 @@ +import type { RpcClient } from '../transport/rpc-client' +import { isMobileMethodUnavailableError, type LegacyFilesListResult } from './file-list-fallback' +import type { + HostFileExplorerDirectoryResult, + HostFileExplorerOperations +} from './host-file-explorer-operations' +import type { MobileDirEntry } from './file-tree' + +export function nativeHostFileExplorerOperations( + client: RpcClient, + reconnect: () => Promise +): HostFileExplorerOperations { + return { + async readDirectory(workspaceId, relativePath) { + const response = await client.sendRequest('files.readDir', { + worktree: `id:${workspaceId}`, + relativePath + }) + if (response.ok) { + return { + kind: 'directory', + entries: response.result as MobileDirEntry[], + truncated: false + } + } + if ( + relativePath === '' && + isMobileMethodUnavailableError(response.error?.code, response.error?.message) + ) { + return readLegacyFileList(client, workspaceId, response.error?.message) + } + throw new Error(response.error?.message || 'Unable to load files') + }, + reconnect + } +} + +async function readLegacyFileList( + client: RpcClient, + workspaceId: string, + readDirectoryMessage: string | undefined +): Promise { + const response = await client.sendRequest('files.list', { + worktree: `id:${workspaceId}` + }) + if (!response.ok) { + throw new Error(response.error?.message || readDirectoryMessage || 'Unable to load files') + } + const result = response.result as LegacyFilesListResult + return { + kind: 'legacy-list', + files: result.files, + truncated: result.truncated + } +} diff --git a/mobile/src/files/native-host-file-operations.ts b/mobile/src/files/native-host-file-operations.ts new file mode 100644 index 000000000000..de86faa51341 --- /dev/null +++ b/mobile/src/files/native-host-file-operations.ts @@ -0,0 +1,14 @@ +import type { RpcClient } from '../transport/rpc-client' +import type { HostFileOperations } from './host-file-operations' +import { nativeHostFileExplorerOperations } from './native-host-file-explorer-operations' +import { nativeHostFilePreviewOperations } from './native-host-file-preview-operations' + +export function nativeHostFileOperations( + client: RpcClient, + reconnect: () => Promise +): HostFileOperations { + return { + explorer: nativeHostFileExplorerOperations(client, reconnect), + preview: nativeHostFilePreviewOperations(client, reconnect) + } +} diff --git a/mobile/src/files/native-host-file-preview-operations.ts b/mobile/src/files/native-host-file-preview-operations.ts new file mode 100644 index 000000000000..237ed1486adf --- /dev/null +++ b/mobile/src/files/native-host-file-preview-operations.ts @@ -0,0 +1,25 @@ +import { nativeDeviceOperations } from '../device/native-device-operations' +import type { RpcClient } from '../transport/rpc-client' +import type { HostFilePreviewOperations } from './host-file-preview-operations' +import { + loadMobileFilePreview, + saveMobileTerminalArtifactPreview +} from './mobile-file-preview-request' + +export function nativeHostFilePreviewOperations( + client: RpcClient, + reconnect: () => Promise +): HostFilePreviewOperations { + return { + load(source, options) { + return loadMobileFilePreview(client, source, undefined, options) + }, + saveTerminalArtifact(source, content, options) { + return saveMobileTerminalArtifactPreview(client, source, content, options) + }, + reconnect, + openExternalUrl(url) { + return nativeDeviceOperations.openExternalUrl(url) + } + } +} diff --git a/mobile/src/session/default-host-session-browser-operations.ts b/mobile/src/session/default-host-session-browser-operations.ts new file mode 100644 index 000000000000..e311e205ae10 --- /dev/null +++ b/mobile/src/session/default-host-session-browser-operations.ts @@ -0,0 +1,9 @@ +import type { RpcClient } from '../transport/rpc-client' +import type { HostSessionBrowserOperations } from './host-session-browser-operations' +import { nativeHostSessionBrowserOperations } from './native-host-session-browser-operations' + +export function defaultHostSessionBrowserOperations( + client: RpcClient +): HostSessionBrowserOperations { + return nativeHostSessionBrowserOperations(client) +} diff --git a/mobile/src/session/default-host-session-file-operations.ts b/mobile/src/session/default-host-session-file-operations.ts new file mode 100644 index 000000000000..2cfee5a1b910 --- /dev/null +++ b/mobile/src/session/default-host-session-file-operations.ts @@ -0,0 +1,7 @@ +import type { RpcClient } from '../transport/rpc-client' +import type { HostSessionFileOperations } from './host-session-file-operations' +import { nativeHostSessionFileOperations } from './native-host-session-file-operations' + +export function defaultHostSessionFileOperations(client: RpcClient): HostSessionFileOperations { + return nativeHostSessionFileOperations(client) +} diff --git a/mobile/src/session/default-host-session-markdown-operations.ts b/mobile/src/session/default-host-session-markdown-operations.ts new file mode 100644 index 000000000000..4c464b8b2043 --- /dev/null +++ b/mobile/src/session/default-host-session-markdown-operations.ts @@ -0,0 +1,9 @@ +import type { RpcClient } from '../transport/rpc-client' +import type { HostSessionMarkdownOperations } from './host-session-markdown-operations' +import { nativeHostSessionMarkdownOperations } from './native-host-session-markdown-operations' + +export function defaultHostSessionMarkdownOperations( + client: RpcClient +): HostSessionMarkdownOperations { + return nativeHostSessionMarkdownOperations(client) +} diff --git a/mobile/src/session/default-host-session-native-chat-operations.ts b/mobile/src/session/default-host-session-native-chat-operations.ts new file mode 100644 index 000000000000..e05c089913e7 --- /dev/null +++ b/mobile/src/session/default-host-session-native-chat-operations.ts @@ -0,0 +1,9 @@ +import type { RpcClient } from '../transport/rpc-client' +import type { HostSessionNativeChatOperations } from './host-session-native-chat-operations' +import { nativeHostSessionNativeChatOperations } from './native-host-session-native-chat-operations' + +export function defaultHostSessionNativeChatOperations( + client: RpcClient +): HostSessionNativeChatOperations { + return nativeHostSessionNativeChatOperations(client) +} diff --git a/mobile/src/session/default-host-session-operations.ts b/mobile/src/session/default-host-session-operations.ts new file mode 100644 index 000000000000..e21c1c9659df --- /dev/null +++ b/mobile/src/session/default-host-session-operations.ts @@ -0,0 +1,7 @@ +import type { RpcClient } from '../transport/rpc-client' +import type { HostSessionOperations } from './host-session-operations' +import { nativeHostSessionOperations } from './native-host-session-operations' + +export function defaultHostSessionOperations(client: RpcClient): HostSessionOperations { + return nativeHostSessionOperations(client) +} diff --git a/mobile/src/session/default-host-session-quick-command-operations.ts b/mobile/src/session/default-host-session-quick-command-operations.ts new file mode 100644 index 000000000000..a67930a756da --- /dev/null +++ b/mobile/src/session/default-host-session-quick-command-operations.ts @@ -0,0 +1,9 @@ +import type { RpcClient } from '../transport/rpc-client' +import type { HostSessionQuickCommandOperations } from './host-session-quick-command-operations' +import { nativeHostSessionQuickCommandOperations } from './native-host-session-quick-command-operations' + +export function defaultHostSessionQuickCommandOperations( + client: RpcClient +): HostSessionQuickCommandOperations { + return nativeHostSessionQuickCommandOperations(client) +} diff --git a/mobile/src/session/default-host-session-tab-operations.ts b/mobile/src/session/default-host-session-tab-operations.ts new file mode 100644 index 000000000000..c29447a29dbf --- /dev/null +++ b/mobile/src/session/default-host-session-tab-operations.ts @@ -0,0 +1,7 @@ +import type { RpcClient } from '../transport/rpc-client' +import type { HostSessionTabOperations } from './host-session-tab-operations' +import { nativeHostSessionTabOperations } from './native-host-session-tab-operations' + +export function defaultHostSessionTabOperations(client: RpcClient): HostSessionTabOperations { + return nativeHostSessionTabOperations(client) +} diff --git a/mobile/src/session/default-host-session-terminal-file-operations.ts b/mobile/src/session/default-host-session-terminal-file-operations.ts new file mode 100644 index 000000000000..796f3f583e36 --- /dev/null +++ b/mobile/src/session/default-host-session-terminal-file-operations.ts @@ -0,0 +1,9 @@ +import type { RpcClient } from '../transport/rpc-client' +import type { HostSessionTerminalFileOperations } from './host-session-terminal-file-operations' +import { nativeHostSessionTerminalFileOperations } from './native-host-session-terminal-file-operations' + +export function defaultHostSessionTerminalFileOperations( + client: RpcClient +): HostSessionTerminalFileOperations { + return nativeHostSessionTerminalFileOperations(client) +} diff --git a/mobile/src/session/default-host-session-terminal-operations.ts b/mobile/src/session/default-host-session-terminal-operations.ts new file mode 100644 index 000000000000..a4827e450060 --- /dev/null +++ b/mobile/src/session/default-host-session-terminal-operations.ts @@ -0,0 +1,9 @@ +import type { RpcClient } from '../transport/rpc-client' +import type { HostSessionTerminalOperations } from './host-session-terminal-operations' +import { nativeHostSessionTerminalOperations } from './native-host-session-terminal-operations' + +export function defaultHostSessionTerminalOperations( + client: RpcClient +): HostSessionTerminalOperations { + return nativeHostSessionTerminalOperations(client) +} diff --git a/mobile/src/session/github-pr-mutations.ts b/mobile/src/session/github-pr-mutations.ts index bd1d9c423b90..e7327fc76b55 100644 --- a/mobile/src/session/github-pr-mutations.ts +++ b/mobile/src/session/github-pr-mutations.ts @@ -1,5 +1,5 @@ import type { GitHubPRMergeMethod } from '../../../src/shared/github/pull-request-types' -import type { RpcClient } from '../transport/rpc-client' +import type { RpcRequestSender } from '../transport/rpc-client' import { buildGithubPrParams, githubPrRepoSlugParam, type GitHubPrRepoSlug } from './github-pr-rpc' // Mutation wrappers for the github.* PR surface, split out so github-pr-rpc.ts @@ -7,7 +7,9 @@ import { buildGithubPrParams, githubPrRepoSlugParam, type GitHubPrRepoSlug } fro // return a host-status outcome (the host mutations all return // `{ ok: true } | { ok: false; error: string }`). -export type GitHubPrMutationOutcome = { ok: true } | { ok: false; error: string } +// `comment` is the server-created entry when the host publishes one; callers that echo the +// comment optimistically need its real id, not a locally minted stub. +export type GitHubPrMutationOutcome = { ok: true; comment?: unknown } | { ok: false; error: string } // Sends a request whose host result is a bare boolean (not the `{ ok }` envelope), // normalizing a transport throw into a failure so the raw-boolean callers below @@ -15,7 +17,7 @@ export type GitHubPrMutationOutcome = { ok: true } | { ok: false; error: string type RawResult = { ok: true; result: unknown } | { ok: false; error: string } async function sendRaw( - client: Pick, + client: RpcRequestSender, method: string, params: Record ): Promise { @@ -50,20 +52,24 @@ function extractMutationError(error: unknown, method: string): string { // `response.ok === false` (timeout/connection) is also a failure. Both collapse // into one outcome the action hook classifies via classifyPrSidebarFailure. async function sendGithubPrMutation( - client: Pick, + client: RpcRequestSender, method: string, - params: Record + params: Record, + options?: { timeoutMs?: number } ): Promise { try { - const response = await client.sendRequest(method, params) + // Keep the two-argument call shape when no timeout is requested. + const response = options + ? await client.sendRequest(method, params, options) + : await client.sendRequest(method, params) if (!response.ok) { return { ok: false, error: response.error?.message || `Request failed: ${method}` } } const result = response.result if (result && typeof result === 'object' && 'ok' in result) { - const r = result as { ok: boolean; error?: unknown } + const r = result as { ok: boolean; error?: unknown; comment?: unknown } if (r.ok === true) { - return { ok: true } + return { ok: true, comment: r.comment } } return { ok: false, error: extractMutationError(r.error, method) } } @@ -77,9 +83,10 @@ async function sendGithubPrMutation( } export async function fetchMergePR( - client: Pick, + client: RpcRequestSender, worktreeId: string, - args: { prNumber: number; method?: GitHubPRMergeMethod; prRepo?: GitHubPrRepoSlug | null } + args: { prNumber: number; method?: GitHubPRMergeMethod; prRepo?: GitHubPrRepoSlug | null }, + options?: { timeoutMs?: number } ): Promise { const params: Record = { prNumber: args.prNumber } if (args.method) { @@ -88,7 +95,8 @@ export async function fetchMergePR( return sendGithubPrMutation( client, 'github.mergePR', - buildGithubPrParams('github.mergePR', worktreeId, params, { prRepo: args.prRepo }) + buildGithubPrParams('github.mergePR', worktreeId, params, { prRepo: args.prRepo }), + options ) } @@ -96,7 +104,7 @@ export async function fetchMergePR( // which sendGithubPrMutation reads via its "no structured status" success branch // only when not boolean — so handle the boolean explicitly like resolveReviewThread. export async function fetchUpdatePRTitle( - client: Pick, + client: RpcRequestSender, worktreeId: string, args: { prNumber: number; title: string; prRepo?: GitHubPrRepoSlug | null } ): Promise { @@ -118,7 +126,7 @@ export async function fetchUpdatePRTitle( } export async function fetchSetPRAutoMerge( - client: Pick, + client: RpcRequestSender, worktreeId: string, args: { prNumber: number @@ -139,7 +147,7 @@ export async function fetchSetPRAutoMerge( } export async function fetchUpdatePRState( - client: Pick, + client: RpcRequestSender, worktreeId: string, args: { prNumber: number; state: 'open' | 'closed'; prRepo?: GitHubPrRepoSlug | null } ): Promise { @@ -156,7 +164,7 @@ export async function fetchUpdatePRState( } export async function fetchRequestPRReviewers( - client: Pick, + client: RpcRequestSender, worktreeId: string, args: { prNumber: number; reviewers: string[]; prRepo?: GitHubPrRepoSlug | null } ): Promise { @@ -173,7 +181,7 @@ export async function fetchRequestPRReviewers( } export async function fetchRemovePRReviewers( - client: Pick, + client: RpcRequestSender, worktreeId: string, args: { prNumber: number; reviewers: string[]; prRepo?: GitHubPrRepoSlug | null } ): Promise { @@ -193,7 +201,7 @@ export async function fetchRemovePRReviewers( // (`{ ok, comment } | { ok:false, error }`), which sendGithubPrMutation reads via // its `ok in result` branch. We refetch afterward, so the returned comment is unused. export async function fetchAddPRReviewCommentReply( - client: Pick, + client: RpcRequestSender, worktreeId: string, args: { prNumber: number @@ -228,16 +236,23 @@ export async function fetchAddPRReviewCommentReply( ) } -// Add a root conversation comment to the PR. Host returns GitHubCommentResult. +// Add a root conversation comment to a PR or an issue. Host returns GitHubCommentResult. export async function fetchAddIssueComment( - client: Pick, + client: RpcRequestSender, worktreeId: string, - args: { prNumber: number; body: string; prRepo?: GitHubPrRepoSlug | null } + args: { + prNumber: number + body: string + prRepo?: GitHubPrRepoSlug | null + // Why: the host addresses the comment by this; an issue row sent as 'pr' targets the + // wrong conversation. PR call sites omit it. + type?: 'issue' | 'pr' + } ): Promise { const params: Record = { number: args.prNumber, body: args.body, - type: 'pr' + type: args.type ?? 'pr' } return sendGithubPrMutation( client, @@ -250,7 +265,7 @@ export async function fetchAddIssueComment( // the matching GraphQL mutation). Unlike the comment mutations, the host returns a // bare boolean, so a falsy result is a failure rather than the "no status" success. export async function fetchResolveReviewThread( - client: Pick, + client: RpcRequestSender, worktreeId: string, args: { threadId: string; resolve: boolean; prRepo?: GitHubPrRepoSlug | null } ): Promise { @@ -283,7 +298,7 @@ export async function fetchResolveReviewThread( // directly rather than via buildGithubPrParams. Host returns the // GitHubProjectMutationResult `{ ok }` envelope sendGithubPrMutation reads. export async function fetchUpdateIssueComment( - client: Pick, + client: RpcRequestSender, args: { owner: string; repo: string; host?: string; commentId: number; body: string } ): Promise { return sendGithubPrMutation(client, 'github.project.updateIssueCommentBySlug', { @@ -295,7 +310,7 @@ export async function fetchUpdateIssueComment( // Delete a root conversation (issue) comment. Slug-addressed like the edit wrapper. export async function fetchDeleteIssueComment( - client: Pick, + client: RpcRequestSender, args: { owner: string; repo: string; host?: string; commentId: number } ): Promise { return sendGithubPrMutation(client, 'github.project.deleteIssueCommentBySlug', { @@ -305,14 +320,15 @@ export async function fetchDeleteIssueComment( } export async function fetchRerunPRChecks( - client: Pick, + client: RpcRequestSender, worktreeId: string, args: { prNumber: number headSha?: string | null failedOnly?: boolean prRepo?: GitHubPrRepoSlug | null - } + }, + options?: { timeoutMs?: number } ): Promise { const params: Record = { prNumber: args.prNumber } if (args.failedOnly !== undefined) { @@ -324,6 +340,7 @@ export async function fetchRerunPRChecks( return sendGithubPrMutation( client, 'github.rerunPRChecks', - buildGithubPrParams('github.rerunPRChecks', worktreeId, params, { prRepo: args.prRepo }) + buildGithubPrParams('github.rerunPRChecks', worktreeId, params, { prRepo: args.prRepo }), + options ) } diff --git a/mobile/src/session/host-session-browser-operations.ts b/mobile/src/session/host-session-browser-operations.ts new file mode 100644 index 000000000000..22954d9cb4ea --- /dev/null +++ b/mobile/src/session/host-session-browser-operations.ts @@ -0,0 +1,77 @@ +import type { BrowserPointerModifier } from '../browser/MobileBrowserPointerModifiers' +import type { MobileBrowserScreencastRequest } from '../browser/browser-screencast-request' +import type { + BrowserScreencastFrame, + BrowserScreencastFrameMetadata +} from '../transport/browser-screencast-protocol' + +export type HostSessionBrowserTarget = { + workspaceId: string + pageId: string +} + +export type HostSessionBrowserEvent = + | { + type: 'ready' | 'navigation' + tab: { + url: string + title: string + canGoBack: boolean + canGoForward: boolean + } + } + | { type: 'end' } + | { type: 'dialog'; dialogType: string; message: string } + | { type: 'dialogClosed' } + | { type: 'error'; message: string } + +export type HostSessionBrowserOperations = { + subscribe( + target: HostSessionBrowserTarget, + request: MobileBrowserScreencastRequest, + listener: { + onEvent: (event: HostSessionBrowserEvent) => void + onFrame: (frame: BrowserScreencastFrame) => void + onError: (error: Error) => void + } + ): () => void + navigate(target: HostSessionBrowserTarget, url: string): Promise<{ url: string }> + scroll( + target: HostSessionBrowserTarget, + point: { x: number; y: number }, + delta: { dx: number; dy: number } + ): Promise + click( + target: HostSessionBrowserTarget, + point: { x: number; y: number }, + button: 'left' | 'right', + modifiers: BrowserPointerModifier[], + radius?: number + ): Promise + insertText(target: HostSessionBrowserTarget, text: string): Promise + keypress( + target: HostSessionBrowserTarget, + key: 'Enter' | 'Backspace' | 'Tab' | 'Escape' + ): Promise + dialog(target: HostSessionBrowserTarget, action: 'accept' | 'dismiss'): Promise + back(target: HostSessionBrowserTarget): Promise + forward(target: HostSessionBrowserTarget): Promise + reload(target: HostSessionBrowserTarget): Promise +} + +export function hostSessionBrowserFrameMetadataEqual( + left: BrowserScreencastFrameMetadata, + right: BrowserScreencastFrameMetadata +): boolean { + return ( + left.offsetTop === right.offsetTop && + left.pageScaleFactor === right.pageScaleFactor && + left.deviceWidth === right.deviceWidth && + left.deviceHeight === right.deviceHeight && + left.imageWidth === right.imageWidth && + left.imageHeight === right.imageHeight && + left.scrollOffsetX === right.scrollOffsetX && + left.scrollOffsetY === right.scrollOffsetY && + left.timestamp === right.timestamp + ) +} diff --git a/mobile/src/session/host-session-file-operations.ts b/mobile/src/session/host-session-file-operations.ts new file mode 100644 index 000000000000..a60c19652ad8 --- /dev/null +++ b/mobile/src/session/host-session-file-operations.ts @@ -0,0 +1,5 @@ +import type { MobileFileTabDoc, MobileFileTabDocRequest } from '../files/mobile-file-tab-doc' + +export type HostSessionFileOperations = { + readTab(request: MobileFileTabDocRequest): Promise +} diff --git a/mobile/src/session/host-session-markdown-operations.ts b/mobile/src/session/host-session-markdown-operations.ts new file mode 100644 index 000000000000..300ab224e551 --- /dev/null +++ b/mobile/src/session/host-session-markdown-operations.ts @@ -0,0 +1,26 @@ +import type { MarkdownDocState } from './mobile-session-route-types' + +export type HostSessionMarkdownTarget = { + workspaceId: string + tabId: string + relativePath: string +} + +export type HostSessionMarkdownReadRequest = HostSessionMarkdownTarget & { + tabIsDirty: boolean +} + +export type HostSessionMarkdownSaveRequest = HostSessionMarkdownTarget & { + content: string + baseVersion: string +} + +export type HostSessionMarkdownOperations = { + readTab( + request: HostSessionMarkdownReadRequest + ): Promise> + saveTab(request: HostSessionMarkdownSaveRequest): Promise<{ + content: string + baseVersion: string + }> +} diff --git a/mobile/src/session/host-session-native-chat-operations.ts b/mobile/src/session/host-session-native-chat-operations.ts new file mode 100644 index 000000000000..2b7236d4ceb4 --- /dev/null +++ b/mobile/src/session/host-session-native-chat-operations.ts @@ -0,0 +1,79 @@ +import type { + NativeChatMessage, + NativeChatTurnLifecycle +} from '../../../src/shared/native-chat-types' +import type { MobileNativeChatSendOutcome } from './mobile-native-chat-send' +import type { MobileNativeChatStreamFrame } from './mobile-native-chat-stream-frame' +import type { MobileImageSource } from './mobile-image-source-picker' + +export type HostSessionNativeChatTarget = { + workspaceId: string + agent: string + sessionId: string + transcriptPath: string | null + terminalId: string | null + clientId: string | null +} + +export type HostSessionNativeChatReadResult = + | { + messages: NativeChatMessage[] + hasMore?: boolean + beforeOffset?: number + lifecycle?: NativeChatTurnLifecycle + } + | { error: string } + +export type HostSessionNativeChatImageAttachment = { + reference: string + previewUri: string +} + +export type HostSessionNativeChatImageAttachResult = + | { status: 'accepted'; attachment: HostSessionNativeChatImageAttachment } + | { status: 'cancelled' | 'permission-denied' | 'too-large' } + +export type HostSessionNativeChatOperations = { + /** Whether the serving host can read this workspace's agent transcripts. */ + readability(workspaceId: string): Promise + subscribe( + target: HostSessionNativeChatTarget, + limit: number, + onEvent: (event: MobileNativeChatStreamFrame) => void, + onError: () => void + ): () => void + read( + target: HostSessionNativeChatTarget, + limit: number, + beforeOffset?: number + ): Promise + sendMessage( + target: HostSessionNativeChatTarget, + text: string, + deadline?: number, + clearInputFirst?: boolean, + resolvedLaunchDraft?: { text: string; createdAt: number }, + typeCommand?: boolean + ): Promise + prepareCommit(target: HostSessionNativeChatTarget, deadline?: number): Promise + respond( + target: HostSessionNativeChatTarget, + text: string, + enter: boolean, + deadline?: number + ): Promise + stop(target: HostSessionNativeChatTarget, deadline?: number): Promise + attachImage?( + target: HostSessionNativeChatTarget, + source: MobileImageSource + ): Promise + pasteImages?( + target: HostSessionNativeChatTarget, + references: readonly string[], + deadline?: number, + followedByText?: boolean + ): Promise + releaseImages?(target: HostSessionNativeChatTarget, references: readonly string[]): Promise + searchFiles(target: HostSessionNativeChatTarget, query: string): Promise + openFile(target: HostSessionNativeChatTarget, pathText: string): Promise +} diff --git a/mobile/src/session/host-session-operations.ts b/mobile/src/session/host-session-operations.ts new file mode 100644 index 000000000000..da3ceca8ed4a --- /dev/null +++ b/mobile/src/session/host-session-operations.ts @@ -0,0 +1,21 @@ +import type { HostSessionBrowserOperations } from './host-session-browser-operations' +import type { HostSessionFileOperations } from './host-session-file-operations' +import type { HostSessionMarkdownOperations } from './host-session-markdown-operations' +import type { HostSessionNativeChatOperations } from './host-session-native-chat-operations' +import type { HostSessionQuickCommandOperations } from './host-session-quick-command-operations' +import type { HostSessionTabOperations } from './host-session-tab-operations' +import type { HostSessionTerminalFileOperations } from './host-session-terminal-file-operations' +import type { HostSessionTerminalOperations } from './host-session-terminal-operations' + +/** Everything the session screen asks a host for, grouped by concern so a screen takes one prop + * and a provider is built once. Each namespace keeps its own contract file. */ +export type HostSessionOperations = { + tab: HostSessionTabOperations + terminal: HostSessionTerminalOperations + terminalFile: HostSessionTerminalFileOperations + file: HostSessionFileOperations + markdown: HostSessionMarkdownOperations + quickCommand: HostSessionQuickCommandOperations + browser: HostSessionBrowserOperations + nativeChat: HostSessionNativeChatOperations +} diff --git a/mobile/src/session/host-session-quick-command-operations.ts b/mobile/src/session/host-session-quick-command-operations.ts new file mode 100644 index 000000000000..9e0022f934d2 --- /dev/null +++ b/mobile/src/session/host-session-quick-command-operations.ts @@ -0,0 +1,25 @@ +import type { + TerminalQuickCommand, + TerminalQuickCommandScope +} from '../../../src/shared/terminal-quick-command-types' +import type { TerminalQuickCommandMutation } from '../terminal/quick-commands' + +export type HostSessionQuickCommandSnapshot = { + commands: TerminalQuickCommand[] + totalCount: number + repoId: string | null +} + +export type HostSessionQuickCommandOperations = { + snapshot(workspaceId: string, signal?: AbortSignal): Promise + mutate( + workspaceId: string, + mutation: TerminalQuickCommandMutation + ): Promise +} + +export function explicitQuickCommandScope( + scope: TerminalQuickCommandScope | undefined +): TerminalQuickCommandScope { + return scope?.type === 'repo' ? { type: 'repo', repoId: scope.repoId } : { type: 'global' } +} diff --git a/mobile/src/session/host-session-runtime-capabilities.ts b/mobile/src/session/host-session-runtime-capabilities.ts new file mode 100644 index 000000000000..201512cde6d1 --- /dev/null +++ b/mobile/src/session/host-session-runtime-capabilities.ts @@ -0,0 +1,17 @@ +export type HostSessionRuntimeCapabilities = { + browserScreencastSupported: boolean + agentHistorySupported: boolean + quickCommandsSupported: boolean + terminalQueryReplyInputSupported: boolean +} + +export function projectHostSessionRuntimeCapabilities( + capabilities: readonly string[] +): HostSessionRuntimeCapabilities { + return { + browserScreencastSupported: capabilities.includes('browser.screencast.v1'), + agentHistorySupported: capabilities.includes('aiVault.v1'), + quickCommandsSupported: capabilities.includes('terminal.quick-commands.v1'), + terminalQueryReplyInputSupported: capabilities.includes('terminal.query-reply-input.v1') + } +} diff --git a/mobile/src/session/host-session-tab-operations.ts b/mobile/src/session/host-session-tab-operations.ts new file mode 100644 index 000000000000..8b8418ff80ab --- /dev/null +++ b/mobile/src/session/host-session-tab-operations.ts @@ -0,0 +1,37 @@ +import type { SessionTabsResult } from './mobile-session-route-types' +import type { HostSessionRuntimeCapabilities } from './host-session-runtime-capabilities' +import type { MobileNewTabAgentOption } from './mobile-new-tab-agent-options' + +export type HostSessionTabCloseResult = + | { outcome: 'closed' } + | { outcome: 'refused'; reason: string | null } + +export type HostSessionQuickCommandLaunchResult = { + snapshot: SessionTabsResult + tabId: string + initialInput: { text: string; enter: false; successToast: string } | null +} + +export type HostSessionTabOperations = { + streamFirstStartup?: boolean + runtimeCapabilities(): Promise + snapshot(workspaceId: string): Promise + subscribe( + workspaceId: string, + onSnapshot: (snapshot: SessionTabsResult) => void, + onError: () => void + ): () => void + agentOptions(workspaceId: string): Promise + createBlank(workspaceId: string): Promise + createAgent( + workspaceId: string, + agent: MobileNewTabAgentOption['agent'] + ): Promise + createQuickCommand?( + workspaceId: string, + commandId: string + ): Promise + createBrowser(workspaceId: string, url: string): Promise<{ browserPageId: string }> + activate(workspaceId: string, tabId: string, leafId?: string): Promise + close(workspaceId: string, tabId: string): Promise +} diff --git a/mobile/src/session/host-session-terminal-file-operations.ts b/mobile/src/session/host-session-terminal-file-operations.ts new file mode 100644 index 000000000000..fed85bebda72 --- /dev/null +++ b/mobile/src/session/host-session-terminal-file-operations.ts @@ -0,0 +1,41 @@ +import type { RuntimeNativeChatFileContext } from '../../../src/shared/runtime-types' + +export type HostSessionTerminalFileTarget = + | { + kind: 'worktree-file' + relativePath: string + localAbsolutePath: string | null + workspaceId?: string + } + | { + kind: 'native-artifact' + absolutePath: string + grantId: string + workspaceId?: string + } + | { + kind: 'web-artifact' + /** The terminal text the desktop re-resolves for every chunk read. */ + pathText: string + displayName: string + previewKind: 'text' | 'raster' + workspaceId?: string + } + +export type HostSessionTerminalFileResolveRequest = { + workspaceId: string + tabId: string + terminalHandle: string | null + pathText: string + cwd: string | null + nativeChatContext: RuntimeNativeChatFileContext | null + line: number | null + column: number | null +} + +export type HostSessionTerminalFileOperations = { + resolveTerminalPath( + request: HostSessionTerminalFileResolveRequest + ): Promise + openWorktreeFile(workspaceId: string, relativePath: string): Promise +} diff --git a/mobile/src/session/host-session-terminal-operations.ts b/mobile/src/session/host-session-terminal-operations.ts new file mode 100644 index 000000000000..6457df719cd2 --- /dev/null +++ b/mobile/src/session/host-session-terminal-operations.ts @@ -0,0 +1,81 @@ +import type { TerminalOscLinkRange } from '../../../src/shared/terminal-osc-link-ranges' + +export type HostSessionTerminalData = string | Uint8Array + +export type HostSessionTerminalStreamEvent = + | { + type: 'subscribed' + cols?: number + rows?: number + } + | { + type: 'scrollback' + cols: number + rows: number + serialized: HostSessionTerminalData + preserveScroll?: boolean + throughSequence?: number + displayMode?: 'auto' | 'desktop' | 'phone' + oscLinks?: TerminalOscLinkRange[] + seq?: number + } + | { + type: 'data' + chunk: HostSessionTerminalData + throughSequence?: number + seq?: number + } + | { + type: 'resized' + cols: number + rows: number + serialized?: HostSessionTerminalData + throughSequence?: number + displayMode?: 'auto' | 'desktop' | 'phone' + oscLinks?: TerminalOscLinkRange[] + seq?: number + } + | { + type: 'metadata' + displayMode?: 'auto' | 'desktop' | 'phone' + cwd?: string + } + | { type: 'end' | 'error' } + +export type HostSessionTerminalSubscribeArgs = { + workspaceId: string + terminalId: string + clientId: string | null + viewport: { cols: number; rows: number } | null | undefined + visible: boolean + capabilities: { terminalBinaryStream: 1; mobileInputLeaseOnly?: 1 } +} + +export type HostSessionTerminalOperations = { + subscribe( + args: HostSessionTerminalSubscribeArgs, + onEvent: (event: HostSessionTerminalStreamEvent) => void, + onError: () => void + ): () => void + acknowledge(terminalId: string, throughSequence: number): void + sendInput( + terminalId: string, + text: string, + enter: boolean, + clientId: string | null + ): Promise + sendQueryReply( + terminalId: string, + bytes: string, + clientId: string | null, + hostSupportsQueryReply: boolean + ): Promise + setDisplayMode( + terminalId: string, + mode: 'auto' | 'desktop', + viewport: { cols: number; rows: number } | null, + clientId: string | null + ): Promise + clear(terminalId: string): Promise + rename(terminalId: string, title: string, workspaceId: string): Promise +} diff --git a/mobile/src/session/mobile-native-chat-open-file.ts b/mobile/src/session/mobile-native-chat-open-file.ts index 3de6755b4b33..685be5689db6 100644 --- a/mobile/src/session/mobile-native-chat-open-file.ts +++ b/mobile/src/session/mobile-native-chat-open-file.ts @@ -1,4 +1,6 @@ import { splitFilePathLineSuffix } from '../components/markdown-file-path-detection' +import type { RuntimeTerminalPathResolution } from '../../../src/shared/runtime-types' +import type { RpcClient } from '../transport/rpc-client' import { openMobileFileTap, type FileTapSessionTab, @@ -28,3 +30,50 @@ export function openMobileNativeChatFileTap( column }) } + +export async function resolveMobileNativeChatWorktreePath(args: { + client: RpcClient + worktreeId: string + pathText: string + terminal: string | null +}): Promise { + try { + const response = await args.client.sendRequest('files.resolveTerminalPath', { + worktree: `id:${args.worktreeId}`, + pathText: args.pathText, + ...(args.terminal ? { terminal: args.terminal } : {}) + }) + if (!response.ok) { + return null + } + const resolved = response.result as RuntimeTerminalPathResolution + if (!resolved.exists || resolved.isDirectory) { + return null + } + return resolved.openTarget?.kind === 'worktree-file' + ? resolved.openTarget.relativePath + : (resolved.relativePath ?? null) + } catch { + return null + } +} + +export async function openMobileNativeChatFile(args: { + client: RpcClient + worktreeId: string + pathText: string + terminal: string | null +}): Promise { + const relativePath = await resolveMobileNativeChatWorktreePath(args) + if (!relativePath) { + return + } + try { + await args.client.sendRequest('files.open', { + worktree: `id:${args.worktreeId}`, + relativePath + }) + } catch { + // Best-effort open from transcript content. + } +} diff --git a/mobile/src/session/mobile-native-chat-send.ts b/mobile/src/session/mobile-native-chat-send.ts index 22c44f3eb84e..a61aee3c205a 100644 --- a/mobile/src/session/mobile-native-chat-send.ts +++ b/mobile/src/session/mobile-native-chat-send.ts @@ -10,11 +10,15 @@ type MobileTerminalClient = { type: 'mobile' } +// Clear a parked TUI launch draft before writing a mobile chat message. +const CLEAR_UNSUBMITTED_INPUT = '\x15' + type MobileNativeChatSendArgs = { client: RpcClient terminal: string text: string enter?: boolean + clearInputFirst?: boolean /** Exact host launch draft this submitting write resolves when accepted. */ resolvedLaunchDraft?: { text: string; createdAt: number } mobileClient?: MobileTerminalClient @@ -55,7 +59,7 @@ export async function sendMobileNativeChatMessageWithOutcome( 'terminal.send', { terminal: args.terminal, - text: args.text, + text: args.clearInputFirst ? `${CLEAR_UNSUBMITTED_INPUT}${args.text}` : args.text, enter: args.enter ?? true, ...(args.resolvedLaunchDraft ? { resolvedLaunchDraft: args.resolvedLaunchDraft } : {}), ...(args.mobileClient ? { client: args.mobileClient } : {}) diff --git a/mobile/src/session/native-host-session-browser-operations.ts b/mobile/src/session/native-host-session-browser-operations.ts new file mode 100644 index 000000000000..11f089f072a1 --- /dev/null +++ b/mobile/src/session/native-host-session-browser-operations.ts @@ -0,0 +1,178 @@ +import type { RpcClient } from '../transport/rpc-client' +import type { RpcSuccess } from '../transport/types' +import type { + HostSessionBrowserEvent, + HostSessionBrowserOperations, + HostSessionBrowserTarget +} from './host-session-browser-operations' + +export function nativeHostSessionBrowserOperations( + client: RpcClient +): HostSessionBrowserOperations { + return { + subscribe(target, request, listener) { + try { + return client.subscribe( + 'browser.screencast', + { ...nativeTarget(target), ...request }, + (event) => { + const presented = nativeBrowserEvent(event) + if (presented) { + listener.onEvent(presented) + } + }, + { onBinaryFrame: listener.onFrame } + ) + } catch (error) { + listener.onError(browserOperationError(error)) + return () => {} + } + }, + async navigate(target, url) { + const result = await requestResult( + client, + 'browser.goto', + { ...nativeTarget(target), url }, + 30_000 + ) + if (!isRecord(result) || typeof result.url !== 'string') { + throw new Error('Browser navigation failed') + } + return { url: result.url } + }, + async scroll(target, point, delta) { + await requestResult(client, 'browser.mouseMove', { ...nativeTarget(target), ...point }, 5_000) + await requestResult( + client, + 'browser.mouseWheel', + { ...nativeTarget(target), ...delta }, + 5_000 + ) + }, + async click(target, point, button, modifiers, radius) { + const click = await client.sendRequest( + 'browser.mouseClick', + { + ...nativeTarget(target), + ...point, + button, + modifiers, + ...(radius === undefined ? {} : { radius }) + }, + { timeoutMs: 5_000 } + ) + if (click.ok || modifiers.length > 0) { + return + } + await requestResult(client, 'browser.mouseMove', { ...nativeTarget(target), ...point }, 5_000) + await requestResult(client, 'browser.mouseDown', { ...nativeTarget(target), button }, 5_000) + await requestResult(client, 'browser.mouseUp', { ...nativeTarget(target), button }, 5_000) + }, + async insertText(target, text) { + await requestResult( + client, + 'browser.keyboardInsertText', + { ...nativeTarget(target), text }, + 5_000 + ) + }, + async keypress(target, key) { + await requestResult(client, 'browser.keypress', { ...nativeTarget(target), key }, 5_000) + }, + async dialog(target, action) { + await requestResult( + client, + action === 'accept' ? 'browser.dialogAccept' : 'browser.dialogDismiss', + nativeTarget(target), + 5_000 + ) + }, + async back(target) { + await requestResult(client, 'browser.back', nativeTarget(target)) + }, + async forward(target) { + await requestResult(client, 'browser.forward', nativeTarget(target)) + }, + async reload(target) { + await requestResult(client, 'browser.reload', nativeTarget(target)) + } + } +} + +function nativeTarget(target: HostSessionBrowserTarget): { worktree: string; page: string } { + return { worktree: `id:${target.workspaceId}`, page: target.pageId } +} + +async function requestResult( + client: RpcClient, + method: string, + payload: unknown, + timeoutMs = 15_000 +): Promise { + const response = await client.sendRequest(method, payload, { timeoutMs }) + if (!response.ok) { + throw new Error(response.error.message) + } + return (response as RpcSuccess).result +} + +function nativeBrowserEvent(value: unknown): HostSessionBrowserEvent | null { + if (!isRecord(value)) { + return null + } + if (value.type === 'ready') { + const tab = isRecord(value.tab) ? value.tab : {} + return { + type: 'ready', + tab: { + url: typeof tab.url === 'string' ? tab.url : 'about:blank', + title: typeof tab.title === 'string' ? tab.title : '', + canGoBack: tab.canGoBack === true, + canGoForward: tab.canGoForward === true + } + } + } + if (value.type === 'navigation') { + const tab = isRecord(value.tab) ? value.tab : {} + return { + type: 'navigation', + tab: { + url: typeof tab.url === 'string' ? tab.url : 'about:blank', + title: typeof tab.title === 'string' ? tab.title : '', + canGoBack: tab.canGoBack === true, + canGoForward: tab.canGoForward === true + } + } + } + if (value.type === 'end' || value.type === 'dialogClosed') { + return { type: value.type } + } + if (value.type === 'dialog') { + return { + type: 'dialog', + dialogType: typeof value.dialogType === 'string' ? value.dialogType : 'alert', + message: typeof value.message === 'string' ? value.message : 'Browser dialog' + } + } + if (value.type === 'error') { + const nested = isRecord(value.error) ? value.error : {} + return { + type: 'error', + message: + typeof value.message === 'string' + ? value.message + : typeof nested.message === 'string' + ? nested.message + : 'Browser stream failed.' + } + } + return null +} + +function browserOperationError(error: unknown): Error { + return error instanceof Error ? error : new Error('Browser command failed') +} + +function isRecord(value: unknown): value is Record { + return typeof value === 'object' && value !== null && !Array.isArray(value) +} diff --git a/mobile/src/session/native-host-session-file-operations.ts b/mobile/src/session/native-host-session-file-operations.ts new file mode 100644 index 000000000000..2b8e6a5fe5d3 --- /dev/null +++ b/mobile/src/session/native-host-session-file-operations.ts @@ -0,0 +1,11 @@ +import { resolveMobileFileTabDoc, type MobileFileTabDocRequest } from '../files/mobile-file-tab-doc' +import type { RpcClient } from '../transport/rpc-client' +import type { HostSessionFileOperations } from './host-session-file-operations' + +export function nativeHostSessionFileOperations(client: RpcClient): HostSessionFileOperations { + return { + readTab(request: MobileFileTabDocRequest) { + return resolveMobileFileTabDoc(client, request) + } + } +} diff --git a/mobile/src/session/native-host-session-markdown-operations.ts b/mobile/src/session/native-host-session-markdown-operations.ts new file mode 100644 index 000000000000..7bee9e7b3748 --- /dev/null +++ b/mobile/src/session/native-host-session-markdown-operations.ts @@ -0,0 +1,79 @@ +import type { RpcFailure, RpcSuccess } from '../transport/types' +import type { RpcClient } from '../transport/rpc-client' +import { + buildMarkdownDiskFallbackDoc, + shouldReadMarkdownFromDiskAfterReadTabFailure +} from './mobile-markdown-disk-fallback' +import type { + HostSessionMarkdownOperations, + HostSessionMarkdownReadRequest +} from './host-session-markdown-operations' + +export function nativeHostSessionMarkdownOperations( + client: RpcClient +): HostSessionMarkdownOperations { + return { + readTab: (request) => readNativeMarkdownTab(client, request), + saveTab: async (request) => { + const response = await client.sendRequest('markdown.saveTab', { + worktree: `id:${request.workspaceId}`, + tabId: request.tabId, + baseVersion: request.baseVersion, + content: request.content + }) + if (!response.ok) { + throw new Error((response as RpcFailure).error.message) + } + const result = (response as RpcSuccess).result as { content: string; version: string } + return { content: result.content, baseVersion: result.version } + } + } +} + +async function readNativeMarkdownTab( + client: RpcClient, + request: HostSessionMarkdownReadRequest +): ReturnType { + const response = await client.sendRequest('markdown.readTab', { + worktree: `id:${request.workspaceId}`, + tabId: request.tabId + }) + if (response.ok) { + const result = (response as RpcSuccess).result as { + content: string + version: string + isDirty: boolean + editable?: boolean + readOnlyReason?: string + } + return { + status: 'ready', + content: result.content, + localContent: result.content, + baseVersion: result.version, + isDirty: false, + editable: result.editable === true, + stale: result.isDirty, + readOnlyReason: result.readOnlyReason + } + } + if (!shouldReadMarkdownFromDiskAfterReadTabFailure(response as RpcFailure)) { + throw new Error((response as RpcFailure).error.message) + } + const fallback = await client.sendRequest('files.read', { + worktree: `id:${request.workspaceId}`, + relativePath: request.relativePath + }) + if (!fallback.ok) { + throw new Error('Unable to read markdown') + } + const result = (fallback as RpcSuccess).result as { + content: string + truncated: boolean + } + return buildMarkdownDiskFallbackDoc({ + content: result.content, + truncated: result.truncated, + tabIsDirty: request.tabIsDirty + }) +} diff --git a/mobile/src/session/native-host-session-native-chat-operations.test.ts b/mobile/src/session/native-host-session-native-chat-operations.test.ts new file mode 100644 index 000000000000..d9ee2dd0d4e5 --- /dev/null +++ b/mobile/src/session/native-host-session-native-chat-operations.test.ts @@ -0,0 +1,66 @@ +import { describe, expect, it, vi } from 'vitest' +import type { RpcClient } from '../transport/rpc-client' +import type { HostSessionNativeChatTarget } from './host-session-native-chat-operations' +import { nativeHostSessionNativeChatOperations } from './native-host-session-native-chat-operations' + +function target(overrides: Partial = {}): HostSessionNativeChatTarget { + return { + workspaceId: 'wt-1', + agent: 'claude', + sessionId: 'session-1', + transcriptPath: null, + terminalId: 'terminal-1', + clientId: 'device-1', + ...overrides + } +} + +function client(sendRequest: RpcClient['sendRequest']): RpcClient { + return { sendRequest } as unknown as RpcClient +} + +describe('native host session native chat operations', () => { + it('stops the agent with a bare Escape that cannot submit the input line', async () => { + const sendRequest = vi.fn().mockResolvedValue({ + ok: true, + result: { delivered: true } + }) + const operations = nativeHostSessionNativeChatOperations(client(sendRequest)) + + await operations.stop(target(), Date.now() + 15_000) + + expect(sendRequest).toHaveBeenCalledWith( + 'terminal.send', + expect.objectContaining({ text: String.fromCharCode(27), enter: false }), + expect.anything() + ) + }) + + it('keeps the legacy file inventory scoped to the workspace that produced it', async () => { + const sendRequest = vi.fn(async (method, params) => { + if (method === 'files.searchPaths') { + return { ok: false, error: { code: 'method_not_found', message: 'unsupported' } } + } + const worktree = (params as { worktree: string }).worktree + return { + ok: true, + result: { + files: + worktree === 'id:wt-1' + ? [{ relativePath: 'alpha/one.ts' }] + : [{ relativePath: 'beta/two.ts' }] + } + } + }) + const operations = nativeHostSessionNativeChatOperations(client(sendRequest)) + + await expect(operations.searchFiles(target(), 'o')).resolves.toEqual(['alpha/one.ts']) + // A second workspace must re-read; the first workspace's inventory is not its own. + await expect(operations.searchFiles(target({ workspaceId: 'wt-2' }), 'o')).resolves.toEqual([ + 'beta/two.ts' + ]) + // The first workspace still answers from its cached inventory. + await expect(operations.searchFiles(target(), 'o')).resolves.toEqual(['alpha/one.ts']) + expect(sendRequest.mock.calls.filter(([method]) => method === 'files.list')).toHaveLength(2) + }) +}) diff --git a/mobile/src/session/native-host-session-native-chat-operations.ts b/mobile/src/session/native-host-session-native-chat-operations.ts new file mode 100644 index 000000000000..198b1d53d1d5 --- /dev/null +++ b/mobile/src/session/native-host-session-native-chat-operations.ts @@ -0,0 +1,197 @@ +import type { RpcClient } from '../transport/rpc-client' +import { buildNativeChatSubscriptionId } from '../../../src/shared/native-chat-stream-unsubscribe' +import { isFloatingWorkspaceWorktreeId } from './floating-workspace' +import { isMobileNativeChatTranscriptReadable } from './mobile-native-chat-eligibility' +import { openMobileNativeChatFile } from './mobile-native-chat-open-file' +import { healMobileNativeChatStaleInput } from './mobile-native-chat-stale-input' +import { + sendMobileNativeChatMessageWithOutcome, + typeMobileNativeChatCommandWithOutcome, + type MobileNativeChatSendOutcome +} from './mobile-native-chat-send' +import { rankSuggestions } from './mobile-native-chat-autocomplete' +import { getRepoIdFromMobileWorktreeId } from './mobile-session-route-helpers' +import type { + HostSessionNativeChatOperations, + HostSessionNativeChatTarget +} from './host-session-native-chat-operations' + +const FILE_RESULT_LIMIT = 16 + +export function nativeHostSessionNativeChatOperations( + client: RpcClient +): HostSessionNativeChatOperations { + let searchSupported: boolean | null = null + // Why: the legacy full-inventory fallback is per workspace — one shared list makes + // `@` autocomplete in a second workspace suggest the first workspace's files. + const legacyPathsByWorkspace = new Map() + const legacyLoadByWorkspace = new Map>() + return { + async readability(workspaceId) { + if (isFloatingWorkspaceWorktreeId(workspaceId)) { + return true + } + const response = await client.sendRequest('repo.list') + const repos = response.ok + ? ((response.result as { repos?: { id: string; connectionId?: string | null }[] }).repos ?? + []) + : [] + const repo = repos.find( + (candidate) => candidate.id === getRepoIdFromMobileWorktreeId(workspaceId) + ) + return repo ? isMobileNativeChatTranscriptReadable(repo.connectionId ?? null) : false + }, + subscribe(target, limit, onEvent) { + return client.subscribe( + 'nativeChat.subscribe', + { + ...nativeChatReadParams(target, limit), + capabilities: { transcriptPending: 1 }, + subscriptionId: buildNativeChatSubscriptionId(target.agent, target.sessionId) + }, + (value) => onEvent(value as Parameters[0]) + ) + }, + async read(target, limit, beforeOffset) { + try { + const response = await client.sendRequest('nativeChat.readSession', { + ...nativeChatReadParams(target, limit), + ...(beforeOffset === undefined ? {} : { beforeOffset }) + }) + return response.ok + ? (response.result as Awaited>) + : { error: response.error.message } + } catch { + return { error: 'Transcript read failed' } + } + }, + sendMessage(target, text, deadline, clearInputFirst, resolvedLaunchDraft, typeCommand) { + if (typeCommand && target.terminalId) { + return typeMobileNativeChatCommandWithOutcome({ + client, + terminal: target.terminalId, + command: text, + resolvedLaunchDraft, + deadline, + ...(target.clientId + ? { mobileClient: { id: target.clientId, type: 'mobile' as const } } + : {}) + }) + } + return sendNative(target, text, true, client, deadline, clearInputFirst, resolvedLaunchDraft) + }, + prepareCommit(target, deadline) { + if (!target.terminalId) { + return Promise.resolve(false) + } + return healMobileNativeChatStaleInput({ + client, + terminal: target.terminalId, + deviceToken: target.clientId, + deadline + }) + }, + respond(target, text, enter, deadline) { + return sendNative(target, text, enter, client, deadline) + }, + stop(target, deadline) { + // Escape must not carry Return: the extra newline submits whatever the agent + // had parked on its input line. + return sendNative(target, escape(), false, client, deadline) + }, + async searchFiles(target, query) { + if (searchSupported !== false) { + const response = await client.sendRequest('files.searchPaths', { + worktree: `id:${target.workspaceId}`, + query, + limit: FILE_RESULT_LIMIT + }) + if (response.ok) { + searchSupported = true + return extractPaths(response.result) + } + if (response.error.code !== 'method_not_found') { + return [] + } + searchSupported = false + } + let legacyPaths = legacyPathsByWorkspace.get(target.workspaceId) + if (!legacyPaths) { + let legacyLoad = legacyLoadByWorkspace.get(target.workspaceId) + if (!legacyLoad) { + // Older hosts expose only the full inventory RPC; overlapping queries must + // share one slow local/SSH read. + legacyLoad = client + .sendRequest('files.list', { + worktree: `id:${target.workspaceId}` + }) + .then((response) => (response.ok ? extractPaths(response.result) : null)) + .finally(() => { + legacyLoadByWorkspace.delete(target.workspaceId) + }) + legacyLoadByWorkspace.set(target.workspaceId, legacyLoad) + } + const paths = await legacyLoad + if (!paths) { + return [] + } + legacyPaths = paths + legacyPathsByWorkspace.set(target.workspaceId, paths) + } + return rankSuggestions(legacyPaths, query, FILE_RESULT_LIMIT) + }, + openFile(target, pathText) { + return openMobileNativeChatFile({ + client, + worktreeId: target.workspaceId, + pathText, + terminal: target.terminalId + }) + } + } +} + +function nativeChatReadParams(target: HostSessionNativeChatTarget, limit: number) { + return { + agent: target.agent, + sessionId: target.sessionId, + limit, + ...(target.transcriptPath ? { transcriptPath: target.transcriptPath } : {}), + ...(target.terminalId ? { worktreeId: target.workspaceId, terminal: target.terminalId } : {}) + } +} + +function sendNative( + target: HostSessionNativeChatTarget, + text: string, + enter: boolean, + client: RpcClient, + deadline?: number, + clearInputFirst?: boolean, + resolvedLaunchDraft?: { text: string; createdAt: number } +): Promise { + if (!target.terminalId) { + return Promise.resolve('rejected') + } + return sendMobileNativeChatMessageWithOutcome({ + client, + terminal: target.terminalId, + text, + enter, + clearInputFirst, + resolvedLaunchDraft, + deadline, + ...(target.clientId ? { mobileClient: { id: target.clientId, type: 'mobile' as const } } : {}) + }) +} + +function escape(): string { + return String.fromCharCode(27) +} + +function extractPaths(result: unknown): string[] { + const files = (result as { files?: Array<{ relativePath?: string }> }).files ?? [] + return files + .map((file) => file.relativePath ?? '') + .filter((path): path is string => path.length > 0) +} diff --git a/mobile/src/session/native-host-session-operations.ts b/mobile/src/session/native-host-session-operations.ts new file mode 100644 index 000000000000..44aaee5bb379 --- /dev/null +++ b/mobile/src/session/native-host-session-operations.ts @@ -0,0 +1,23 @@ +import type { RpcClient } from '../transport/rpc-client' +import type { HostSessionOperations } from './host-session-operations' +import { nativeHostSessionBrowserOperations } from './native-host-session-browser-operations' +import { nativeHostSessionFileOperations } from './native-host-session-file-operations' +import { nativeHostSessionMarkdownOperations } from './native-host-session-markdown-operations' +import { nativeHostSessionNativeChatOperations } from './native-host-session-native-chat-operations' +import { nativeHostSessionQuickCommandOperations } from './native-host-session-quick-command-operations' +import { nativeHostSessionTabOperations } from './native-host-session-tab-operations' +import { nativeHostSessionTerminalFileOperations } from './native-host-session-terminal-file-operations' +import { nativeHostSessionTerminalOperations } from './native-host-session-terminal-operations' + +export function nativeHostSessionOperations(client: RpcClient): HostSessionOperations { + return { + tab: nativeHostSessionTabOperations(client), + terminal: nativeHostSessionTerminalOperations(client), + terminalFile: nativeHostSessionTerminalFileOperations(client), + file: nativeHostSessionFileOperations(client), + markdown: nativeHostSessionMarkdownOperations(client), + quickCommand: nativeHostSessionQuickCommandOperations(client), + browser: nativeHostSessionBrowserOperations(client), + nativeChat: nativeHostSessionNativeChatOperations(client) + } +} diff --git a/mobile/src/session/native-host-session-quick-command-operations.ts b/mobile/src/session/native-host-session-quick-command-operations.ts new file mode 100644 index 000000000000..ad5e4f85c340 --- /dev/null +++ b/mobile/src/session/native-host-session-quick-command-operations.ts @@ -0,0 +1,85 @@ +import { + parseNormalizedTerminalQuickCommands, + type TerminalQuickCommandMutation +} from '../terminal/quick-commands' +import type { RpcClient } from '../transport/rpc-client' +import { isLogicalClientCutoverError } from '../transport/stable-logical-rpc-client' +import type { + HostSessionQuickCommandOperations, + HostSessionQuickCommandSnapshot +} from './host-session-quick-command-operations' +import { isFloatingWorkspaceWorktreeId } from './floating-workspace' +import { getRepoIdFromMobileWorktreeId } from './mobile-session-route-helpers' + +const LOAD_CUTOVER_MAX_RETRIES = 5 + +export function nativeHostSessionQuickCommandOperations( + client: RpcClient +): HostSessionQuickCommandOperations { + return { + async snapshot(workspaceId, signal) { + return quickCommandSnapshot( + await quickCommandRequest(client, 'settings.getTerminalQuickCommands', undefined, signal), + workspaceId, + 'Failed to load quick commands' + ) + }, + async mutate(workspaceId, mutation) { + return quickCommandSnapshot( + await quickCommandRequest(client, 'settings.updateTerminalQuickCommands', { + mutation + }), + workspaceId, + 'Failed to save quick command' + ) + } + } +} + +async function quickCommandRequest( + client: RpcClient, + method: 'settings.getTerminalQuickCommands' | 'settings.updateTerminalQuickCommands', + params?: { mutation: TerminalQuickCommandMutation }, + signal?: AbortSignal +) { + for (let retry = 0; ; retry += 1) { + try { + const response = params + ? await client.sendRequest(method, params) + : await client.sendRequest(method) + if (!response.ok) { + throw new Error(response.error.message || 'quick_commands_failed') + } + return response.result + } catch (error) { + if ( + signal?.aborted || + !isLogicalClientCutoverError(error) || + retry >= LOAD_CUTOVER_MAX_RETRIES + ) { + throw error + } + } + } +} + +function quickCommandSnapshot( + result: unknown, + workspaceId: string, + invalidResultMessage: string +): HostSessionQuickCommandSnapshot { + const commands = parseNormalizedTerminalQuickCommands( + (result as { terminalQuickCommands?: unknown } | null)?.terminalQuickCommands + ) + if (!commands) { + throw new Error(invalidResultMessage) + } + return { + commands, + totalCount: commands.length, + repoId: + workspaceId.startsWith('folder:') || isFloatingWorkspaceWorktreeId(workspaceId) + ? null + : getRepoIdFromMobileWorktreeId(workspaceId) + } +} diff --git a/mobile/src/session/native-host-session-tab-operations.test.ts b/mobile/src/session/native-host-session-tab-operations.test.ts new file mode 100644 index 000000000000..d064b683853d --- /dev/null +++ b/mobile/src/session/native-host-session-tab-operations.test.ts @@ -0,0 +1,217 @@ +import { describe, expect, it, vi } from 'vitest' +import type { RpcClient } from '../transport/rpc-client' +import { LogicalClientCutoverError } from '../transport/stable-logical-rpc-client' +import { nativeHostSessionTabOperations } from './native-host-session-tab-operations' + +describe('native host session tab operations', () => { + it('projects status into the reviewed Session feature gates', async () => { + const sendRequest = vi.fn().mockResolvedValue({ + ok: true, + result: { + capabilities: [ + 'browser.screencast.v1', + 'aiVault.v1', + 'terminal.quick-commands.v1', + 'terminal.query-reply-input.v1', + 'secret.unreviewed.v1' + ] + } + }) + const operations = nativeHostSessionTabOperations({ + sendRequest + } as unknown as RpcClient) + + await expect(operations.runtimeCapabilities()).resolves.toEqual({ + browserScreencastSupported: true, + agentHistorySupported: true, + quickCommandsSupported: true, + terminalQueryReplyInputSupported: true + }) + expect(sendRequest).toHaveBeenCalledWith('status.get') + }) + + it('maps named lifecycle operations to the existing caller-local RPCs', async () => { + const sendRequest = vi + .fn() + .mockResolvedValueOnce({ ok: true, result: sessionSnapshot(1) }) + .mockResolvedValueOnce({ ok: true, result: { created: true } }) + .mockResolvedValueOnce({ ok: true, result: sessionSnapshot(2) }) + .mockResolvedValueOnce({ ok: true, result: { browserPageId: 'browser-1' } }) + .mockResolvedValueOnce({ ok: true, result: sessionSnapshot(3) }) + .mockResolvedValueOnce({ ok: true, result: { closed: true } }) + const operations = nativeHostSessionTabOperations({ + sendRequest + } as unknown as RpcClient) + + await expect(operations.snapshot('workspace-1')).resolves.toEqual(sessionSnapshot(1)) + await expect(operations.createBlank('workspace-1')).resolves.toEqual(sessionSnapshot(2)) + await expect(operations.createBrowser('workspace-1', 'https://example.com')).resolves.toEqual({ + browserPageId: 'browser-1' + }) + await expect(operations.activate('workspace-1', 'tab-1', 'leaf-1')).resolves.toEqual( + sessionSnapshot(3) + ) + await expect(operations.close('workspace-1', 'tab-1')).resolves.toEqual({ + outcome: 'closed' + }) + + expect(sendRequest.mock.calls).toEqual([ + ['session.tabs.list', { worktree: 'id:workspace-1' }], + [ + 'session.tabs.createTerminal', + { + worktree: 'id:workspace-1', + clientMutationId: expect.stringMatching(/^mobile-create:/), + activate: false, + select: true, + navigation: 'caller' + } + ], + ['session.tabs.list', { worktree: 'id:workspace-1' }], + [ + 'browser.tabCreate', + { + worktree: 'id:workspace-1', + url: 'https://example.com', + activate: true + } + ], + [ + 'session.tabs.activate', + { + worktree: 'id:workspace-1', + tabId: 'tab-1', + leafId: 'leaf-1', + notifyClients: false, + navigation: 'caller', + intent: 'user' + } + ], + ['session.tabs.close', { worktree: 'id:workspace-1', tabId: 'tab-1', reason: 'user' }] + ]) + }) + + it('forwards only snapshot events and preserves subscription cleanup', () => { + const unsubscribe = vi.fn() + let listener: ((event: unknown) => void) | null = null + const subscribe = vi.fn((_method, _params, onData) => { + listener = onData + return unsubscribe + }) + const onSnapshot = vi.fn() + const operations = nativeHostSessionTabOperations({ + subscribe + } as unknown as RpcClient) + + const cleanup = operations.subscribe('workspace-1', onSnapshot, vi.fn()) + listener?.({ type: 'ready' }) + listener?.({ type: 'updated', ...sessionSnapshot(3) }) + cleanup() + + expect(subscribe).toHaveBeenCalledWith( + 'session.tabs.subscribe', + { worktree: 'id:workspace-1' }, + expect.any(Function) + ) + expect(onSnapshot).toHaveBeenCalledWith({ + type: 'updated', + ...sessionSnapshot(3) + }) + expect(unsubscribe).toHaveBeenCalledOnce() + }) + + // Why: a host-side subscription cleanup ends the stream; without degrading, the tab + // list freezes on its last snapshot and never refetches. + it('degrades the stream on end and error rather than dropping them silently', () => { + let listener: ((event: unknown) => void) | null = null + const subscribe = vi.fn((_method, _params, onData) => { + listener = onData + return vi.fn() + }) + const onSnapshot = vi.fn() + const onError = vi.fn() + const operations = nativeHostSessionTabOperations({ subscribe } as unknown as RpcClient) + + operations.subscribe('workspace-1', onSnapshot, onError) + listener?.({ type: 'end' }) + listener?.({ type: 'error' }) + + expect(onSnapshot).not.toHaveBeenCalled() + expect(onError).toHaveBeenCalledTimes(2) + }) + + // Why: a relay-to-direct cutover rejects the in-flight request; activation is idempotent, + // so one retry keeps the host's active tab in step with the tab the user just tapped. + it('retries activation once after a logical client cutover', async () => { + const sendRequest = vi + .fn() + .mockRejectedValueOnce(new LogicalClientCutoverError('cutover')) + .mockResolvedValueOnce({ ok: true, result: sessionSnapshot(4) }) + const operations = nativeHostSessionTabOperations({ sendRequest } as unknown as RpcClient) + + await expect(operations.activate('workspace-1', 'tab-1')).resolves.toEqual(sessionSnapshot(4)) + expect(sendRequest).toHaveBeenCalledTimes(2) + }) + + it('loads enabled agent choices and creates the selected agent through named operations', async () => { + const sendRequest = vi.fn(async (method) => { + if (method === 'settings.get') { + return { + ok: true, + result: { settings: { defaultTuiAgent: 'codex', disabledTuiAgents: [] } } + } + } + if (method === 'preflight.detectAgents') { + return { ok: true, result: ['claude', 'codex'] } + } + if (method === 'session.tabs.createTerminal') { + return { ok: true, result: { created: true } } + } + return { ok: true, result: sessionSnapshot(4) } + }) + const operations = nativeHostSessionTabOperations({ + sendRequest + } as unknown as RpcClient) + + await expect(operations.agentOptions('global-floating-terminal')).resolves.toEqual([ + { agent: 'codex', label: 'Codex' }, + { agent: 'claude', label: 'Claude' } + ]) + await expect(operations.createAgent('global-floating-terminal', 'codex')).resolves.toEqual( + sessionSnapshot(4) + ) + expect(sendRequest).toHaveBeenCalledWith('session.tabs.createTerminal', { + worktree: 'id:global-floating-terminal', + clientMutationId: expect.stringMatching(/^mobile-create:/), + agent: 'codex', + activate: false, + select: true, + navigation: 'caller' + }) + }) + + it('keeps refused closes visible to the shared screen', async () => { + const operations = nativeHostSessionTabOperations({ + sendRequest: vi.fn().mockResolvedValue({ + ok: true, + result: { closed: true, refused: true, refusalReason: 'live-host-pty' } + }) + } as unknown as RpcClient) + + await expect(operations.close('workspace-1', 'tab-1')).resolves.toEqual({ + outcome: 'refused', + reason: 'live-host-pty' + }) + }) +}) + +function sessionSnapshot(snapshotVersion: number) { + return { + worktree: 'workspace-1', + publicationEpoch: 'epoch-1', + snapshotVersion, + tabs: [], + activeTabId: null, + activeTabType: null + } +} diff --git a/mobile/src/session/native-host-session-tab-operations.ts b/mobile/src/session/native-host-session-tab-operations.ts new file mode 100644 index 000000000000..c35f8b1ca316 --- /dev/null +++ b/mobile/src/session/native-host-session-tab-operations.ts @@ -0,0 +1,147 @@ +import type { RpcClient } from '../transport/rpc-client' +import type { RpcSuccess } from '../transport/types' +import type { HostSessionTabOperations } from './host-session-tab-operations' +import { projectHostSessionRuntimeCapabilities } from './host-session-runtime-capabilities' +import type { SessionTabsResult } from './mobile-session-route-types' +import { loadMobileNewTabAgentOptions } from './mobile-new-tab-agent-loader' +import { activateMobileSessionTab } from './mobile-session-tab-activation' + +export function nativeHostSessionTabOperations(client: RpcClient): HostSessionTabOperations { + return { + async runtimeCapabilities() { + const response = await client.sendRequest('status.get') + if (!response.ok) { + throw new Error('session_capabilities_failed') + } + const result = (response as RpcSuccess).result as { capabilities?: unknown } + const capabilities = Array.isArray(result.capabilities) + ? result.capabilities.filter((value): value is string => typeof value === 'string') + : [] + return projectHostSessionRuntimeCapabilities(capabilities) + }, + async snapshot(workspaceId) { + return successfulSnapshot( + await client.sendRequest('session.tabs.list', { + worktree: `id:${workspaceId}` + }) + ) + }, + subscribe(workspaceId, onSnapshot, onError) { + return client.subscribe( + 'session.tabs.subscribe', + { worktree: `id:${workspaceId}` }, + (payload) => { + const event = payload as { type?: string } & SessionTabsResult + if (event.type === 'snapshot' || event.type === 'updated') { + onSnapshot(event) + return + } + // Why: a host-side subscription cleanup ends the stream; without degrading here the + // tab list freezes on its last snapshot and never refetches. + if (event.type === 'end' || event.type === 'error') { + onError() + } + } + ) + }, + agentOptions(workspaceId) { + return loadMobileNewTabAgentOptions({ client, worktreeId: workspaceId }) + }, + async createBlank(workspaceId) { + const create = await client.sendRequest('session.tabs.createTerminal', { + worktree: `id:${workspaceId}`, + clientMutationId: nativeSessionCreateMutationId(), + activate: false, + select: true, + navigation: 'caller' + }) + if (!create.ok) { + throw new Error('session_create_failed') + } + return successfulSnapshot( + await client.sendRequest('session.tabs.list', { + worktree: `id:${workspaceId}` + }) + ) + }, + async createAgent(workspaceId, agent) { + const create = await client.sendRequest('session.tabs.createTerminal', { + worktree: `id:${workspaceId}`, + clientMutationId: nativeSessionCreateMutationId(), + agent, + activate: false, + select: true, + navigation: 'caller' + }) + if (!create.ok) { + throw new Error('session_create_failed') + } + return successfulSnapshot( + await client.sendRequest('session.tabs.list', { + worktree: `id:${workspaceId}` + }) + ) + }, + async createBrowser(workspaceId, url) { + const response = await client.sendRequest('browser.tabCreate', { + worktree: `id:${workspaceId}`, + url, + activate: true + }) + if (!response.ok) { + throw new Error('browser_create_failed') + } + const result = (response as RpcSuccess).result as { browserPageId?: unknown } + if (typeof result.browserPageId !== 'string') { + throw new Error('browser_create_failed') + } + return { browserPageId: result.browserPageId } + }, + async activate(workspaceId, tabId, leafId) { + // Why: a relay-to-direct cutover rejects the in-flight request; activation is idempotent, + // so retrying once keeps the host's active tab in step with the UI the user just switched. + return successfulSnapshot( + await activateMobileSessionTab(client, { + worktree: `id:${workspaceId}`, + tabId, + ...(leafId ? { leafId } : {}), + notifyClients: false, + navigation: 'caller', + intent: 'user' + }) + ) + }, + async close(workspaceId, tabId) { + const response = await client.sendRequest('session.tabs.close', { + worktree: `id:${workspaceId}`, + tabId, + reason: 'user' + }) + if (!response.ok) { + throw new Error('session_close_failed') + } + const result = (response as RpcSuccess).result as { + closed?: boolean + refused?: boolean + refusalReason?: string + } + if (result.closed !== true) { + throw new Error('session_close_failed') + } + return result.refused + ? { outcome: 'refused', reason: result.refusalReason ?? null } + : { outcome: 'closed' } + } + } +} + +function nativeSessionCreateMutationId(): string { + return `mobile-create:${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}` +} + +function successfulSnapshot(response: Awaited>) { + if (!response.ok) { + throw new Error('session_snapshot_failed') + } + return (response as RpcSuccess).result as SessionTabsResult +} diff --git a/mobile/src/session/native-host-session-terminal-file-operations.ts b/mobile/src/session/native-host-session-terminal-file-operations.ts new file mode 100644 index 000000000000..ff1ba0e83f46 --- /dev/null +++ b/mobile/src/session/native-host-session-terminal-file-operations.ts @@ -0,0 +1,79 @@ +import type { + RuntimeFileOpenResult, + RuntimeTerminalPathResolution +} from '../../../src/shared/runtime-types' +import type { RpcClient } from '../transport/rpc-client' +import type { RpcSuccess } from '../transport/types' +import type { + HostSessionTerminalFileOperations, + HostSessionTerminalFileTarget +} from './host-session-terminal-file-operations' + +export function nativeHostSessionTerminalFileOperations( + client: RpcClient +): HostSessionTerminalFileOperations { + return { + async resolveTerminalPath(request) { + const response = await client.sendRequest( + 'files.resolveTerminalPath', + { + worktree: `id:${request.workspaceId}`, + pathText: request.pathText, + crossWorkspace: true, + ...(request.terminalHandle ? { terminal: request.terminalHandle } : {}), + ...(request.cwd ? { cwd: request.cwd } : {}), + ...(request.nativeChatContext ? { nativeChatContext: request.nativeChatContext } : {}) + }, + { timeoutMs: 10_000 } + ) + if (!response.ok) { + return null + } + return nativeTerminalFileTarget( + (response as RpcSuccess).result as RuntimeTerminalPathResolution + ) + }, + async openWorktreeFile(workspaceId, relativePath) { + const response = await client.sendRequest( + 'files.open', + { worktree: `id:${workspaceId}`, relativePath }, + { timeoutMs: 15_000 } + ) + if (!response.ok || !(response.result as RuntimeFileOpenResult).opened) { + throw new Error('file_open_failed') + } + } + } +} + +function nativeTerminalFileTarget( + resolved: RuntimeTerminalPathResolution +): HostSessionTerminalFileTarget | null { + if (!resolved.exists || resolved.isDirectory) { + return null + } + if (resolved.openTarget?.kind === 'absolute-file') { + return { + kind: 'native-artifact', + absolutePath: resolved.openTarget.absolutePath, + grantId: resolved.openTarget.grantId, + ...(resolved.worktree ? { workspaceId: resolved.worktree } : {}) + } + } + const relativePath = + resolved.openTarget?.kind === 'worktree-file' + ? resolved.openTarget.relativePath + : resolved.relativePath + if (!relativePath) { + return null + } + return { + kind: 'worktree-file', + relativePath, + ...(resolved.worktree ? { workspaceId: resolved.worktree } : {}), + localAbsolutePath: + resolved.openTarget?.kind === 'worktree-file' && resolved.openTarget.provider === 'local' + ? resolved.openTarget.absolutePath + : null + } +} diff --git a/mobile/src/session/native-host-session-terminal-operations.test.ts b/mobile/src/session/native-host-session-terminal-operations.test.ts new file mode 100644 index 000000000000..78e3f8d6cfa5 --- /dev/null +++ b/mobile/src/session/native-host-session-terminal-operations.test.ts @@ -0,0 +1,110 @@ +import { describe, expect, it, vi } from 'vitest' +import type { RpcClient } from '../transport/rpc-client' +import { nativeHostSessionTerminalOperations } from './native-host-session-terminal-operations' + +describe('native host session terminal operations', () => { + it('preserves the existing mobile subscription and input RPC semantics', async () => { + const unsubscribe = vi.fn() + let onData: ((event: unknown) => void) | null = null + const subscribe = vi.fn((_method, _params, listener) => { + onData = listener + return unsubscribe + }) + const sendRequest = vi + .fn() + .mockResolvedValue({ ok: true, result: { send: { accepted: true } } }) + const operations = nativeHostSessionTerminalOperations({ + subscribe, + sendRequest + } as unknown as RpcClient) + const onEvent = vi.fn() + + const cleanup = operations.subscribe( + { + workspaceId: 'workspace-1', + terminalId: 'terminal-native-1', + clientId: 'device-1', + viewport: { cols: 90, rows: 30 }, + visible: true, + capabilities: { terminalBinaryStream: 1 } + }, + onEvent, + vi.fn() + ) + onData?.({ type: 'data', chunk: 'hello' }) + + expect(subscribe).toHaveBeenCalledWith( + 'terminal.subscribe', + { + terminal: 'terminal-native-1', + client: { id: 'device-1', type: 'mobile' }, + viewport: { cols: 90, rows: 30 }, + capabilities: { terminalBinaryStream: 1 } + }, + expect.any(Function) + ) + expect(onEvent).toHaveBeenCalledWith({ type: 'data', chunk: 'hello' }) + await expect(operations.sendInput('terminal-native-1', 'ls', true, 'device-1')).resolves.toBe( + true + ) + expect(sendRequest).toHaveBeenCalledWith( + 'terminal.send', + { + terminal: 'terminal-native-1', + text: 'ls', + enter: true, + client: { id: 'device-1', type: 'mobile' } + }, + { failWhenDisconnected: true } + ) + await expect( + operations.setDisplayMode('terminal-native-1', 'auto', { cols: 90, rows: 30 }, 'device-1') + ).resolves.toBe(true) + await expect( + operations.rename('terminal-native-1', 'Build', 'workspace-native-1') + ).resolves.toBe(true) + await expect(operations.clear('terminal-native-1')).resolves.toBe(true) + expect(sendRequest).toHaveBeenCalledWith('terminal.setDisplayMode', { + terminal: 'terminal-native-1', + mode: 'auto', + client: { id: 'device-1', type: 'mobile' }, + viewport: { cols: 90, rows: 30 } + }) + expect(sendRequest).toHaveBeenCalledWith('terminal.rename', { + terminal: 'terminal-native-1', + title: 'Build' + }) + expect(sendRequest).toHaveBeenCalledWith('terminal.clearBuffer', { + terminal: 'terminal-native-1' + }) + + cleanup() + expect(unsubscribe).toHaveBeenCalledOnce() + }) + + it('keeps query replies capability-gated and bound to an active subscription', async () => { + const operations = nativeHostSessionTerminalOperations({ + subscribe: vi.fn().mockReturnValue(vi.fn()), + sendRequest: vi.fn().mockResolvedValue({ ok: true, result: { send: { accepted: true } } }) + } as unknown as RpcClient) + operations.subscribe( + { + workspaceId: 'workspace-1', + terminalId: 'terminal-native-1', + clientId: null, + viewport: null, + visible: true, + capabilities: { terminalBinaryStream: 1 } + }, + vi.fn(), + vi.fn() + ) + + await expect( + operations.sendQueryReply('terminal-native-1', '\u001b[0n', null, false) + ).resolves.toBe(false) + await expect( + operations.sendQueryReply('terminal-native-1', '\u001b[0n', null, true) + ).resolves.toBe(true) + }) +}) diff --git a/mobile/src/session/native-host-session-terminal-operations.ts b/mobile/src/session/native-host-session-terminal-operations.ts new file mode 100644 index 000000000000..18886f6b3eea --- /dev/null +++ b/mobile/src/session/native-host-session-terminal-operations.ts @@ -0,0 +1,83 @@ +import { sendMobileTerminalQueryReply } from '../terminal/mobile-terminal-query-reply' +import { isTerminalSendRpcAccepted } from '../terminal/terminal-send-rpc-response' +import { TERMINAL_INPUT_SEND_OPTIONS } from '../terminal/terminal-send-request' +import type { RpcClient } from '../transport/rpc-client' +import type { HostSessionTerminalOperations } from './host-session-terminal-operations' +import { subscribeMobileTerminalSafely } from './mobile-terminal-stream-subscribe' + +export function nativeHostSessionTerminalOperations( + client: RpcClient +): HostSessionTerminalOperations { + const subscribedTerminals = new Set() + return { + subscribe(args, onEvent, onError) { + const unsubscribe = subscribeMobileTerminalSafely( + client, + { + terminal: args.terminalId, + ...(args.clientId ? { client: { id: args.clientId, type: 'mobile' as const } } : {}), + viewport: args.viewport, + capabilities: args.capabilities + }, + (event) => onEvent(event as Parameters[0]), + onError + ) + subscribedTerminals.add(args.terminalId) + return () => { + subscribedTerminals.delete(args.terminalId) + unsubscribe() + } + }, + acknowledge() {}, + async sendInput(terminalId, text, enter, clientId) { + return client + .sendRequest( + 'terminal.send', + { + terminal: terminalId, + text, + enter, + ...(clientId ? { client: { id: clientId, type: 'mobile' as const } } : {}) + }, + TERMINAL_INPUT_SEND_OPTIONS + ) + .then(isTerminalSendRpcAccepted, () => false) + }, + sendQueryReply(terminalId, bytes, clientId, hostSupportsQueryReply) { + return sendMobileTerminalQueryReply({ + bytes, + client, + clientId, + connected: true, + handle: terminalId, + hostSupportsQueryReplyInput: hostSupportsQueryReply, + subscribedTerminals + }) + }, + setDisplayMode(terminalId, mode, viewport, clientId) { + return client + .sendRequest('terminal.setDisplayMode', { + terminal: terminalId, + mode, + ...(clientId ? { client: { id: clientId, type: 'mobile' as const } } : {}), + ...(viewport && mode === 'auto' ? { viewport } : {}) + }) + .then( + (response) => response.ok, + () => false + ) + }, + clear(terminalId) { + return client.sendRequest('terminal.clearBuffer', { terminal: terminalId }).then( + (response) => response.ok, + () => false + ) + }, + rename(terminalId, title) { + return client.sendRequest('terminal.rename', { terminal: terminalId, title }).then( + (response) => response.ok, + () => false + ) + } + } +} diff --git a/mobile/src/tasks/composer-source-base-resolve.ts b/mobile/src/tasks/composer-source-base-resolve.ts index 423c3b05294a..45da479393a2 100644 --- a/mobile/src/tasks/composer-source-base-resolve.ts +++ b/mobile/src/tasks/composer-source-base-resolve.ts @@ -1,4 +1,4 @@ -import type { RpcClient } from '../transport/rpc-client' +import type { RpcRequestSender } from '../transport/rpc-client' import type { RpcSuccess } from '../transport/types' import type { GitHubPrStartPoint } from '../../../src/shared/worktree/types' @@ -14,14 +14,18 @@ type HostedBaseResult = ComposerHostedBase | { error: string } // Resolves a GitHub PR's base via worktree.resolvePrBase, mirroring desktop's // select-time resolution. The runtime returns a soft { error } payload rather // than an RPC error for provider failures. -export async function resolveComposerPrBase(args: { - client: RpcClient +export type ResolveComposerPrBaseArgs = { + client: RpcRequestSender repoId: string prNumber: number headRefName?: string baseRefName?: string isCrossRepository?: boolean -}): Promise { +} + +export async function resolveComposerPrBase( + args: ResolveComposerPrBaseArgs +): Promise { const { client, repoId, prNumber, headRefName, baseRefName, isCrossRepository } = args const response = await client.sendRequest( 'worktree.resolvePrBase', @@ -45,14 +49,18 @@ export async function resolveComposerPrBase(args: { } // Resolves a GitLab MR's base via worktree.resolveMrBase. -export async function resolveComposerMrBase(args: { - client: RpcClient +export type ResolveComposerMrBaseArgs = { + client: RpcRequestSender repoId: string mrIid: number sourceBranch?: string targetBranch?: string isCrossRepository?: boolean -}): Promise { +} + +export async function resolveComposerMrBase( + args: ResolveComposerMrBaseArgs +): Promise { const { client, repoId, mrIid, sourceBranch, targetBranch, isCrossRepository } = args const response = await client.sendRequest( 'worktree.resolveMrBase', diff --git a/mobile/src/tasks/default-host-task-detail-operations.ts b/mobile/src/tasks/default-host-task-detail-operations.ts new file mode 100644 index 000000000000..54ed3161ff84 --- /dev/null +++ b/mobile/src/tasks/default-host-task-detail-operations.ts @@ -0,0 +1,7 @@ +import type { HostTaskDetailOperations } from './host-task-detail-operations' +import { nativeHostTaskDetailOperations } from './native-host-task-detail-operations' +import type { RpcClient } from '../transport/rpc-client' + +export function defaultHostTaskDetailOperations(client: RpcClient): HostTaskDetailOperations { + return nativeHostTaskDetailOperations(client) +} diff --git a/mobile/src/tasks/default-host-task-item-file-operations.ts b/mobile/src/tasks/default-host-task-item-file-operations.ts new file mode 100644 index 000000000000..899a236c5888 --- /dev/null +++ b/mobile/src/tasks/default-host-task-item-file-operations.ts @@ -0,0 +1,7 @@ +import type { HostTaskItemFileOperations } from './host-task-item-file-operations' +import { nativeHostTaskItemFileOperations } from './native-host-task-item-file-operations' +import type { RpcClient } from '../transport/rpc-client' + +export function defaultHostTaskItemFileOperations(client: RpcClient): HostTaskItemFileOperations { + return nativeHostTaskItemFileOperations(client) +} diff --git a/mobile/src/tasks/default-host-task-item-mutation-operations.ts b/mobile/src/tasks/default-host-task-item-mutation-operations.ts new file mode 100644 index 000000000000..17f920626861 --- /dev/null +++ b/mobile/src/tasks/default-host-task-item-mutation-operations.ts @@ -0,0 +1,9 @@ +import type { HostTaskItemMutationOperations } from './host-task-item-mutation-operations' +import { nativeHostTaskItemMutationOperations } from './native-host-task-item-mutation-operations' +import type { RpcClient } from '../transport/rpc-client' + +export function defaultHostTaskItemMutationOperations( + client: RpcClient +): HostTaskItemMutationOperations { + return nativeHostTaskItemMutationOperations(client) +} diff --git a/mobile/src/tasks/default-host-task-item-review-operations.ts b/mobile/src/tasks/default-host-task-item-review-operations.ts new file mode 100644 index 000000000000..a080dc3b5ece --- /dev/null +++ b/mobile/src/tasks/default-host-task-item-review-operations.ts @@ -0,0 +1,9 @@ +import type { HostTaskItemReviewOperations } from './host-task-item-review-operations' +import { nativeHostTaskItemReviewOperations } from './native-host-task-item-review-operations' +import type { RpcClient } from '../transport/rpc-client' + +export function defaultHostTaskItemReviewOperations( + client: RpcClient +): HostTaskItemReviewOperations { + return nativeHostTaskItemReviewOperations(client) +} diff --git a/mobile/src/tasks/default-host-task-linear-operations.ts b/mobile/src/tasks/default-host-task-linear-operations.ts new file mode 100644 index 000000000000..1408163e7171 --- /dev/null +++ b/mobile/src/tasks/default-host-task-linear-operations.ts @@ -0,0 +1,7 @@ +import type { HostTaskLinearOperations } from './host-task-linear-operations' +import { nativeHostTaskLinearOperations } from './native-host-task-linear-operations' +import type { RpcClient } from '../transport/rpc-client' + +export function defaultHostTaskLinearOperations(client: RpcClient): HostTaskLinearOperations { + return nativeHostTaskLinearOperations(client) +} diff --git a/mobile/src/tasks/default-host-task-list-operations.ts b/mobile/src/tasks/default-host-task-list-operations.ts new file mode 100644 index 000000000000..81472b9d7709 --- /dev/null +++ b/mobile/src/tasks/default-host-task-list-operations.ts @@ -0,0 +1,7 @@ +import type { HostTaskListOperations } from './host-task-list-operations' +import { nativeHostTaskListOperations } from './native-host-task-list-operations' +import type { RpcClient } from '../transport/rpc-client' + +export function defaultHostTaskListOperations(client: RpcClient): HostTaskListOperations { + return nativeHostTaskListOperations(client) +} diff --git a/mobile/src/tasks/default-host-task-operations.ts b/mobile/src/tasks/default-host-task-operations.ts new file mode 100644 index 000000000000..0d44f5dbd102 --- /dev/null +++ b/mobile/src/tasks/default-host-task-operations.ts @@ -0,0 +1,7 @@ +import type { RpcClient } from '../transport/rpc-client' +import type { HostTaskOperations } from './host-task-operations' +import { nativeHostTaskOperations } from './native-host-task-operations' + +export function defaultHostTaskOperations(client: RpcClient): HostTaskOperations { + return nativeHostTaskOperations(client) +} diff --git a/mobile/src/tasks/default-host-task-preference-operations.ts b/mobile/src/tasks/default-host-task-preference-operations.ts new file mode 100644 index 000000000000..5328d37a5caa --- /dev/null +++ b/mobile/src/tasks/default-host-task-preference-operations.ts @@ -0,0 +1,9 @@ +import type { HostTaskPreferenceOperations } from './host-task-preference-operations' +import { nativeHostTaskPreferenceOperations } from './native-host-task-preference-operations' +import type { RpcClient } from '../transport/rpc-client' + +export function defaultHostTaskPreferenceOperations( + client: RpcClient +): HostTaskPreferenceOperations { + return nativeHostTaskPreferenceOperations(client) +} diff --git a/mobile/src/tasks/default-host-task-project-file-operations.ts b/mobile/src/tasks/default-host-task-project-file-operations.ts new file mode 100644 index 000000000000..523b4c73b9f9 --- /dev/null +++ b/mobile/src/tasks/default-host-task-project-file-operations.ts @@ -0,0 +1,9 @@ +import type { HostTaskProjectFileOperations } from './host-task-project-file-operations' +import { nativeHostTaskProjectFileOperations } from './native-host-task-project-file-operations' +import type { RpcClient } from '../transport/rpc-client' + +export function defaultHostTaskProjectFileOperations( + client: RpcClient +): HostTaskProjectFileOperations { + return nativeHostTaskProjectFileOperations(client) +} diff --git a/mobile/src/tasks/default-host-task-project-mutation-operations.ts b/mobile/src/tasks/default-host-task-project-mutation-operations.ts new file mode 100644 index 000000000000..d47eb21d5383 --- /dev/null +++ b/mobile/src/tasks/default-host-task-project-mutation-operations.ts @@ -0,0 +1,9 @@ +import type { HostTaskProjectMutationOperations } from './host-task-project-mutation-operations' +import { nativeHostTaskProjectMutationOperations } from './native-host-task-project-mutation-operations' +import type { RpcClient } from '../transport/rpc-client' + +export function defaultHostTaskProjectMutationOperations( + client: RpcClient +): HostTaskProjectMutationOperations { + return nativeHostTaskProjectMutationOperations(client) +} diff --git a/mobile/src/tasks/default-host-task-project-read-operations.ts b/mobile/src/tasks/default-host-task-project-read-operations.ts new file mode 100644 index 000000000000..b4346f6f0f43 --- /dev/null +++ b/mobile/src/tasks/default-host-task-project-read-operations.ts @@ -0,0 +1,9 @@ +import type { HostTaskProjectReadOperations } from './host-task-project-read-operations' +import { nativeHostTaskProjectReadOperations } from './native-host-task-project-read-operations' +import type { RpcClient } from '../transport/rpc-client' + +export function defaultHostTaskProjectReadOperations( + client: RpcClient +): HostTaskProjectReadOperations { + return nativeHostTaskProjectReadOperations(client) +} diff --git a/mobile/src/tasks/default-host-task-provider-write-operations.ts b/mobile/src/tasks/default-host-task-provider-write-operations.ts new file mode 100644 index 000000000000..0521e8bb77fb --- /dev/null +++ b/mobile/src/tasks/default-host-task-provider-write-operations.ts @@ -0,0 +1,9 @@ +import type { HostTaskProviderWriteOperations } from './host-task-provider-write-operations' +import { nativeHostTaskProviderWriteOperations } from './native-host-task-provider-write-operations' +import type { RpcClient } from '../transport/rpc-client' + +export function defaultHostTaskProviderWriteOperations( + client: RpcClient +): HostTaskProviderWriteOperations { + return nativeHostTaskProviderWriteOperations(client) +} diff --git a/mobile/src/tasks/default-host-task-read-operations.ts b/mobile/src/tasks/default-host-task-read-operations.ts new file mode 100644 index 000000000000..abf2a2c8e435 --- /dev/null +++ b/mobile/src/tasks/default-host-task-read-operations.ts @@ -0,0 +1,7 @@ +import type { HostTaskReadOperations } from './host-task-read-operations' +import { nativeHostTaskReadOperations } from './native-host-task-read-operations' +import type { RpcClient } from '../transport/rpc-client' + +export function defaultHostTaskReadOperations(client: RpcClient): HostTaskReadOperations { + return nativeHostTaskReadOperations(client) +} diff --git a/mobile/src/tasks/github-task-detail-projection.ts b/mobile/src/tasks/github-task-detail-projection.ts new file mode 100644 index 000000000000..e7b97ce58628 --- /dev/null +++ b/mobile/src/tasks/github-task-detail-projection.ts @@ -0,0 +1,32 @@ +import type { HostTaskGitHubDetail } from './host-task-provider-payloads' +import type { GitHubAssignableUser } from './mobile-tasks-provider-detail-types' + +type GitHubRawDetails = Partial & { + item?: { + labels?: string[] + reviewDecision?: string | null + reviewRequests?: GitHubAssignableUser[] + latestReviews?: HostTaskGitHubDetail['latestReviews'] + } +} + +export function projectGitHubTaskDetail(value: unknown): HostTaskGitHubDetail { + const details = value as GitHubRawDetails | null + if (!details) { + throw new Error('Details not found') + } + return { + body: details.body ?? '', + comments: details.comments ?? [], + labels: details.item?.labels ?? details.labels, + assignees: details.assignees ?? [], + reviewDecision: details.item?.reviewDecision ?? details.reviewDecision, + reviewRequests: details.item?.reviewRequests ?? details.reviewRequests, + latestReviews: details.item?.latestReviews ?? details.latestReviews, + headSha: details.headSha, + baseSha: details.baseSha, + pullRequestId: details.pullRequestId, + checks: details.checks ?? [], + files: details.files ?? [] + } +} diff --git a/mobile/src/tasks/host-task-detail-operations.ts b/mobile/src/tasks/host-task-detail-operations.ts new file mode 100644 index 000000000000..d1dbc8e33563 --- /dev/null +++ b/mobile/src/tasks/host-task-detail-operations.ts @@ -0,0 +1,27 @@ +import type { + HostTaskGitHubDetail, + HostTaskGitHubDetailPayload, + HostTaskGitLabDetail, + HostTaskLinearDetail +} from './host-task-provider-payloads' +import type { GitHubAssignableUser } from './mobile-tasks-provider-detail-types' + +export type HostTaskGitLabDetailPayload = { + repoId: string + number: number + type: 'issue' | 'mr' + projectRef?: { host: string; path: string } +} + +export type HostTaskLinearDetailPayload = { + issueId: string + workspaceId?: string +} + +export type HostTaskDetailOperations = { + listGitHubLabels(repoId: string): Promise + listGitHubAssignableUsers(repoId: string): Promise + loadGitHub(payload: HostTaskGitHubDetailPayload): Promise + loadGitLab(payload: HostTaskGitLabDetailPayload): Promise + loadLinear(payload: HostTaskLinearDetailPayload): Promise +} diff --git a/mobile/src/tasks/host-task-item-file-operations.ts b/mobile/src/tasks/host-task-item-file-operations.ts new file mode 100644 index 000000000000..846b58b6d605 --- /dev/null +++ b/mobile/src/tasks/host-task-item-file-operations.ts @@ -0,0 +1,43 @@ +import type { HostTaskGitHubDetail } from './host-task-provider-payloads' +import type { DetailComment } from './mobile-tasks-provider-detail-types' +import type { GitHubPRFileContents } from '../../../src/shared/github/pull-request-types' +import type { HostTaskGitHubItemTarget } from './host-task-item-mutation-operations' + +export type HostTaskItemFileStatus = + | 'added' + | 'modified' + | 'removed' + | 'renamed' + | 'copied' + | 'changed' + | 'unchanged' + +export type HostTaskItemFileOperations = { + refreshChecks( + target: HostTaskGitHubItemTarget, + headSha?: string + ): Promise + rerunChecks( + target: HostTaskGitHubItemTarget, + headSha: string | undefined, + failedOnly: boolean + ): Promise + setFileViewed( + target: HostTaskGitHubItemTarget, + payload: { pullRequestId: string; path: string; viewed: boolean } + ): Promise + loadFileContents( + target: HostTaskGitHubItemTarget, + payload: { + path: string + oldPath?: string + status: HostTaskItemFileStatus + headSha: string + baseSha: string + } + ): Promise + addInlineComment( + target: HostTaskGitHubItemTarget, + payload: { commitId: string; path: string; line: number; body: string } + ): Promise +} diff --git a/mobile/src/tasks/host-task-item-mutation-operations.ts b/mobile/src/tasks/host-task-item-mutation-operations.ts new file mode 100644 index 000000000000..367698c5640e --- /dev/null +++ b/mobile/src/tasks/host-task-item-mutation-operations.ts @@ -0,0 +1,33 @@ +export type HostTaskItemMetadataUpdates = { + title?: string + body?: string + addLabels?: string[] + removeLabels?: string[] + addAssignees?: string[] + removeAssignees?: string[] +} + +export type HostTaskGitHubItemTarget = { + provider: 'github' + repoId: string + number: number + type: 'issue' | 'pr' +} + +export type HostTaskGitLabItemTarget = { + provider: 'gitlab' + repoId: string + number: number + type: 'issue' | 'mr' + projectRef?: { host: string; path: string } +} + +export type HostTaskItemMutationTarget = HostTaskGitHubItemTarget | HostTaskGitLabItemTarget + +export type HostTaskItemMutationOperations = { + setClosed(target: HostTaskItemMutationTarget, closed: boolean): Promise + updateMetadata( + target: HostTaskItemMutationTarget, + updates: HostTaskItemMetadataUpdates + ): Promise +} diff --git a/mobile/src/tasks/host-task-item-review-operations.ts b/mobile/src/tasks/host-task-item-review-operations.ts new file mode 100644 index 000000000000..a474946d2cd3 --- /dev/null +++ b/mobile/src/tasks/host-task-item-review-operations.ts @@ -0,0 +1,24 @@ +import type { DetailComment } from './mobile-tasks-provider-detail-types' +import type { HostTaskItemMutationTarget } from './host-task-item-mutation-operations' + +type GitHubTarget = Extract +export type HostTaskReviewMergeMethod = 'merge' | 'squash' | 'rebase' + +export type HostTaskItemReviewOperations = { + addComment(target: HostTaskItemMutationTarget, body: string): Promise + requestReviewers(target: GitHubTarget, reviewers: string[]): Promise + resolveThread(target: GitHubTarget, threadId: string, resolve: boolean): Promise + replyReviewComment( + target: GitHubTarget, + payload: { + commentId: number + body: string + threadId?: string + path?: string + line?: number + } + // Why: the server comment carries the real id; a local stub id fails the numeric-id check + // that routes a follow-up reply back to the same review thread. + ): Promise + merge(target: HostTaskItemMutationTarget, method: HostTaskReviewMergeMethod): Promise +} diff --git a/mobile/src/tasks/host-task-linear-operations.ts b/mobile/src/tasks/host-task-linear-operations.ts new file mode 100644 index 000000000000..2114f2389efd --- /dev/null +++ b/mobile/src/tasks/host-task-linear-operations.ts @@ -0,0 +1,25 @@ +import type { HostTaskLinearCreatedIssue } from './host-task-provider-payloads' +import type { LinearIssue, LinearState, LinearTeam } from './mobile-tasks-provider-detail-types' + +export type HostTaskLinearTarget = { + issueId: string + workspaceId?: string + teamId: string + projectId?: string +} + +export type HostTaskLinearOperations = { + connect(apiKey: string): Promise + listTeams(): Promise + teamStates(target: HostTaskLinearTarget): Promise + selectWorkspace(workspaceId: string): Promise + updateState(target: HostTaskLinearTarget, stateId: string): Promise + addComment(target: HostTaskLinearTarget, body: string): Promise + loadIssue(target: HostTaskLinearTarget): Promise + createSubIssue(target: HostTaskLinearTarget, title: string): Promise + createIssue(payload: { + team: LinearTeam + title: string + description?: string + }): Promise +} diff --git a/mobile/src/tasks/host-task-list-operations.ts b/mobile/src/tasks/host-task-list-operations.ts new file mode 100644 index 000000000000..e3420409c394 --- /dev/null +++ b/mobile/src/tasks/host-task-list-operations.ts @@ -0,0 +1,17 @@ +import type { + HostTaskGitHubCountPayload, + HostTaskGitHubListPayload, + HostTaskGitHubListResult, + HostTaskGitLabListPayload, + HostTaskGitLabListResult, + HostTaskLinearListPayload +} from './host-task-provider-payloads' +import type { GitLabTodo, LinearIssue } from './mobile-tasks-provider-detail-types' + +export type HostTaskListOperations = { + listGitHub(payload: HostTaskGitHubListPayload): Promise + countGitHub(payload: HostTaskGitHubCountPayload): Promise + listGitLab(payload: HostTaskGitLabListPayload): Promise + listGitLabTodos(repoId: string): Promise + listLinear(payload: HostTaskLinearListPayload): Promise +} diff --git a/mobile/src/tasks/host-task-operations.ts b/mobile/src/tasks/host-task-operations.ts new file mode 100644 index 000000000000..32723be6e8bb --- /dev/null +++ b/mobile/src/tasks/host-task-operations.ts @@ -0,0 +1,29 @@ +import type { HostTaskDetailOperations } from './host-task-detail-operations' +import type { HostTaskItemFileOperations } from './host-task-item-file-operations' +import type { HostTaskItemMutationOperations } from './host-task-item-mutation-operations' +import type { HostTaskItemReviewOperations } from './host-task-item-review-operations' +import type { HostTaskLinearOperations } from './host-task-linear-operations' +import type { HostTaskListOperations } from './host-task-list-operations' +import type { HostTaskPreferenceOperations } from './host-task-preference-operations' +import type { HostTaskProjectFileOperations } from './host-task-project-file-operations' +import type { HostTaskProjectMutationOperations } from './host-task-project-mutation-operations' +import type { HostTaskProjectReadOperations } from './host-task-project-read-operations' +import type { HostTaskProviderWriteOperations } from './host-task-provider-write-operations' +import type { HostTaskReadOperations } from './host-task-read-operations' + +/** Everything the task screens ask a host for, grouped by concern so a screen takes one prop and + * a provider is built once. Each namespace keeps its own contract file. */ +export type HostTaskOperations = { + read: HostTaskReadOperations + preference: HostTaskPreferenceOperations + list: HostTaskListOperations + detail: HostTaskDetailOperations + itemMutation: HostTaskItemMutationOperations + itemReview: HostTaskItemReviewOperations + itemFile: HostTaskItemFileOperations + linear: HostTaskLinearOperations + providerWrite: HostTaskProviderWriteOperations + projectRead: HostTaskProjectReadOperations + projectMutation: HostTaskProjectMutationOperations + projectFile: HostTaskProjectFileOperations +} diff --git a/mobile/src/tasks/host-task-preference-operations.ts b/mobile/src/tasks/host-task-preference-operations.ts new file mode 100644 index 000000000000..8f563b1fee40 --- /dev/null +++ b/mobile/src/tasks/host-task-preference-operations.ts @@ -0,0 +1,15 @@ +import type { PersistedTrustedOrcaHooks } from '../../../src/shared/orca-yaml-hook-types' +import type { HostTaskBootstrap, HostTaskSettingsUpdate } from './host-task-runtime-payloads' + +export type { HostTaskSettingsUpdate } + +export type HostTaskPreferenceOperations = { + updateResume(taskResumeState: HostTaskBootstrap['taskResumeState']): Promise + updateSettings(settings: Partial): Promise + persistSetupTrust(args: { + trust: PersistedTrustedOrcaHooks + repoId: string + contentHash: string + alwaysTrust: boolean + }): Promise +} diff --git a/mobile/src/tasks/host-task-project-file-operations.ts b/mobile/src/tasks/host-task-project-file-operations.ts new file mode 100644 index 000000000000..0107e245f5df --- /dev/null +++ b/mobile/src/tasks/host-task-project-file-operations.ts @@ -0,0 +1,33 @@ +import type { HostTaskGitHubDetail } from './host-task-provider-payloads' +import type { DetailComment } from './mobile-tasks-provider-detail-types' +import type { GitHubPRFileContents } from '../../../src/shared/github/pull-request-types' +import type { HostTaskProjectItemTarget } from './host-task-project-mutation-operations' + +export type HostTaskProjectFileOperations = { + refreshChecks( + target: HostTaskProjectItemTarget, + repoId: string, + headSha?: string + ): Promise + setFileViewed( + target: HostTaskProjectItemTarget, + repoId: string, + payload: { pullRequestId: string; path: string; viewed: boolean } + ): Promise + loadFileContents( + target: HostTaskProjectItemTarget, + repoId: string, + payload: { + path: string + oldPath?: string + status: 'added' | 'modified' | 'removed' | 'renamed' | 'copied' | 'changed' | 'unchanged' + headSha: string + baseSha: string + } + ): Promise + addInlineComment( + target: HostTaskProjectItemTarget, + repoId: string, + payload: { commitId: string; path: string; line: number; body: string } + ): Promise +} diff --git a/mobile/src/tasks/host-task-project-mutation-operations.ts b/mobile/src/tasks/host-task-project-mutation-operations.ts new file mode 100644 index 000000000000..0efb1ba32f35 --- /dev/null +++ b/mobile/src/tasks/host-task-project-mutation-operations.ts @@ -0,0 +1,81 @@ +import type { DetailComment } from './mobile-tasks-provider-detail-types' +import type { GitHubProjectFieldMutationValue } from './mobile-tasks-view-state-types' + +export type HostTaskProjectItemTarget = { + owner: string + repo: string + host: string + number: number + type: 'issue' | 'pr' +} + +export type HostTaskProjectFieldTarget = HostTaskProjectItemTarget & { + projectId: string + itemId: string +} + +export type HostTaskProjectMetadataUpdates = { + addLabels?: string[] + removeLabels?: string[] + addAssignees?: string[] + removeAssignees?: string[] +} + +export type HostTaskProjectMutationOperations = { + updateItem( + target: HostTaskProjectItemTarget, + updates: { title?: string; body?: string; state?: 'open' | 'closed' } + ): Promise + addComment(target: HostTaskProjectItemTarget, body: string): Promise + updateComment(target: HostTaskProjectItemTarget, commentId: number, body: string): Promise + deleteComment(target: HostTaskProjectItemTarget, commentId: number): Promise + updateMetadata( + target: HostTaskProjectItemTarget, + updates: HostTaskProjectMetadataUpdates + ): Promise + updateField( + target: HostTaskProjectFieldTarget, + fieldId: string, + value: GitHubProjectFieldMutationValue | null + ): Promise + updateIssueType(target: HostTaskProjectItemTarget, issueTypeId: string | null): Promise + resolveReviewThread( + target: HostTaskProjectItemTarget, + repoId: string, + threadId: string, + resolve: boolean + ): Promise + replyReviewComment( + target: HostTaskProjectItemTarget, + repoId: string, + payload: { + commentId: number + body: string + threadId?: string + path?: string + line?: number + } + // Why: the server comment carries the real id; a local stub id fails the numeric-id check + // that routes a follow-up reply back to the same review thread. + ): Promise + addConversationComment( + target: HostTaskProjectItemTarget, + repoId: string, + body: string + ): Promise + requestReviewers( + target: HostTaskProjectItemTarget, + repoId: string, + reviewers: string[] + ): Promise + rerunChecks( + target: HostTaskProjectItemTarget, + repoId: string, + payload: { headSha?: string; failedOnly: boolean } + ): Promise + merge( + target: HostTaskProjectItemTarget, + repoId: string, + method: 'merge' | 'squash' | 'rebase' + ): Promise +} diff --git a/mobile/src/tasks/host-task-project-payloads.ts b/mobile/src/tasks/host-task-project-payloads.ts new file mode 100644 index 000000000000..c17cc7c80136 --- /dev/null +++ b/mobile/src/tasks/host-task-project-payloads.ts @@ -0,0 +1,48 @@ +import type { + GitHubProjectPartialFailure, + GitHubProjectRef, + GitHubProjectSummary +} from './github-project-reference' +import type { GitHubIssueType } from './mobile-tasks-view-state-types' + +export type HostTaskProjectListResult = { + projects: GitHubProjectSummary[] + partialFailures: GitHubProjectPartialFailure[] +} + +export type HostTaskProjectResolvePayload = { + input: string + host: string +} + +export type HostTaskProjectResolveResult = { + owner: string + ownerType: GitHubProjectRef['ownerType'] + number: number + title: string + host?: string + viewNumber?: number +} + +export type HostTaskProjectTablePayload = GitHubProjectRef & { + viewId: string + queryOverride?: string + cursor?: string +} + +export type HostTaskProjectSlugPayload = { + owner: string + repo: string + host: string +} + +export type HostTaskProjectItemDetailPayload = HostTaskProjectSlugPayload & { + number: number + type: 'issue' | 'pr' +} + +export type HostTaskProjectAssignableUsersPayload = HostTaskProjectSlugPayload & { + seedLogins?: string[] +} + +export type HostTaskProjectIssueType = GitHubIssueType diff --git a/mobile/src/tasks/host-task-project-read-operations.ts b/mobile/src/tasks/host-task-project-read-operations.ts new file mode 100644 index 000000000000..a973bd4cb411 --- /dev/null +++ b/mobile/src/tasks/host-task-project-read-operations.ts @@ -0,0 +1,27 @@ +import type { GitHubProjectRef, GitHubProjectViewSummary } from './github-project-reference' +import type { + HostTaskProjectAssignableUsersPayload, + HostTaskProjectIssueType, + HostTaskProjectItemDetailPayload, + HostTaskProjectListResult, + HostTaskProjectResolvePayload, + HostTaskProjectResolveResult, + HostTaskProjectSlugPayload, + HostTaskProjectTablePayload +} from './host-task-project-payloads' +import type { HostTaskGitHubDetail } from './host-task-provider-payloads' +import type { GitHubAssignableUser } from './mobile-tasks-provider-detail-types' +import type { GitHubProjectTable } from './mobile-tasks-view-state-types' + +export type HostTaskProjectReadOperations = { + listAccessible(host: string): Promise + listViews(project: GitHubProjectRef): Promise + resolveRef(payload: HostTaskProjectResolvePayload): Promise + loadTable(payload: Omit): Promise + loadItemDetail(payload: HostTaskProjectItemDetailPayload): Promise + listItemLabels(payload: HostTaskProjectSlugPayload): Promise + listItemAssignableUsers( + payload: HostTaskProjectAssignableUsersPayload + ): Promise + listIssueTypes(payload: HostTaskProjectSlugPayload): Promise +} diff --git a/mobile/src/tasks/host-task-provider-payloads.ts b/mobile/src/tasks/host-task-provider-payloads.ts new file mode 100644 index 000000000000..a22e3ee2b9f0 --- /dev/null +++ b/mobile/src/tasks/host-task-provider-payloads.ts @@ -0,0 +1,105 @@ +import type { + DetailComment, + GitHubAssignableUser, + GitHubDetailCheck, + GitHubDetailFile, + GitHubPRMergeableState, + GitHubPRReviewSummary, + GitHubRepoSources, + GitHubWorkItem, + GitLabWorkItem, + LinearIssue +} from './mobile-tasks-provider-detail-types' +import type { LinearFilter } from './mobile-tasks-view-state-types' + +export type HostTaskGitHubDetailPayload = { + repoId: string + number: number + type: 'issue' | 'pr' +} + +/** The host's work-item detail as the task screens read it: `provider` is the caller's, and the + * item-level fields stay optional so a caller can fall back to the row it already has. */ +export type HostTaskGitHubDetail = { + body: string + comments: DetailComment[] + labels?: string[] + assignees: string[] + reviewDecision?: string | null + reviewRequests?: GitHubAssignableUser[] + latestReviews?: GitHubPRReviewSummary[] + headSha?: string + baseSha?: string + pullRequestId?: string + checks: GitHubDetailCheck[] + files: GitHubDetailFile[] +} + +export type HostTaskGitLabDetail = { + body: string + comments: DetailComment[] + labels?: string[] + assignees: string[] + item?: { mergeable?: GitHubPRMergeableState } + reviewers?: unknown[] + approvalState?: { approvalsRequired: number | null; approvalsLeft: number | null } + pipelineJobs: Array<{ + id?: number + name: string + stage: string + status: string + webUrl?: string | null + duration?: number | null + }> +} + +export type HostTaskLinearDetail = { + issue: LinearIssue + comments: DetailComment[] +} + +export type HostTaskGitHubListPayload = { + repoId: string + limit: number + query: string + before?: string +} + +export type HostTaskGitHubListResult = { + items: GitHubWorkItem[] + sources?: GitHubRepoSources + errors?: { issues?: { message: string } } + issueSourceFellBack?: true +} + +export type HostTaskGitHubCountPayload = { + repoId: string + query: string +} + +export type HostTaskGitLabListPayload = { + repoId: string + state: 'opened' | 'merged' | 'closed' | 'all' + page: number + perPage: number + query?: string +} + +export type HostTaskGitLabListResult = { + items: GitLabWorkItem[] + error?: { type?: string; message: string } +} + +export type HostTaskLinearListPayload = { + query?: string + filter?: LinearFilter + limit: number + workspaceId?: string +} + +export type HostTaskLinearCreatedIssue = { + id: string + identifier: string + title?: string + url?: string +} diff --git a/mobile/src/tasks/host-task-provider-write-operations.ts b/mobile/src/tasks/host-task-provider-write-operations.ts new file mode 100644 index 000000000000..5ab6fd10f099 --- /dev/null +++ b/mobile/src/tasks/host-task-provider-write-operations.ts @@ -0,0 +1,9 @@ +export type HostTaskProviderWriteOperations = { + createIssue(payload: { + provider: 'github' | 'gitlab' + repoId: string + title: string + body: string + }): Promise<{ number?: number; url?: string }> + updateIssueSource(repoId: string, preference: 'upstream' | 'origin'): Promise +} diff --git a/mobile/src/tasks/host-task-read-operations.ts b/mobile/src/tasks/host-task-read-operations.ts new file mode 100644 index 000000000000..dc9810d920ab --- /dev/null +++ b/mobile/src/tasks/host-task-read-operations.ts @@ -0,0 +1,15 @@ +import type { GitHubOwnerRepo } from '../../../src/shared/github/pull-request-types' +import type { + HostTaskBootstrap, + HostTaskLinearContext, + HostTaskRepository +} from './host-task-runtime-payloads' + +export type { HostTaskBootstrap, HostTaskLinearContext, HostTaskRepository } + +export type HostTaskReadOperations = { + bootstrap(): Promise + listRepositories(): Promise + loadLinearContext(): Promise + resolveGitHubRepoSlug(repoId: string): Promise +} diff --git a/mobile/src/tasks/host-task-runtime-payloads.ts b/mobile/src/tasks/host-task-runtime-payloads.ts new file mode 100644 index 000000000000..973fa0d340e0 --- /dev/null +++ b/mobile/src/tasks/host-task-runtime-payloads.ts @@ -0,0 +1,39 @@ +import type { PersistedTrustedOrcaHooks } from '../../../src/shared/orca-yaml-hook-types' +import type { + LinearWorkspace, + RuntimeTaskSettings, + TaskResumeState +} from './mobile-tasks-view-state-types' +import type { LinearTeam, RepoSummary } from './mobile-tasks-provider-detail-types' + +export type HostTaskLinearStatus = { + connected: boolean + workspaces: LinearWorkspace[] + selectedWorkspaceId: string | null + activeWorkspaceId: string | null +} + +export type HostTaskBootstrap = { + supported: boolean + settings: RuntimeTaskSettings + taskResumeState: TaskResumeState + trustedOrcaHooks: PersistedTrustedOrcaHooks + gitLabInstalled: boolean + linearStatus: HostTaskLinearStatus +} + +export type HostTaskRepository = RepoSummary + +export type HostTaskLinearContext = { + status: HostTaskLinearStatus + teams: LinearTeam[] +} + +export type HostTaskSettingsUpdate = Pick< + RuntimeTaskSettings, + | 'defaultTaskSource' + | 'defaultTaskViewPreset' + | 'defaultRepoSelection' + | 'defaultLinearTeamSelection' + | 'githubProjects' +> diff --git a/mobile/src/tasks/native-host-task-detail-operations.ts b/mobile/src/tasks/native-host-task-detail-operations.ts new file mode 100644 index 000000000000..2a4481e5c6c0 --- /dev/null +++ b/mobile/src/tasks/native-host-task-detail-operations.ts @@ -0,0 +1,114 @@ +import type { HostTaskGitLabDetail } from './host-task-provider-payloads' +import type { DetailComment, LinearIssue } from './mobile-tasks-provider-detail-types' +import type { HostTaskDetailOperations } from './host-task-detail-operations' +import { projectGitHubTaskDetail } from './github-task-detail-projection' +import type { RpcRequestSender } from '../transport/rpc-client' + +type GitLabRawDetails = Partial & { + item?: { + labels?: string[] + mergeable?: 'MERGEABLE' | 'CONFLICTING' | 'UNKNOWN' + } +} + +export function nativeHostTaskDetailOperations(client: RpcRequestSender): HostTaskDetailOperations { + return { + async listGitHubLabels(repoId) { + return successfulResult( + client.sendRequest('github.listLabels', { repo: `id:${repoId}` }, { timeoutMs: 30_000 }) + ) + }, + async listGitHubAssignableUsers(repoId) { + return successfulResult( + client.sendRequest( + 'github.listAssignableUsers', + { repo: `id:${repoId}` }, + { timeoutMs: 30_000 } + ) + ) + }, + async loadGitHub(payload) { + const details = await successfulResult( + client.sendRequest( + 'github.workItemDetails', + { + repo: `id:${payload.repoId}`, + number: payload.number, + type: payload.type + }, + { timeoutMs: 30_000 } + ) + ) + return projectGitHubTaskDetail(details) + }, + async loadGitLab(payload) { + const details = await successfulResult( + client.sendRequest( + 'gitlab.workItemDetails', + { + repo: `id:${payload.repoId}`, + iid: payload.number, + type: payload.type, + projectRef: payload.projectRef + }, + { timeoutMs: 30_000 } + ) + ) + if (!details) { + throw new Error('Details not found') + } + return { + body: details.body ?? '', + comments: details.comments ?? [], + labels: details.item?.labels ?? details.labels, + assignees: details.assignees ?? [], + pipelineJobs: details.pipelineJobs ?? [], + ...(details.item?.mergeable ? { item: { mergeable: details.item.mergeable } } : {}), + ...(details.reviewers ? { reviewers: details.reviewers } : {}), + ...(details.approvalState ? { approvalState: details.approvalState } : {}) + } + }, + async loadLinear(payload) { + const [issue, comments] = await Promise.all([ + successfulResult( + client.sendRequest( + 'linear.getIssue', + { id: payload.issueId, workspaceId: payload.workspaceId }, + { timeoutMs: 30_000 } + ) + ), + optionalComments( + client.sendRequest( + 'linear.issueComments', + { issueId: payload.issueId, workspaceId: payload.workspaceId }, + { timeoutMs: 30_000 } + ) + ) + ]) + if (!issue) { + throw new Error('Details not found') + } + return { issue, comments } + } + } +} + +async function optionalComments(request: Promise): Promise { + try { + return await successfulResult(request) + } catch { + return [] + } +} + +async function successfulResult(request: Promise): Promise { + const response = (await request) as { + ok: boolean + result?: unknown + error?: { message?: string } + } + if (!response.ok) { + throw new Error(response.error?.message ?? 'Task provider request failed') + } + return response.result as T +} diff --git a/mobile/src/tasks/native-host-task-item-file-operations.ts b/mobile/src/tasks/native-host-task-item-file-operations.ts new file mode 100644 index 000000000000..17a37175c5d5 --- /dev/null +++ b/mobile/src/tasks/native-host-task-item-file-operations.ts @@ -0,0 +1,85 @@ +import type { HostTaskItemFileOperations } from './host-task-item-file-operations' +import type { RpcRequestSender } from '../transport/rpc-client' + +export function nativeHostTaskItemFileOperations( + client: RpcRequestSender +): HostTaskItemFileOperations { + return { + async refreshChecks(target, headSha) { + const checks = await request(client, 'github.prChecks', { + ...repoPayload(target), + prNumber: target.number, + headSha, + noCache: true + }) + if (!Array.isArray(checks)) { + throw new Error('Invalid checks response') + } + return checks + }, + async rerunChecks(target, headSha, failedOnly) { + const result = await request<{ ok?: boolean; error?: string }>( + client, + 'github.rerunPRChecks', + { + ...repoPayload(target), + prNumber: target.number, + headSha, + failedOnly + }, + 60_000 + ) + if (result.ok === false) { + throw new Error(result.error ?? 'Failed to rerun checks') + } + }, + async setFileViewed(target, payload) { + const result = await request(client, 'github.setPRFileViewed', { + ...repoPayload(target), + ...payload + }) + if (result !== true) { + throw new Error('Failed to sync viewed state with GitHub.') + } + }, + loadFileContents(target, payload) { + return request(client, 'github.prFileContents', { + ...repoPayload(target), + prNumber: target.number, + ...payload + }) + }, + async addInlineComment(target, payload) { + const result = await request<{ + ok?: boolean + error?: string + comment?: Awaited> + }>(client, 'github.addPRReviewComment', { + ...repoPayload(target), + prNumber: target.number, + ...payload + }) + if (result.ok === false) { + throw new Error(result.error ?? 'Failed to add review comment') + } + return result.comment + } + } +} + +function repoPayload(target: { repoId: string }) { + return { repo: `id:${target.repoId}` } +} + +async function request( + client: RpcRequestSender, + method: string, + payload: object, + timeoutMs = 30_000 +): Promise { + const response = await client.sendRequest(method, payload, { timeoutMs }) + if (!response.ok) { + throw new Error(response.error?.message ?? 'Task request failed') + } + return response.result as T +} diff --git a/mobile/src/tasks/native-host-task-item-mutation-operations.ts b/mobile/src/tasks/native-host-task-item-mutation-operations.ts new file mode 100644 index 000000000000..59f385bee777 --- /dev/null +++ b/mobile/src/tasks/native-host-task-item-mutation-operations.ts @@ -0,0 +1,135 @@ +import type { HostTaskItemMetadataUpdates } from './host-task-item-mutation-operations' +import type { + HostTaskItemMutationOperations, + HostTaskItemMutationTarget +} from './host-task-item-mutation-operations' +import type { RpcRequestSender } from '../transport/rpc-client' + +export function nativeHostTaskItemMutationOperations( + client: RpcRequestSender +): HostTaskItemMutationOperations { + return { + async setClosed(target, closed) { + const response = + target.provider === 'github' + ? await setGitHubClosed(client, target, closed) + : await setGitLabClosed(client, target, closed) + assertMutation(response, 'Failed to update task status') + }, + async updateMetadata(target, updates) { + const response = + target.provider === 'github' + ? await updateGitHubMetadata(client, target, updates) + : await updateGitLabMetadata(client, target, updates) + assertMutation(response, 'Failed to update task') + } + } +} + +function setGitHubClosed( + client: RpcRequestSender, + target: Extract, + closed: boolean +) { + const state = closed ? 'closed' : 'open' + return target.type === 'issue' + ? client.sendRequest('github.updateIssue', { + repo: `id:${target.repoId}`, + number: target.number, + updates: { state } + }) + : client.sendRequest('github.updatePRState', { + repo: `id:${target.repoId}`, + prNumber: target.number, + updates: { state } + }) +} + +function setGitLabClosed( + client: RpcRequestSender, + target: Extract, + closed: boolean +) { + const state = closed ? 'closed' : 'opened' + return target.type === 'issue' + ? client.sendRequest('gitlab.updateIssue', { + repo: `id:${target.repoId}`, + number: target.number, + updates: { state }, + projectRef: target.projectRef + }) + : client.sendRequest('gitlab.updateMRState', { + repo: `id:${target.repoId}`, + iid: target.number, + state, + projectRef: target.projectRef + }) +} + +function updateGitHubMetadata( + client: RpcRequestSender, + target: Extract, + updates: HostTaskItemMetadataUpdates +) { + return target.type === 'issue' + ? client.sendRequest( + 'github.updateIssue', + { repo: `id:${target.repoId}`, number: target.number, updates }, + { timeoutMs: 30_000 } + ) + : client.sendRequest( + 'github.updatePR', + { + repo: `id:${target.repoId}`, + prNumber: target.number, + updates: { title: updates.title, body: updates.body } + }, + { timeoutMs: 30_000 } + ) +} + +function updateGitLabMetadata( + client: RpcRequestSender, + target: Extract, + updates: HostTaskItemMetadataUpdates +) { + return target.type === 'issue' + ? client.sendRequest( + 'gitlab.updateIssue', + { + repo: `id:${target.repoId}`, + number: target.number, + updates, + projectRef: target.projectRef + }, + { timeoutMs: 30_000 } + ) + : client.sendRequest( + 'gitlab.updateMR', + { + repo: `id:${target.repoId}`, + iid: target.number, + projectRef: target.projectRef, + updates: { + title: updates.title, + body: updates.body, + addLabels: updates.addLabels, + removeLabels: updates.removeLabels + } + }, + { timeoutMs: 30_000 } + ) +} + +function assertMutation( + response: Awaited>, + fallback: string +): void { + if (!response.ok) { + throw new Error(response.error?.message ?? 'Task request failed') + } + const result = response.result as { ok?: boolean; error?: string } + if (result.ok === false) { + throw new Error(result.error ?? fallback) + } +} diff --git a/mobile/src/tasks/native-host-task-item-review-operations.ts b/mobile/src/tasks/native-host-task-item-review-operations.ts new file mode 100644 index 000000000000..d262b68c0e99 --- /dev/null +++ b/mobile/src/tasks/native-host-task-item-review-operations.ts @@ -0,0 +1,148 @@ +import type { DetailComment } from './mobile-tasks-provider-detail-types' +import type { HostTaskItemMutationTarget } from './host-task-item-mutation-operations' +import type { HostTaskItemReviewOperations } from './host-task-item-review-operations' +import type { RpcRequestSender } from '../transport/rpc-client' + +export function nativeHostTaskItemReviewOperations( + client: RpcRequestSender +): HostTaskItemReviewOperations { + return { + async addComment(target, body) { + const response = + target.provider === 'github' + ? await client.sendRequest( + 'github.addIssueComment', + { + repo: `id:${target.repoId}`, + number: target.number, + body, + type: target.type + }, + { timeoutMs: 30_000 } + ) + : await addGitLabComment(client, target, body) + return mutationComment(response, 'Failed to add comment') + }, + async requestReviewers(target, reviewers) { + assertMutation( + await client.sendRequest( + 'github.requestPRReviewers', + { + repo: `id:${target.repoId}`, + prNumber: target.number, + reviewers + }, + { timeoutMs: 30_000 } + ), + 'Failed to request reviewers' + ) + }, + async resolveThread(target, threadId, resolve) { + const response = await client.sendRequest( + 'github.resolveReviewThread', + { repo: `id:${target.repoId}`, threadId, resolve }, + { timeoutMs: 30_000 } + ) + if (!response.ok || response.result !== true) { + throw new Error(resolve ? 'Failed to resolve thread' : 'Failed to reopen thread') + } + }, + async replyReviewComment(target, payload) { + return mutationComment( + await client.sendRequest( + 'github.addPRReviewCommentReply', + { + repo: `id:${target.repoId}`, + prNumber: target.number, + commentId: payload.commentId, + body: payload.body, + threadId: payload.threadId, + path: payload.path, + line: payload.line + }, + { timeoutMs: 30_000 } + ), + 'Failed to reply' + ) + }, + async merge(target, method) { + const response = + target.provider === 'github' + ? await client.sendRequest( + 'github.mergePR', + { repo: `id:${target.repoId}`, prNumber: target.number, method }, + { timeoutMs: 60_000 } + ) + : await client.sendRequest( + 'gitlab.mergeMR', + { + repo: `id:${target.repoId}`, + iid: target.number, + method, + projectRef: target.projectRef + }, + { timeoutMs: 60_000 } + ) + assertMutation(response, 'Failed to merge review') + } + } +} + +function addGitLabComment( + client: RpcRequestSender, + target: Extract, + body: string +) { + return target.type === 'mr' + ? client.sendRequest( + 'gitlab.addMRComment', + { + repo: `id:${target.repoId}`, + iid: target.number, + body, + projectRef: target.projectRef + }, + { timeoutMs: 30_000 } + ) + : client.sendRequest( + 'gitlab.addIssueComment', + { + repo: `id:${target.repoId}`, + number: target.number, + body, + projectRef: target.projectRef + }, + { timeoutMs: 30_000 } + ) +} + +function mutationComment( + response: Awaited>, + fallback: string +): DetailComment | undefined { + if (!response.ok) { + throw new Error(response.error?.message ?? 'Task request failed') + } + const result = response.result as { + ok?: boolean + error?: string + comment?: DetailComment + } + if (result.ok === false) { + throw new Error(result.error ?? fallback) + } + return result.comment +} + +function assertMutation( + response: Awaited>, + fallback: string +): void { + if (!response.ok) { + throw new Error(response.error?.message ?? 'Task request failed') + } + const result = response.result as { ok?: boolean; error?: string } + if (result.ok === false) { + throw new Error(result.error ?? fallback) + } +} diff --git a/mobile/src/tasks/native-host-task-linear-operations.ts b/mobile/src/tasks/native-host-task-linear-operations.ts new file mode 100644 index 000000000000..4f2fd3c2679e --- /dev/null +++ b/mobile/src/tasks/native-host-task-linear-operations.ts @@ -0,0 +1,115 @@ +import type { HostTaskLinearOperations } from './host-task-linear-operations' +import type { RpcRequestSender } from '../transport/rpc-client' + +export function nativeHostTaskLinearOperations(client: RpcRequestSender): HostTaskLinearOperations { + return { + async connect(apiKey) { + assertMutation( + await request(client, 'linear.connect', { apiKey }), + 'Failed to connect Linear' + ) + }, + listTeams: () => request(client, 'linear.listTeams', undefined), + teamStates: (target) => + request(client, 'linear.teamStates', { + teamId: target.teamId, + workspaceId: target.workspaceId + }), + async selectWorkspace(workspaceId) { + assertMutation( + await request(client, 'linear.selectWorkspace', { workspaceId }), + 'Failed to select workspace' + ) + }, + async updateState(target, stateId) { + assertMutation( + await request(client, 'linear.updateIssue', { + id: target.issueId, + workspaceId: target.workspaceId, + updates: { stateId } + }), + 'Failed to update Linear issue' + ) + }, + async addComment(target, body) { + const result = await request<{ ok?: boolean; id?: string; error?: string }>( + client, + 'linear.addIssueComment', + { issueId: target.issueId, workspaceId: target.workspaceId, body } + ) + assertMutation(result, 'Failed to add comment') + return result.id + }, + async loadIssue(target) { + const issue = await request + > | null>(client, 'linear.getIssue', { id: target.issueId, workspaceId: target.workspaceId }) + if (!issue) { + throw new Error('Linear issue not found') + } + return issue + }, + async createSubIssue(target, title) { + return createdIssue( + await request(client, 'linear.createIssue', { + teamId: target.teamId, + title, + workspaceId: target.workspaceId, + parentIssueId: target.issueId, + projectId: target.projectId ?? null + }) + ) + }, + async createIssue(payload) { + return createdIssue( + await request(client, 'linear.createIssue', { + teamId: payload.team.id, + title: payload.title, + description: payload.description, + workspaceId: payload.team.workspaceId + }) + ) + } + } +} + +async function request( + client: RpcRequestSender, + method: string, + payload?: object +): Promise { + const response = await client.sendRequest(method, payload, { timeoutMs: 30_000 }) + if (!response.ok) { + throw new Error(response.error?.message ?? 'Task request failed') + } + return response.result as T +} + +function assertMutation( + result: { ok?: boolean; error?: string } | undefined, + fallback: string +): void { + if (result?.ok === false) { + throw new Error(result.error ?? fallback) + } +} + +function createdIssue(result: unknown) { + const issue = result as { + ok?: boolean + id?: string + identifier?: string + title?: string + url?: string + error?: string + } + if (issue.ok === false || !issue.id || !issue.identifier) { + throw new Error(issue.error ?? 'Failed to create Linear issue') + } + return { + id: issue.id, + identifier: issue.identifier, + ...(issue.title ? { title: issue.title } : {}), + ...(issue.url ? { url: issue.url } : {}) + } +} diff --git a/mobile/src/tasks/native-host-task-list-operations.ts b/mobile/src/tasks/native-host-task-list-operations.ts new file mode 100644 index 000000000000..532f4efdb848 --- /dev/null +++ b/mobile/src/tasks/native-host-task-list-operations.ts @@ -0,0 +1,76 @@ +import { extractLinearIssueReadItems } from './linear-mobile-issue-read' +import type { HostTaskListOperations } from './host-task-list-operations' +import type { RpcRequestSender } from '../transport/rpc-client' + +export function nativeHostTaskListOperations(client: RpcRequestSender): HostTaskListOperations { + return { + async listGitHub(payload) { + return successfulResult( + client.sendRequest( + 'github.listWorkItems', + { + repo: `id:${payload.repoId}`, + limit: payload.limit, + query: payload.query, + before: payload.before + }, + { timeoutMs: 30_000 } + ) + ) + }, + async countGitHub(payload) { + const result = await successfulResult( + client.sendRequest( + 'github.countWorkItems', + { repo: `id:${payload.repoId}`, query: payload.query }, + { timeoutMs: 30_000 } + ) + ) + return typeof result === 'number' ? result : 0 + }, + listGitLab(payload) { + return successfulResult( + client.sendRequest('gitlab.listWorkItems', { + repo: `id:${payload.repoId}`, + state: payload.state, + page: payload.page, + perPage: payload.perPage, + query: payload.query + }) + ) + }, + async listGitLabTodos(repoId) { + // An empty todo list comes back as null from older hosts; the seam promises an array. + const todos = await successfulResult( + client.sendRequest('gitlab.todos', { repo: `id:${repoId}` }) + ) + return Array.isArray(todos) ? todos : [] + }, + async listLinear(payload) { + const response = payload.query + ? client.sendRequest('linear.searchIssues', { + query: payload.query, + limit: payload.limit, + workspaceId: payload.workspaceId + }) + : client.sendRequest('linear.listIssues', { + filter: payload.filter, + limit: payload.limit, + workspaceId: payload.workspaceId + }) + return extractLinearIssueReadItems(await successfulResult(response)) + } + } +} + +async function successfulResult(request: Promise): Promise { + const response = (await request) as { + ok: boolean + result?: unknown + error?: { message?: string } + } + if (!response.ok) { + throw new Error(response.error?.message ?? 'Task provider request failed') + } + return response.result as T +} diff --git a/mobile/src/tasks/native-host-task-operation-contracts.test.ts b/mobile/src/tasks/native-host-task-operation-contracts.test.ts new file mode 100644 index 000000000000..99d2bcd2d859 --- /dev/null +++ b/mobile/src/tasks/native-host-task-operation-contracts.test.ts @@ -0,0 +1,57 @@ +import { describe, expect, it, vi } from 'vitest' +import type { RpcClient } from '../transport/rpc-client' +import { nativeHostTaskItemFileOperations } from './native-host-task-item-file-operations' +import { nativeHostTaskListOperations } from './native-host-task-list-operations' +import { nativeHostTaskProjectFileOperations } from './native-host-task-project-file-operations' +import { nativeHostTaskProjectMutationOperations } from './native-host-task-project-mutation-operations' + +function client(sendRequest: RpcClient['sendRequest']): RpcClient { + return { sendRequest } as unknown as RpcClient +} + +const itemTarget = { repoId: 'repo-1', number: 7 } +const projectTarget = { number: 7, slug: { owner: 'orca', repo: 'orca' }, type: 'pr' as const } + +describe('native host task operation contracts', () => { + it('rejects a non-array checks payload instead of crashing the checks list', async () => { + const sendRequest = vi + .fn() + .mockResolvedValue({ ok: true, result: { error: 'rate limited' } }) + + await expect( + nativeHostTaskItemFileOperations(client(sendRequest)).refreshChecks(itemTarget, 'sha') + ).rejects.toThrow('Invalid checks response') + await expect( + nativeHostTaskProjectFileOperations(client(sendRequest)).refreshChecks( + projectTarget, + 'repo-1', + 'sha' + ) + ).rejects.toThrow('Invalid checks response') + }) + + it('reads an absent GitLab todo list as empty rather than an error banner', async () => { + const sendRequest = vi + .fn() + .mockResolvedValue({ ok: true, result: null }) + + await expect( + nativeHostTaskListOperations(client(sendRequest)).listGitLabTodos('repo-1') + ).resolves.toEqual([]) + }) + + it('gives project merge and rerun the long timeout their item-level twins use', async () => { + const sendRequest = vi.fn().mockResolvedValue({ + ok: true, + result: { ok: true } + }) + const operations = nativeHostTaskProjectMutationOperations(client(sendRequest)) + + await operations.rerunChecks(projectTarget, 'repo-1', { failedOnly: true }) + await operations.merge(projectTarget, 'repo-1', 'squash') + + for (const call of sendRequest.mock.calls) { + expect(call[2]).toEqual({ timeoutMs: 60_000 }) + } + }) +}) diff --git a/mobile/src/tasks/native-host-task-operations.ts b/mobile/src/tasks/native-host-task-operations.ts new file mode 100644 index 000000000000..61182b6378ad --- /dev/null +++ b/mobile/src/tasks/native-host-task-operations.ts @@ -0,0 +1,31 @@ +import type { RpcClient } from '../transport/rpc-client' +import type { HostTaskOperations } from './host-task-operations' +import { nativeHostTaskDetailOperations } from './native-host-task-detail-operations' +import { nativeHostTaskItemFileOperations } from './native-host-task-item-file-operations' +import { nativeHostTaskItemMutationOperations } from './native-host-task-item-mutation-operations' +import { nativeHostTaskItemReviewOperations } from './native-host-task-item-review-operations' +import { nativeHostTaskLinearOperations } from './native-host-task-linear-operations' +import { nativeHostTaskListOperations } from './native-host-task-list-operations' +import { nativeHostTaskPreferenceOperations } from './native-host-task-preference-operations' +import { nativeHostTaskProjectFileOperations } from './native-host-task-project-file-operations' +import { nativeHostTaskProjectMutationOperations } from './native-host-task-project-mutation-operations' +import { nativeHostTaskProjectReadOperations } from './native-host-task-project-read-operations' +import { nativeHostTaskProviderWriteOperations } from './native-host-task-provider-write-operations' +import { nativeHostTaskReadOperations } from './native-host-task-read-operations' + +export function nativeHostTaskOperations(client: RpcClient): HostTaskOperations { + return { + read: nativeHostTaskReadOperations(client), + preference: nativeHostTaskPreferenceOperations(client), + list: nativeHostTaskListOperations(client), + detail: nativeHostTaskDetailOperations(client), + itemMutation: nativeHostTaskItemMutationOperations(client), + itemReview: nativeHostTaskItemReviewOperations(client), + itemFile: nativeHostTaskItemFileOperations(client), + linear: nativeHostTaskLinearOperations(client), + providerWrite: nativeHostTaskProviderWriteOperations(client), + projectRead: nativeHostTaskProjectReadOperations(client), + projectMutation: nativeHostTaskProjectMutationOperations(client), + projectFile: nativeHostTaskProjectFileOperations(client) + } +} diff --git a/mobile/src/tasks/native-host-task-preference-operations.ts b/mobile/src/tasks/native-host-task-preference-operations.ts new file mode 100644 index 000000000000..06986c2f4752 --- /dev/null +++ b/mobile/src/tasks/native-host-task-preference-operations.ts @@ -0,0 +1,23 @@ +import { persistSetupHookTrustApproval } from './setup-hook-trust' +import type { HostTaskPreferenceOperations } from './host-task-preference-operations' +import type { RpcRequestSender } from '../transport/rpc-client' + +export function nativeHostTaskPreferenceOperations( + client: RpcRequestSender +): HostTaskPreferenceOperations { + return { + async updateResume(taskResumeState) { + requireSuccess(await client.sendRequest('ui.set', { taskResumeState })) + }, + async updateSettings(settings) { + requireSuccess(await client.sendRequest('settings.update', settings)) + }, + persistSetupTrust: (args) => persistSetupHookTrustApproval({ client, ...args }) + } +} + +function requireSuccess(response: { ok: boolean; error?: { message?: string } }): void { + if (!response.ok) { + throw new Error(response.error?.message ?? 'Task preference update failed') + } +} diff --git a/mobile/src/tasks/native-host-task-project-file-operations.ts b/mobile/src/tasks/native-host-task-project-file-operations.ts new file mode 100644 index 000000000000..126bbf0eae3a --- /dev/null +++ b/mobile/src/tasks/native-host-task-project-file-operations.ts @@ -0,0 +1,72 @@ +import type { HostTaskProjectFileOperations } from './host-task-project-file-operations' +import type { HostTaskProjectItemTarget } from './host-task-project-mutation-operations' +import type { RpcRequestSender } from '../transport/rpc-client' + +export function nativeHostTaskProjectFileOperations( + client: RpcRequestSender +): HostTaskProjectFileOperations { + return { + async refreshChecks(target, repoId, headSha) { + const checks = await request(client, 'github.prChecks', { + ...repoPayload(target, repoId), + prNumber: target.number, + headSha, + noCache: true + }) + if (!Array.isArray(checks)) { + throw new Error('Invalid checks response') + } + return checks + }, + async setFileViewed(target, repoId, payload) { + const result = await request(client, 'github.setPRFileViewed', { + ...repoPayload(target, repoId), + ...payload + }) + if (result !== true) { + throw new Error('Failed to sync viewed state with GitHub.') + } + }, + loadFileContents(target, repoId, payload) { + return request(client, 'github.prFileContents', { + ...repoPayload(target, repoId), + prNumber: target.number, + ...payload + }) + }, + async addInlineComment(target, repoId, payload) { + const result = await request<{ + ok?: boolean + error?: string + comment?: Awaited> + }>(client, 'github.addPRReviewComment', { + ...repoPayload(target, repoId), + prNumber: target.number, + ...payload + }) + if (result.ok === false) { + throw new Error(result.error ?? 'Failed to add review comment') + } + return result.comment + } + } +} + +function repoPayload(target: HostTaskProjectItemTarget, repoId: string) { + return { + repo: `id:${repoId}`, + prRepo: { owner: target.owner, repo: target.repo, host: target.host } + } +} + +async function request( + client: RpcRequestSender, + method: string, + payload: object +): Promise { + const response = await client.sendRequest(method, payload, { timeoutMs: 30_000 }) + if (!response.ok) { + throw new Error(response.error?.message ?? 'Task request failed') + } + return response.result as T +} diff --git a/mobile/src/tasks/native-host-task-project-mutation-operations.ts b/mobile/src/tasks/native-host-task-project-mutation-operations.ts new file mode 100644 index 000000000000..3f2f5dd339cf --- /dev/null +++ b/mobile/src/tasks/native-host-task-project-mutation-operations.ts @@ -0,0 +1,187 @@ +import type { DetailComment } from './mobile-tasks-provider-detail-types' +import type { + HostTaskProjectItemTarget, + HostTaskProjectMutationOperations +} from './host-task-project-mutation-operations' +import type { RpcRequestSender } from '../transport/rpc-client' +import { + fetchAddIssueComment, + fetchAddPRReviewCommentReply, + fetchMergePR, + fetchRequestPRReviewers, + fetchRerunPRChecks, + fetchResolveReviewThread, + type GitHubPrMutationOutcome +} from '../session/github-pr-mutations' + +const PROJECT_PR_MUTATION_TIMEOUT_MS = 60_000 + +export function nativeHostTaskProjectMutationOperations( + client: RpcRequestSender +): HostTaskProjectMutationOperations { + return { + async updateItem(target, updates) { + await projectMutation( + client, + target.type === 'issue' + ? 'github.project.updateIssueBySlug' + : 'github.project.updatePullRequestBySlug', + { ...slugPayload(target), updates } + ) + }, + async addComment(target, body) { + const result = await projectMutation<{ comment?: DetailComment }>( + client, + 'github.project.addIssueCommentBySlug', + { ...slugPayload(target), body } + ) + return result.comment + }, + async updateComment(target, commentId, body) { + await projectMutation(client, 'github.project.updateIssueCommentBySlug', { + owner: target.owner, + repo: target.repo, + host: target.host, + commentId, + body + }) + }, + async deleteComment(target, commentId) { + await projectMutation(client, 'github.project.deleteIssueCommentBySlug', { + owner: target.owner, + repo: target.repo, + host: target.host, + commentId + }) + }, + async updateMetadata(target, updates) { + await projectMutation(client, 'github.project.updateIssueBySlug', { + ...slugPayload(target), + updates + }) + }, + async updateField(target, fieldId, value) { + await projectMutation( + client, + value === null ? 'github.project.clearItemField' : 'github.project.updateItemField', + value === null + ? { projectId: target.projectId, host: target.host, itemId: target.itemId, fieldId } + : { + projectId: target.projectId, + host: target.host, + itemId: target.itemId, + fieldId, + value + } + ) + }, + async updateIssueType(target, issueTypeId) { + await projectMutation(client, 'github.project.updateIssueTypeBySlug', { + ...slugPayload(target), + issueTypeId + }) + }, + async resolveReviewThread(target, repoId, threadId, resolve) { + requirePrMutation( + await fetchResolveReviewThread(client, repoId, { + threadId, + resolve, + // Why: `prRepo` is fork/GHES decoration the host treats as optional, and a draft row + // has no slug — send it only when one resolved rather than an empty pair. + prRepo: target.owner && target.repo ? slugPayload(target) : null + }) + ) + }, + async replyReviewComment(target, repoId, payload) { + return prMutationComment( + await fetchAddPRReviewCommentReply(client, repoId, { + prNumber: target.number, + ...payload, + prRepo: slugPayload(target) + }) + ) + }, + async addConversationComment(target, repoId, body) { + return prMutationComment( + await fetchAddIssueComment(client, repoId, { + prNumber: target.number, + body, + prRepo: slugPayload(target), + type: target.type + }) + ) + }, + async requestReviewers(target, repoId, reviewers) { + requirePrMutation( + await fetchRequestPRReviewers(client, repoId, { + prNumber: target.number, + reviewers, + prRepo: slugPayload(target) + }) + ) + }, + async rerunChecks(target, repoId, payload) { + requirePrMutation( + await fetchRerunPRChecks( + client, + repoId, + { prNumber: target.number, ...payload, prRepo: slugPayload(target) }, + // A CI rerun and a merge both routinely outrun the 30s default. + { timeoutMs: PROJECT_PR_MUTATION_TIMEOUT_MS } + ) + ) + }, + async merge(target, repoId, method) { + requirePrMutation( + await fetchMergePR( + client, + repoId, + { prNumber: target.number, method, prRepo: slugPayload(target) }, + { timeoutMs: PROJECT_PR_MUTATION_TIMEOUT_MS } + ) + ) + } + } +} + +function slugPayload(target: HostTaskProjectItemTarget) { + return { + owner: target.owner, + repo: target.repo, + host: target.host, + number: target.number + } +} + +async function projectMutation( + client: RpcRequestSender, + method: string, + payload: object +): Promise { + const response = (await client.sendRequest(method, payload, { timeoutMs: 30_000 })) as { + ok: boolean + result?: { ok?: boolean; error?: string | { message?: string } } + error?: { message?: string } + } + if (!response.ok) { + throw new Error(response.error?.message ?? 'GitHub Project request failed') + } + if (response.result?.ok === false) { + const error = response.result.error + throw new Error( + typeof error === 'string' ? error : (error?.message ?? 'GitHub Project request failed') + ) + } + return (response.result ?? {}) as T +} + +function requirePrMutation(result: GitHubPrMutationOutcome): void { + if (!result.ok) { + throw new Error(result.error) + } +} + +function prMutationComment(result: GitHubPrMutationOutcome): DetailComment | undefined { + requirePrMutation(result) + return (result as { comment?: DetailComment }).comment +} diff --git a/mobile/src/tasks/native-host-task-project-read-operations.ts b/mobile/src/tasks/native-host-task-project-read-operations.ts new file mode 100644 index 000000000000..502102802c07 --- /dev/null +++ b/mobile/src/tasks/native-host-task-project-read-operations.ts @@ -0,0 +1,113 @@ +import type { GitHubProjectViewSummary } from './github-project-reference' +import type { + HostTaskProjectListResult, + HostTaskProjectResolveResult +} from './host-task-project-payloads' +import type { GitHubProjectTable } from './mobile-tasks-view-state-types' +import type { HostTaskProjectReadOperations } from './host-task-project-read-operations' +import { projectGitHubTaskDetail } from './github-task-detail-projection' +import type { RpcRequestSender } from '../transport/rpc-client' + +export function nativeHostTaskProjectReadOperations( + client: RpcRequestSender +): HostTaskProjectReadOperations { + return { + async listAccessible(host) { + return projectResult<{ + projects: HostTaskProjectListResult['projects'] + partialFailures?: HostTaskProjectListResult['partialFailures'] + }>(client.sendRequest('github.project.listAccessible', { host })).then((result) => ({ + projects: result.projects, + partialFailures: result.partialFailures ?? [] + })) + }, + async listViews(project) { + const result = await projectResult<{ views: GitHubProjectViewSummary[] }>( + client.sendRequest('github.project.listViews', { + owner: project.owner, + host: project.host, + ownerType: project.ownerType, + projectNumber: project.number + }) + ) + return result.views + }, + async resolveRef(payload) { + const result = await projectResult( + client.sendRequest('github.project.resolveRef', payload) + ) + return { + owner: result.owner, + ownerType: result.ownerType, + number: result.number, + title: result.title, + host: result.host, + viewNumber: result.viewNumber + } + }, + async loadTable(payload) { + const result = await projectResult<{ data: GitHubProjectTable }>( + client.sendRequest( + 'github.project.viewTable', + { + owner: payload.owner, + host: payload.host, + ownerType: payload.ownerType, + projectNumber: payload.number, + viewId: payload.viewId, + queryOverride: payload.queryOverride + }, + { timeoutMs: 60_000 } + ) + ) + return result.data + }, + async loadItemDetail(payload) { + const result = await projectResult<{ details: unknown }>( + client.sendRequest('github.project.workItemDetailsBySlug', payload, { timeoutMs: 30_000 }) + ) + return projectGitHubTaskDetail(result.details) + }, + async listItemLabels(payload) { + const result = await projectResult<{ labels?: string[] }>( + client.sendRequest('github.project.listLabelsBySlug', payload, { timeoutMs: 30_000 }) + ) + return result.labels ?? [] + }, + async listItemAssignableUsers(payload) { + const result = await projectResult<{ + users?: Awaited> + }>( + client.sendRequest('github.project.listAssignableUsersBySlug', payload, { + timeoutMs: 30_000 + }) + ) + return result.users ?? [] + }, + async listIssueTypes(payload) { + const result = await projectResult<{ + types?: Awaited> + }>( + client.sendRequest('github.project.listIssueTypesBySlug', payload, { + timeoutMs: 30_000 + }) + ) + return result.types ?? [] + } + } +} + +export async function projectResult(request: Promise): Promise { + const response = (await request) as { + ok: boolean + result?: { ok?: boolean; error?: { message?: string } } + error?: { message?: string } + } + if (!response.ok) { + throw new Error(response.error?.message ?? 'GitHub Project request failed') + } + if (response.result?.ok === false) { + throw new Error(response.result.error?.message ?? 'GitHub Project request failed') + } + return response.result as T +} diff --git a/mobile/src/tasks/native-host-task-provider-write-operations.ts b/mobile/src/tasks/native-host-task-provider-write-operations.ts new file mode 100644 index 000000000000..be5741b80c6d --- /dev/null +++ b/mobile/src/tasks/native-host-task-provider-write-operations.ts @@ -0,0 +1,48 @@ +import type { HostTaskProviderWriteOperations } from './host-task-provider-write-operations' +import type { RpcRequestSender } from '../transport/rpc-client' + +export function nativeHostTaskProviderWriteOperations( + client: RpcRequestSender +): HostTaskProviderWriteOperations { + return { + async createIssue(payload) { + const response = await client.sendRequest( + payload.provider === 'github' ? 'github.createIssue' : 'gitlab.createIssue', + { + repo: `id:${payload.repoId}`, + title: payload.title, + body: payload.body + } + ) + if (!response.ok) { + throw new Error(response.error?.message ?? 'Task request failed') + } + const result = response.result as { + ok?: boolean + number?: number + url?: string + error?: string + } + if (result.ok === false) { + throw new Error(result.error ?? `Failed to create ${payload.provider} issue`) + } + return { + ...(typeof result.number === 'number' ? { number: result.number } : {}), + ...(result.url ? { url: result.url } : {}) + } + }, + async updateIssueSource(repoId, preference) { + const response = await client.sendRequest( + 'repo.update', + { + repo: `id:${repoId}`, + updates: { issueSourcePreference: preference } + }, + { timeoutMs: 15_000 } + ) + if (!response.ok) { + throw new Error(response.error?.message ?? 'Task request failed') + } + } + } +} diff --git a/mobile/src/tasks/native-host-task-read-operations.ts b/mobile/src/tasks/native-host-task-read-operations.ts new file mode 100644 index 000000000000..9cb7d5f38175 --- /dev/null +++ b/mobile/src/tasks/native-host-task-read-operations.ts @@ -0,0 +1,124 @@ +import type { GitHubOwnerRepo } from '../../../src/shared/github/pull-request-types' +import { MOBILE_TASKS_CAPABILITY } from './mobile-tasks-capability' +import type { + HostTaskBootstrap, + HostTaskLinearContext, + HostTaskReadOperations, + HostTaskRepository +} from './host-task-read-operations' +import type { RpcRequestSender } from '../transport/rpc-client' +import type { RpcResponse, RpcSuccess } from '../transport/types' + +export function nativeHostTaskReadOperations(client: RpcRequestSender): HostTaskReadOperations { + return { + bootstrap: () => bootstrap(client), + listRepositories: () => listRepositories(client), + loadLinearContext: () => loadLinearContext(client), + resolveGitHubRepoSlug: (repoId) => resolveGitHubRepoSlug(client, repoId) + } +} + +async function bootstrap(client: RpcRequestSender): Promise { + const statusResponse = await client.sendRequest('status.get') + requireSuccess(statusResponse) + const status = statusResponse.result as { capabilities?: string[] } + if (!status.capabilities?.includes(MOBILE_TASKS_CAPABILITY)) { + return emptyBootstrap(false) + } + const [settingsResponse, uiResponse, preflightResponse, linearStatusResponse] = await Promise.all( + [ + client.sendRequest('settings.get'), + client.sendRequest('ui.get'), + client.sendRequest('preflight.check'), + client.sendRequest('linear.status') + ] + ) + const settingsEnvelope = successResult<{ settings?: HostTaskBootstrap['settings'] }>( + settingsResponse + ) + const uiEnvelope = successResult<{ + ui?: { + taskResumeState?: HostTaskBootstrap['taskResumeState'] + trustedOrcaHooks?: HostTaskBootstrap['trustedOrcaHooks'] + } + }>(uiResponse) + const preflight = successResult<{ glab?: { installed?: boolean } }>(preflightResponse) + return { + supported: true, + settings: settingsEnvelope?.settings ?? {}, + taskResumeState: uiEnvelope?.ui?.taskResumeState ?? {}, + trustedOrcaHooks: uiEnvelope?.ui?.trustedOrcaHooks ?? {}, + gitLabInstalled: preflight?.glab?.installed === true, + linearStatus: normalizeLinearStatus(successResult(linearStatusResponse)) + } +} + +async function listRepositories(client: RpcRequestSender): Promise { + const response = await client.sendRequest('repo.list') + requireSuccess(response) + const result = response.result as { repos?: HostTaskRepository[] } + return result.repos ?? [] +} + +async function loadLinearContext(client: RpcRequestSender): Promise { + const statusResponse = await client.sendRequest('linear.status') + requireSuccess(statusResponse) + const status = normalizeLinearStatus(statusResponse.result) + if (!status.connected) { + return { status, teams: [] } + } + const workspaceId = + status.selectedWorkspaceId ?? status.activeWorkspaceId ?? status.workspaces[0]?.id ?? null + const teamsResponse = await client.sendRequest('linear.listTeams', { + workspaceId: workspaceId ?? undefined + }) + requireSuccess(teamsResponse) + return { + status: { ...status, selectedWorkspaceId: workspaceId }, + teams: teamsResponse.result as HostTaskLinearContext['teams'] + } +} + +async function resolveGitHubRepoSlug( + client: RpcRequestSender, + repoId: string +): Promise { + const response = await client.sendRequest( + 'github.repoSlug', + { repo: `id:${repoId}` }, + { timeoutMs: 30_000 } + ) + requireSuccess(response) + return response.result as GitHubOwnerRepo | null +} + +function emptyBootstrap(supported: boolean): HostTaskBootstrap { + return { + supported, + settings: {}, + taskResumeState: {}, + trustedOrcaHooks: {}, + gitLabInstalled: false, + linearStatus: normalizeLinearStatus(null) + } +} + +function normalizeLinearStatus(value: unknown): HostTaskBootstrap['linearStatus'] { + const status = (value ?? {}) as Partial + return { + connected: status.connected === true, + workspaces: Array.isArray(status.workspaces) ? status.workspaces : [], + selectedWorkspaceId: status.selectedWorkspaceId ?? null, + activeWorkspaceId: status.activeWorkspaceId ?? null + } +} + +function successResult(response: RpcResponse): T | null { + return response.ok ? (response.result as T) : null +} + +function requireSuccess(response: RpcResponse): asserts response is RpcSuccess { + if (!response.ok) { + throw new Error(response.error?.message ?? 'Task operation failed') + } +} diff --git a/mobile/src/tasks/native-host-task-review-comment-addressing.test.ts b/mobile/src/tasks/native-host-task-review-comment-addressing.test.ts new file mode 100644 index 000000000000..d0c280267ce5 --- /dev/null +++ b/mobile/src/tasks/native-host-task-review-comment-addressing.test.ts @@ -0,0 +1,78 @@ +import { describe, expect, it, vi } from 'vitest' +import type { RpcClient } from '../transport/rpc-client' +import { nativeHostTaskItemReviewOperations } from './native-host-task-item-review-operations' +import { nativeHostTaskProjectMutationOperations } from './native-host-task-project-mutation-operations' + +const ISSUE_ROW = { + owner: 'orca', + repo: 'orca', + host: 'github.com', + number: 42, + type: 'issue' +} as const + +const PR_ROW = { ...ISSUE_ROW, number: 7, type: 'pr' } as const + +function client(sendRequest: RpcClient['sendRequest']): RpcClient { + return { sendRequest } as unknown as RpcClient +} + +describe('native task review comment addressing', () => { + // Why: an issue row addressed as a PR posts into the wrong conversation on the host. + it('addresses a project conversation comment by the row type', async () => { + const sendRequest = vi.fn().mockResolvedValue({ + ok: true, + result: { ok: true } + }) + const operations = nativeHostTaskProjectMutationOperations(client(sendRequest)) + + await operations.addConversationComment(ISSUE_ROW, 'repo-1', 'hi') + await operations.addConversationComment(PR_ROW, 'repo-1', 'hi') + + expect(sendRequest.mock.calls[0]?.[1]).toMatchObject({ number: 42, type: 'issue' }) + expect(sendRequest.mock.calls[1]?.[1]).toMatchObject({ number: 7, type: 'pr' }) + }) + + // Why: only the server entry carries the numeric id a follow-up reply needs to stay on the + // same review thread; a locally minted `local-` id silently downgrades the next reply. + it('returns the server comment from a project reply instead of dropping it', async () => { + const comment = { id: 991, body: 'hi', author: 'octocat' } + const operations = nativeHostTaskProjectMutationOperations( + client(vi.fn().mockResolvedValue({ ok: true, result: { ok: true, comment } })) + ) + + await expect( + operations.replyReviewComment(PR_ROW, 'repo-1', { commentId: 5, body: 'hi' }) + ).resolves.toEqual(comment) + await expect(operations.addConversationComment(ISSUE_ROW, 'repo-1', 'hi')).resolves.toEqual( + comment + ) + }) + + it('returns the server comment from an item-level review reply', async () => { + const comment = { id: 992, body: 'hi', author: 'octocat' } + const operations = nativeHostTaskItemReviewOperations( + client(vi.fn().mockResolvedValue({ ok: true, result: { ok: true, comment } })) + ) + + await expect( + operations.replyReviewComment( + { provider: 'github', repoId: 'repo-1', number: 7, type: 'pr' }, + { commentId: 5, body: 'hi' } + ) + ).resolves.toEqual(comment) + }) + + it('still raises the host failure message when a reply is refused', async () => { + const operations = nativeHostTaskItemReviewOperations( + client(vi.fn().mockResolvedValue({ ok: true, result: { ok: false, error: 'locked' } })) + ) + + await expect( + operations.replyReviewComment( + { provider: 'github', repoId: 'repo-1', number: 7, type: 'pr' }, + { commentId: 5, body: 'hi' } + ) + ).rejects.toThrow('locked') + }) +}) diff --git a/mobile/src/tasks/setup-hook-trust.ts b/mobile/src/tasks/setup-hook-trust.ts index 723813939890..493f4ba9d2c1 100644 --- a/mobile/src/tasks/setup-hook-trust.ts +++ b/mobile/src/tasks/setup-hook-trust.ts @@ -1,5 +1,5 @@ import type { PersistedTrustedOrcaHooks } from '../../../src/shared/orca-yaml-hook-types' -import type { RpcClient } from '../transport/rpc-client' +import type { RpcRequestSender } from '../transport/rpc-client' export type SetupHookTrust = { contentHash: string @@ -38,7 +38,7 @@ export function trustedOrcaHooksWithSetupApproval(args: { } export async function persistSetupHookTrustApproval(args: { - client: RpcClient + client: RpcRequestSender trust: PersistedTrustedOrcaHooks repoId: string contentHash: string @@ -47,7 +47,7 @@ export async function persistSetupHookTrustApproval(args: { const next = trustedOrcaHooksWithSetupApproval(args) const response = await args.client.sendRequest('ui.set', { trustedOrcaHooks: next }) if (!response.ok) { - throw new Error(response.error.message) + throw new Error(response.error?.message ?? 'Hook trust update failed') } return next } diff --git a/mobile/src/tasks/smart-source-search-requests.ts b/mobile/src/tasks/smart-source-search-requests.ts index 876e2ef1a209..734b435657f1 100644 --- a/mobile/src/tasks/smart-source-search-requests.ts +++ b/mobile/src/tasks/smart-source-search-requests.ts @@ -2,7 +2,7 @@ import type { GitHubWorkItem } from '../../../src/shared/github/work-item-types' import type { GitLabWorkItem } from '../../../src/shared/gitlab-types' import type { LinearIssue } from '../../../src/shared/linear/issue-types' import type { BaseRefSearchResult } from '../../../src/shared/repo-types' -import type { RpcClient } from '../transport/rpc-client' +import type { RpcRequestSender } from '../transport/rpc-client' import type { RpcSuccess } from '../transport/types' import { extractLinearIssueReadItems } from './linear-mobile-issue-read' import { PER_REPO_FETCH_LIMIT } from './mobile-work-items' @@ -22,7 +22,7 @@ export function scopeGitHubQuery(query: string): string { } export async function searchGitHubItems( - client: RpcClient, + client: RpcRequestSender, repoId: string, query: string ): Promise { @@ -41,7 +41,7 @@ export async function searchGitHubItems( } export async function searchGitLabItems( - client: RpcClient, + client: RpcRequestSender, repoId: string, query: string, state: MrStateFilter @@ -67,7 +67,7 @@ export async function searchGitLabItems( } export async function searchLinearIssues( - client: RpcClient, + client: RpcRequestSender, query: string, linearWorkspaceId: string | null | undefined ): Promise { @@ -94,7 +94,7 @@ export async function searchLinearIssues( } export async function searchBranches( - client: RpcClient, + client: RpcRequestSender, repoId: string, query: string ): Promise { diff --git a/mobile/src/tasks/source-workspace-create.ts b/mobile/src/tasks/source-workspace-create.ts index 6e666005ac3b..b96c28610ccf 100644 --- a/mobile/src/tasks/source-workspace-create.ts +++ b/mobile/src/tasks/source-workspace-create.ts @@ -28,8 +28,9 @@ export type CreateWorkspaceFromComposerArgs = { setupDecision: WorkspaceCreateSetupDecision agent: WorkspaceCreateAgentBundle workspaceName: string | undefined - nameIsAutoManaged?: boolean note: string | undefined + sparseCheckout?: { directories: string[]; presetId?: string } + nameIsAutoManaged?: boolean worktreeCreateIdempotency: WorktreeCreateIdempotencyProbe } @@ -91,8 +92,9 @@ async function createWorkItemWorkspace(args: { setupDecision: WorkspaceCreateSetupDecision agent: WorkspaceCreateAgentBundle workspaceName: string | undefined - nameIsAutoManaged?: boolean note: string | undefined + sparseCheckout?: { directories: string[]; presetId?: string } + nameIsAutoManaged?: boolean worktreeCreateIdempotency: WorktreeCreateIdempotencyProbe }): Promise { const { client, selection, targetRepoId, setupDecision, agent, workspaceName, note } = args @@ -130,6 +132,7 @@ async function createWorkItemWorkspace(args: { compareBaseRef, branchNameOverride, pushTarget, + sparseCheckout: args.sparseCheckout, nameIsAutoManaged: args.nameIsAutoManaged }) // buildTaskWorkspaceCreateParams computes the name; reuse it as the retry base diff --git a/mobile/src/tasks/worktree-create-capability.ts b/mobile/src/tasks/worktree-create-capability.ts index c4ca8170312b..926d89f38e49 100644 --- a/mobile/src/tasks/worktree-create-capability.ts +++ b/mobile/src/tasks/worktree-create-capability.ts @@ -1,5 +1,5 @@ import { useCallback, useEffect, useRef, useState } from 'react' -import type { RpcClient } from '../transport/rpc-client' +import type { RpcClient, RpcRequestSender } from '../transport/rpc-client' import { isLogicalClientCutoverError } from '../transport/stable-logical-rpc-client' import type { RpcSuccess } from '../transport/types' import { readMobileRuntimeHostPlatform } from '../transport/mobile-runtime-host-platform' @@ -32,7 +32,7 @@ const UNSUPPORTED_CAPABILITIES: NewWorktreeRuntimeCapabilities = { // Why: status.get is safe to replay and must settle before create, independently // of slower provider probes, so ambiguous cutover retries are gated correctly. export async function readNewWorktreeRuntimeCapabilities( - client: RpcClient + client: RpcRequestSender ): Promise { for (let migrationRetry = 0; ; migrationRetry += 1) { try { diff --git a/mobile/src/tasks/worktree-create-retry.ts b/mobile/src/tasks/worktree-create-retry.ts index a3fa8ae2e1b7..a395e59baf42 100644 --- a/mobile/src/tasks/worktree-create-retry.ts +++ b/mobile/src/tasks/worktree-create-retry.ts @@ -21,7 +21,9 @@ import { // branches outlive worktrees in git, and remote branches/PRs aren't visible from // worktree.ps. Retry by appending -2, -3, ... mirroring the desktop createWorktree // loop in src/renderer/src/store/slices/worktrees.ts. -export type WorktreeCreateResult = { worktreeId: string; name: string } | { error: string } +export type WorktreeCreateResult = + | { worktreeId: string; name: string; warning?: string } + | { error: string } // Why: a create in flight when the mobile transport migrates (relay/direct // hand-off on shoddy cellular, relay lease rotation) rejects with a cutover error @@ -84,6 +86,7 @@ export async function createWorktreeWithNameRetry( if (response.ok) { const result = (response as RpcSuccess).result as { worktree: { id: string; displayName?: string } + warning?: string } const authoritativeName = result.worktree.displayName return { @@ -91,7 +94,8 @@ export async function createWorktreeWithNameRetry( name: typeof authoritativeName === 'string' && authoritativeName.trim() ? authoritativeName - : candidateName + : candidateName, + ...(result.warning ? { warning: result.warning } : {}) } } lastError = response.error.message diff --git a/mobile/src/transport/rpc-client.ts b/mobile/src/transport/rpc-client.ts index 10f586d2780c..4ea94677de76 100644 --- a/mobile/src/transport/rpc-client.ts +++ b/mobile/src/transport/rpc-client.ts @@ -46,6 +46,10 @@ export type RpcClient = { close: () => void } +/** The one method a request adapter needs. Narrowing to it keeps adapters testable with a stub + * and free of the reconnect and subscription surface they never touch. */ +export type RpcRequestSender = Pick + export type ConnectOptions = { onStateChange?: (state: ConnectionState) => void onLog?: ConnectionLogSink diff --git a/mobile/src/worktree/default-host-workspace-catalog-operations.ts b/mobile/src/worktree/default-host-workspace-catalog-operations.ts new file mode 100644 index 000000000000..9bb742878282 --- /dev/null +++ b/mobile/src/worktree/default-host-workspace-catalog-operations.ts @@ -0,0 +1,9 @@ +import type { RpcClient } from '../transport/rpc-client' +import type { HostWorkspaceCatalogOperations } from './host-workspace-catalog-operations' +import { nativeHostWorkspaceCatalogOperations } from './native-host-workspace-catalog-operations' + +export function defaultHostWorkspaceCatalogOperations( + client: RpcClient +): HostWorkspaceCatalogOperations { + return nativeHostWorkspaceCatalogOperations(client) +} diff --git a/mobile/src/worktree/default-host-workspace-creation-operations.ts b/mobile/src/worktree/default-host-workspace-creation-operations.ts new file mode 100644 index 000000000000..21e0ca6d0967 --- /dev/null +++ b/mobile/src/worktree/default-host-workspace-creation-operations.ts @@ -0,0 +1,9 @@ +import type { RpcClient } from '../transport/rpc-client' +import type { HostWorkspaceCreationOperations } from './host-workspace-creation-operations' +import { nativeHostWorkspaceCreationOperations } from './native-host-workspace-creation-operations' + +export function defaultHostWorkspaceCreationOperations( + client: RpcClient +): HostWorkspaceCreationOperations { + return nativeHostWorkspaceCreationOperations(client) +} diff --git a/mobile/src/worktree/default-host-workspace-operations.ts b/mobile/src/worktree/default-host-workspace-operations.ts new file mode 100644 index 000000000000..8ee207f93974 --- /dev/null +++ b/mobile/src/worktree/default-host-workspace-operations.ts @@ -0,0 +1,7 @@ +import type { RpcClient } from '../transport/rpc-client' +import type { HostWorkspaceOperations } from './host-workspace-operations' +import { nativeHostWorkspaceOperations } from './native-host-workspace-operations' + +export function defaultHostWorkspaceOperations(client: RpcClient): HostWorkspaceOperations { + return nativeHostWorkspaceOperations(client) +} diff --git a/mobile/src/worktree/host-workspace-catalog-operations.ts b/mobile/src/worktree/host-workspace-catalog-operations.ts new file mode 100644 index 000000000000..d63bfbd6f3d2 --- /dev/null +++ b/mobile/src/worktree/host-workspace-catalog-operations.ts @@ -0,0 +1,39 @@ +import type { HostWorkspaceHostContext } from './host-workspace-host-context' +import type { RepoSummary } from './host-worktree-rpc-types' +import type { Worktree } from './workspace-list-types' +import type { WorkspaceViewSettings } from './workspace-view-settings' + +export type HostWorkspaceChange = { + type: 'ready' | 'end' | 'reposChanged' | 'worktreesChanged' | 'error' +} + +export type HostWorkspaceCatalogFetch = + // Why (STA-3123): a failed poll must stay distinguishable from an empty catalog, so the + // host's own error code survives instead of collapsing into a generic transport failure. + | { kind: 'request_failed'; code: string } + // `commit` is deferred so the caller runs its own staleness check first; a superseded + // response must not advance the binding's snapshot token. + | { kind: 'response'; invalidShape: boolean; commit(): Worktree[] | null } + +export type HostWorkspaceCatalogOperations = { + getViewSettings(): Promise + setViewSettings(settings: WorkspaceViewSettings): Promise + listRepos(): Promise + listWorkspaces(limit: number): Promise + /** + * Snapshot-token catalog poll. Bindings that omit it fall back to `listWorkspaces`, which + * always transfers the full catalog and cannot report a host-side error code. + */ + fetchWorkspaceCatalog?(hostId: string): Promise + /** SSH labels and host platform for multi-host catalogs; bindings that omit it keep single-host rows. */ + listHostContext?(): Promise + setPinned(workspaceId: string, pinned: boolean): Promise + removeWorkspace(workspaceId: string): Promise + activateWorkspace(workspaceId: string): Promise + sleepWorkspace(workspaceId: string): Promise + notifyForeground(): void + subscribeChanges(listener: (event: HostWorkspaceChange) => void): () => void + // Why: a hosted page reads `connected` from the shell's relayed snapshot, so it can issue its + // first catalog request a beat before that socket serves one. A direct socket omits this. + readonly connectionStateIsRelayed?: boolean +} diff --git a/mobile/src/worktree/host-workspace-creation-operations.ts b/mobile/src/worktree/host-workspace-creation-operations.ts new file mode 100644 index 000000000000..5fee7251d743 --- /dev/null +++ b/mobile/src/worktree/host-workspace-creation-operations.ts @@ -0,0 +1,132 @@ +import type { GitHubWorkItem } from '../../../src/shared/github/work-item-types' +import type { GitLabWorkItem } from '../../../src/shared/gitlab-types' +import type { LinearIssue } from '../../../src/shared/linear/issue-types' +import type { PersistedTrustedOrcaHooks } from '../../../src/shared/orca-yaml-hook-types' +import type { BaseRefSearchResult } from '../../../src/shared/repo-types' +import type { TuiAgent } from '../../../src/shared/tui-agent' +import type { SparsePreset } from '../../../src/shared/worktree/create-types' +import type { GitHubPrStartPoint } from '../../../src/shared/worktree/types' +import type { RepoSlug } from '../../../src/shared/new-workspace/github-links' +import type { SshConnectionState } from '../../../src/shared/ssh-types' +import type { WorktreeCreateResult } from '../tasks/worktree-create-retry' +import type { WorktreeCreateIdempotencyProbe } from '../tasks/worktree-create-idempotency-policy' +import type { NewWorktreeRuntimeCapabilities } from '../tasks/worktree-create-capability' +import type { + MrStateFilter, + MobileComposerCreateSelection +} from '../tasks/mobile-composer-source-types' +import type { + ComposerHostedBase, + ResolveComposerMrBaseArgs, + ResolveComposerPrBaseArgs +} from '../tasks/composer-source-base-resolve' +import type { WorkspaceAgentChoice } from '../tasks/workspace-agent-selection' +import type { WorkspaceCreateSetupDecision } from '../tasks/workspace-create-params' +import type { SetupHookTrust } from '../tasks/setup-hook-trust' +import type { ExecutionHostId } from '../../../src/shared/execution-host' +import type { GitRemoteIdentity } from '../../../src/shared/git-remote-identity' +import type { RepoIcon } from '../../../src/shared/repo-icon' +import type { RetiredNameRegistry } from '../../../src/shared/worktree/retired-name-registry' + +export type NewWorkspaceRepository = { + id: string + displayName: string + path: string + badgeColor?: string + connectionId?: string | null + executionHostId?: ExecutionHostId | null + executionHostLabel?: string + projectId?: string + kind?: 'git' | 'folder' + upstream?: { owner: string; repo: string; host?: string } | null + repoIcon?: RepoIcon | null + gitRemoteIdentity?: GitRemoteIdentity | null +} + +export type NewWorkspaceRuntimeSettings = { + defaultTuiAgent?: TuiAgent | 'blank' | null + disabledTuiAgents?: TuiAgent[] + visibleTaskProviders?: unknown +} + +export type NewWorkspaceRepoHooks = { + hooks: { scripts?: { setup?: string } } | null + source: string | null + setupRunPolicy?: 'ask' | 'run-by-default' | 'skip-by-default' + setupTrust?: SetupHookTrust +} + +export type CreateBlankWorkspaceOperationArgs = { + repoId: string + baseName: string + agentChoice: WorkspaceAgentChoice + nameWasGenerated: boolean + comment: string | undefined + setupDecision: WorkspaceCreateSetupDecision + worktreeCreateIdempotency: WorktreeCreateIdempotencyProbe +} + +export type CreateWorkspaceFromSourceOperationArgs = { + selection: MobileComposerCreateSelection + targetRepoId: string + setupDecision: WorkspaceCreateSetupDecision + agentChoice: WorkspaceAgentChoice + workspaceName: string | undefined + note: string | undefined + sparseCheckout?: { directories: string[]; presetId?: string } + nameIsAutoManaged?: boolean + worktreeCreateIdempotency: WorktreeCreateIdempotencyProbe +} + +export type HostWorkspaceCreationOperations = { + listRepositories(): Promise + readRetiredWorktreeNames(repoId: string): Promise + readRuntimeSettings(): Promise + readTrustedHooks(): Promise + isGitLabCliInstalled(): Promise + isLinearConnected(): Promise + readSshState(targetId: string): Promise + connectSsh(targetId: string): Promise + detectAgents(connectionId: string | null): Promise + readRepoHooks(repoId: string): Promise + readRuntimeCapabilities(): Promise + listSparsePresets(repoId: string): Promise + saveSparsePreset( + repoId: string, + payload: { id?: string; name: string; directories: string[] } + ): Promise + persistSetupTrust(args: { + trust: PersistedTrustedOrcaHooks + repoId: string + contentHash: string + alwaysTrust: boolean + }): Promise + searchGitHubItems(repoId: string, query: string): Promise + searchGitLabItems(repoId: string, query: string, state: MrStateFilter): Promise + searchLinearIssues( + query: string, + linearWorkspaceId: string | null | undefined + ): Promise + searchBranches(repoId: string, query: string): Promise + resolveGitHubRepoSlug(repoId: string): Promise<{ supported: boolean; slug: RepoSlug | null }> + lookupGitHubItem(repoId: string, number: number): Promise + lookupGitHubItemByOwnerRepo(args: { + repoId: string + slug: RepoSlug + number: number + type: 'issue' | 'pr' + }): Promise + lookupGitLabItemByPath(args: { + repoId: string + host: string + path: string + iid: number + type: 'issue' | 'mr' + }): Promise + resolvePrBase(args: Omit): Promise + resolveMrBase(args: Omit): Promise + createBlankWorkspace(args: CreateBlankWorkspaceOperationArgs): Promise + createWorkspaceFromSource( + args: CreateWorkspaceFromSourceOperationArgs + ): Promise +} diff --git a/mobile/src/worktree/host-workspace-host-context.ts b/mobile/src/worktree/host-workspace-host-context.ts new file mode 100644 index 000000000000..f17f7ae843d8 --- /dev/null +++ b/mobile/src/worktree/host-workspace-host-context.ts @@ -0,0 +1,32 @@ +export type HostWorkspaceSshTarget = { id: string; label: string } + +/** Inputs the workspace list needs to name and badge rows from non-local execution hosts. */ +export type HostWorkspaceHostContext = { + sshTargets: readonly HostWorkspaceSshTarget[] + hostSettingOverrides: unknown + platform: NodeJS.Platform | null +} + +export function readHostWorkspaceSshTargets(result: unknown): HostWorkspaceSshTarget[] { + const targets = (result as { targets?: unknown } | null)?.targets + if (!Array.isArray(targets)) { + return [] + } + return targets.filter( + (target): target is HostWorkspaceSshTarget => + typeof target === 'object' && + target !== null && + typeof (target as HostWorkspaceSshTarget).id === 'string' && + typeof (target as HostWorkspaceSshTarget).label === 'string' + ) +} + +export function readHostWorkspacePlatform(result: unknown): NodeJS.Platform | null { + const platform = (result as { platform?: unknown } | null)?.platform + return typeof platform === 'string' && platform ? (platform as NodeJS.Platform) : null +} + +export function readHostWorkspaceSettingOverrides(result: unknown): unknown { + return (result as { settings?: { hostSettingOverrides?: unknown } } | null)?.settings + ?.hostSettingOverrides +} diff --git a/mobile/src/worktree/host-workspace-operations.ts b/mobile/src/worktree/host-workspace-operations.ts new file mode 100644 index 000000000000..fc2294b981b1 --- /dev/null +++ b/mobile/src/worktree/host-workspace-operations.ts @@ -0,0 +1,9 @@ +import type { HostWorkspaceCatalogOperations } from './host-workspace-catalog-operations' +import type { HostWorkspaceCreationOperations } from './host-workspace-creation-operations' + +/** Everything the workspace screens ask a host for, grouped by concern so a screen takes one prop + * and a provider is built once. Each namespace keeps its own contract file. */ +export type HostWorkspaceOperations = { + catalog: HostWorkspaceCatalogOperations + creation: HostWorkspaceCreationOperations +} diff --git a/mobile/src/worktree/native-host-workspace-catalog-operations.test.ts b/mobile/src/worktree/native-host-workspace-catalog-operations.test.ts new file mode 100644 index 000000000000..7d45231b5c7d --- /dev/null +++ b/mobile/src/worktree/native-host-workspace-catalog-operations.test.ts @@ -0,0 +1,171 @@ +import { describe, expect, it, vi } from 'vitest' +import type { RpcClient } from '../transport/rpc-client' +import { nativeHostWorkspaceCatalogOperations } from './native-host-workspace-catalog-operations' + +describe('native host workspace operations', () => { + it('does not relay its connection state, so a first failure stays a failure', () => { + const client = { sendRequest: vi.fn(), notifyForeground: vi.fn(), subscribe: vi.fn() } + + expect( + nativeHostWorkspaceCatalogOperations(client as unknown as RpcClient).connectionStateIsRelayed + ).toBeUndefined() + }) + + it('maps named reads and mutations to the existing RPC authority', async () => { + const sendRequest = vi + .fn() + .mockResolvedValueOnce({ ok: true, result: { ui: { sortBy: 'recent' } } }) + .mockResolvedValueOnce({ ok: true, result: {} }) + .mockResolvedValueOnce({ ok: true, result: { repos: [{ id: 'repo-1' }] } }) + .mockResolvedValueOnce({ ok: true, result: { worktrees: [{ worktreeId: 'workspace-1' }] } }) + .mockResolvedValueOnce({ ok: true, result: {} }) + .mockResolvedValueOnce({ ok: true, result: {} }) + .mockResolvedValueOnce({ ok: true, result: {} }) + .mockResolvedValueOnce({ ok: true, result: {} }) + const client = { + sendRequest, + notifyForeground: vi.fn(), + subscribe: vi.fn(() => vi.fn()) + } as unknown as RpcClient + const operations = nativeHostWorkspaceCatalogOperations(client) + + await operations.getViewSettings() + await operations.setViewSettings({ sortBy: 'recent' }) + await operations.listRepos() + await operations.listWorkspaces(200) + await operations.setPinned('workspace-1', true) + await operations.activateWorkspace('workspace-1') + await operations.sleepWorkspace('workspace-1') + await expect(operations.removeWorkspace('workspace-1')).resolves.toBe(true) + + expect(sendRequest.mock.calls).toEqual([ + ['ui.get'], + ['ui.set', { sortBy: 'recent' }], + ['repo.list'], + ['worktree.ps', { limit: 200 }], + ['worktree.set', { worktree: 'id:workspace-1', isPinned: true }], + [ + 'worktree.activate', + { + worktree: 'id:workspace-1', + notifyClients: false, + navigation: 'caller' + } + ], + ['worktree.sleep', { worktree: 'id:workspace-1' }], + ['worktree.rm', { worktree: 'id:workspace-1', force: true }] + ]) + }) + + it('filters the generic host event stream into named workspace changes', () => { + let receive: ((payload: unknown) => void) | undefined + const unsubscribe = vi.fn() + const client = { + sendRequest: vi.fn(), + notifyForeground: vi.fn(), + subscribe: vi.fn((_method, _params, listener) => { + receive = listener + return unsubscribe + }) + } as unknown as RpcClient + const listener = vi.fn() + + const cleanup = nativeHostWorkspaceCatalogOperations(client).subscribeChanges(listener) + receive?.({ type: 'worktreesChanged' }) + receive?.({ type: 'terminalData', secret: 'must-not-forward' }) + cleanup() + + expect(listener).toHaveBeenCalledOnce() + expect(listener).toHaveBeenCalledWith({ type: 'worktreesChanged' }) + expect(unsubscribe).toHaveBeenCalledOnce() + }) + + it('polls the catalog with a snapshot token and reuses the confirmed rows when unchanged', async () => { + const sendRequest = vi + .fn() + .mockResolvedValueOnce({ + ok: true, + result: { snapshotId: 'snap-1', worktrees: [{ worktreeId: 'workspace-1' }] } + }) + .mockResolvedValueOnce({ ok: true, result: { snapshotId: 'snap-1', unchanged: true } }) + const operations = nativeHostWorkspaceCatalogOperations({ + sendRequest, + notifyForeground: vi.fn(), + subscribe: vi.fn() + } as unknown as RpcClient) + + const first = await operations.fetchWorkspaceCatalog!('host-1') + const firstRows = first.kind === 'response' ? first.commit() : null + const second = await operations.fetchWorkspaceCatalog!('host-1') + const secondRows = second.kind === 'response' ? second.commit() : null + + expect(sendRequest.mock.calls).toEqual([ + ['worktree.ps', { limit: 10_000, afterSnapshotId: null }], + ['worktree.ps', { limit: 10_000, afterSnapshotId: 'snap-1' }] + ]) + expect(firstRows).toEqual([{ worktreeId: 'workspace-1' }]) + // Why (bandwidth over relay): an unchanged reply still reasserts the confirmed rows. + expect(secondRows).toEqual([{ worktreeId: 'workspace-1' }]) + }) + + // Why (STA-3123): the host's own code has to survive, or an unreachable remote host + // is indistinguishable from a healthy host with zero workspaces. + it('passes the host error code through instead of collapsing it', async () => { + const sendRequest = vi + .fn() + .mockResolvedValue({ ok: false, error: { code: 'worktree_list_unavailable', message: 'x' } }) + const operations = nativeHostWorkspaceCatalogOperations({ + sendRequest, + notifyForeground: vi.fn(), + subscribe: vi.fn() + } as unknown as RpcClient) + + await expect(operations.fetchWorkspaceCatalog!('host-1')).resolves.toEqual({ + kind: 'request_failed', + code: 'worktree_list_unavailable' + }) + }) + + it('reads ssh labels, host overrides and platform for multi-host catalogs', async () => { + const sendRequest = vi + .fn() + .mockImplementation(async (method: string) => { + if (method === 'ssh.listTargetSummaries') { + return { ok: true, result: { targets: [{ id: 'ssh-1', label: 'Build box' }, { id: 7 }] } } + } + if (method === 'settings.get') { + return { ok: true, result: { settings: { hostSettingOverrides: { 'ssh:ssh-1': {} } } } } + } + return { ok: true, result: { platform: 'linux' } } + }) + const operations = nativeHostWorkspaceCatalogOperations({ + sendRequest, + notifyForeground: vi.fn(), + subscribe: vi.fn() + } as unknown as RpcClient) + + await expect(operations.listHostContext!()).resolves.toEqual({ + sshTargets: [{ id: 'ssh-1', label: 'Build box' }], + hostSettingOverrides: { 'ssh:ssh-1': {} }, + platform: 'linux' + }) + }) + + // Hosts that predate a method still list repos; labels degrade to host ids. + it('degrades host context when the older host rejects or drops the calls', async () => { + const sendRequest = vi.fn().mockImplementation(async () => { + throw new Error('unknown method') + }) + const operations = nativeHostWorkspaceCatalogOperations({ + sendRequest, + notifyForeground: vi.fn(), + subscribe: vi.fn() + } as unknown as RpcClient) + + await expect(operations.listHostContext!()).resolves.toEqual({ + sshTargets: [], + hostSettingOverrides: undefined, + platform: null + }) + }) +}) diff --git a/mobile/src/worktree/native-host-workspace-catalog-operations.ts b/mobile/src/worktree/native-host-workspace-catalog-operations.ts new file mode 100644 index 000000000000..80b40b2da526 --- /dev/null +++ b/mobile/src/worktree/native-host-workspace-catalog-operations.ts @@ -0,0 +1,135 @@ +import type { RuntimeClientEventStreamMessage } from '../../../src/shared/runtime-client-events' +import type { RpcClient } from '../transport/rpc-client' +import type { RpcSuccess } from '../transport/types' +import type { + HostWorkspaceChange, + HostWorkspaceCatalogOperations +} from './host-workspace-catalog-operations' +import { + readHostWorkspacePlatform, + readHostWorkspaceSettingOverrides, + readHostWorkspaceSshTargets +} from './host-workspace-host-context' +import type { RepoSummary } from './host-worktree-rpc-types' +import { WorktreeCatalogSnapshotClient } from './worktree-catalog-snapshot-client' +import type { Worktree } from './workspace-list-types' +import type { WorkspaceViewSettings } from './workspace-view-settings' + +export function nativeHostWorkspaceCatalogOperations( + client: RpcClient +): HostWorkspaceCatalogOperations { + // Why: the token is per-connection state, so it lives with the binding rather than the + // screen — a reconnect builds a new binding and correctly restarts from a full catalog. + const catalog = new WorktreeCatalogSnapshotClient() + return { + async getViewSettings() { + const response = await client.sendRequest('ui.get') + requireSuccess(response) + return ((response as RpcSuccess).result as { ui?: WorkspaceViewSettings }).ui ?? null + }, + async setViewSettings(settings) { + requireSuccess(await client.sendRequest('ui.set', settings)) + }, + async listRepos() { + const response = await client.sendRequest('repo.list') + requireSuccess(response) + return ((response as RpcSuccess).result as { repos: RepoSummary[] }).repos + }, + async listWorkspaces(limit) { + const response = await client.sendRequest('worktree.ps', { limit }) + requireSuccess(response) + return ((response as RpcSuccess).result as { worktrees: Worktree[] }).worktrees + }, + async fetchWorkspaceCatalog(hostId) { + const fetched = await catalog.fetch(client, hostId) + if (fetched.kind === 'request_failed') { + return fetched + } + return { + kind: 'response', + invalidShape: fetched.pending.admission.kind === 'invalid', + commit: () => catalog.admit(fetched.pending) + } + }, + async listHostContext() { + const [sshTargets, hostSettings, hostPlatform] = await Promise.all([ + optionalResult(client, 'ssh.listTargetSummaries'), + optionalResult(client, 'settings.get'), + optionalResult(client, 'host.platform') + ]) + return { + sshTargets: readHostWorkspaceSshTargets(sshTargets), + hostSettingOverrides: readHostWorkspaceSettingOverrides(hostSettings), + platform: readHostWorkspacePlatform(hostPlatform) + } + }, + async setPinned(workspaceId, pinned) { + requireSuccess( + await client.sendRequest('worktree.set', { + worktree: `id:${workspaceId}`, + isPinned: pinned + }) + ) + }, + async removeWorkspace(workspaceId) { + const response = await client.sendRequest('worktree.rm', { + worktree: `id:${workspaceId}`, + force: true + }) + return response.ok + }, + async activateWorkspace(workspaceId) { + requireSuccess( + await client.sendRequest('worktree.activate', { + worktree: `id:${workspaceId}`, + notifyClients: false, + navigation: 'caller' + }) + ) + }, + async sleepWorkspace(workspaceId) { + requireSuccess(await client.sendRequest('worktree.sleep', { worktree: `id:${workspaceId}` })) + }, + notifyForeground() { + client.notifyForeground() + }, + subscribeChanges(listener) { + return client.subscribe('runtime.clientEvents.subscribe', null, (payload) => { + const event = hostWorkspaceChange(payload) + if (event) { + listener(event) + } + }) + } + } +} + +function hostWorkspaceChange(payload: unknown): HostWorkspaceChange | null { + if (!payload || typeof payload !== 'object' || !('type' in payload)) { + return null + } + const event = payload as RuntimeClientEventStreamMessage | { type: 'error' } + return event.type === 'ready' || + event.type === 'end' || + event.type === 'reposChanged' || + event.type === 'worktreesChanged' || + event.type === 'error' + ? event + : null +} + +// Why: hosts that predate a method still list repos, so labels degrade to host ids. +async function optionalResult(client: RpcClient, method: string): Promise { + try { + const response = await client.sendRequest(method) + return response.ok ? (response as RpcSuccess).result : null + } catch { + return null + } +} + +function requireSuccess(response: { ok: boolean }): void { + if (!response.ok) { + throw new Error('host_workspace_operation_failed') + } +} diff --git a/mobile/src/worktree/native-host-workspace-creation-operations.test.ts b/mobile/src/worktree/native-host-workspace-creation-operations.test.ts new file mode 100644 index 000000000000..03f726f61d99 --- /dev/null +++ b/mobile/src/worktree/native-host-workspace-creation-operations.test.ts @@ -0,0 +1,142 @@ +import { describe, expect, it, vi } from 'vitest' +import type { RpcClient } from '../transport/rpc-client' +import { nativeHostWorkspaceCreationOperations } from './native-host-workspace-creation-operations' + +describe('native host workspace creation operations', () => { + it('maps named repository and environment reads to existing RPC authority', async () => { + const sendRequest = vi + .fn() + .mockResolvedValueOnce({ + ok: true, + result: { repos: [{ id: 'repo-1', path: '/host/repo' }] } + }) + .mockResolvedValueOnce({ ok: true, result: { settings: { defaultTuiAgent: 'codex' } } }) + .mockResolvedValueOnce({ + ok: true, + result: { ui: { trustedOrcaHooks: { 'repo-1': { all: { approvedAt: 10 } } } } } + }) + .mockResolvedValueOnce({ ok: true, result: { glab: { installed: true } } }) + .mockResolvedValueOnce({ ok: true, result: { connected: true } }) + .mockResolvedValueOnce({ + ok: true, + result: { + state: { + targetId: 'ssh-1', + status: 'connected', + error: null, + reconnectAttempt: 0 + } + } + }) + .mockResolvedValueOnce({ ok: true, result: ['codex', 'claude'] }) + .mockResolvedValueOnce({ + ok: true, + result: { hooks: { scripts: { setup: 'pnpm install' } }, source: '/host/orca.yaml' } + }) + const operations = nativeHostWorkspaceCreationOperations({ + sendRequest + } as unknown as RpcClient) + + await expect(operations.listRepositories()).resolves.toEqual([ + { id: 'repo-1', path: '/host/repo' } + ]) + await expect(operations.readRuntimeSettings()).resolves.toEqual({ + defaultTuiAgent: 'codex' + }) + await expect(operations.readTrustedHooks()).resolves.toEqual({ + 'repo-1': { all: { approvedAt: 10 } } + }) + await expect(operations.isGitLabCliInstalled()).resolves.toBe(true) + await expect(operations.isLinearConnected()).resolves.toBe(true) + await expect(operations.readSshState('ssh-1')).resolves.toMatchObject({ + targetId: 'ssh-1', + status: 'connected' + }) + await expect(operations.detectAgents('ssh-1')).resolves.toEqual(['codex', 'claude']) + await expect(operations.readRepoHooks('repo-1')).resolves.toMatchObject({ + hooks: { scripts: { setup: 'pnpm install' } } + }) + + expect(sendRequest.mock.calls).toEqual([ + ['repo.list'], + ['settings.get'], + ['ui.get'], + ['preflight.check'], + ['linear.status'], + ['ssh.getState', { targetId: 'ssh-1' }], + ['preflight.detectRemoteAgents', { connectionId: 'ssh-1' }], + ['repo.hooks', { repo: 'id:repo-1' }] + ]) + }) + + it('preserves provider and SSH execution ownership behind named source operations', async () => { + const sendRequest = vi + .fn() + .mockResolvedValueOnce({ + ok: true, + result: { owner: 'acme', repo: 'orca', host: 'github.example.com' } + }) + .mockResolvedValueOnce({ + ok: true, + result: { + id: 'item-7', + type: 'pr', + number: 7, + title: 'Seven', + state: 'open', + url: 'https://github.example.com/acme/orca/pull/7', + labels: [], + updatedAt: '2026-07-23T00:00:00Z', + author: null + } + }) + .mockResolvedValueOnce({ ok: true, result: {} }) + const operations = nativeHostWorkspaceCreationOperations({ + sendRequest + } as unknown as RpcClient) + + await expect(operations.resolveGitHubRepoSlug('repo-1')).resolves.toEqual({ + supported: true, + slug: { owner: 'acme', repo: 'orca', host: 'github.example.com' } + }) + await expect( + operations.lookupGitHubItemByOwnerRepo({ + repoId: 'repo-1', + slug: { owner: 'acme', repo: 'orca', host: 'github.example.com' }, + number: 7, + type: 'pr' + }) + ).resolves.toMatchObject({ repoId: 'repo-1', number: 7 }) + await operations.persistSetupTrust({ + trust: {}, + repoId: 'repo-1', + contentHash: 'a'.repeat(64), + alwaysTrust: false + }) + + expect(sendRequest.mock.calls).toEqual([ + ['github.repoSlug', { repo: 'id:repo-1' }], + [ + 'github.workItemByOwnerRepo', + { + repo: 'id:repo-1', + owner: 'acme', + ownerRepo: 'orca', + host: 'github.example.com', + number: 7, + type: 'pr' + } + ], + [ + 'ui.set', + { + trustedOrcaHooks: { + 'repo-1': { + setup: { contentHash: 'a'.repeat(64), approvedAt: expect.any(Number) } + } + } + } + ] + ]) + }) +}) diff --git a/mobile/src/worktree/native-host-workspace-creation-operations.ts b/mobile/src/worktree/native-host-workspace-creation-operations.ts new file mode 100644 index 000000000000..3f76cb4e8d1c --- /dev/null +++ b/mobile/src/worktree/native-host-workspace-creation-operations.ts @@ -0,0 +1,27 @@ +import type { RpcClient } from '../transport/rpc-client' +import { createBlankWorkspace } from '../tasks/blank-workspace-create' +import { createWorkspaceFromComposerSource } from '../tasks/source-workspace-create' +import type { HostWorkspaceCreationOperations } from './host-workspace-creation-operations' +import { rpcWorkspaceCreationOperations } from './rpc-workspace-creation-operations' + +export function nativeHostWorkspaceCreationOperations( + client: RpcClient +): HostWorkspaceCreationOperations { + return { + ...rpcWorkspaceCreationOperations(client), + async createBlankWorkspace(args) { + return createBlankWorkspace({ + client, + ...args, + createdWithAgentId: args.agentChoice === 'blank' ? undefined : args.agentChoice + }) + }, + async createWorkspaceFromSource(args) { + return createWorkspaceFromComposerSource({ + client, + ...args, + agent: { choice: args.agentChoice } + }) + } + } +} diff --git a/mobile/src/worktree/native-host-workspace-creation-read-operations.ts b/mobile/src/worktree/native-host-workspace-creation-read-operations.ts new file mode 100644 index 000000000000..cb13a1caae0f --- /dev/null +++ b/mobile/src/worktree/native-host-workspace-creation-read-operations.ts @@ -0,0 +1,116 @@ +import type { PersistedTrustedOrcaHooks } from '../../../src/shared/orca-yaml-hook-types' +import type { SshConnectionState } from '../../../src/shared/ssh-types' +import type { RpcRequestSender } from '../transport/rpc-client' +import type { RpcSuccess } from '../transport/types' +import { readNewWorktreeRuntimeCapabilities } from '../tasks/worktree-create-capability' +import { readRetiredNameRegistryForRepo } from '../../../src/shared/worktree/retired-name-cache' +import type { + HostWorkspaceCreationOperations, + NewWorkspaceRepoHooks, + NewWorkspaceRepository, + NewWorkspaceRuntimeSettings +} from './host-workspace-creation-operations' + +type ReadOperations = Pick< + HostWorkspaceCreationOperations, + | 'listRepositories' + | 'readRetiredWorktreeNames' + | 'readRuntimeSettings' + | 'readTrustedHooks' + | 'isGitLabCliInstalled' + | 'isLinearConnected' + | 'readSshState' + | 'connectSsh' + | 'detectAgents' + | 'readRepoHooks' + | 'readRuntimeCapabilities' +> + +export function nativeHostWorkspaceCreationReadOperations( + client: RpcRequestSender +): ReadOperations { + return { + async listRepositories() { + const result = await successfulResult<{ repos: NewWorkspaceRepository[] }>( + client.sendRequest('repo.list') + ) + return result.repos + }, + async readRetiredWorktreeNames(repoId) { + const result = await successfulResult( + client.sendRequest('worktree.listRetiredNames', { repo: `id:${repoId}` }) + ) + return readRetiredNameRegistryForRepo(result, repoId) + }, + async readRuntimeSettings() { + const result = await successfulResult<{ settings: NewWorkspaceRuntimeSettings }>( + client.sendRequest('settings.get') + ) + return result.settings + }, + async readTrustedHooks() { + const result = await successfulResult<{ + ui?: { trustedOrcaHooks?: PersistedTrustedOrcaHooks } + }>(client.sendRequest('ui.get')) + return result.ui?.trustedOrcaHooks ?? {} + }, + async isGitLabCliInstalled() { + const response = await client.sendRequest('preflight.check') + return response.ok + ? ((response as RpcSuccess).result as { glab?: { installed?: boolean } }).glab + ?.installed === true + : false + }, + async isLinearConnected() { + const response = await client.sendRequest('linear.status') + return response.ok + ? ((response as RpcSuccess).result as { connected?: boolean }).connected === true + : false + }, + async readSshState(targetId) { + const result = await successfulResult<{ state?: SshConnectionState | null }>( + client.sendRequest('ssh.getState', { targetId }) + ) + return result.state ?? disconnectedSshState(targetId) + }, + async connectSsh(targetId) { + const result = await successfulResult<{ state?: SshConnectionState | null }>( + client.sendRequest('ssh.connect', { targetId }, { timeoutMs: 120_000 }) + ) + return result.state ?? { ...disconnectedSshState(targetId), status: 'connected' } + }, + async detectAgents(connectionId) { + const response = connectionId + ? await client.sendRequest('preflight.detectRemoteAgents', { connectionId }) + : await client.sendRequest('preflight.detectAgents') + return response.ok ? ((response as RpcSuccess).result as string[]) : [] + }, + async readRepoHooks(repoId) { + return successfulResult( + client.sendRequest('repo.hooks', { repo: `id:${repoId}` }) + ) + }, + readRuntimeCapabilities() { + return readNewWorktreeRuntimeCapabilities(client) + } + } +} + +async function successfulResult( + responsePromise: ReturnType +): Promise { + const response = await responsePromise + if (!response.ok) { + throw new Error(response.error.message) + } + return (response as RpcSuccess).result as T +} + +function disconnectedSshState(targetId: string): SshConnectionState { + return { + targetId, + status: 'disconnected', + error: null, + reconnectAttempt: 0 + } +} diff --git a/mobile/src/worktree/native-host-workspace-creation-source-operations.ts b/mobile/src/worktree/native-host-workspace-creation-source-operations.ts new file mode 100644 index 000000000000..57743c4a1aff --- /dev/null +++ b/mobile/src/worktree/native-host-workspace-creation-source-operations.ts @@ -0,0 +1,91 @@ +import type { RepoSlug } from '../../../src/shared/new-workspace/github-links' +import type { GitHubWorkItem } from '../../../src/shared/github/work-item-types' +import type { GitLabWorkItem } from '../../../src/shared/gitlab-types' +import type { RpcRequestSender } from '../transport/rpc-client' +import type { RpcSuccess } from '../transport/types' +import { resolveComposerMrBase, resolveComposerPrBase } from '../tasks/composer-source-base-resolve' +import { + searchBranches, + searchGitHubItems, + searchGitLabItems, + searchLinearIssues +} from '../tasks/smart-source-search-requests' +import type { HostWorkspaceCreationOperations } from './host-workspace-creation-operations' + +type SourceOperations = Pick< + HostWorkspaceCreationOperations, + | 'searchGitHubItems' + | 'searchGitLabItems' + | 'searchLinearIssues' + | 'searchBranches' + | 'resolveGitHubRepoSlug' + | 'lookupGitHubItem' + | 'lookupGitHubItemByOwnerRepo' + | 'lookupGitLabItemByPath' + | 'resolvePrBase' + | 'resolveMrBase' +> + +export function nativeHostWorkspaceCreationSourceOperations( + client: RpcRequestSender +): SourceOperations { + return { + searchGitHubItems: (repoId, query) => searchGitHubItems(client, repoId, query), + searchGitLabItems: (repoId, query, state) => searchGitLabItems(client, repoId, query, state), + searchLinearIssues: (query, linearWorkspaceId) => + searchLinearIssues(client, query, linearWorkspaceId), + searchBranches: (repoId, query) => searchBranches(client, repoId, query), + async resolveGitHubRepoSlug(repoId) { + const response = await client.sendRequest('github.repoSlug', { repo: `id:${repoId}` }) + if (!response.ok && response.error.code === 'method_not_found') { + return { supported: false, slug: null } + } + return { + supported: true, + slug: response.ok ? ((response as RpcSuccess).result as RepoSlug | null) : null + } + }, + async lookupGitHubItem(repoId, number) { + const response = await client.sendRequest('github.workItem', { + repo: `id:${repoId}`, + number + }) + if (!response.ok) { + throw new Error(response.error.message) + } + const item = (response as RpcSuccess).result as GitHubWorkItem | null + return item ? { ...item, repoId } : null + }, + async lookupGitHubItemByOwnerRepo({ repoId, slug, number, type }) { + const response = await client.sendRequest('github.workItemByOwnerRepo', { + repo: `id:${repoId}`, + owner: slug.owner, + ownerRepo: slug.repo, + ...(slug.host ? { host: slug.host } : {}), + number, + type + }) + if (!response.ok) { + throw new Error(response.error.message) + } + const item = (response as RpcSuccess).result as GitHubWorkItem | null + return item ? { ...item, repoId } : null + }, + async lookupGitLabItemByPath({ repoId, host, path, iid, type }) { + const response = await client.sendRequest('gitlab.workItemByPath', { + repo: `id:${repoId}`, + host, + path, + iid, + type + }) + if (!response.ok) { + throw new Error(response.error.message) + } + const item = (response as RpcSuccess).result as GitLabWorkItem | null + return item ? { ...item, repoId } : null + }, + resolvePrBase: (args) => resolveComposerPrBase({ client, ...args }), + resolveMrBase: (args) => resolveComposerMrBase({ client, ...args }) + } +} diff --git a/mobile/src/worktree/native-host-workspace-operations.ts b/mobile/src/worktree/native-host-workspace-operations.ts new file mode 100644 index 000000000000..d99a238e09be --- /dev/null +++ b/mobile/src/worktree/native-host-workspace-operations.ts @@ -0,0 +1,11 @@ +import type { RpcClient } from '../transport/rpc-client' +import type { HostWorkspaceOperations } from './host-workspace-operations' +import { nativeHostWorkspaceCatalogOperations } from './native-host-workspace-catalog-operations' +import { nativeHostWorkspaceCreationOperations } from './native-host-workspace-creation-operations' + +export function nativeHostWorkspaceOperations(client: RpcClient): HostWorkspaceOperations { + return { + catalog: nativeHostWorkspaceCatalogOperations(client), + creation: nativeHostWorkspaceCreationOperations(client) + } +} diff --git a/mobile/src/worktree/rpc-workspace-creation-operations.ts b/mobile/src/worktree/rpc-workspace-creation-operations.ts new file mode 100644 index 000000000000..0a411d65fc43 --- /dev/null +++ b/mobile/src/worktree/rpc-workspace-creation-operations.ts @@ -0,0 +1,54 @@ +import type { RpcRequestSender } from '../transport/rpc-client' +import { persistSetupHookTrustApproval } from '../tasks/setup-hook-trust' +import type { HostWorkspaceCreationOperations } from './host-workspace-creation-operations' +import { nativeHostWorkspaceCreationReadOperations } from './native-host-workspace-creation-read-operations' +import { nativeHostWorkspaceCreationSourceOperations } from './native-host-workspace-creation-source-operations' + +export type RpcWorkspaceCreationOperations = Omit< + HostWorkspaceCreationOperations, + 'createBlankWorkspace' | 'createWorkspaceFromSource' +> + +/** Every workspace-creation call that is a plain desktop request. The native app passes its socket + * and the hosted page passes a bridge-backed sender, so neither side owns a second copy. Creation + * itself is excluded: it needs connection state for its retry, which a sender cannot report. */ +export function rpcWorkspaceCreationOperations( + client: RpcRequestSender +): RpcWorkspaceCreationOperations { + return { + ...nativeHostWorkspaceCreationReadOperations(client), + ...nativeHostWorkspaceCreationSourceOperations(client), + async listSparsePresets(repoId) { + const response = await client.sendRequest('repo.sparsePresets', { repo: `id:${repoId}` }) + if (!response.ok) { + throw new Error(response.error.message) + } + return ( + ( + response.result as { + presets?: Awaited> + } + ).presets ?? [] + ) + }, + async saveSparsePreset(repoId, payload) { + const response = await client.sendRequest('repo.saveSparsePreset', { + repo: `id:${repoId}`, + ...payload + }) + if (!response.ok) { + throw new Error(response.error.message) + } + const preset = ( + response.result as { + preset?: Awaited> + } + ).preset + if (!preset) { + throw new Error('Failed to save sparse preset.') + } + return preset + }, + persistSetupTrust: (args) => persistSetupHookTrustApproval({ client, ...args }) + } +} From ee61c992fa6c17bd9c56a42ed525ab0b524b2c50 Mon Sep 17 00:00:00 2001 From: Jinwoo-H Date: Tue, 8 Sep 2026 22:48:57 -0400 Subject: [PATCH 02/40] refactor(mobile): route task screens through HostTaskOperations The Tasks screens and the new-workspace composer now take an operations adapter instead of an RpcClient. Every RPC envelope check, response cast and payload literal that lived in a hook body moved into the matching native-host-task-* adapter, and the composer's search and create requests moved into HostWorkspaceCreationOperations. Behavior is unchanged apart from four adapter-owned differences noted in the PR body. `worktree.create` from a task item stays inline: the creation adapter builds the composer's params and adds name-collision retry, which is a different request, not the same one behind a seam. Claude-Session: https://claude.ai/code/session_01JNnE9qzUZMMnqpZWCqM3nb --- mobile/src/components/NewWorktreeModal.tsx | 23 ++- .../components/NewWorktreeModalDrawers.tsx | 4 +- .../components/SmartWorkspaceSourceDrawer.tsx | 12 +- .../use-new-workspace-execution-target.ts | 49 ++---- .../use-new-workspace-repositories.ts | 26 ++- .../use-new-workspace-runtime-context.ts | 44 ++--- .../use-new-workspace-setup-script.ts | 26 ++- ...github-project-host-routing-source.test.ts | 86 +++++---- .../src/tasks/mobile-tasks-filter-pickers.tsx | 8 +- .../tasks/mobile-tasks-mutation-targets.ts | 52 ++++++ .../tasks/mobile-tasks-project-row-targets.ts | 62 +++++++ .../mobile-tasks-refactor-parity.test.ts | 45 +++-- mobile/src/tasks/smart-source-fan-out.test.ts | 79 ++++++--- mobile/src/tasks/smart-source-fan-out.ts | 20 +-- .../smart-source-paste-concurrency.test.ts | 27 +-- .../tasks/smart-source-paste-intent.test.ts | 65 +++---- mobile/src/tasks/smart-source-paste-intent.ts | 46 ++--- ...e-mobile-tasks-client-settings-actions.tsx | 57 +++--- ...mobile-tasks-github-check-file-actions.tsx | 136 +++++---------- ...obile-tasks-github-reply-merge-actions.tsx | 105 +++-------- ...ile-tasks-gitlab-github-status-actions.tsx | 60 ++----- .../use-mobile-tasks-item-detail-loading.tsx | 163 ++++-------------- ...ile-tasks-item-detail-metadata-effects.tsx | 37 ++-- .../use-mobile-tasks-linear-item-actions.tsx | 83 ++------- ...e-mobile-tasks-list-and-detail-effects.tsx | 51 ++---- ...se-mobile-tasks-project-detail-loading.tsx | 93 +++------- ...obile-tasks-project-file-merge-actions.tsx | 153 +++++----------- ...e-mobile-tasks-project-loading-actions.tsx | 121 ++++--------- ...-mobile-tasks-project-metadata-actions.tsx | 98 +++-------- ...-mobile-tasks-project-metadata-loading.tsx | 94 +++------- ...le-tasks-project-repository-resolution.tsx | 29 ++-- ...ile-tasks-project-review-check-actions.tsx | 131 +++++--------- ...ile-tasks-project-thread-reply-actions.tsx | 133 +++++--------- ...asks-project-workspace-comment-actions.tsx | 102 +++-------- ...use-mobile-tasks-provider-load-actions.tsx | 83 +++------ .../use-mobile-tasks-route-and-item-state.tsx | 31 ++-- .../use-mobile-tasks-runtime-hydration.tsx | 60 ++----- .../use-mobile-tasks-task-create-actions.tsx | 74 ++------ .../use-mobile-tasks-task-list-loading.tsx | 68 +++----- ...e-mobile-tasks-task-pagination-actions.tsx | 34 ++-- ...-mobile-tasks-workspace-create-actions.tsx | 93 +++------- ...-mobile-tasks-workspace-source-effects.tsx | 50 ++---- ...-mobile-tasks-workspace-sparse-actions.tsx | 69 ++++---- .../use-mobile-tasks-workspace-ssh-state.tsx | 81 +++------ .../src/tasks/use-smart-workspace-source.ts | 40 +++-- .../src/tasks/worktree-create-capability.ts | 21 +-- .../use-retired-worktree-names.test.tsx | 53 ++++-- .../worktree/use-retired-worktree-names.ts | 21 +-- 48 files changed, 1139 insertions(+), 1959 deletions(-) create mode 100644 mobile/src/tasks/mobile-tasks-mutation-targets.ts create mode 100644 mobile/src/tasks/mobile-tasks-project-row-targets.ts diff --git a/mobile/src/components/NewWorktreeModal.tsx b/mobile/src/components/NewWorktreeModal.tsx index a986d347782d..4bbdf3f8b121 100644 --- a/mobile/src/components/NewWorktreeModal.tsx +++ b/mobile/src/components/NewWorktreeModal.tsx @@ -7,6 +7,7 @@ import type { SmartModeAvailabilityInput } from '../tasks/mobile-smart-source-mo import { deriveRepoSlug, type PasteRepoCandidate } from '../tasks/smart-source-paste-intent' import { useMobileComposerSource } from '../tasks/use-mobile-composer-source' import { useNewWorktreeRuntimeCapabilities } from '../tasks/worktree-create-capability' +import { defaultHostWorkspaceCreationOperations } from '../worktree/default-host-workspace-creation-operations' import { buildRetiredWorktreeNamesRefreshKey, useRetiredWorktreeNames @@ -57,24 +58,28 @@ export function NewWorktreeModal(props: NewWorktreeModalProps) { function NewWorktreeModalContent(props: NewWorktreeModalProps) { const { visible, client, hostId, existingWorktreePaths, existingWorktrees, onCreated, onClose } = props + const operations = useMemo( + () => (client ? defaultHostWorkspaceCreationOperations(client) : null), + [client] + ) const { repos, selectedRepo, setSelectedRepo, loading } = useNewWorkspaceRepositories({ - client, + operations, hostId, visible }) const navigation = useNewWorktreeDrawerNavigation(visible) const [note, setNote] = useState('') const [error, setError] = useState('') - const runtime = useNewWorkspaceRuntimeContext(client, visible, hostId) + const runtime = useNewWorkspaceRuntimeContext(operations, visible, hostId) const { tasksSupported, hostPlatform, getWorktreeCreateCutoverSupport } = - useNewWorktreeRuntimeCapabilities(client, visible) + useNewWorktreeRuntimeCapabilities(operations, visible) const selectedRepoConnectionId = selectedRepo?.connectionId ?? null const executionTarget = useNewWorkspaceExecutionTarget({ - client, + operations, connectionId: selectedRepoConnectionId, visible }) - const setupScript = useNewWorkspaceSetupScript({ client, selectedRepo }) + const setupScript = useNewWorkspaceSetupScript({ operations, selectedRepo }) const selectedRepoWorktreeBranches = useMemo( () => getComposerRepoWorktreeBranches(existingWorktrees ?? [], selectedRepo?.id ?? null), [existingWorktrees, selectedRepo] @@ -94,8 +99,12 @@ function NewWorktreeModalContent(props: NewWorktreeModalProps) { () => buildRetiredWorktreeNamesRefreshKey(existingWorktreePaths), [existingWorktreePaths] ) + const readRetiredWorktreeNames = useMemo( + () => (operations ? (repoId: string) => operations.readRetiredWorktreeNames(repoId) : null), + [operations] + ) const retiredWorktreeNames = useRetiredWorktreeNames( - client, + readRetiredWorktreeNames, selectedRepo?.id, retiredNamesRefreshKey ) @@ -233,7 +242,7 @@ function NewWorktreeModalContent(props: NewWorktreeModalProps) { export function NewWorktreeModalDrawers(props: { visible: boolean drawerView: NewWorktreeDrawerView - client: Parameters[0]['client'] + operations: Parameters[0]['operations'] composer: Composer sourceAvailability: SmartModeAvailabilityInput selectedRepo: MobileWorkspaceRepo | null @@ -49,7 +49,7 @@ export function NewWorktreeModalDrawers(props: { <> { - if (!client || !crossRepoPrompt) { + if (!operations || !crossRepoPrompt) { return } const { link, matchingRepo } = crossRepoPrompt try { const item = await lookupGitHubItemByOwnerRepo( - client, + operations, matchingRepo.id, link.slug, link.number, diff --git a/mobile/src/components/use-new-workspace-execution-target.ts b/mobile/src/components/use-new-workspace-execution-target.ts index 27302d9ecb21..db6b84219e80 100644 --- a/mobile/src/components/use-new-workspace-execution-target.ts +++ b/mobile/src/components/use-new-workspace-execution-target.ts @@ -1,8 +1,7 @@ import { useEffect, useState } from 'react' import type { SshConnectionState } from '../../../src/shared/ssh-types' -import type { RpcClient } from '../transport/rpc-client' -import type { RpcSuccess } from '../transport/types' import { deriveWorkspaceSshGate, type WorkspaceSshGate } from '../tasks/workspace-ssh-gate' +import type { HostWorkspaceCreationOperations } from '../worktree/host-workspace-creation-operations' type DetectedAgentIdsState = { connectionId: string | null @@ -18,7 +17,7 @@ function fallbackSshState( } export function useNewWorkspaceExecutionTarget(args: { - client: RpcClient | null + operations: HostWorkspaceCreationOperations | null connectionId: string | null visible: boolean }): { @@ -26,7 +25,7 @@ export function useNewWorkspaceExecutionTarget(args: { detectedAgentIds: Set | null connect: () => Promise } { - const { client, connectionId, visible } = args + const { operations, connectionId, visible } = args const [sshState, setSshState] = useState(null) const [connectingTargetId, setConnectingTargetId] = useState(null) const [detectedAgentIdsState, setDetectedAgentIdsState] = useState( @@ -44,21 +43,16 @@ export function useNewWorkspaceExecutionTarget(args: { : null useEffect(() => { - if (!visible || !client || !connectionId) { + if (!visible || !operations || !connectionId) { return } let stale = false - void client - .sendRequest('ssh.getState', { targetId: connectionId }) - .then((response) => { - if (stale) { - return - } - if (!response.ok) { - throw new Error(response.error.message) + void operations + .readSshState(connectionId) + .then((state) => { + if (!stale) { + setSshState(state) } - const state = (response as RpcSuccess).result as { state?: SshConnectionState | null } - setSshState(state.state ?? fallbackSshState(connectionId, 'disconnected', null)) }) .catch((error) => { if (!stale) { @@ -74,22 +68,20 @@ export function useNewWorkspaceExecutionTarget(args: { return () => { stale = true } - }, [client, connectionId, visible]) + }, [operations, connectionId, visible]) useEffect(() => { - if (!visible || !client || (connectionId && sshGate.status !== 'connected')) { + if (!visible || !operations || (connectionId && sshGate.status !== 'connected')) { return } let stale = false void (async () => { try { - const response = connectionId - ? await client.sendRequest('preflight.detectRemoteAgents', { connectionId }) - : await client.sendRequest('preflight.detectAgents') + const agentIds = await operations.detectAgents(connectionId) if (!stale) { setDetectedAgentIdsState({ connectionId, - ids: response.ok ? new Set((response as RpcSuccess).result as string[]) : new Set() + ids: new Set(agentIds) }) } } catch { @@ -101,25 +93,16 @@ export function useNewWorkspaceExecutionTarget(args: { return () => { stale = true } - }, [client, connectionId, sshGate.status, visible]) + }, [operations, connectionId, sshGate.status, visible]) async function connect(): Promise { - if (!client || !connectionId) { + if (!operations || !connectionId) { return } setConnectingTargetId(connectionId) setSshState(fallbackSshState(connectionId, 'connecting', null)) try { - const response = await client.sendRequest( - 'ssh.connect', - { targetId: connectionId }, - { timeoutMs: 120_000 } - ) - if (!response.ok) { - throw new Error(response.error.message) - } - const result = (response as RpcSuccess).result as { state?: SshConnectionState | null } - setSshState(result.state ?? fallbackSshState(connectionId, 'connected', null)) + setSshState(await operations.connectSsh(connectionId)) } catch (error) { setSshState( fallbackSshState( diff --git a/mobile/src/components/use-new-workspace-repositories.ts b/mobile/src/components/use-new-workspace-repositories.ts index d2b700cc9ab9..45cd182fb14a 100644 --- a/mobile/src/components/use-new-workspace-repositories.ts +++ b/mobile/src/components/use-new-workspace-repositories.ts @@ -1,6 +1,4 @@ import { useEffect, useState } from 'react' -import type { RpcClient } from '../transport/rpc-client' -import type { RpcSuccess } from '../transport/types' import { getCachedRepos, setCachedRepos } from '../cache/repo-cache' import { useLastVisitedWorktreeRepoId } from '../worktree/use-last-visited-worktree-repo' import { @@ -8,10 +6,11 @@ import { refreshMobileNewWorkspaceDialogSelectedRepo, resolveMobileNewWorkspaceDialogRepoId } from '../worktree/new-workspace-dialog-repo-selection' +import type { HostWorkspaceCreationOperations } from '../worktree/host-workspace-creation-operations' import type { MobileWorkspaceRepo } from './new-worktree-modal-types' export function useNewWorkspaceRepositories(args: { - client: RpcClient | null + operations: HostWorkspaceCreationOperations | null hostId?: string visible: boolean }): { @@ -20,7 +19,7 @@ export function useNewWorkspaceRepositories(args: { setSelectedRepo: (repo: MobileWorkspaceRepo | null) => void loading: boolean } { - const { client, hostId, visible } = args + const { operations, hostId, visible } = args const [initialRepos] = useState(() => hostId ? (getCachedRepos(hostId) as MobileWorkspaceRepo[] | null) : null ) @@ -45,24 +44,23 @@ export function useNewWorkspaceRepositories(args: { }, [lastVisitedRepo.loaded, lastVisitedRepo.repoId, repos, selectedRepo, visible]) useEffect(() => { - if (!visible || !client) { + if (!visible || !operations) { return } let stale = false setLoading(true) - void client - .sendRequest('repo.list') - .then((response) => { - if (stale || !response.ok) { + void operations + .listRepositories() + .then((nextRepos) => { + if (stale) { return } - const result = (response as RpcSuccess).result as { repos: MobileWorkspaceRepo[] } - setRepos(result.repos) + setRepos(nextRepos) if (hostId) { - setCachedRepos(hostId, result.repos) + setCachedRepos(hostId, nextRepos) } setSelectedRepo((current) => - refreshMobileNewWorkspaceDialogSelectedRepo(result.repos, current) + refreshMobileNewWorkspaceDialogSelectedRepo(nextRepos, current) ) }) .catch(() => undefined) @@ -74,7 +72,7 @@ export function useNewWorkspaceRepositories(args: { return () => { stale = true } - }, [visible, client, hostId]) + }, [visible, operations, hostId]) return { repos, selectedRepo, setSelectedRepo, loading: loading && repos.length === 0 } } diff --git a/mobile/src/components/use-new-workspace-runtime-context.ts b/mobile/src/components/use-new-workspace-runtime-context.ts index 05df7b53fe38..9e71d8ffa690 100644 --- a/mobile/src/components/use-new-workspace-runtime-context.ts +++ b/mobile/src/components/use-new-workspace-runtime-context.ts @@ -1,20 +1,15 @@ import { useEffect, useState } from 'react' import type { PersistedTrustedOrcaHooks } from '../../../src/shared/orca-yaml-hook-types' -import type { RpcClient } from '../transport/rpc-client' -import type { RpcResponse, RpcSuccess } from '../transport/types' import { filterAvailableTaskProviders, normalizeVisibleTaskProviders, type TaskProvider } from '../tasks/mobile-task-providers' +import type { HostWorkspaceCreationOperations } from '../worktree/host-workspace-creation-operations' import type { NewWorktreeRuntimeSettings } from './new-worktree-agent-selection' -function settledSuccess(entry: PromiseSettledResult): RpcSuccess | null { - return entry.status === 'fulfilled' && entry.value.ok ? (entry.value as RpcSuccess) : null -} - export function useNewWorkspaceRuntimeContext( - client: RpcClient | null, + operations: HostWorkspaceCreationOperations | null, visible: boolean, hostId?: string ): { @@ -29,50 +24,37 @@ export function useNewWorkspaceRuntimeContext( const [availableProviders, setAvailableProviders] = useState([]) useEffect(() => { - if (!visible || !client) { + if (!visible || !operations) { return } let stale = false void (async () => { const probes = Promise.allSettled([ - client.sendRequest('preflight.check'), - client.sendRequest('linear.status') + operations.isGitLabCliInstalled(), + operations.isLinearConnected() ]) const [settingsRes, uiRes] = await Promise.allSettled([ - client.sendRequest('settings.get'), - client.sendRequest('ui.get') + operations.readRuntimeSettings(), + operations.readTrustedHooks() ]) if (stale) { return } - const settingsResult = settledSuccess(settingsRes) - const settingsValue = settingsResult - ? ( - settingsResult.result as { - settings: NewWorktreeRuntimeSettings & { visibleTaskProviders?: unknown } - } - ).settings - : null + const settingsValue = settingsRes.status === 'fulfilled' ? settingsRes.value : null if (settingsValue) { setRuntimeSettings(settingsValue) } - const uiResult = settledSuccess(uiRes) - if (uiResult) { - const ui = (uiResult.result as { ui?: { trustedOrcaHooks?: PersistedTrustedOrcaHooks } }).ui - setTrustedOrcaHooks(ui?.trustedOrcaHooks ?? {}) + if (uiRes.status === 'fulfilled') { + setTrustedOrcaHooks(uiRes.value) } const [preflightRes, linearRes] = await probes if (stale) { return } - const glabInstalled = - (settledSuccess(preflightRes)?.result as { glab?: { installed?: boolean } } | undefined) - ?.glab?.installed === true - const linearConnected = - (settledSuccess(linearRes)?.result as { connected?: boolean } | undefined)?.connected === - true + const glabInstalled = preflightRes.status === 'fulfilled' && preflightRes.value + const linearConnected = linearRes.status === 'fulfilled' && linearRes.value const visibleProviders = normalizeVisibleTaskProviders(settingsValue?.visibleTaskProviders) setAvailableProviders( filterAvailableTaskProviders(visibleProviders, { @@ -84,7 +66,7 @@ export function useNewWorkspaceRuntimeContext( return () => { stale = true } - }, [visible, client, hostId]) + }, [visible, operations, hostId]) return { runtimeSettings, diff --git a/mobile/src/components/use-new-workspace-setup-script.ts b/mobile/src/components/use-new-workspace-setup-script.ts index e564b8365e34..db81043210f3 100644 --- a/mobile/src/components/use-new-workspace-setup-script.ts +++ b/mobile/src/components/use-new-workspace-setup-script.ts @@ -1,16 +1,11 @@ import { useEffect, useState } from 'react' -import type { RpcClient } from '../transport/rpc-client' -import type { RpcSuccess } from '../transport/types' import { normalizeSetupHookTrust } from '../tasks/setup-hook-trust' import type { WorkspaceCreateSetupDecision } from '../tasks/workspace-create-params' -import type { - MobileWorkspaceRepo, - RepoHooksResponse, - SetupHookDetails -} from './new-worktree-modal-types' +import type { HostWorkspaceCreationOperations } from '../worktree/host-workspace-creation-operations' +import type { MobileWorkspaceRepo, SetupHookDetails } from './new-worktree-modal-types' export function useNewWorkspaceSetupScript(args: { - client: RpcClient | null + operations: HostWorkspaceCreationOperations | null selectedRepo: MobileWorkspaceRepo | null }): { setupCommand: string | null @@ -24,7 +19,7 @@ export function useNewWorkspaceSetupScript(args: { showAdvanced: boolean setShowAdvanced: (show: boolean) => void } { - const { client, selectedRepo } = args + const { operations, selectedRepo } = args const [details, setDetails] = useState(null) const [setupDecisionChoice, setSetupDecisionChoice] = useState { - if (!client || !selectedRepo) { + if (!operations || !selectedRepo) { return } let stale = false - void client - .sendRequest('repo.hooks', { repo: `id:${selectedRepo.id}` }) - .then((response) => { - if (stale || !response.ok) { + void operations + .readRepoHooks(selectedRepo.id) + .then((result) => { + if (stale) { return } - const result = (response as RpcSuccess).result as RepoHooksResponse const command = result.hooks?.scripts?.setup?.trim() || null const runPolicy = result.setupRunPolicy ?? 'run-by-default' setDetails({ @@ -76,7 +70,7 @@ export function useNewWorkspaceSetupScript(args: { return () => { stale = true } - }, [client, selectedRepo]) + }, [operations, selectedRepo]) return { setupCommand: activeDetails?.command ?? null, diff --git a/mobile/src/tasks/github-project-host-routing-source.test.ts b/mobile/src/tasks/github-project-host-routing-source.test.ts index 7a13aab09a2a..be992ed4558c 100644 --- a/mobile/src/tasks/github-project-host-routing-source.test.ts +++ b/mobile/src/tasks/github-project-host-routing-source.test.ts @@ -2,51 +2,73 @@ import { readFileSync } from 'node:fs' import { describe, expect, it } from 'vitest' const readSource = (path: string): string => readFileSync(new URL(path, import.meta.url), 'utf8') -const source = [ - readSource('./use-mobile-tasks-project-loading-actions.tsx'), - readSource('./use-mobile-tasks-project-workspace-comment-actions.tsx'), - readSource('./use-mobile-tasks-project-thread-reply-actions.tsx'), - readSource('./use-mobile-tasks-project-detail-loading.tsx'), - readSource('./use-mobile-tasks-project-metadata-actions.tsx'), - readSource('./use-mobile-tasks-project-metadata-loading.tsx'), - readSource('./use-mobile-tasks-project-review-check-actions.tsx'), - readSource('./use-mobile-tasks-project-file-merge-actions.tsx') -].join('\n') +// Composition layer: the hooks that drive Project rows. +const compositionSource = [ + './use-mobile-tasks-project-loading-actions.tsx', + './use-mobile-tasks-project-workspace-comment-actions.tsx', + './use-mobile-tasks-project-thread-reply-actions.tsx', + './use-mobile-tasks-project-detail-loading.tsx', + './use-mobile-tasks-project-metadata-actions.tsx', + './use-mobile-tasks-project-metadata-loading.tsx', + './use-mobile-tasks-project-review-check-actions.tsx', + './use-mobile-tasks-project-file-merge-actions.tsx' +] + .map(readSource) + .join('\n') +// Adapter layer: where the composition's typed targets become RPC payloads. +const projectReadAdapter = readSource('./native-host-task-project-read-operations.ts') +const projectMutationAdapter = readSource('./native-host-task-project-mutation-operations.ts') +const projectFileAdapter = readSource('./native-host-task-project-file-operations.ts') +const adapterSource = [projectReadAdapter, projectMutationAdapter, projectFileAdapter].join('\n') describe('mobile GitHub Project host routing boundary', () => { + it('keeps every Project RPC behind the adapter layer', () => { + expect(compositionSource).not.toContain('sendRequest(') + expect( + [...adapterSource.matchAll(/['"](github\.project\.[^'"]+)['"]/g)].length + ).toBeGreaterThan(10) + }) + it('host-qualifies every Project RPC request', () => { - const calls = [...source.matchAll(/['"](github\.project\.[^'"]+)['"]/g)] - expect(calls.length).toBeGreaterThan(10) + const calls = [...adapterSource.matchAll(/['"](github\.project\.[^'"]+)['"]/g)] for (const call of calls) { - const request = source.slice(call.index, call.index + 700) - expect(request, `${call[1]} must carry a host`).toMatch(/\bhost\s*:/) + const request = adapterSource.slice(call.index, call.index + 700) + expect(request, `${call[1]} must carry a host`).toMatch( + /\bhost:|slugPayload\(target\)|\bpayload\b/ + ) } + // slugPayload is the single place a row identity becomes a wire payload. + expect(projectMutationAdapter).toMatch( + /function slugPayload\(target: HostTaskProjectItemTarget\) \{\s*return \{\s*owner: target\.owner,\s*repo: target\.repo,\s*host: target\.host,/ + ) }) it('pins Project-row PR actions to the row repository identity', () => { - const actions = source.slice(source.indexOf('const toggleProjectGitHubReviewThread')) + // Every Project-row action resolves its target from the row plus the active Project host. + const targets = [...compositionSource.matchAll(/projectRowMutationTarget\(([^)]*)\)/g)] + expect(targets.length).toBeGreaterThan(10) + for (const target of targets) { + expect(target[1].replace(/\s+/g, ' ').trim()).toBe('row, activeGitHubProjectHost') + } + // The target type carries the host that the PR mutations forward as prRepo. + expect(projectMutationAdapter).toContain('prRepo: slugPayload(target)') for (const method of [ - 'github.resolveReviewThread', - 'github.addPRReviewCommentReply', - 'github.addIssueComment', - 'github.requestPRReviewers', - 'github.prChecks', - 'github.rerunPRChecks', - 'github.setPRFileViewed', - 'github.prFileContents', - 'github.addPRReviewComment', - 'github.mergePR' + 'fetchResolveReviewThread', + 'fetchAddPRReviewCommentReply', + 'fetchAddIssueComment', + 'fetchRequestPRReviewers', + 'fetchRerunPRChecks', + 'fetchMergePR' ]) { - const offset = actions.indexOf(`'${method}'`) - expect(offset, `${method} must remain wired in the Project action path`).toBeGreaterThan(-1) - expect(actions.slice(offset, offset + 700), `${method} must carry prRepo`).toContain( - 'prRepo: projectRowGitHubRepository(row, activeGitHubProjectHost)' - ) + expect(projectMutationAdapter, `${method} must remain wired`).toContain(method) + } + for (const method of ['github.prChecks', 'github.setPRFileViewed', 'github.prFileContents']) { + expect(projectFileAdapter, `${method} must remain wired`).toContain(method) } }) it('pins discovery to github.com while pasted URLs supply their parsed host', () => { - expect(source).toContain("'github.project.listAccessible', {\n host: 'github.com'") - expect(source).toContain('host: githubProjectHost(parsed.host)') + expect(compositionSource).toContain("listAccessible('github.com')") + expect(compositionSource).toContain('host: githubProjectHost(parsed.host)') }) }) diff --git a/mobile/src/tasks/mobile-tasks-filter-pickers.tsx b/mobile/src/tasks/mobile-tasks-filter-pickers.tsx index 78d406db9ac1..c8cc279ccdb4 100644 --- a/mobile/src/tasks/mobile-tasks-filter-pickers.tsx +++ b/mobile/src/tasks/mobile-tasks-filter-pickers.tsx @@ -148,7 +148,6 @@ export function renderMobileTasksLinearFilterPicker(model: ConnectionPresentatio export function renderMobileTasksLinearWorkspacePicker(model: ConnectionPresentationModel) { const { - client, linearWorkspaceOptions, loadLinearContext, selectedLinearWorkspaceId, @@ -157,6 +156,7 @@ export function renderMobileTasksLinearWorkspacePicker(model: ConnectionPresenta setSelectedLinearWorkspaceId, setShowLinearWorkspacePicker, showLinearWorkspacePicker, + taskOperations, taskUiReady } = model return ( @@ -168,9 +168,9 @@ export function renderMobileTasksLinearWorkspacePicker(model: ConnectionPresenta onSelect={(workspaceId) => { setSelectedLinearWorkspaceId(workspaceId) setSelectedLinearTeamIds(new Set()) - if (client) { - void client - .sendRequest('linear.selectWorkspace', { workspaceId }) + if (taskOperations) { + void taskOperations.linear + .selectWorkspace(workspaceId) .then(() => loadLinearContext()) .catch((err) => { setError(err instanceof Error ? err.message : 'Failed to switch workspace') diff --git a/mobile/src/tasks/mobile-tasks-mutation-targets.ts b/mobile/src/tasks/mobile-tasks-mutation-targets.ts new file mode 100644 index 000000000000..cf82d2d5112c --- /dev/null +++ b/mobile/src/tasks/mobile-tasks-mutation-targets.ts @@ -0,0 +1,52 @@ +import type { + HostTaskGitHubItemTarget, + HostTaskGitLabItemTarget, + HostTaskItemMutationTarget +} from './host-task-item-mutation-operations' +import type { HostTaskLinearTarget } from './host-task-linear-operations' +import type { TaskItem } from './mobile-tasks-project-workspace-types' + +export { + projectRowIdentityTarget, + projectRowMutationTarget, + projectRowSlugTarget +} from './mobile-tasks-project-row-targets' + +export function taskItemMutationTarget( + item: Extract +): HostTaskGitHubItemTarget +export function taskItemMutationTarget( + item: Extract +): HostTaskGitLabItemTarget +export function taskItemMutationTarget( + item: Extract +): HostTaskItemMutationTarget +export function taskItemMutationTarget( + item: Extract +): HostTaskItemMutationTarget { + return item.provider === 'github' + ? { + provider: 'github', + repoId: item.source.repoId, + number: item.source.number, + type: item.source.type + } + : { + provider: 'gitlab', + repoId: item.source.repoId, + number: item.source.number, + type: item.source.type, + projectRef: item.source.projectRef + } +} + +export function taskLinearTarget( + item: Extract +): HostTaskLinearTarget { + return { + issueId: item.source.id, + workspaceId: item.source.workspaceId, + teamId: item.source.team.id, + projectId: item.source.project?.id + } +} diff --git a/mobile/src/tasks/mobile-tasks-project-row-targets.ts b/mobile/src/tasks/mobile-tasks-project-row-targets.ts new file mode 100644 index 000000000000..e24f73b22e3a --- /dev/null +++ b/mobile/src/tasks/mobile-tasks-project-row-targets.ts @@ -0,0 +1,62 @@ +import type { HostTaskProjectItemTarget } from './host-task-project-mutation-operations' +import type { GitHubProjectRow } from './mobile-tasks-view-state-types' + +// Why local, not imported from mobile-tasks-item-mapping: these two readers are pure row +// identity, while that module value-imports the Tasks barrel (and the RN theme through it). +function projectRowType(row: GitHubProjectRow): 'issue' | 'pr' | null { + return row.itemType === 'ISSUE' ? 'issue' : row.itemType === 'PULL_REQUEST' ? 'pr' : null +} + +function splitRepositorySlug(slug: string | null): { owner: string; repo: string } | null { + const [owner, repo] = slug?.split('/') ?? [] + return owner && repo ? { owner, repo } : null +} + +/** For mutations the host addresses by issue/PR number and kind: comment adds, item edits, merges. */ +export function projectRowMutationTarget( + row: GitHubProjectRow, + host: string +): HostTaskProjectItemTarget | null { + const slug = splitRepositorySlug(row.content.repository) + const type = projectRowType(row) + return slug && type && row.content.number + ? { ...slug, host, number: row.content.number, type } + : null +} + +/** + * For mutations the host addresses by repository slug and comment id — the `*BySlug` comment + * edits. They read no issue number and no issue/PR kind, so requiring those refused rows + * (draft project items, PR rows before their number lands) the host would have accepted. + */ +export function projectRowSlugTarget( + row: GitHubProjectRow, + host: string +): HostTaskProjectItemTarget | null { + const slug = splitRepositorySlug(row.content.repository) + return slug ? { ...slug, host, ...rowIdentityFallbacks(row) } : null +} + +/** + * For mutations the host addresses by project item id or review thread id — `updateItemField`, + * `clearItemField` and `resolveReviewThread`. None of them read the slug, the number or the + * kind, so a DRAFT_ISSUE row must not be refused. + */ +export function projectRowIdentityTarget( + row: GitHubProjectRow, + host: string +): HostTaskProjectItemTarget { + const slug = splitRepositorySlug(row.content.repository) + return { + owner: slug?.owner ?? '', + repo: slug?.repo ?? '', + host, + ...rowIdentityFallbacks(row) + } +} + +// Why: the target shape carries these for the number-addressed methods; the id-addressed ones +// never read them, so a placeholder cannot reach the host. +function rowIdentityFallbacks(row: GitHubProjectRow): { number: number; type: 'issue' | 'pr' } { + return { number: row.content.number ?? 0, type: projectRowType(row) ?? 'issue' } +} diff --git a/mobile/src/tasks/mobile-tasks-refactor-parity.test.ts b/mobile/src/tasks/mobile-tasks-refactor-parity.test.ts index 8d35398c3dfd..9f5844bbb5c2 100644 --- a/mobile/src/tasks/mobile-tasks-refactor-parity.test.ts +++ b/mobile/src/tasks/mobile-tasks-refactor-parity.test.ts @@ -16,50 +16,59 @@ const hash = (parts: string[] | string): string => .update(Array.isArray(parts) ? parts.join('\n') : parts) .digest('hex') -const PRE_REFACTOR_SCREEN_HOOKS = '42174315a76c475d09dcb7209af4481f01258c4c9dc012127ff07a893d8cd291' -const PRE_REFACTOR_DIFF_HOOKS = '93c7189b32bed8456cc51814fffa8ce80cf62011ef968a9d53ddec2b9686f58f' -const PRE_REFACTOR_STATEMENTS = '9323fbee7c3806f37de42578ba73ce659c786c0ed5f8b6bcbc321b201ca50a73' -const PRE_REFACTOR_DECLARATIONS = 'cff54172af17a877789be1479c2eb6ca97d83c3e31dd831cd59395962f2b4c4a' -const PRE_REFACTOR_SEMANTICS = '5219d210d6f274e9ce2716a37c4c6fc4860a736a80f059ab6e89da6123043263' -const PRE_REFACTOR_STYLES = '1db6af69c791d9963928541ad5310942fcbda6d984b422c90b6eb92b6816579a' -const PRE_REFACTOR_RENDER_TREE = '2111145136b1e4fbca150d4792d735a90e992488e9934cfc1a8b8f3be981f39f' +/** + * Re-frozen when the Tasks screens stopped calling `client.sendRequest` and started calling the + * host operation adapters. Every RPC envelope check, response cast and payload literal moved out + * of the composition into `native-host-task-*-operations.ts`, so the semantic source shrinks and + * the render tree loses the two casts that lived inside JSX callbacks. Screen hooks gain the three + * `useMemo` adapter bindings in `useMobileTasksRouteAndItemState`; statements gain the same three + * plus the row-target locals the adapters take in place of inline slug/number checks. Diff hooks, + * declarations and styles are untouched. + */ +const SCREEN_HOOKS = 'e7c47c8624d0c51100d1704cd7865a022d1ea372ad659c1f9d2581afa9e0de6a' +const DIFF_HOOKS = '93c7189b32bed8456cc51814fffa8ce80cf62011ef968a9d53ddec2b9686f58f' +const STATEMENTS = '268d9cebe985c14b35052128ce985e81306d4507aae49a6301c165dc65d93337' +const DECLARATIONS = 'cff54172af17a877789be1479c2eb6ca97d83c3e31dd831cd59395962f2b4c4a' +const SEMANTICS = '69cfc4f59322d1050b47f7028171ef5c9cbda6c3e51878676ecf9be68122affa' +const STYLES = '1db6af69c791d9963928541ad5310942fcbda6d984b422c90b6eb92b6816579a' +const RENDER_TREE = 'a959c6712c70024127a429a47ae7689c629393752fa99a1ac6ba311d0bf13ca6' describe('Mobile Tasks refactor parity', () => { it('preserves recursively flattened hook and dependency order', () => { const screenHooks = readFlattenedMobileTasksHookSignatures('MobileTasksScreen') - expect(screenHooks).toHaveLength(350) - expect(hash(screenHooks)).toBe(PRE_REFACTOR_SCREEN_HOOKS) + expect(screenHooks).toHaveLength(353) + expect(hash(screenHooks)).toBe(SCREEN_HOOKS) const diffHooks = readFlattenedMobileTasksHookSignatures('GitHubPrFileDiff') expect(diffHooks).toHaveLength(3) - expect(hash(diffHooks)).toBe(PRE_REFACTOR_DIFF_HOOKS) + expect(hash(diffHooks)).toBe(DIFF_HOOKS) }) it('preserves every screen statement in execution order', () => { const statements = readFlattenedMobileTasksCoreStatements() - expect(statements).toHaveLength(417) - expect(hash(statements)).toBe(PRE_REFACTOR_STATEMENTS) + expect(statements).toHaveLength(420) + expect(hash(statements)).toBe(STATEMENTS) }) it('preserves every moved top-level declaration', () => { const declarations = readMobileTasksDeclarationSignatures() expect(declarations).toHaveLength(193) - expect(hash(declarations)).toBe(PRE_REFACTOR_DECLARATIONS) + expect(hash(declarations)).toBe(DECLARATIONS) }) it('preserves RPC calls, runtime strings, and JSX host signatures', () => { const semantics = readMobileTasksSemanticSource() - expect(semantics.split('\n')).toHaveLength(3_499) - expect(hash(semantics)).toBe(PRE_REFACTOR_SEMANTICS) + expect(semantics.split('\n')).toHaveLength(3_276) + expect(hash(semantics)).toBe(SEMANTICS) }) it('preserves render expressions and event handlers in tree order', () => { const tokens = readFlattenedMobileTasksRenderTokens() - expect(tokens).toHaveLength(35_195) - expect(hash(tokens)).toBe(PRE_REFACTOR_RENDER_TREE) + expect(tokens).toHaveLength(35_193) + expect(hash(tokens)).toBe(RENDER_TREE) }) it('preserves every StyleSheet property and value', () => { - expect(hash(readMobileTasksStyleSource())).toBe(PRE_REFACTOR_STYLES) + expect(hash(readMobileTasksStyleSource())).toBe(STYLES) }) }) diff --git a/mobile/src/tasks/smart-source-fan-out.test.ts b/mobile/src/tasks/smart-source-fan-out.test.ts index cffdc287e22f..241b3bb1428d 100644 --- a/mobile/src/tasks/smart-source-fan-out.test.ts +++ b/mobile/src/tasks/smart-source-fan-out.test.ts @@ -1,25 +1,46 @@ import { describe, expect, it } from 'vitest' -import type { RpcClient } from '../transport/rpc-client' +import type { HostWorkspaceCreationOperations } from '../worktree/host-workspace-creation-operations' import { fanOutSmartSearch } from './smart-source-fan-out' type Call = { method: string; params: Record } -function fakeClient(byMethod: Record, calls: Call[]): RpcClient { +function fakeOperations( + byMethod: Record, + calls: Call[] +): HostWorkspaceCreationOperations { + const invoke = async (method: string, params: Record): Promise => { + calls.push({ method, params }) + const result = byMethod[method] + if (result instanceof Error) { + throw result + } + return result as T + } return { - sendRequest: async (method: string, params?: unknown) => { - calls.push({ method, params: (params ?? {}) as Record }) - const result = byMethod[method] - if (result instanceof Error) { - return { - id: '1', - ok: false, - error: { code: 'x', message: result.message }, - _meta: { runtimeId: 'r' } - } - } - return { id: '1', ok: true, result: result ?? { items: [] }, _meta: { runtimeId: 'r' } } + searchGitHubItems: async (repoId, query) => { + const result = await invoke<{ items?: never[] }>('github.listWorkItems', { repoId, query }) + return (result?.items ?? []).map((item) => ({ ...item, repoId })) + }, + searchGitLabItems: async (repoId, query, state) => { + const result = await invoke<{ items?: never[] }>('gitlab.listWorkItems', { + repoId, + query, + state + }) + return (result?.items ?? []).map((item) => ({ ...item, repoId })) + }, + searchLinearIssues: async (query, linearWorkspaceId) => { + const result = await invoke<{ items?: never[] }>('linear.searchIssues', { + query, + linearWorkspaceId + }) + return result?.items ?? [] + }, + searchBranches: async (repoId, query) => { + const result = await invoke<{ refDetails?: never[] }>('repo.searchRefs', { repoId, query }) + return result?.refDetails ?? [] } - } as unknown as RpcClient + } as unknown as HostWorkspaceCreationOperations } const smartArgs = { @@ -36,7 +57,7 @@ const smartArgs = { describe('fanOutSmartSearch', () => { it('fans out to every provider in smart mode and stamps repoId', async () => { const calls: Call[] = [] - const client = fakeClient( + const operations = fakeOperations( { 'github.listWorkItems': { items: [{ id: 'g1', type: 'issue', number: 1, title: 'A' }] }, 'gitlab.listWorkItems': { items: [{ id: 'gl1', type: 'mr', number: 2, title: 'B' }] }, @@ -45,7 +66,7 @@ describe('fanOutSmartSearch', () => { }, calls ) - const result = await fanOutSmartSearch({ client, ...smartArgs }) + const result = await fanOutSmartSearch({ operations, ...smartArgs }) expect(calls.map((c) => c.method).sort()).toEqual([ 'github.listWorkItems', 'gitlab.listWorkItems', @@ -61,7 +82,7 @@ describe('fanOutSmartSearch', () => { it('swallows a single provider failure in smart mode (best-effort)', async () => { const calls: Call[] = [] - const client = fakeClient( + const operations = fakeOperations( { 'github.listWorkItems': new Error('gh down'), 'gitlab.listWorkItems': { items: [{ id: 'gl1', type: 'mr', number: 2, title: 'B' }] }, @@ -70,37 +91,41 @@ describe('fanOutSmartSearch', () => { }, calls ) - const result = await fanOutSmartSearch({ client, ...smartArgs }) + const result = await fanOutSmartSearch({ operations, ...smartArgs }) expect(result.error).toBe('') expect(result.gitlabItems).toHaveLength(1) }) it('surfaces the error for a single-provider mode', async () => { const calls: Call[] = [] - const client = fakeClient({ 'gitlab.listWorkItems': new Error('gl boom') }, calls) - const result = await fanOutSmartSearch({ ...smartArgs, mode: 'gitlab', client }) + const operations = fakeOperations({ 'gitlab.listWorkItems': new Error('gl boom') }, calls) + const result = await fanOutSmartSearch({ ...smartArgs, mode: 'gitlab', operations }) expect(calls.map((c) => c.method)).toEqual(['gitlab.listWorkItems']) expect(result.error).toBe('gl boom') }) it('only searches branches in smart mode when the query is non-empty', async () => { const calls: Call[] = [] - const client = fakeClient({}, calls) - await fanOutSmartSearch({ ...smartArgs, query: '', client }) + const operations = fakeOperations({}, calls) + await fanOutSmartSearch({ ...smartArgs, query: '', operations }) expect(calls.map((c) => c.method)).not.toContain('repo.searchRefs') }) it('skips GitHub in smart mode when GitHub is unavailable', async () => { const calls: Call[] = [] - const client = fakeClient({}, calls) - await fanOutSmartSearch({ ...smartArgs, githubAvailable: false, client }) + const operations = fakeOperations({}, calls) + await fanOutSmartSearch({ ...smartArgs, githubAvailable: false, operations }) expect(calls.map((c) => c.method)).not.toContain('github.listWorkItems') }) it('does not send oversized source queries to any provider', async () => { const calls: Call[] = [] - const client = fakeClient({}, calls) - const result = await fanOutSmartSearch({ ...smartArgs, query: 'x'.repeat(2049), client }) + const operations = fakeOperations({}, calls) + const result = await fanOutSmartSearch({ + ...smartArgs, + query: 'x'.repeat(2049), + operations + }) expect(calls).toEqual([]) expect(result).toMatchObject({ githubItems: [], diff --git a/mobile/src/tasks/smart-source-fan-out.ts b/mobile/src/tasks/smart-source-fan-out.ts index 3050effb7fc0..ff5f368f09e6 100644 --- a/mobile/src/tasks/smart-source-fan-out.ts +++ b/mobile/src/tasks/smart-source-fan-out.ts @@ -6,15 +6,9 @@ import { isSmartWorkspaceSourceQueryWithinLimit, type SmartNameMode } from '../../../src/shared/new-workspace/smart-workspace-source-results' -import type { RpcClient } from '../transport/rpc-client' +import type { HostWorkspaceCreationOperations } from '../worktree/host-workspace-creation-operations' import { isGitHubWorkItemsSshRemoteRequiredError } from './mobile-work-items' import type { MrStateFilter } from './mobile-composer-source-types' -import { - searchBranches, - searchGitHubItems, - searchGitLabItems, - searchLinearIssues -} from './smart-source-search-requests' export type SmartFanOutResult = { githubItems: GitHubWorkItem[] @@ -49,7 +43,7 @@ function shouldSearchBranches(mode: SmartNameMode, query: string): boolean { } type FanOutArgs = { - client: RpcClient + operations: HostWorkspaceCreationOperations mode: SmartNameMode query: string repoId: string | null @@ -71,7 +65,7 @@ export async function fanOutSmartSearch(args: FanOutArgs): Promise([]), diff --git a/mobile/src/tasks/smart-source-paste-concurrency.test.ts b/mobile/src/tasks/smart-source-paste-concurrency.test.ts index fe97fe462d3b..254e019ffb23 100644 --- a/mobile/src/tasks/smart-source-paste-concurrency.test.ts +++ b/mobile/src/tasks/smart-source-paste-concurrency.test.ts @@ -1,12 +1,14 @@ import { createElement } from 'react' import { act, create, type ReactTestRenderer } from 'react-test-renderer' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import type { RpcClient } from '../transport/rpc-client' +import type { HostWorkspaceCreationOperations } from '../worktree/host-workspace-creation-operations' import { useSmartWorkspaceSource } from './use-smart-workspace-source' -function Probe(props: { client: RpcClient; query: string }) { +const REPOS = [{ id: 'repo-1', displayName: 'orca', slug: { owner: 'stablyai', repo: 'orca' } }] + +function Probe(props: { operations: HostWorkspaceCreationOperations; query: string }) { useSmartWorkspaceSource({ - client: props.client, + operations: props.operations, enabled: true, mode: 'smart', query: props.query, @@ -15,7 +17,7 @@ function Probe(props: { client: RpcClient; query: string }) { gitlabAvailable: false, linearAvailable: false, mrStateFilter: 'opened', - repos: [{ id: 'repo-1', displayName: 'orca', slug: { owner: 'stablyai', repo: 'orca' } }] + repos: REPOS }) return null } @@ -39,15 +41,18 @@ describe('smart source paste lookup concurrency', () => { it('issues the pasted-number lookup while the fan-out is still in flight', async () => { const sent: string[] = [] - const sendRequest = vi.fn((method: string) => { - sent.push(method) - // Nothing ever settles: only requests issued concurrently can be observed. - return new Promise(() => {}) - }) - const client = { sendRequest } as unknown as RpcClient + const pendingOperation = (operation: string) => { + sent.push(operation) + return new Promise(() => {}) + } + const operations = { + searchGitHubItems: () => pendingOperation('github.listWorkItems'), + searchBranches: () => pendingOperation('repo.branches'), + lookupGitHubItem: () => pendingOperation('github.workItem') + } as unknown as HostWorkspaceCreationOperations await act(async () => { - mounted.push(create(createElement(Probe, { client, query: '16831' }))) + mounted.push(create(createElement(Probe, { operations, query: '16831' }))) }) await act(async () => { await vi.advanceTimersByTimeAsync(300) diff --git a/mobile/src/tasks/smart-source-paste-intent.test.ts b/mobile/src/tasks/smart-source-paste-intent.test.ts index 4cd34cb0057d..3eb26493be95 100644 --- a/mobile/src/tasks/smart-source-paste-intent.test.ts +++ b/mobile/src/tasks/smart-source-paste-intent.test.ts @@ -7,7 +7,7 @@ import { resolvePasteIntent, type PasteRepoCandidate } from './smart-source-paste-intent' -import type { RpcClient } from '../transport/rpc-client' +import type { HostWorkspaceCreationOperations } from '../worktree/host-workspace-creation-operations' describe('resolvePasteIntent', () => { it('classifies a GitHub issue/PR URL as a github-link', () => { @@ -99,62 +99,63 @@ describe('findRepoMatchingSlug', () => { it('falls back to the host-aware repo slug RPC for SSH and enterprise repos', async () => { const calls: string[] = [] - const client = { - sendRequest: async (_method: string, params: unknown) => { - const repo = (params as { repo: string }).repo - calls.push(repo) + const operations = { + resolveGitHubRepoSlug: async (repoId: string) => { + calls.push(repoId) return { - ok: true, - result: - repo === 'id:b' + supported: true, + slug: + repoId === 'b' ? { owner: 'enterprise', repo: 'widgets', host: 'github.corp.example' } : null } } - } as unknown as RpcClient + } as unknown as HostWorkspaceCreationOperations await expect( findRepoMatchingSlugForPaste( - client, + operations, repos, { owner: 'enterprise', repo: 'widgets', host: 'github.corp.example' }, new Map() ) ).resolves.toMatchObject({ id: 'b' }) - expect(calls).toEqual(['id:a', 'id:b']) + expect(calls).toEqual(['a', 'b']) }) it('keeps local matching usable when an older desktop lacks the repo slug RPC', async () => { let calls = 0 - const client = { - sendRequest: async () => { + const operations = { + resolveGitHubRepoSlug: async () => { calls += 1 - return { - ok: false, - error: { code: 'method_not_found', message: 'Unknown method: github.repoSlug' } - } + return { supported: false, slug: null } } - } as unknown as RpcClient + } as unknown as HostWorkspaceCreationOperations const cache = new Map() await expect( - findRepoMatchingSlugForPaste(client, repos, { owner: 'enterprise', repo: 'widgets' }, cache) + findRepoMatchingSlugForPaste( + operations, + repos, + { owner: 'enterprise', repo: 'widgets' }, + cache + ) ).resolves.toBeNull() await expect( - findRepoMatchingSlugForPaste(client, repos, { owner: 'enterprise', repo: 'other' }, cache) + findRepoMatchingSlugForPaste(operations, repos, { owner: 'enterprise', repo: 'other' }, cache) ).resolves.toBeNull() expect(calls).toBe(1) }) it('keeps local matching usable when the optional repo slug lookup rejects', async () => { - const client = { - sendRequest: async () => { + const operations = { + resolveGitHubRepoSlug: async () => { throw new Error('connection closed') } - } as unknown as RpcClient + } as unknown as HostWorkspaceCreationOperations await expect( findRepoMatchingSlugForPaste( - client, + operations, repos, { owner: 'enterprise', repo: 'widgets' }, new Map() @@ -163,22 +164,22 @@ describe('findRepoMatchingSlug', () => { }) it('sends the pasted host through the exact owner/repo lookup RPC', async () => { - const sendRequest = vi.fn().mockResolvedValue({ ok: true, result: null }) - const client = { sendRequest } as unknown as RpcClient + const lookup = vi.fn().mockResolvedValue(null) + const operations = { + lookupGitHubItemByOwnerRepo: lookup + } as unknown as HostWorkspaceCreationOperations await lookupGitHubItemByOwnerRepo( - client, + operations, 'repo-1', { owner: 'acme', repo: 'widgets', host: 'github.corp.example' }, 7, 'pr' ) - expect(sendRequest).toHaveBeenCalledWith('github.workItemByOwnerRepo', { - repo: 'id:repo-1', - owner: 'acme', - ownerRepo: 'widgets', - host: 'github.corp.example', + expect(lookup).toHaveBeenCalledWith({ + repoId: 'repo-1', + slug: { owner: 'acme', repo: 'widgets', host: 'github.corp.example' }, number: 7, type: 'pr' }) diff --git a/mobile/src/tasks/smart-source-paste-intent.ts b/mobile/src/tasks/smart-source-paste-intent.ts index 21afd4157de3..29b786ce3276 100644 --- a/mobile/src/tasks/smart-source-paste-intent.ts +++ b/mobile/src/tasks/smart-source-paste-intent.ts @@ -8,8 +8,7 @@ import { } from '../../../src/shared/new-workspace/github-links' import { parseGitLabIssueOrMRLink } from '../../../src/shared/new-workspace/gitlab-links' import { isSmartWorkspaceSourceQueryWithinLimit } from '../../../src/shared/new-workspace/smart-workspace-source-results' -import type { RpcClient } from '../transport/rpc-client' -import type { RpcSuccess } from '../transport/types' +import type { HostWorkspaceCreationOperations } from '../worktree/host-workspace-creation-operations' import { githubRepoIdentityKey } from '../../../src/shared/github/repository-identity-key' // A repo the picker can switch to for a cross-repo GitHub paste. Slug is derived @@ -93,7 +92,7 @@ export function findRepoMatchingSlug( } export async function findRepoMatchingSlugForPaste( - client: RpcClient, + operations: HostWorkspaceCreationOperations, repos: readonly PasteRepoCandidate[], slug: RepoSlug, cache: Map @@ -108,14 +107,14 @@ export async function findRepoMatchingSlugForPaste( let resolved = cache.get(repo.id) if (!cache.has(repo.id)) { try { - const response = await client.sendRequest('github.repoSlug', { repo: `id:${repo.id}` }) - if (!response.ok && response.error.code === 'method_not_found') { + const result = await operations.resolveGitHubRepoSlug(repo.id) + if (!result.supported) { // Why: RPC availability is host-wide; avoid repeating an unsupported // probe for every repo or on the next paste attempt. repos.forEach((candidate) => cache.set(candidate.id, null)) return null } - resolved = response.ok ? ((response as RpcSuccess).result as RepoSlug | null) : null + resolved = result.slug } catch { resolved = null } @@ -129,55 +128,38 @@ export async function findRepoMatchingSlugForPaste( } export async function lookupGitHubItemByNumber( - client: RpcClient, + operations: HostWorkspaceCreationOperations, repoId: string, number: number ): Promise { - const response = await client.sendRequest('github.workItem', { repo: `id:${repoId}`, number }) - if (!response.ok) { - throw new Error(response.error.message) - } - const item = (response as RpcSuccess).result as GitHubWorkItem | null - return item ? { ...item, repoId } : null + return operations.lookupGitHubItem(repoId, number) } export async function lookupGitHubItemByOwnerRepo( - client: RpcClient, + operations: HostWorkspaceCreationOperations, repoId: string, slug: RepoSlug, number: number, type: 'issue' | 'pr' ): Promise { - const response = await client.sendRequest('github.workItemByOwnerRepo', { - repo: `id:${repoId}`, - owner: slug.owner, - ownerRepo: slug.repo, - ...(slug.host ? { host: slug.host } : {}), + return operations.lookupGitHubItemByOwnerRepo({ + repoId, + slug, number, type }) - if (!response.ok) { - throw new Error(response.error.message) - } - const item = (response as RpcSuccess).result as GitHubWorkItem | null - return item ? { ...item, repoId } : null } export async function lookupGitLabItemByPath( - client: RpcClient, + operations: HostWorkspaceCreationOperations, repoId: string, link: NonNullable> ): Promise { - const response = await client.sendRequest('gitlab.workItemByPath', { - repo: `id:${repoId}`, + return operations.lookupGitLabItemByPath({ + repoId, host: link.slug.host, path: link.slug.path, iid: link.number, type: link.type }) - if (!response.ok) { - throw new Error(response.error.message) - } - const item = (response as RpcSuccess).result as GitLabWorkItem | null - return item ? { ...item, repoId } : null } diff --git a/mobile/src/tasks/use-mobile-tasks-client-settings-actions.tsx b/mobile/src/tasks/use-mobile-tasks-client-settings-actions.tsx index fe048e7a5b7d..1f9d278f029b 100644 --- a/mobile/src/tasks/use-mobile-tasks-client-settings-actions.tsx +++ b/mobile/src/tasks/use-mobile-tasks-client-settings-actions.tsx @@ -2,17 +2,11 @@ import type { ProjectRepositoryResolutionModel } from './use-mobile-tasks-projec import { type GitHubProjectSettings, type TaskProvider, - trustedOrcaHooksWithSetupApproval, useCallback, useLayoutEffect, useState } from './mobile-tasks-dependencies' -import { - type GitHubPreset, - type RepoSummary, - type TaskResumeState, - isSuccess -} from './mobile-tasks-legacy-foundation' +import type { GitHubPreset, RepoSummary, TaskResumeState } from './mobile-tasks-legacy-foundation' export function useMobileTasksClientSettingsActions(model: ProjectRepositoryResolutionModel) { const { @@ -64,6 +58,7 @@ export function useMobileTasksClientSettingsActions(model: ProjectRepositoryReso setWorkspaceSparseSaving, setWorkspaceSshConnecting, setWorkspaceSshState, + taskOperations, taskResumeRef, taskUiReady, trustedOrcaHooks @@ -101,16 +96,16 @@ export function useMobileTasksClientSettingsActions(model: ProjectRepositoryReso const persistTaskResumeState = useCallback( (updates: Partial) => { - if (!client || !taskUiReady) { + if (!taskOperations || !taskUiReady) { return } const next = { ...taskResumeRef.current, ...updates } taskResumeRef.current = next - void client.sendRequest('ui.set', { taskResumeState: next }).catch(() => { + void taskOperations.preference.updateResume(next).catch(() => { // Best-effort: desktop treats task resume as a convenience preference. }) }, - [client, taskUiReady] + [taskOperations, taskUiReady] ) const toggleGitHubProjectFieldVisibility = useCallback( @@ -140,77 +135,75 @@ export function useMobileTasksClientSettingsActions(model: ProjectRepositoryReso const persistTaskSource = useCallback( (nextProvider: TaskProvider) => { - if (!client || !taskUiReady) { + if (!taskOperations || !taskUiReady) { return } - void client.sendRequest('settings.update', { defaultTaskSource: nextProvider }).catch(() => { - // Best-effort: a failed settings write should not block switching views. - }) + void taskOperations.preference + .updateSettings({ defaultTaskSource: nextProvider }) + .catch(() => { + // Best-effort: a failed settings write should not block switching views. + }) }, - [client, taskUiReady] + [taskOperations, taskUiReady] ) const persistRepoSelection = useCallback( (selection: Set, allRepos: RepoSummary[]) => { - if (!client || !taskUiReady) { + if (!taskOperations || !taskUiReady) { return } const nextSelection = selection.size === 0 || selection.size === allRepos.length ? null : [...selection] defaultRepoSelectionRef.current = nextSelection - void client - .sendRequest('settings.update', { defaultRepoSelection: nextSelection }) + void taskOperations.preference + .updateSettings({ defaultRepoSelection: nextSelection }) .catch(() => { // Best-effort: the in-memory repo picker already reflects the change. }) }, - [client, taskUiReady] + [taskOperations, taskUiReady] ) const persistDefaultGitHubPreset = useCallback( (preset: GitHubPreset) => { setDefaultGitHubPreset(preset) - if (!client || !taskUiReady) { + if (!taskOperations || !taskUiReady) { return } - void client.sendRequest('settings.update', { defaultTaskViewPreset: preset }).catch(() => { + void taskOperations.preference.updateSettings({ defaultTaskViewPreset: preset }).catch(() => { // Best-effort: the current session still uses the selected preset. }) }, - [client, taskUiReady] + [taskOperations, taskUiReady] ) const persistGitHubProjectSettings = useCallback( (nextSettings: GitHubProjectSettings) => { setGithubProjectSettings(nextSettings) - if (!client || !taskUiReady) { + if (!taskOperations || !taskUiReady) { return } - void client.sendRequest('settings.update', { githubProjects: nextSettings }).catch(() => { + void taskOperations.preference.updateSettings({ githubProjects: nextSettings }).catch(() => { // Best-effort: project selection can still work for the current session. }) }, - [client, taskUiReady] + [taskOperations, taskUiReady] ) const persistSetupHookTrust = useCallback( async (repoId: string, contentHash: string, alwaysTrust: boolean): Promise => { - if (!client) { + if (!taskOperations) { return } - const next = trustedOrcaHooksWithSetupApproval({ + const next = await taskOperations.preference.persistSetupTrust({ trust: trustedOrcaHooks, repoId, contentHash, alwaysTrust }) - const response = await client.sendRequest('ui.set', { trustedOrcaHooks: next }) - if (!isSuccess(response)) { - throw new Error(response.error.message) - } setTrustedOrcaHooks(next) }, - [client, trustedOrcaHooks] + [taskOperations, trustedOrcaHooks] ) const resetWorkspaceCreateState = useCallback((): void => { diff --git a/mobile/src/tasks/use-mobile-tasks-github-check-file-actions.tsx b/mobile/src/tasks/use-mobile-tasks-github-check-file-actions.tsx index a21649cdf4bd..7a645ae553ca 100644 --- a/mobile/src/tasks/use-mobile-tasks-github-check-file-actions.tsx +++ b/mobile/src/tasks/use-mobile-tasks-github-check-file-actions.tsx @@ -1,17 +1,15 @@ import type { HostedCommentReviewActionsModel } from './use-mobile-tasks-hosted-comment-review-actions' import { useCallback } from './mobile-tasks-dependencies' -import { - type DetailComment, - type DetailPayload, - type GitHubDetailFile, - type GitHubPRFileContents, - type TaskItem, - isSuccess +import type { + DetailComment, + DetailPayload, + GitHubDetailFile, + TaskItem } from './mobile-tasks-legacy-foundation' +import { taskItemMutationTarget } from './mobile-tasks-mutation-targets' export function useMobileTasksGithubCheckFileActions(model: HostedCommentReviewActionsModel) { const { - client, detailPayload, expandedPrFilePath, mutatingStatus, @@ -24,33 +22,22 @@ export function useMobileTasksGithubCheckFileActions(model: HostedCommentReviewA setMutatingStatus, setPrFileCommentDrafts, setPrFileContents, - setPrFileLoadingPath + setPrFileLoadingPath, + taskOperations } = model const rerunGitHubChecks = useCallback( async (item: Extract, failedOnly: boolean): Promise => { - if (!client || mutatingStatus || item.source.type !== 'pr') { + if (!taskOperations || mutatingStatus || item.source.type !== 'pr') { return } setMutatingStatus(true) setError('') try { - const response = await client.sendRequest( - 'github.rerunPRChecks', - { - repo: `id:${item.source.repoId}`, - prNumber: item.source.number, - headSha: detailPayload?.provider === 'github' ? detailPayload.headSha : undefined, - failedOnly - }, - { timeoutMs: 60_000 } + await taskOperations.itemFile.rerunChecks( + taskItemMutationTarget(item), + detailPayload?.provider === 'github' ? detailPayload.headSha : undefined, + failedOnly ) - if (!isSuccess(response)) { - throw new Error(response.error.message) - } - const result = response.result as { ok?: boolean; error?: string } - if (result.ok === false) { - throw new Error(result.error ?? 'Failed to rerun checks') - } setDetailRefreshSeq((current) => current + 1) } catch (err) { setError(err instanceof Error ? err.message : 'Failed to rerun checks') @@ -58,7 +45,7 @@ export function useMobileTasksGithubCheckFileActions(model: HostedCommentReviewA setMutatingStatus(false) } }, - [client, detailPayload, mutatingStatus] + [detailPayload, mutatingStatus, taskOperations] ) const toggleGitHubFileViewed = useCallback( @@ -66,7 +53,7 @@ export function useMobileTasksGithubCheckFileActions(model: HostedCommentReviewA item: Extract, file: NonNullable['files'][number]> ): Promise => { - if (!client || mutatingStatus || item.source.type !== 'pr') { + if (!taskOperations || mutatingStatus || item.source.type !== 'pr') { return } if (detailPayload?.provider !== 'github' || !detailPayload.pullRequestId) { @@ -77,22 +64,11 @@ export function useMobileTasksGithubCheckFileActions(model: HostedCommentReviewA setMutatingStatus(true) setError('') try { - const response = await client.sendRequest( - 'github.setPRFileViewed', - { - repo: `id:${item.source.repoId}`, - pullRequestId: detailPayload.pullRequestId, - path: file.path, - viewed - }, - { timeoutMs: 30_000 } - ) - if (!isSuccess(response)) { - throw new Error(response.error.message) - } - if (response.result !== true) { - throw new Error('Failed to sync viewed state with GitHub.') - } + await taskOperations.itemFile.setFileViewed(taskItemMutationTarget(item), { + pullRequestId: detailPayload.pullRequestId, + path: file.path, + viewed + }) setDetailPayload((current) => current?.provider === 'github' ? { @@ -111,7 +87,7 @@ export function useMobileTasksGithubCheckFileActions(model: HostedCommentReviewA setMutatingStatus(false) } }, - [client, detailPayload, mutatingStatus] + [detailPayload, mutatingStatus, taskOperations] ) const toggleGitHubReviewThread = useCallback( @@ -119,28 +95,18 @@ export function useMobileTasksGithubCheckFileActions(model: HostedCommentReviewA item: Extract, comment: DetailComment ): Promise => { - if (!client || mutatingStatus || item.source.type !== 'pr' || !comment.threadId) { + if (!taskOperations || mutatingStatus || item.source.type !== 'pr' || !comment.threadId) { return } const resolve = !comment.isResolved setMutatingStatus(true) setError('') try { - const response = await client.sendRequest( - 'github.resolveReviewThread', - { - repo: `id:${item.source.repoId}`, - threadId: comment.threadId, - resolve - }, - { timeoutMs: 30_000 } + await taskOperations.itemReview.resolveThread( + taskItemMutationTarget(item), + comment.threadId, + resolve ) - if (!isSuccess(response)) { - throw new Error(response.error.message) - } - if (response.result !== true) { - throw new Error(resolve ? 'Failed to resolve thread' : 'Failed to reopen thread') - } setDetailPayload((current) => current?.provider === 'github' ? { @@ -159,7 +125,7 @@ export function useMobileTasksGithubCheckFileActions(model: HostedCommentReviewA setMutatingStatus(false) } }, - [client, mutatingStatus] + [mutatingStatus, taskOperations] ) const toggleGitHubFileExpansion = useCallback( @@ -176,7 +142,7 @@ export function useMobileTasksGithubCheckFileActions(model: HostedCommentReviewA return } if ( - !client || + !taskOperations || item.source.type !== 'pr' || detailPayload?.provider !== 'github' || !detailPayload.headSha || @@ -188,33 +154,24 @@ export function useMobileTasksGithubCheckFileActions(model: HostedCommentReviewA setPrFileLoadingPath(file.path) setError('') try { - const response = await client.sendRequest( - 'github.prFileContents', + const contents = await taskOperations.itemFile.loadFileContents( + taskItemMutationTarget(item), { - repo: `id:${item.source.repoId}`, - prNumber: item.source.number, path: file.path, oldPath: file.oldPath, status: file.status ?? 'modified', headSha: detailPayload.headSha, baseSha: detailPayload.baseSha - }, - { timeoutMs: 30_000 } + } ) - if (!isSuccess(response)) { - throw new Error(response.error.message) - } - setPrFileContents((current) => ({ - ...current, - [file.path]: response.result as GitHubPRFileContents - })) + setPrFileContents((current) => ({ ...current, [file.path]: contents })) } catch (err) { setError(err instanceof Error ? err.message : 'Failed to load file contents') } finally { setPrFileLoadingPath(null) } }, - [client, detailPayload, expandedPrFilePath, prFileContents] + [detailPayload, expandedPrFilePath, prFileContents, taskOperations] ) const addGitHubFileReviewComment = useCallback( @@ -223,7 +180,7 @@ export function useMobileTasksGithubCheckFileActions(model: HostedCommentReviewA file: GitHubDetailFile, line: number ): Promise => { - if (!client || mutatingStatus || item.source.type !== 'pr') { + if (!taskOperations || mutatingStatus || item.source.type !== 'pr') { return } if (detailPayload?.provider !== 'github' || !detailPayload.headSha) { @@ -238,30 +195,15 @@ export function useMobileTasksGithubCheckFileActions(model: HostedCommentReviewA setMutatingStatus(true) setError('') try { - const response = await client.sendRequest( - 'github.addPRReviewComment', + const comment: DetailComment = (await taskOperations.itemFile.addInlineComment( + taskItemMutationTarget(item), { - repo: `id:${item.source.repoId}`, - prNumber: item.source.number, commitId: detailPayload.headSha, path: file.path, line, body - }, - { timeoutMs: 30_000 } - ) - if (!isSuccess(response)) { - throw new Error(response.error.message) - } - const result = response.result as { - ok?: boolean - error?: string - comment?: DetailComment - } - if (result.ok === false) { - throw new Error(result.error ?? 'Failed to add review comment') - } - const comment: DetailComment = result.comment ?? { + } + )) ?? { id: `local-${Date.now()}`, author: 'You', body, @@ -285,7 +227,7 @@ export function useMobileTasksGithubCheckFileActions(model: HostedCommentReviewA setMutatingStatus(false) } }, - [client, detailPayload, mutatingStatus, prFileCommentDrafts] + [detailPayload, mutatingStatus, prFileCommentDrafts, taskOperations] ) return Object.assign(model, { rerunGitHubChecks, diff --git a/mobile/src/tasks/use-mobile-tasks-github-reply-merge-actions.tsx b/mobile/src/tasks/use-mobile-tasks-github-reply-merge-actions.tsx index 9bf6b14a23b9..2b6596cdffd1 100644 --- a/mobile/src/tasks/use-mobile-tasks-github-reply-merge-actions.tsx +++ b/mobile/src/tasks/use-mobile-tasks-github-reply-merge-actions.tsx @@ -7,13 +7,12 @@ import { type TaskItem, commentAuthor, createLinearTask, - isGitHubPrMergeBlocked, - isSuccess + isGitHubPrMergeBlocked } from './mobile-tasks-legacy-foundation' +import { taskItemMutationTarget, taskLinearTarget } from './mobile-tasks-mutation-targets' export function useMobileTasksGithubReplyMergeActions(model: GithubCheckFileActionsModel) { const { - client, itemReplyDrafts, loadTasks, mutatingStatus, @@ -23,6 +22,7 @@ export function useMobileTasksGithubReplyMergeActions(model: GithubCheckFileActi setItemReplyDrafts, setItems, setMutatingStatus, + taskOperations, taskUiReady } = model const replyToGitHubComment = useCallback( @@ -30,7 +30,7 @@ export function useMobileTasksGithubReplyMergeActions(model: GithubCheckFileActi item: Extract, comment: DetailComment ): Promise => { - if (!client || mutatingStatus) { + if (!taskOperations || mutatingStatus) { return } const key = String(comment.id) @@ -46,42 +46,19 @@ export function useMobileTasksGithubReplyMergeActions(model: GithubCheckFileActi comment.path && typeof comment.line === 'number' && typeof comment.id === 'number' - const response = canUseReviewReply - ? await client.sendRequest( - 'github.addPRReviewCommentReply', - { - repo: `id:${item.source.repoId}`, - prNumber: item.source.number, - commentId: comment.id, - body, - threadId: comment.threadId, - path: comment.path, - line: comment.line - }, - { timeoutMs: 30_000 } - ) - : await client.sendRequest( - 'github.addIssueComment', - { - repo: `id:${item.source.repoId}`, - number: item.source.number, - body: `@${commentAuthor(comment)} ${body}`, - type: item.source.type - }, - { timeoutMs: 30_000 } - ) - if (!isSuccess(response)) { - throw new Error(response.error.message) - } - const result = response.result as { - ok?: boolean - error?: string - comment?: DetailComment - } - if (result.ok === false) { - throw new Error(result.error ?? 'Failed to reply') - } - const reply: DetailComment = result.comment ?? { + const posted = await (canUseReviewReply + ? taskOperations.itemReview.replyReviewComment(taskItemMutationTarget(item), { + commentId: comment.id as number, + body, + ...(comment.threadId ? { threadId: comment.threadId } : {}), + path: comment.path as string, + line: comment.line as number + }) + : taskOperations.itemReview.addComment( + taskItemMutationTarget(item), + `@${commentAuthor(comment)} ${body}` + )) + const reply: DetailComment = posted ?? { id: `local-${Date.now()}`, body, createdAt: new Date().toISOString(), @@ -106,7 +83,7 @@ export function useMobileTasksGithubReplyMergeActions(model: GithubCheckFileActi setMutatingStatus(false) } }, - [client, itemReplyDrafts, mutatingStatus] + [itemReplyDrafts, mutatingStatus, taskOperations] ) const mergeHostedReview = useCallback( @@ -114,7 +91,7 @@ export function useMobileTasksGithubReplyMergeActions(model: GithubCheckFileActi item: Extract | Extract, method: HostedReviewMergeMethod ): Promise => { - if (!client || mutatingStatus) { + if (!taskOperations || mutatingStatus) { return } if (item.provider === 'github' && item.source.type !== 'pr') { @@ -130,34 +107,7 @@ export function useMobileTasksGithubReplyMergeActions(model: GithubCheckFileActi setMutatingStatus(true) setError('') try { - const response = - item.provider === 'github' - ? await client.sendRequest( - 'github.mergePR', - { - repo: `id:${item.source.repoId}`, - prNumber: item.source.number, - method - }, - { timeoutMs: 60_000 } - ) - : await client.sendRequest( - 'gitlab.mergeMR', - { - repo: `id:${item.source.repoId}`, - iid: item.source.number, - method, - projectRef: item.source.projectRef - }, - { timeoutMs: 60_000 } - ) - if (!isSuccess(response)) { - throw new Error(response.error.message) - } - const result = response.result as { ok?: boolean; error?: string } - if (result.ok === false) { - throw new Error(result.error ?? 'Failed to merge') - } + await taskOperations.itemReview.merge(taskItemMutationTarget(item), method) setActionItem(null) await loadTasks({ silent: true }) } catch (err) { @@ -166,7 +116,7 @@ export function useMobileTasksGithubReplyMergeActions(model: GithubCheckFileActi setMutatingStatus(false) } }, - [client, loadTasks, mutatingStatus] + [loadTasks, mutatingStatus, taskOperations] ) const setLinearStatus = useCallback( @@ -175,20 +125,13 @@ export function useMobileTasksGithubReplyMergeActions(model: GithubCheckFileActi state: LinearState, options: { closeDetail?: boolean } = {} ): Promise => { - if (!client || !taskUiReady || mutatingStatus) { + if (!taskOperations || !taskUiReady || mutatingStatus) { return } setMutatingStatus(true) setError('') try { - const response = await client.sendRequest('linear.updateIssue', { - id: item.source.id, - workspaceId: item.source.workspaceId, - updates: { stateId: state.id } - }) - if (!isSuccess(response)) { - throw new Error(response.error.message) - } + await taskOperations.linear.updateState(taskLinearTarget(item), state.id) const nextState = { name: state.name, type: state.type, @@ -220,7 +163,7 @@ export function useMobileTasksGithubReplyMergeActions(model: GithubCheckFileActi setMutatingStatus(false) } }, - [client, loadTasks, mutatingStatus, taskUiReady] + [loadTasks, mutatingStatus, taskOperations, taskUiReady] ) return Object.assign(model, { replyToGitHubComment, mergeHostedReview, setLinearStatus }) } diff --git a/mobile/src/tasks/use-mobile-tasks-gitlab-github-status-actions.tsx b/mobile/src/tasks/use-mobile-tasks-gitlab-github-status-actions.tsx index b36f7da117e1..c01e6e739dc8 100644 --- a/mobile/src/tasks/use-mobile-tasks-gitlab-github-status-actions.tsx +++ b/mobile/src/tasks/use-mobile-tasks-gitlab-github-status-actions.tsx @@ -1,10 +1,10 @@ import type { ProjectFileMergeActionsModel } from './use-mobile-tasks-project-file-merge-actions' import { useCallback } from './mobile-tasks-dependencies' -import { type TaskItem, isSuccess } from './mobile-tasks-legacy-foundation' +import type { TaskItem } from './mobile-tasks-legacy-foundation' +import { taskItemMutationTarget } from './mobile-tasks-mutation-targets' export function useMobileTasksGitlabGithubStatusActions(model: ProjectFileMergeActionsModel) { const { - client, detailPayload, loadTasks, mutatingStatus, @@ -16,38 +16,22 @@ export function useMobileTasksGitlabGithubStatusActions(model: ProjectFileMergeA setItemRemoveAssigneesDraft, setItemRemoveLabelsDraft, setItems, - setMutatingStatus + setMutatingStatus, + taskOperations } = model const toggleGitLabStatus = useCallback( async (item: Extract): Promise => { - if (!client || mutatingStatus || item.source.state === 'merged') { + if (!taskOperations || mutatingStatus || item.source.state === 'merged') { return } setMutatingStatus(true) setError('') const nextState = item.source.state === 'closed' ? 'opened' : 'closed' try { - const response = - item.source.type === 'issue' - ? await client.sendRequest('gitlab.updateIssue', { - repo: `id:${item.source.repoId}`, - number: item.source.number, - updates: { state: nextState }, - projectRef: item.source.projectRef - }) - : await client.sendRequest('gitlab.updateMRState', { - repo: `id:${item.source.repoId}`, - iid: item.source.number, - state: nextState, - projectRef: item.source.projectRef - }) - if (!isSuccess(response)) { - throw new Error(response.error.message) - } - const result = response.result as { ok?: boolean; error?: string } - if (result.ok === false) { - throw new Error(result.error ?? 'Failed to update GitLab item') - } + await taskOperations.itemMutation.setClosed( + taskItemMutationTarget(item), + nextState === 'closed' + ) setActionItem(null) await loadTasks({ silent: true }) } catch (err) { @@ -56,7 +40,7 @@ export function useMobileTasksGitlabGithubStatusActions(model: ProjectFileMergeA setMutatingStatus(false) } }, - [client, loadTasks, mutatingStatus] + [loadTasks, mutatingStatus, taskOperations] ) const updateGitHubIssueMetadata = useCallback( @@ -71,28 +55,18 @@ export function useMobileTasksGitlabGithubStatusActions(model: ProjectFileMergeA removeAssignees?: string[] } ): Promise => { - if (!client || mutatingStatus) { + if (!taskOperations || mutatingStatus) { return } setMutatingStatus(true) setError('') try { - const response = await client.sendRequest( - 'github.updateIssue', - { - repo: `id:${item.source.repoId}`, - number: item.source.number, - updates - }, - { timeoutMs: 30_000 } + // Why `type: 'issue'` for PR rows too: labels and assignees only exist on GitHub's + // issue endpoint, and the PR endpoint would silently drop them. + await taskOperations.itemMutation.updateMetadata( + { ...taskItemMutationTarget(item), type: 'issue' }, + updates ) - if (!isSuccess(response)) { - throw new Error(response.error.message) - } - const result = response.result as { ok?: boolean; error?: string } - if (result.ok === false) { - throw new Error(result.error ?? 'Failed to update GitHub issue') - } const nextLabels = [ ...new Set([ @@ -167,7 +141,7 @@ export function useMobileTasksGitlabGithubStatusActions(model: ProjectFileMergeA setMutatingStatus(false) } }, - [client, detailPayload, loadTasks, mutatingStatus] + [detailPayload, loadTasks, mutatingStatus, taskOperations] ) return Object.assign(model, { toggleGitLabStatus, updateGitHubIssueMetadata }) } diff --git a/mobile/src/tasks/use-mobile-tasks-item-detail-loading.tsx b/mobile/src/tasks/use-mobile-tasks-item-detail-loading.tsx index 4b4019275962..c61a212c3f20 100644 --- a/mobile/src/tasks/use-mobile-tasks-item-detail-loading.tsx +++ b/mobile/src/tasks/use-mobile-tasks-item-detail-loading.tsx @@ -4,32 +4,22 @@ import { buildGitLabCheckSummary, useEffect } from './mobile-tasks-dependencies' -import { - type DetailComment, - type GitHubAssignableUser, - type GitHubDetailCheck, - type GitHubDetailFile, - type GitHubPRReviewSummary, - type LinearIssue, - type TaskItem, - createLinearTask, - isSuccess -} from './mobile-tasks-legacy-foundation' +import { type TaskItem, createLinearTask } from './mobile-tasks-legacy-foundation' export function useMobileTasksItemDetailLoading(model: ItemDetailMetadataEffectsModel) { const { actionItem, - client, detailRefreshSeq, setActionItem, setDetailError, setDetailLoading, setDetailPayload, setItems, + taskOperations, tasksSupported } = model useEffect(() => { - if (!tasksSupported || !actionItem || !client) { + if (!tasksSupported || !actionItem || !taskOperations) { setDetailPayload(null) setDetailLoading(false) setDetailError('') @@ -43,106 +33,47 @@ export function useMobileTasksItemDetailLoading(model: ItemDetailMetadataEffects const loadDetails = async (): Promise => { if (actionItem.provider === 'github') { - const response = await client.sendRequest( - 'github.workItemDetails', - { - repo: `id:${actionItem.source.repoId}`, - number: actionItem.source.number, - type: actionItem.source.type - }, - { timeoutMs: 30_000 } - ) - if (!isSuccess(response)) { - throw new Error(response.error.message) - } - const details = response.result as { - body?: string - comments?: DetailComment[] - item?: { - labels?: string[] - reviewDecision?: string | null - reviewRequests?: GitHubAssignableUser[] - latestReviews?: GitHubPRReviewSummary[] - } - assignees?: string[] - headSha?: string - baseSha?: string - pullRequestId?: string - checks?: GitHubDetailCheck[] - files?: Array<{ - path: string - oldPath?: string - status?: GitHubDetailFile['status'] - additions?: number - deletions?: number - isBinary?: boolean - viewerViewedState?: 'DISMISSED' | 'VIEWED' | 'UNVIEWED' - }> - } | null - if (!details) { - throw new Error('Details not found') - } + const details = await taskOperations.detail.loadGitHub({ + repoId: actionItem.source.repoId, + number: actionItem.source.number, + type: actionItem.source.type + }) if (!stale) { setDetailPayload({ provider: 'github', - body: details.body ?? '', - comments: details.comments ?? [], - labels: details.item?.labels ?? actionItem.source.labels, - assignees: details.assignees ?? [], - reviewDecision: details.item?.reviewDecision ?? actionItem.source.reviewDecision, - reviewRequests: details.item?.reviewRequests ?? actionItem.source.reviewRequests ?? [], - latestReviews: details.item?.latestReviews ?? actionItem.source.latestReviews ?? [], + body: details.body, + comments: details.comments, + // Why: keep the row's own fields when the host omits them from the detail. + labels: details.labels ?? actionItem.source.labels, + assignees: details.assignees, + reviewDecision: details.reviewDecision ?? actionItem.source.reviewDecision, + reviewRequests: details.reviewRequests ?? actionItem.source.reviewRequests ?? [], + latestReviews: details.latestReviews ?? actionItem.source.latestReviews ?? [], headSha: details.headSha, baseSha: details.baseSha, pullRequestId: details.pullRequestId, - checks: details.checks ?? [], - files: details.files ?? [] + checks: details.checks, + files: details.files }) } return } if (actionItem.provider === 'gitlab') { - const response = await client.sendRequest( - 'gitlab.workItemDetails', - { - repo: `id:${actionItem.source.repoId}`, - iid: actionItem.source.number, - type: actionItem.source.type, - projectRef: actionItem.source.projectRef - }, - { timeoutMs: 30_000 } - ) - if (!isSuccess(response)) { - throw new Error(response.error.message) - } - const details = response.result as { - body?: string - comments?: DetailComment[] - item?: { labels?: string[]; mergeable?: 'MERGEABLE' | 'CONFLICTING' | 'UNKNOWN' } - assignees?: string[] - pipelineJobs?: Array<{ - id?: number - name: string - stage: string - status: string - webUrl?: string | null - duration?: number | null - }> - reviewers?: unknown[] - approvalState?: { approvalsRequired: number | null; approvalsLeft: number | null } - } | null - if (!details) { - throw new Error('Details not found') - } + const details = await taskOperations.detail.loadGitLab({ + repoId: actionItem.source.repoId, + number: actionItem.source.number, + type: actionItem.source.type, + projectRef: actionItem.source.projectRef + }) if (!stale) { setDetailPayload({ provider: 'gitlab', - body: details.body ?? '', - comments: details.comments ?? [], - labels: details.item?.labels ?? actionItem.source.labels, - assignees: details.assignees ?? [], - pipelineJobs: details.pipelineJobs ?? [] + body: details.body, + comments: details.comments, + labels: details.labels ?? actionItem.source.labels, + assignees: details.assignees, + pipelineJobs: details.pipelineJobs }) const checksSummary = buildGitLabCheckSummary(details.pipelineJobs ?? []) const reviewDecision: Exclude | undefined = @@ -186,39 +117,15 @@ export function useMobileTasksItemDetailLoading(model: ItemDetailMetadataEffects return } - const [issueResponse, commentsResponse] = await Promise.all([ - client.sendRequest( - 'linear.getIssue', - { - id: actionItem.source.id, - workspaceId: actionItem.source.workspaceId - }, - { timeoutMs: 30_000 } - ), - client.sendRequest( - 'linear.issueComments', - { - issueId: actionItem.source.id, - workspaceId: actionItem.source.workspaceId - }, - { timeoutMs: 30_000 } - ) - ]) - if (!isSuccess(issueResponse)) { - throw new Error(issueResponse.error.message) - } - const issue = issueResponse.result as LinearIssue | null - const comments = isSuccess(commentsResponse) - ? ((commentsResponse.result as DetailComment[]) ?? []) - : [] - if (!issue) { - throw new Error('Details not found') - } + const { issue, comments } = await taskOperations.detail.loadLinear({ + issueId: actionItem.source.id, + workspaceId: actionItem.source.workspaceId + }) if (!stale) { setDetailPayload({ provider: 'linear', description: issue.description ?? '', - comments, + comments: comments ?? [], labels: issue.labels ?? [], assignee: issue.assignee?.displayName, project: issue.project, @@ -256,7 +163,7 @@ export function useMobileTasksItemDetailLoading(model: ItemDetailMetadataEffects return () => { stale = true } - }, [actionItem, client, detailRefreshSeq, tasksSupported]) + }, [actionItem, detailRefreshSeq, taskOperations, tasksSupported]) return model } diff --git a/mobile/src/tasks/use-mobile-tasks-item-detail-metadata-effects.tsx b/mobile/src/tasks/use-mobile-tasks-item-detail-metadata-effects.tsx index 44aff16e637e..fd6476bcc6d6 100644 --- a/mobile/src/tasks/use-mobile-tasks-item-detail-metadata-effects.tsx +++ b/mobile/src/tasks/use-mobile-tasks-item-detail-metadata-effects.tsx @@ -1,11 +1,9 @@ import type { ListAndDetailEffectsModel } from './use-mobile-tasks-list-and-detail-effects' import { useEffect } from './mobile-tasks-dependencies' -import { type GitHubAssignableUser, isSuccess } from './mobile-tasks-legacy-foundation' export function useMobileTasksItemDetailMetadataEffects(model: ListAndDetailEffectsModel) { const { actionItem, - client, detailPayload, setItemAssignableUsers, setItemAssignableUsersError, @@ -14,6 +12,7 @@ export function useMobileTasksItemDetailMetadataEffects(model: ListAndDetailEffe setItemBodyDraft, setItemLabelsError, setItemLabelsLoading, + taskOperations, tasksSupported } = model useEffect(() => { @@ -27,7 +26,7 @@ export function useMobileTasksItemDetailMetadataEffects(model: ListAndDetailEffe }, [detailPayload]) useEffect(() => { - if (!tasksSupported || !client || actionItem?.provider !== 'github') { + if (!tasksSupported || !taskOperations || actionItem?.provider !== 'github') { setItemAvailableLabels([]) setItemLabelsLoading(false) setItemLabelsError('') @@ -42,20 +41,13 @@ export function useMobileTasksItemDetailMetadataEffects(model: ListAndDetailEffe setItemAvailableLabels([]) setItemLabelsError('') setItemLabelsLoading(true) - void client - .sendRequest( - 'github.listLabels', - { repo: `id:${actionItem.source.repoId}` }, - { timeoutMs: 30_000 } - ) - .then((response) => { + void taskOperations.detail + .listGitHubLabels(actionItem.source.repoId) + .then((labels) => { if (stale) { return } - if (!isSuccess(response)) { - throw new Error(response.error.message) - } - setItemAvailableLabels(response.result as string[]) + setItemAvailableLabels(labels) }) .catch((err) => { if (!stale) { @@ -76,20 +68,13 @@ export function useMobileTasksItemDetailMetadataEffects(model: ListAndDetailEffe setItemAssignableUsers([]) setItemAssignableUsersError('') setItemAssignableUsersLoading(true) - void client - .sendRequest( - 'github.listAssignableUsers', - { repo: `id:${actionItem.source.repoId}` }, - { timeoutMs: 30_000 } - ) - .then((response) => { + void taskOperations.detail + .listGitHubAssignableUsers(actionItem.source.repoId) + .then((users) => { if (stale) { return } - if (!isSuccess(response)) { - throw new Error(response.error.message) - } - setItemAssignableUsers(response.result as GitHubAssignableUser[]) + setItemAssignableUsers(users) }) .catch((err) => { if (!stale) { @@ -107,7 +92,7 @@ export function useMobileTasksItemDetailMetadataEffects(model: ListAndDetailEffe return () => { stale = true } - }, [actionItem, client, tasksSupported]) + }, [actionItem, taskOperations, tasksSupported]) return model } diff --git a/mobile/src/tasks/use-mobile-tasks-linear-item-actions.tsx b/mobile/src/tasks/use-mobile-tasks-linear-item-actions.tsx index 021737f5672e..4e18efbdb0f3 100644 --- a/mobile/src/tasks/use-mobile-tasks-linear-item-actions.tsx +++ b/mobile/src/tasks/use-mobile-tasks-linear-item-actions.tsx @@ -2,16 +2,14 @@ import type { GithubReplyMergeActionsModel } from './use-mobile-tasks-github-rep import { useCallback } from './mobile-tasks-dependencies' import { type DetailComment, - type LinearIssue, type LinearIssueChild, type TaskItem, - createLinearTask, - isSuccess + createLinearTask } from './mobile-tasks-legacy-foundation' +import { taskLinearTarget } from './mobile-tasks-mutation-targets' export function useMobileTasksLinearItemActions(model: GithubReplyMergeActionsModel) { const { - client, linearCommentDraft, linearSubIssueTitle, mutatingStatus, @@ -20,11 +18,12 @@ export function useMobileTasksLinearItemActions(model: GithubReplyMergeActionsMo setError, setLinearCommentDraft, setLinearSubIssueTitle, - setMutatingStatus + setMutatingStatus, + taskOperations } = model const addLinearComment = useCallback( async (item: Extract): Promise => { - if (!client || mutatingStatus) { + if (!taskOperations || mutatingStatus) { return } const body = linearCommentDraft.trim() @@ -34,24 +33,9 @@ export function useMobileTasksLinearItemActions(model: GithubReplyMergeActionsMo setMutatingStatus(true) setError('') try { - const response = await client.sendRequest( - 'linear.addIssueComment', - { - issueId: item.source.id, - workspaceId: item.source.workspaceId, - body - }, - { timeoutMs: 30_000 } - ) - if (!isSuccess(response)) { - throw new Error(response.error.message) - } - const result = response.result as { ok?: boolean; id?: string; error?: string } - if (result.ok === false) { - throw new Error(result.error ?? 'Failed to add comment') - } + const commentId = await taskOperations.linear.addComment(taskLinearTarget(item), body) const comment: DetailComment = { - id: result.id ?? `local-${Date.now()}`, + id: commentId ?? `local-${Date.now()}`, body, createdAt: new Date().toISOString(), user: { displayName: 'You' } @@ -68,29 +52,22 @@ export function useMobileTasksLinearItemActions(model: GithubReplyMergeActionsMo setMutatingStatus(false) } }, - [client, linearCommentDraft, mutatingStatus] + [linearCommentDraft, mutatingStatus, taskOperations] ) const openLinearSubIssue = useCallback( async (child: LinearIssueChild, workspaceId?: string): Promise => { - if (!client || mutatingStatus) { + if (!taskOperations || mutatingStatus) { return } setMutatingStatus(true) setError('') try { - const response = await client.sendRequest( - 'linear.getIssue', - { id: child.id, workspaceId }, - { timeoutMs: 30_000 } - ) - if (!isSuccess(response)) { - throw new Error(response.error.message) - } - const issue = response.result as LinearIssue | null - if (!issue) { - throw new Error('Sub-issue not found') - } + const issue = await taskOperations.linear.loadIssue({ + issueId: child.id, + workspaceId, + teamId: '' + }) setActionItem(createLinearTask(issue) as Extract) } catch (err) { setError(err instanceof Error ? err.message : 'Failed to load Linear sub-issue') @@ -98,12 +75,12 @@ export function useMobileTasksLinearItemActions(model: GithubReplyMergeActionsMo setMutatingStatus(false) } }, - [client, mutatingStatus] + [mutatingStatus, taskOperations] ) const createLinearSubIssue = useCallback( async (item: Extract): Promise => { - if (!client || mutatingStatus) { + if (!taskOperations || mutatingStatus) { return } const title = linearSubIssueTitle.trim() @@ -113,31 +90,7 @@ export function useMobileTasksLinearItemActions(model: GithubReplyMergeActionsMo setMutatingStatus(true) setError('') try { - const response = await client.sendRequest( - 'linear.createIssue', - { - teamId: item.source.team.id, - title, - workspaceId: item.source.workspaceId, - parentIssueId: item.source.id, - projectId: item.source.project?.id ?? null - }, - { timeoutMs: 30_000 } - ) - if (!isSuccess(response)) { - throw new Error(response.error.message) - } - const result = response.result as { - ok?: boolean - id?: string - identifier?: string - title?: string - url?: string - error?: string - } - if (result.ok === false || !result.id || !result.identifier) { - throw new Error(result.error ?? 'Failed to create sub-issue') - } + const result = await taskOperations.linear.createSubIssue(taskLinearTarget(item), title) const child: LinearIssueChild = { id: result.id, identifier: result.identifier, @@ -161,7 +114,7 @@ export function useMobileTasksLinearItemActions(model: GithubReplyMergeActionsMo setMutatingStatus(false) } }, - [client, linearSubIssueTitle, mutatingStatus] + [linearSubIssueTitle, mutatingStatus, taskOperations] ) return Object.assign(model, { addLinearComment, openLinearSubIssue, createLinearSubIssue }) } diff --git a/mobile/src/tasks/use-mobile-tasks-list-and-detail-effects.tsx b/mobile/src/tasks/use-mobile-tasks-list-and-detail-effects.tsx index 25b6c975e61c..f20116bae940 100644 --- a/mobile/src/tasks/use-mobile-tasks-list-and-detail-effects.tsx +++ b/mobile/src/tasks/use-mobile-tasks-list-and-detail-effects.tsx @@ -6,13 +6,8 @@ import { useCallback, useEffect } from './mobile-tasks-dependencies' -import { - type LinearState, - type LinearTeam, - getTaskPresetQuery, - isSuccess, - scopeGitHubTaskSearch -} from './mobile-tasks-legacy-foundation' +import { getTaskPresetQuery, scopeGitHubTaskSearch } from './mobile-tasks-legacy-foundation' +import { taskLinearTarget } from './mobile-tasks-mutation-targets' export function useMobileTasksListAndDetailEffects(model: ProjectLoadingActionsModel) { const { @@ -21,7 +16,6 @@ export function useMobileTasksListAndDetailEffects(model: ProjectLoadingActionsM activeGitHubProjectViewId, appliedGithubProjectSearch, appliedQuery, - client, connState, copiedLinkResetTimerRef, githubKind, @@ -68,6 +62,7 @@ export function useMobileTasksListAndDetailEffects(model: ProjectLoadingActionsM setPrFileLoadingPath, showCreateTask, showGitHubProjectPicker, + taskOperations, taskStateHydrated, taskUiReady, tasksSupported @@ -186,25 +181,19 @@ export function useMobileTasksListAndDetailEffects(model: ProjectLoadingActionsM ) return } - if (!client) { + if (!taskOperations) { return } let stale = false setCreateTeamId(null) - void client - .sendRequest('linear.listTeams') - .then((response) => { + void taskOperations.linear + .listTeams() + .then((teams) => { if (stale) { return } - if (isSuccess(response)) { - const teams = response.result as LinearTeam[] - setLinearTeams(teams) - setCreateTeamId((current) => current ?? teams[0]?.id ?? null) - } else { - setLinearTeams([]) - setCreateTeamId(null) - } + setLinearTeams(teams) + setCreateTeamId((current) => current ?? teams[0]?.id ?? null) }) .catch(() => { if (!stale) { @@ -215,10 +204,10 @@ export function useMobileTasksListAndDetailEffects(model: ProjectLoadingActionsM return () => { stale = true } - }, [client, hostedRepos, provider, showCreateTask, taskStateHydrated, tasksSupported]) + }, [hostedRepos, provider, showCreateTask, taskOperations, taskStateHydrated, tasksSupported]) useEffect(() => { - if (!tasksSupported || !linearMetadataItem || !client) { + if (!tasksSupported || !linearMetadataItem || !taskOperations) { setLinearStates([]) setLinearCommentDraft('') setLinearSubIssueTitle('') @@ -228,21 +217,13 @@ export function useMobileTasksListAndDetailEffects(model: ProjectLoadingActionsM setLinearStatesLoading(true) setLinearCommentDraft('') setLinearSubIssueTitle('') - const baseParams = { - teamId: linearMetadataItem.source.team.id, - workspaceId: linearMetadataItem.source.workspaceId - } - void client - .sendRequest('linear.teamStates', baseParams) - .then((statesResponse) => { + void taskOperations.linear + .teamStates(taskLinearTarget(linearMetadataItem)) + .then((states) => { if (stale) { return } - if (isSuccess(statesResponse)) { - setLinearStates(statesResponse.result as LinearState[]) - } else { - setLinearStates([]) - } + setLinearStates(states) }) .catch(() => { if (!stale) { @@ -257,7 +238,7 @@ export function useMobileTasksListAndDetailEffects(model: ProjectLoadingActionsM return () => { stale = true } - }, [client, linearMetadataItem, tasksSupported]) + }, [linearMetadataItem, taskOperations, tasksSupported]) useEffect(() => { if (!actionItem) { diff --git a/mobile/src/tasks/use-mobile-tasks-project-detail-loading.tsx b/mobile/src/tasks/use-mobile-tasks-project-detail-loading.tsx index b596f8858a90..1a410f176d3e 100644 --- a/mobile/src/tasks/use-mobile-tasks-project-detail-loading.tsx +++ b/mobile/src/tasks/use-mobile-tasks-project-detail-loading.tsx @@ -1,13 +1,7 @@ import type { ItemDetailLoadingModel } from './use-mobile-tasks-item-detail-loading' import { useEffect } from './mobile-tasks-dependencies' import { - type DetailComment, - type GitHubAssignableUser, - type GitHubDetailCheck, - type GitHubDetailFile, - type GitHubPRReviewSummary, editableProjectFields, - isSuccess, projectFieldDraftValue, projectRowType, splitRepositorySlug @@ -16,7 +10,6 @@ import { export function useMobileTasksProjectDetailLoading(model: ItemDetailLoadingModel) { const { activeGitHubProjectHost, - client, githubProjectTable, projectRowDetailRefreshSeq, projectRowItem, @@ -34,6 +27,7 @@ export function useMobileTasksProjectDetailLoading(model: ItemDetailLoadingModel setProjectRowDetailError, setProjectRowDetailLoading, setProjectTitleDraft, + taskOperations, tasksSupported } = model useEffect(() => { @@ -78,7 +72,7 @@ export function useMobileTasksProjectDetailLoading(model: ItemDetailLoadingModel setProjectRowDetail(null) setProjectRowDetailError('') - if (!tasksSupported || !client || !type || !slug || !projectRowItem.content.number) { + if (!tasksSupported || !taskOperations || !type || !slug || !projectRowItem.content.number) { setProjectRowDetailLoading(false) return } @@ -86,71 +80,33 @@ export function useMobileTasksProjectDetailLoading(model: ItemDetailLoadingModel let stale = false setProjectRowDetailLoading(true) - void client - .sendRequest( - 'github.project.workItemDetailsBySlug', - { - owner: slug.owner, - repo: slug.repo, - host: activeGitHubProjectHost, - number: projectRowItem.content.number, - type - }, - { timeoutMs: 30_000 } - ) - .then((response) => { + void taskOperations.projectRead + .loadItemDetail({ + owner: slug.owner, + repo: slug.repo, + host: activeGitHubProjectHost, + number: projectRowItem.content.number, + type + }) + .then((details) => { if (stale) { return } - if (!isSuccess(response)) { - throw new Error(response.error.message) - } - const result = response.result as - | { - ok: true - details: { - body?: string - comments?: DetailComment[] - item?: { - labels?: string[] - reviewDecision?: string | null - reviewRequests?: GitHubAssignableUser[] - latestReviews?: GitHubPRReviewSummary[] - } - assignees?: string[] - headSha?: string - baseSha?: string - pullRequestId?: string - checks?: GitHubDetailCheck[] - files?: Array<{ - path: string - oldPath?: string - status?: GitHubDetailFile['status'] - additions?: number - deletions?: number - isBinary?: boolean - viewerViewedState?: 'DISMISSED' | 'VIEWED' | 'UNVIEWED' - }> - } - } - | { ok: false; error: { message: string } } - if (!result.ok) { - throw new Error(result.error.message) - } setProjectRowDetail({ provider: 'github', - body: result.details.body ?? '', - comments: result.details.comments ?? [], - labels: result.details.item?.labels ?? projectRowItem.content.labels.map((l) => l.name), - assignees: result.details.assignees ?? [], - reviewDecision: result.details.item?.reviewDecision, - reviewRequests: result.details.item?.reviewRequests ?? [], - latestReviews: result.details.item?.latestReviews ?? [], - headSha: result.details.headSha, - baseSha: result.details.baseSha, - pullRequestId: result.details.pullRequestId, - checks: result.details.checks ?? [], - files: result.details.files ?? [] + body: details.body, + comments: details.comments, + // Why: the row already knows its labels when the host omits them. + labels: details.labels ?? projectRowItem.content.labels.map((label) => label.name), + assignees: details.assignees, + reviewDecision: details.reviewDecision, + reviewRequests: details.reviewRequests ?? [], + latestReviews: details.latestReviews ?? [], + headSha: details.headSha, + baseSha: details.baseSha, + pullRequestId: details.pullRequestId, + checks: details.checks, + files: details.files }) }) .catch((err) => { @@ -169,7 +125,6 @@ export function useMobileTasksProjectDetailLoading(model: ItemDetailLoadingModel } }, [ activeGitHubProjectHost, - client, githubProjectTable, projectRowDetailRefreshSeq, projectRowItem, diff --git a/mobile/src/tasks/use-mobile-tasks-project-file-merge-actions.tsx b/mobile/src/tasks/use-mobile-tasks-project-file-merge-actions.tsx index 6586d0541973..a8cfff17a079 100644 --- a/mobile/src/tasks/use-mobile-tasks-project-file-merge-actions.tsx +++ b/mobile/src/tasks/use-mobile-tasks-project-file-merge-actions.tsx @@ -1,20 +1,17 @@ import type { ProjectReviewCheckActionsModel } from './use-mobile-tasks-project-review-check-actions' import { useCallback } from './mobile-tasks-dependencies' -import { - type DetailComment, - type GitHubDetailFile, - type GitHubPRFileContents, - type GitHubProjectRow, - type HostedReviewMergeMethod, - type TaskItem, - isSuccess, - projectRowGitHubRepository +import type { + DetailComment, + GitHubDetailFile, + GitHubProjectRow, + HostedReviewMergeMethod, + TaskItem } from './mobile-tasks-legacy-foundation' +import { projectRowMutationTarget, taskItemMutationTarget } from './mobile-tasks-mutation-targets' export function useMobileTasksProjectFileMergeActions(model: ProjectReviewCheckActionsModel) { const { activeGitHubProjectHost, - client, expandedPrFilePath, findProjectRowRepo, loadTasks, @@ -34,7 +31,8 @@ export function useMobileTasksProjectFileMergeActions(model: ProjectReviewCheckA setProjectMutating, setProjectRowDetail, setProjectRowDetailError, - setProjectRowItem + setProjectRowItem, + taskOperations } = model const toggleProjectGitHubFileExpansion = useCallback( async (row: GitHubProjectRow, file: GitHubDetailFile): Promise => { @@ -47,11 +45,12 @@ export function useMobileTasksProjectFileMergeActions(model: ProjectReviewCheckA return } const repo = findProjectRowRepo(row) + const target = projectRowMutationTarget(row, activeGitHubProjectHost) if ( - !client || + !taskOperations || row.itemType !== 'PULL_REQUEST' || !repo || - !row.content.number || + !target || projectRowDetail?.provider !== 'github' || !projectRowDetail.headSha || !projectRowDetail.baseSha @@ -62,27 +61,14 @@ export function useMobileTasksProjectFileMergeActions(model: ProjectReviewCheckA setPrFileLoadingPath(file.path) setProjectRowDetailError('') try { - const response = await client.sendRequest( - 'github.prFileContents', - { - repo: `id:${repo.id}`, - prNumber: row.content.number, - prRepo: projectRowGitHubRepository(row, activeGitHubProjectHost), - path: file.path, - oldPath: file.oldPath, - status: file.status ?? 'modified', - headSha: projectRowDetail.headSha, - baseSha: projectRowDetail.baseSha - }, - { timeoutMs: 30_000 } - ) - if (!isSuccess(response)) { - throw new Error(response.error.message) - } - setPrFileContents((current) => ({ - ...current, - [file.path]: response.result as GitHubPRFileContents - })) + const contents = await taskOperations.projectFile.loadFileContents(target, repo.id, { + path: file.path, + oldPath: file.oldPath, + status: file.status ?? 'modified', + headSha: projectRowDetail.headSha, + baseSha: projectRowDetail.baseSha + }) + setPrFileContents((current) => ({ ...current, [file.path]: contents })) } catch (err) { setProjectRowDetailError( err instanceof Error ? err.message : 'Failed to load file contents' @@ -93,23 +79,24 @@ export function useMobileTasksProjectFileMergeActions(model: ProjectReviewCheckA }, [ activeGitHubProjectHost, - client, expandedPrFilePath, findProjectRowRepo, prFileContents, - projectRowDetail + projectRowDetail, + taskOperations ] ) const addProjectGitHubFileReviewComment = useCallback( async (row: GitHubProjectRow, file: GitHubDetailFile, line: number): Promise => { const repo = findProjectRowRepo(row) + const target = projectRowMutationTarget(row, activeGitHubProjectHost) if ( - !client || + !taskOperations || projectMutating || row.itemType !== 'PULL_REQUEST' || !repo || - !row.content.number + !target ) { return } @@ -125,31 +112,13 @@ export function useMobileTasksProjectFileMergeActions(model: ProjectReviewCheckA setProjectMutating(true) setProjectRowDetailError('') try { - const response = await client.sendRequest( - 'github.addPRReviewComment', - { - repo: `id:${repo.id}`, - prNumber: row.content.number, - prRepo: projectRowGitHubRepository(row, activeGitHubProjectHost), - commitId: projectRowDetail.headSha, - path: file.path, - line, - body - }, - { timeoutMs: 30_000 } - ) - if (!isSuccess(response)) { - throw new Error(response.error.message) - } - const result = response.result as { - ok?: boolean - error?: string - comment?: DetailComment - } - if (result.ok === false) { - throw new Error(result.error ?? 'Failed to add review comment') - } - const comment: DetailComment = result.comment ?? { + const addedComment = await taskOperations.projectFile.addInlineComment(target, repo.id, { + commitId: projectRowDetail.headSha, + path: file.path, + line, + body + }) + const comment: DetailComment = addedComment ?? { id: `local-${Date.now()}`, author: 'You', body, @@ -177,23 +146,24 @@ export function useMobileTasksProjectFileMergeActions(model: ProjectReviewCheckA }, [ activeGitHubProjectHost, - client, findProjectRowRepo, prFileCommentDrafts, projectMutating, - projectRowDetail + projectRowDetail, + taskOperations ] ) const mergeProjectGitHubPullRequest = useCallback( async (row: GitHubProjectRow, method: HostedReviewMergeMethod): Promise => { const repo = findProjectRowRepo(row) + const target = projectRowMutationTarget(row, activeGitHubProjectHost) if ( - !client || + !taskOperations || projectMutating || row.itemType !== 'PULL_REQUEST' || !repo || - !row.content.number + !target ) { return } @@ -203,23 +173,7 @@ export function useMobileTasksProjectFileMergeActions(model: ProjectReviewCheckA setProjectMutating(true) setProjectRowDetailError('') try { - const response = await client.sendRequest( - 'github.mergePR', - { - repo: `id:${repo.id}`, - prNumber: row.content.number, - prRepo: projectRowGitHubRepository(row, activeGitHubProjectHost), - method - }, - { timeoutMs: 60_000 } - ) - if (!isSuccess(response)) { - throw new Error(response.error.message) - } - const result = response.result as { ok?: boolean; error?: string } - if (result.ok === false) { - throw new Error(result.error ?? 'Failed to merge pull request') - } + await taskOperations.projectMutation.merge(target, repo.id, method) setProjectRowItem((current) => current?.id === row.id ? { ...current, content: { ...current.content, state: 'MERGED' } } @@ -245,39 +199,22 @@ export function useMobileTasksProjectFileMergeActions(model: ProjectReviewCheckA setProjectMutating(false) } }, - [activeGitHubProjectHost, client, findProjectRowRepo, projectMutating] + [activeGitHubProjectHost, findProjectRowRepo, projectMutating, taskOperations] ) const toggleGitHubStatus = useCallback( async (item: Extract): Promise => { - if (!client || mutatingStatus || item.source.state === 'merged') { + if (!taskOperations || mutatingStatus || item.source.state === 'merged') { return } setMutatingStatus(true) setError('') const nextState = item.source.state === 'closed' ? 'open' : 'closed' try { - const method = item.source.type === 'issue' ? 'github.updateIssue' : 'github.updatePRState' - const params = - item.source.type === 'issue' - ? { - repo: `id:${item.source.repoId}`, - number: item.source.number, - updates: { state: nextState } - } - : { - repo: `id:${item.source.repoId}`, - prNumber: item.source.number, - updates: { state: nextState } - } - const response = await client.sendRequest(method, params) - if (!isSuccess(response)) { - throw new Error(response.error.message) - } - const result = response.result as { ok?: boolean; error?: string } - if (result.ok === false) { - throw new Error(result.error ?? 'Failed to update GitHub status') - } + await taskOperations.itemMutation.setClosed( + taskItemMutationTarget(item), + nextState === 'closed' + ) setActionItem(null) await loadTasks({ silent: true }) } catch (err) { @@ -286,7 +223,7 @@ export function useMobileTasksProjectFileMergeActions(model: ProjectReviewCheckA setMutatingStatus(false) } }, - [client, loadTasks, mutatingStatus] + [loadTasks, mutatingStatus, taskOperations] ) return Object.assign(model, { toggleProjectGitHubFileExpansion, diff --git a/mobile/src/tasks/use-mobile-tasks-project-loading-actions.tsx b/mobile/src/tasks/use-mobile-tasks-project-loading-actions.tsx index 221134e46ee4..19337765bc67 100644 --- a/mobile/src/tasks/use-mobile-tasks-project-loading-actions.tsx +++ b/mobile/src/tasks/use-mobile-tasks-project-loading-actions.tsx @@ -1,24 +1,19 @@ import type { TaskPaginationActionsModel } from './use-mobile-tasks-task-pagination-actions' import { - type GitHubProjectOwnerType, - type GitHubProjectPartialFailure, type GitHubProjectRef, type GitHubProjectSettings, - type GitHubProjectSummary, type GitHubProjectViewSummary, githubProjectHost, githubProjectKey, parseProjectInput, useCallback } from './mobile-tasks-dependencies' -import { type GitHubProjectTable, isSuccess } from './mobile-tasks-legacy-foundation' export function useMobileTasksProjectLoadingActions(model: TaskPaginationActionsModel) { const { activeGitHubProject, activeGitHubProjectHost, activeGitHubProjectViewId, - client, connState, githubProjectPasteInput, githubProjectSettings, @@ -39,65 +34,42 @@ export function useMobileTasksProjectLoadingActions(model: TaskPaginationActions setPendingGitHubProjectViewSelection, setShowGitHubProjectPicker, setShowGitHubProjectViewPicker, + taskOperations, taskStateHydrated, tasksSupported } = model const loadGitHubProjects = useCallback(async (): Promise => { - if (!client || connState !== 'connected' || !tasksSupported) { + if (!taskOperations || connState !== 'connected' || !tasksSupported) { return } setGithubProjectError('') setGithubProjectPartialFailures([]) - const response = await client.sendRequest('github.project.listAccessible', { - host: 'github.com' - }) - if (!isSuccess(response)) { - throw new Error(response.error.message) - } - const result = response.result as - | { - ok: true - projects: GitHubProjectSummary[] - partialFailures?: GitHubProjectPartialFailure[] - } - | { ok: false; error: { message: string } } - if (!result.ok) { - throw new Error(result.error.message) - } + const result = await taskOperations.projectRead.listAccessible('github.com') setGithubProjects(result.projects) - setGithubProjectPartialFailures(result.partialFailures ?? []) - }, [client, connState, tasksSupported]) + setGithubProjectPartialFailures(result.partialFailures) + }, [connState, taskOperations, tasksSupported]) const loadGitHubProjectViews = useCallback( async (project: GitHubProjectRef): Promise => { - if (!client || connState !== 'connected' || !tasksSupported || !taskStateHydrated) { + if (!taskOperations || connState !== 'connected' || !tasksSupported || !taskStateHydrated) { return [] } - const response = await client.sendRequest('github.project.listViews', { + const views = await taskOperations.projectRead.listViews({ owner: project.owner, host: githubProjectHost(project.host), ownerType: project.ownerType, - projectNumber: project.number + number: project.number }) - if (!isSuccess(response)) { - throw new Error(response.error.message) - } - const result = response.result as - | { ok: true; views: GitHubProjectViewSummary[] } - | { ok: false; error: { message: string } } - if (!result.ok) { - throw new Error(result.error.message) - } - setGithubProjectViews(result.views) - return result.views + setGithubProjectViews(views) + return views }, - [client, connState, taskStateHydrated, tasksSupported] + [connState, taskOperations, taskStateHydrated, tasksSupported] ) const loadGitHubProjectTable = useCallback( async (options: { force?: boolean; queryOverride?: string } = {}): Promise => { if ( - !client || + !taskOperations || connState !== 'connected' || !tasksSupported || !activeGitHubProject || @@ -109,39 +81,26 @@ export function useMobileTasksProjectLoadingActions(model: TaskPaginationActions setGithubProjectLoading(true) setGithubProjectError('') try { - const response = await client.sendRequest( - 'github.project.viewTable', - { - owner: activeGitHubProject.owner, - host: activeGitHubProjectHost, - ownerType: activeGitHubProject.ownerType, - projectNumber: activeGitHubProject.number, - viewId: activeGitHubProjectViewId, - ...(options.queryOverride !== undefined ? { queryOverride: options.queryOverride } : {}) - }, - { timeoutMs: 60_000 } - ) - if (!isSuccess(response)) { - throw new Error(response.error.message) - } - const result = response.result as - | { ok: true; data: GitHubProjectTable } - | { ok: false; error: { message: string }; totalCount?: number } - if (!result.ok) { - throw new Error(result.error.message) - } - setGithubProjectTable(result.data) - setGithubProjectSearch(options.queryOverride ?? result.data.selectedView.filter ?? '') + const table = await taskOperations.projectRead.loadTable({ + owner: activeGitHubProject.owner, + host: activeGitHubProjectHost, + ownerType: activeGitHubProject.ownerType, + number: activeGitHubProject.number, + viewId: activeGitHubProjectViewId, + ...(options.queryOverride !== undefined ? { queryOverride: options.queryOverride } : {}) + }) + setGithubProjectTable(table) + setGithubProjectSearch(options.queryOverride ?? table.selectedView.filter ?? '') setGithubProjectViews((current) => - current.some((view) => view.id === result.data.selectedView.id) + current.some((view) => view.id === table.selectedView.id) ? current : [ ...current, { - id: result.data.selectedView.id, - number: result.data.selectedView.number, - name: result.data.selectedView.name, - layout: result.data.selectedView.layout + id: table.selectedView.id, + number: table.selectedView.number, + name: table.selectedView.name, + layout: table.selectedView.layout } ] ) @@ -156,8 +115,8 @@ export function useMobileTasksProjectLoadingActions(model: TaskPaginationActions activeGitHubProject, activeGitHubProjectHost, activeGitHubProjectViewId, - client, connState, + taskOperations, tasksSupported ] ) @@ -249,7 +208,7 @@ export function useMobileTasksProjectLoadingActions(model: TaskPaginationActions ) const resolveGitHubProjectFromInput = useCallback(async (): Promise => { - if (!client || connState !== 'connected' || !tasksSupported || !taskStateHydrated) { + if (!taskOperations || connState !== 'connected' || !tasksSupported || !taskStateHydrated) { return } const input = githubProjectPasteInput.trim() @@ -262,28 +221,10 @@ export function useMobileTasksProjectLoadingActions(model: TaskPaginationActions setGithubProjectPasteError('') setGithubProjectError('') try { - const response = await client.sendRequest('github.project.resolveRef', { + const result = await taskOperations.projectRead.resolveRef({ input, host: githubProjectHost(parsed.host) }) - if (!isSuccess(response)) { - throw new Error(response.error.message) - } - const result = response.result as - | { - ok: true - owner: string - ownerType: GitHubProjectOwnerType - number: number - title: string - host?: string - viewNumber?: number - } - | { ok: false; error: { message: string } } - if (!result.ok) { - setGithubProjectPasteError(result.error.message) - return - } setGithubProjectPasteInput('') setShowGitHubProjectPicker(false) await selectGitHubProject( @@ -301,10 +242,10 @@ export function useMobileTasksProjectLoadingActions(model: TaskPaginationActions setGithubProjectPasteBusy(false) } }, [ - client, connState, githubProjectPasteInput, selectGitHubProject, + taskOperations, taskStateHydrated, tasksSupported ]) diff --git a/mobile/src/tasks/use-mobile-tasks-project-metadata-actions.tsx b/mobile/src/tasks/use-mobile-tasks-project-metadata-actions.tsx index 90c217f36965..1a29bf6ff022 100644 --- a/mobile/src/tasks/use-mobile-tasks-project-metadata-actions.tsx +++ b/mobile/src/tasks/use-mobile-tasks-project-metadata-actions.tsx @@ -5,15 +5,13 @@ import { type GitHubProjectField, type GitHubProjectFieldMutationValue, type GitHubProjectRow, - isSuccess, - optimisticProjectFieldValue, - splitRepositorySlug + optimisticProjectFieldValue } from './mobile-tasks-legacy-foundation' +import { projectRowIdentityTarget, projectRowMutationTarget } from './mobile-tasks-mutation-targets' export function useMobileTasksProjectMetadataActions(model: ProjectThreadReplyActionsModel) { const { activeGitHubProjectHost, - client, githubProjectTable, projectMutating, setGithubProjectTable, @@ -21,7 +19,8 @@ export function useMobileTasksProjectMetadataActions(model: ProjectThreadReplyAc setProjectMutating, setProjectRowDetail, setProjectRowDetailError, - setProjectRowItem + setProjectRowItem, + taskOperations } = model const mutateProjectRowMetadata = useCallback( async ( @@ -33,34 +32,17 @@ export function useMobileTasksProjectMetadataActions(model: ProjectThreadReplyAc removeAssignees?: string[] } ): Promise => { - if (!client || projectMutating) { + if (!taskOperations || projectMutating) { return } - const slug = splitRepositorySlug(row.content.repository) - if (!slug || !row.content.number) { + const target = projectRowMutationTarget(row, activeGitHubProjectHost) + if (!target) { setProjectRowDetailError('This project item cannot be edited from mobile.') return } setProjectMutating(true) try { - const response = await client.sendRequest( - 'github.project.updateIssueBySlug', - { - owner: slug.owner, - repo: slug.repo, - host: activeGitHubProjectHost, - number: row.content.number, - updates - }, - { timeoutMs: 30_000 } - ) - if (!isSuccess(response)) { - throw new Error(response.error.message) - } - const result = response.result as { ok?: boolean; error?: { message?: string } } - if (result.ok === false) { - throw new Error(result.error?.message ?? 'Failed to update GitHub item') - } + await taskOperations.projectMutation.updateMetadata(target, updates) const applyContentUpdate = (candidate: GitHubProjectRow): GitHubProjectRow => { const labels = new Map(candidate.content.labels.map((label) => [label.name, label])) for (const label of updates.addLabels ?? []) { @@ -133,7 +115,7 @@ export function useMobileTasksProjectMetadataActions(model: ProjectThreadReplyAc setProjectMutating(false) } }, - [activeGitHubProjectHost, client, projectMutating] + [activeGitHubProjectHost, projectMutating, taskOperations] ) const mutateProjectRowField = useCallback( @@ -142,36 +124,19 @@ export function useMobileTasksProjectMetadataActions(model: ProjectThreadReplyAc field: GitHubProjectField, value: GitHubProjectFieldMutationValue | null ): Promise => { - if (!client || !githubProjectTable || projectMutating) { + if (!taskOperations || !githubProjectTable || projectMutating) { return } + // Why: the host addresses a field edit by project id + item id, so a draft row with no + // repository slug, issue number or issue/PR kind is still editable. + const target = projectRowIdentityTarget(row, activeGitHubProjectHost) setProjectMutating(true) try { - const response = await client.sendRequest( - value === null ? 'github.project.clearItemField' : 'github.project.updateItemField', - value === null - ? { - projectId: githubProjectTable.project.id, - host: activeGitHubProjectHost, - itemId: row.id, - fieldId: field.id - } - : { - projectId: githubProjectTable.project.id, - host: activeGitHubProjectHost, - itemId: row.id, - fieldId: field.id, - value - }, - { timeoutMs: 30_000 } + await taskOperations.projectMutation.updateField( + { ...target, projectId: githubProjectTable.project.id, itemId: row.id }, + field.id, + value ) - if (!isSuccess(response)) { - throw new Error(response.error.message) - } - const result = response.result as { ok?: boolean; error?: { message?: string } } - if (result.ok === false) { - throw new Error(result.error?.message ?? 'Failed to update project field') - } const patchRow = (candidate: GitHubProjectRow): GitHubProjectRow => { const fieldValuesByFieldId = { ...candidate.fieldValuesByFieldId } if (value === null) { @@ -205,39 +170,22 @@ export function useMobileTasksProjectMetadataActions(model: ProjectThreadReplyAc setProjectMutating(false) } }, - [activeGitHubProjectHost, client, githubProjectTable, projectMutating] + [activeGitHubProjectHost, githubProjectTable, projectMutating, taskOperations] ) const mutateProjectRowIssueType = useCallback( async (row: GitHubProjectRow, issueType: GitHubIssueType | null): Promise => { - if (!client || projectMutating) { + if (!taskOperations || projectMutating) { return } - const slug = splitRepositorySlug(row.content.repository) - if (row.itemType !== 'ISSUE' || !slug || !row.content.number) { + const target = projectRowMutationTarget(row, activeGitHubProjectHost) + if (row.itemType !== 'ISSUE' || !target) { setProjectRowDetailError('This project issue type cannot be edited from mobile.') return } setProjectMutating(true) try { - const response = await client.sendRequest( - 'github.project.updateIssueTypeBySlug', - { - owner: slug.owner, - repo: slug.repo, - host: activeGitHubProjectHost, - number: row.content.number, - issueTypeId: issueType?.id ?? null - }, - { timeoutMs: 30_000 } - ) - if (!isSuccess(response)) { - throw new Error(response.error.message) - } - const result = response.result as { ok?: boolean; error?: { message?: string } } - if (result.ok === false) { - throw new Error(result.error?.message ?? 'Failed to update issue type') - } + await taskOperations.projectMutation.updateIssueType(target, issueType?.id ?? null) const patchRow = (candidate: GitHubProjectRow): GitHubProjectRow => ({ ...candidate, content: { ...candidate.content, issueType } @@ -261,7 +209,7 @@ export function useMobileTasksProjectMetadataActions(model: ProjectThreadReplyAc setProjectMutating(false) } }, - [activeGitHubProjectHost, client, projectMutating] + [activeGitHubProjectHost, projectMutating, taskOperations] ) return Object.assign(model, { mutateProjectRowMetadata, diff --git a/mobile/src/tasks/use-mobile-tasks-project-metadata-loading.tsx b/mobile/src/tasks/use-mobile-tasks-project-metadata-loading.tsx index 5a4e9c48d1f3..3395111ac4d9 100644 --- a/mobile/src/tasks/use-mobile-tasks-project-metadata-loading.tsx +++ b/mobile/src/tasks/use-mobile-tasks-project-metadata-loading.tsx @@ -1,16 +1,10 @@ import type { ProjectDetailLoadingModel } from './use-mobile-tasks-project-detail-loading' import { useEffect } from './mobile-tasks-dependencies' -import { - type GitHubAssignableUser, - type GitHubIssueType, - isSuccess, - splitRepositorySlug -} from './mobile-tasks-legacy-foundation' +import { splitRepositorySlug } from './mobile-tasks-legacy-foundation' export function useMobileTasksProjectMetadataLoading(model: ProjectDetailLoadingModel) { const { activeGitHubProjectHost, - client, projectIssueTypeRepository, projectMetadataRepository, projectMetadataSeedLogins, @@ -23,11 +17,12 @@ export function useMobileTasksProjectMetadataLoading(model: ProjectDetailLoading setProjectIssueTypesLoading, setProjectLabelsError, setProjectLabelsLoading, + taskOperations, tasksSupported } = model useEffect(() => { const slug = splitRepositorySlug(projectMetadataRepository) - if (!tasksSupported || !client || !slug) { + if (!tasksSupported || !taskOperations || !slug) { setProjectAvailableLabels([]) setProjectLabelsLoading(false) setProjectLabelsError('') @@ -38,26 +33,13 @@ export function useMobileTasksProjectMetadataLoading(model: ProjectDetailLoading setProjectAvailableLabels([]) setProjectLabelsError('') setProjectLabelsLoading(true) - void client - .sendRequest( - 'github.project.listLabelsBySlug', - { owner: slug.owner, repo: slug.repo, host: activeGitHubProjectHost }, - { timeoutMs: 30_000 } - ) - .then((response) => { + void taskOperations.projectRead + .listItemLabels({ owner: slug.owner, repo: slug.repo, host: activeGitHubProjectHost }) + .then((labels) => { if (stale) { return } - if (!isSuccess(response)) { - throw new Error(response.error.message) - } - const result = response.result as - | { ok: true; labels?: string[] } - | { ok: false; error?: { message?: string } } - if (!result.ok) { - throw new Error(result.error?.message ?? 'Failed to load labels') - } - setProjectAvailableLabels(result.labels ?? []) + setProjectAvailableLabels(labels) }) .catch((err) => { if (!stale) { @@ -73,11 +55,11 @@ export function useMobileTasksProjectMetadataLoading(model: ProjectDetailLoading return () => { stale = true } - }, [activeGitHubProjectHost, client, projectMetadataRepository, tasksSupported]) + }, [activeGitHubProjectHost, projectMetadataRepository, taskOperations, tasksSupported]) useEffect(() => { const slug = splitRepositorySlug(projectMetadataRepository) - if (!tasksSupported || !client || !slug) { + if (!tasksSupported || !taskOperations || !slug) { setProjectAssignableUsers([]) setProjectAssignableUsersLoading(false) setProjectAssignableUsersError('') @@ -88,31 +70,18 @@ export function useMobileTasksProjectMetadataLoading(model: ProjectDetailLoading setProjectAssignableUsers([]) setProjectAssignableUsersError('') setProjectAssignableUsersLoading(true) - void client - .sendRequest( - 'github.project.listAssignableUsersBySlug', - { - owner: slug.owner, - repo: slug.repo, - host: activeGitHubProjectHost, - ...(projectMetadataSeedLogins ? { seedLogins: projectMetadataSeedLogins.split(',') } : {}) - }, - { timeoutMs: 30_000 } - ) - .then((response) => { + void taskOperations.projectRead + .listItemAssignableUsers({ + owner: slug.owner, + repo: slug.repo, + host: activeGitHubProjectHost, + ...(projectMetadataSeedLogins ? { seedLogins: projectMetadataSeedLogins.split(',') } : {}) + }) + .then((users) => { if (stale) { return } - if (!isSuccess(response)) { - throw new Error(response.error.message) - } - const result = response.result as - | { ok: true; users?: GitHubAssignableUser[] } - | { ok: false; error?: { message?: string } } - if (!result.ok) { - throw new Error(result.error?.message ?? 'Failed to load assignees') - } - setProjectAssignableUsers(result.users ?? []) + setProjectAssignableUsers(users) }) .catch((err) => { if (!stale) { @@ -132,15 +101,15 @@ export function useMobileTasksProjectMetadataLoading(model: ProjectDetailLoading } }, [ activeGitHubProjectHost, - client, projectMetadataRepository, projectMetadataSeedLogins, + taskOperations, tasksSupported ]) useEffect(() => { const slug = splitRepositorySlug(projectIssueTypeRepository) - if (!tasksSupported || !client || !slug) { + if (!tasksSupported || !taskOperations || !slug) { setProjectIssueTypes([]) setProjectIssueTypesLoading(false) setProjectIssueTypesError('') @@ -151,26 +120,13 @@ export function useMobileTasksProjectMetadataLoading(model: ProjectDetailLoading setProjectIssueTypes([]) setProjectIssueTypesError('') setProjectIssueTypesLoading(true) - void client - .sendRequest( - 'github.project.listIssueTypesBySlug', - { owner: slug.owner, repo: slug.repo, host: activeGitHubProjectHost }, - { timeoutMs: 30_000 } - ) - .then((response) => { + void taskOperations.projectRead + .listIssueTypes({ owner: slug.owner, repo: slug.repo, host: activeGitHubProjectHost }) + .then((types) => { if (stale) { return } - if (!isSuccess(response)) { - throw new Error(response.error.message) - } - const result = response.result as - | { ok: true; types?: GitHubIssueType[] } - | { ok: false; error?: { message?: string } } - if (!result.ok) { - throw new Error(result.error?.message ?? 'Failed to load issue types') - } - setProjectIssueTypes(result.types ?? []) + setProjectIssueTypes(types) }) .catch((err) => { if (!stale) { @@ -188,7 +144,7 @@ export function useMobileTasksProjectMetadataLoading(model: ProjectDetailLoading return () => { stale = true } - }, [activeGitHubProjectHost, client, projectIssueTypeRepository, tasksSupported]) + }, [activeGitHubProjectHost, projectIssueTypeRepository, taskOperations, tasksSupported]) return model } diff --git a/mobile/src/tasks/use-mobile-tasks-project-repository-resolution.tsx b/mobile/src/tasks/use-mobile-tasks-project-repository-resolution.tsx index e2d077493b63..626b8ddb5311 100644 --- a/mobile/src/tasks/use-mobile-tasks-project-repository-resolution.tsx +++ b/mobile/src/tasks/use-mobile-tasks-project-repository-resolution.tsx @@ -1,14 +1,8 @@ import type { ProjectProjectionModel } from './use-mobile-tasks-project-projection' -import { - type GitHubOwnerRepo, - githubProjectKey, - useEffect, - useMemo -} from './mobile-tasks-dependencies' +import { githubProjectKey, useEffect, useMemo } from './mobile-tasks-dependencies' import { GITHUB_REPO_CONCURRENCY, getGitHubReviewerSeedUsers, - isSuccess, mapWithConcurrency, mergeGitHubAssignableUsers, projectRowType @@ -18,7 +12,6 @@ export function useMobileTasksProjectRepositoryResolution(model: ProjectProjecti const { actionItem, activeGitHubProject, - client, connState, detailPayload, findProjectRowRepo, @@ -34,12 +27,13 @@ export function useMobileTasksProjectRepositoryResolution(model: ProjectProjecti projectRowItem, provider, setGithubRepoSlugCache, + taskOperations, taskStateHydrated, tasksSupported } = model useEffect(() => { if ( - !client || + !taskOperations || connState !== 'connected' || !tasksSupported || !taskStateHydrated || @@ -59,16 +53,13 @@ export function useMobileTasksProjectRepositoryResolution(model: ProjectProjecti let cancelled = false void mapWithConcurrency(missing, GITHUB_REPO_CONCURRENCY, async (repo) => { try { - const response = await client.sendRequest( - 'github.repoSlug', - { repo: `id:${repo.id}` }, - { timeoutMs: 30_000 } - ) - if (!isSuccess(response)) { - throw new Error(response.error.message) + return { + repoId: repo.id, + entry: { + path: repo.path, + repository: await taskOperations.read.resolveGitHubRepoSlug(repo.id) + } } - const result = response.result as GitHubOwnerRepo | null - return { repoId: repo.id, entry: { path: repo.path, repository: result } } } catch { // Cached so readiness settles; `failed` marks it for retry on refresh. return { repoId: repo.id, entry: { path: repo.path, repository: null, failed: true } } @@ -90,12 +81,12 @@ export function useMobileTasksProjectRepositoryResolution(model: ProjectProjecti cancelled = true } }, [ - client, connState, githubMode, githubRepoSlugCache, hostedRepos, provider, + taskOperations, taskStateHydrated, tasksSupported ]) diff --git a/mobile/src/tasks/use-mobile-tasks-project-review-check-actions.tsx b/mobile/src/tasks/use-mobile-tasks-project-review-check-actions.tsx index ac538cee29c7..6f8621db38d8 100644 --- a/mobile/src/tasks/use-mobile-tasks-project-review-check-actions.tsx +++ b/mobile/src/tasks/use-mobile-tasks-project-review-check-actions.tsx @@ -2,18 +2,15 @@ import type { ProjectMetadataActionsModel } from './use-mobile-tasks-project-met import { useCallback } from './mobile-tasks-dependencies' import { type GitHubAssignableUser, - type GitHubDetailCheck, type GitHubDetailFile, type GitHubProjectRow, - isSuccess, - projectRowGitHubRepository, splitReviewerList } from './mobile-tasks-legacy-foundation' +import { projectRowMutationTarget } from './mobile-tasks-mutation-targets' export function useMobileTasksProjectReviewCheckActions(model: ProjectMetadataActionsModel) { const { activeGitHubProjectHost, - client, findProjectRowRepo, projectMutating, projectReviewersDraft, @@ -22,12 +19,20 @@ export function useMobileTasksProjectReviewCheckActions(model: ProjectMetadataAc setProjectReviewersDraft, setProjectRowDetail, setProjectRowDetailError, - setProjectRowDetailRefreshSeq + setProjectRowDetailRefreshSeq, + taskOperations } = model const requestProjectGitHubReviewers = useCallback( async (row: GitHubProjectRow, logins?: string[]): Promise => { const repo = findProjectRowRepo(row) - if (!client || projectMutating || row.itemType !== 'PULL_REQUEST' || !repo) { + const target = projectRowMutationTarget(row, activeGitHubProjectHost) + if ( + !taskOperations || + projectMutating || + row.itemType !== 'PULL_REQUEST' || + !repo || + !target + ) { return } const reviewers = logins ?? splitReviewerList(projectReviewersDraft) @@ -37,23 +42,7 @@ export function useMobileTasksProjectReviewCheckActions(model: ProjectMetadataAc setProjectMutating(true) setProjectRowDetailError('') try { - const response = await client.sendRequest( - 'github.requestPRReviewers', - { - repo: `id:${repo.id}`, - prNumber: row.content.number, - prRepo: projectRowGitHubRepository(row, activeGitHubProjectHost), - reviewers - }, - { timeoutMs: 30_000 } - ) - if (!isSuccess(response)) { - throw new Error(response.error.message) - } - const result = response.result as { ok?: boolean; error?: string } - if (result.ok === false) { - throw new Error(result.error ?? 'Failed to request reviewers') - } + await taskOperations.projectMutation.requestReviewers(target, repo.id, reviewers) const nextReviewRequests = (() => { const byLogin = new Map() for (const reviewer of projectRowDetail?.provider === 'github' @@ -92,47 +81,35 @@ export function useMobileTasksProjectReviewCheckActions(model: ProjectMetadataAc }, [ activeGitHubProjectHost, - client, findProjectRowRepo, projectMutating, projectReviewersDraft, - projectRowDetail + projectRowDetail, + taskOperations ] ) const refreshProjectGitHubChecks = useCallback( async (row: GitHubProjectRow): Promise => { const repo = findProjectRowRepo(row) + const target = projectRowMutationTarget(row, activeGitHubProjectHost) if ( - !client || + !taskOperations || projectMutating || row.itemType !== 'PULL_REQUEST' || !repo || - !row.content.number + !target ) { return } setProjectMutating(true) setProjectRowDetailError('') try { - const response = await client.sendRequest( - 'github.prChecks', - { - repo: `id:${repo.id}`, - prNumber: row.content.number, - prRepo: projectRowGitHubRepository(row, activeGitHubProjectHost), - headSha: projectRowDetail?.provider === 'github' ? projectRowDetail.headSha : undefined, - noCache: true - }, - { timeoutMs: 30_000 } + const checks = await taskOperations.projectFile.refreshChecks( + target, + repo.id, + projectRowDetail?.provider === 'github' ? projectRowDetail.headSha : undefined ) - if (!isSuccess(response)) { - throw new Error(response.error.message) - } - if (!Array.isArray(response.result)) { - throw new Error('Invalid checks response') - } - const checks = response.result as GitHubDetailCheck[] setProjectRowDetail((current) => current?.provider === 'github' ? { ...current, checks } : current ) @@ -142,42 +119,31 @@ export function useMobileTasksProjectReviewCheckActions(model: ProjectMetadataAc setProjectMutating(false) } }, - [activeGitHubProjectHost, client, findProjectRowRepo, projectMutating, projectRowDetail] + [activeGitHubProjectHost, findProjectRowRepo, projectMutating, projectRowDetail, taskOperations] ) const rerunProjectGitHubChecks = useCallback( async (row: GitHubProjectRow, failedOnly: boolean): Promise => { const repo = findProjectRowRepo(row) + const target = projectRowMutationTarget(row, activeGitHubProjectHost) if ( - !client || + !taskOperations || projectMutating || row.itemType !== 'PULL_REQUEST' || !repo || - !row.content.number + !target ) { return } setProjectMutating(true) setProjectRowDetailError('') try { - const response = await client.sendRequest( - 'github.rerunPRChecks', - { - repo: `id:${repo.id}`, - prNumber: row.content.number, - prRepo: projectRowGitHubRepository(row, activeGitHubProjectHost), - headSha: projectRowDetail?.provider === 'github' ? projectRowDetail.headSha : undefined, - failedOnly - }, - { timeoutMs: 60_000 } - ) - if (!isSuccess(response)) { - throw new Error(response.error.message) - } - const result = response.result as { ok?: boolean; error?: string } - if (result.ok === false) { - throw new Error(result.error ?? 'Failed to rerun checks') - } + await taskOperations.projectMutation.rerunChecks(target, repo.id, { + ...(projectRowDetail?.provider === 'github' && projectRowDetail.headSha + ? { headSha: projectRowDetail.headSha } + : {}), + failedOnly + }) setProjectRowDetailRefreshSeq((current) => current + 1) } catch (err) { setProjectRowDetailError(err instanceof Error ? err.message : 'Failed to rerun checks') @@ -185,13 +151,20 @@ export function useMobileTasksProjectReviewCheckActions(model: ProjectMetadataAc setProjectMutating(false) } }, - [activeGitHubProjectHost, client, findProjectRowRepo, projectMutating, projectRowDetail] + [activeGitHubProjectHost, findProjectRowRepo, projectMutating, projectRowDetail, taskOperations] ) const toggleProjectGitHubFileViewed = useCallback( async (row: GitHubProjectRow, file: GitHubDetailFile): Promise => { const repo = findProjectRowRepo(row) - if (!client || projectMutating || row.itemType !== 'PULL_REQUEST' || !repo) { + const target = projectRowMutationTarget(row, activeGitHubProjectHost) + if ( + !taskOperations || + projectMutating || + row.itemType !== 'PULL_REQUEST' || + !repo || + !target + ) { return } if (projectRowDetail?.provider !== 'github' || !projectRowDetail.pullRequestId) { @@ -202,23 +175,11 @@ export function useMobileTasksProjectReviewCheckActions(model: ProjectMetadataAc setProjectMutating(true) setProjectRowDetailError('') try { - const response = await client.sendRequest( - 'github.setPRFileViewed', - { - repo: `id:${repo.id}`, - prRepo: projectRowGitHubRepository(row, activeGitHubProjectHost), - pullRequestId: projectRowDetail.pullRequestId, - path: file.path, - viewed - }, - { timeoutMs: 30_000 } - ) - if (!isSuccess(response)) { - throw new Error(response.error.message) - } - if (response.result !== true) { - throw new Error('Failed to sync viewed state with GitHub.') - } + await taskOperations.projectFile.setFileViewed(target, repo.id, { + pullRequestId: projectRowDetail.pullRequestId, + path: file.path, + viewed + }) setProjectRowDetail((current) => current?.provider === 'github' ? { @@ -239,7 +200,7 @@ export function useMobileTasksProjectReviewCheckActions(model: ProjectMetadataAc setProjectMutating(false) } }, - [activeGitHubProjectHost, client, findProjectRowRepo, projectMutating, projectRowDetail] + [activeGitHubProjectHost, findProjectRowRepo, projectMutating, projectRowDetail, taskOperations] ) return Object.assign(model, { requestProjectGitHubReviewers, diff --git a/mobile/src/tasks/use-mobile-tasks-project-thread-reply-actions.tsx b/mobile/src/tasks/use-mobile-tasks-project-thread-reply-actions.tsx index e853bcb03bbd..7e5135b4698c 100644 --- a/mobile/src/tasks/use-mobile-tasks-project-thread-reply-actions.tsx +++ b/mobile/src/tasks/use-mobile-tasks-project-thread-reply-actions.tsx @@ -3,19 +3,19 @@ import { useCallback } from './mobile-tasks-dependencies' import { type DetailComment, type GitHubProjectRow, - commentAuthor, - isSuccess, - projectRowGitHubRepository, - projectRowType, - splitRepositorySlug + commentAuthor } from './mobile-tasks-legacy-foundation' +import { + projectRowIdentityTarget, + projectRowMutationTarget, + projectRowSlugTarget +} from './mobile-tasks-mutation-targets' export function useMobileTasksProjectThreadReplyActions( model: ProjectWorkspaceCommentActionsModel ) { const { activeGitHubProjectHost, - client, findProjectRowRepo, itemReplyDrafts, projectEditingCommentId, @@ -25,46 +25,25 @@ export function useMobileTasksProjectThreadReplyActions( setProjectEditingCommentId, setProjectMutating, setProjectRowDetail, - setProjectRowDetailError + setProjectRowDetailError, + taskOperations } = model const deleteProjectRowComment = useCallback( async (row: GitHubProjectRow, comment: DetailComment): Promise => { - if (!client || projectMutating) { + if (!taskOperations || projectMutating) { return } - const slug = splitRepositorySlug(row.content.repository) + // Why: `deleteIssueCommentBySlug` addresses by repository and comment id only. + const target = projectRowSlugTarget(row, activeGitHubProjectHost) const commentId = Number(comment.id) - if (!slug || !Number.isInteger(commentId) || commentId <= 0) { + if (!target || !Number.isInteger(commentId) || commentId <= 0) { setProjectRowDetailError('This project comment cannot be deleted from mobile.') return } setProjectMutating(true) setProjectRowDetailError('') try { - const response = await client.sendRequest( - 'github.project.deleteIssueCommentBySlug', - { - owner: slug.owner, - repo: slug.repo, - host: activeGitHubProjectHost, - commentId - }, - { timeoutMs: 30_000 } - ) - if (!isSuccess(response)) { - throw new Error(response.error.message) - } - const result = response.result as { - ok?: boolean - error?: string | { message?: string } - } - if (result.ok === false) { - throw new Error( - typeof result.error === 'string' - ? result.error - : (result.error?.message ?? 'Failed to delete comment') - ) - } + await taskOperations.projectMutation.deleteComment(target, commentId) setProjectRowDetail((current) => current?.provider === 'github' ? { @@ -83,14 +62,17 @@ export function useMobileTasksProjectThreadReplyActions( setProjectMutating(false) } }, - [activeGitHubProjectHost, client, projectEditingCommentId, projectMutating] + [activeGitHubProjectHost, projectEditingCommentId, projectMutating, taskOperations] ) const toggleProjectGitHubReviewThread = useCallback( async (row: GitHubProjectRow, comment: DetailComment): Promise => { const repo = findProjectRowRepo(row) + // Why: `resolveReviewThread` addresses by repo id and thread id; the slug, number and kind + // are decoration the host treats as optional. + const target = projectRowIdentityTarget(row, activeGitHubProjectHost) if ( - !client || + !taskOperations || projectMutating || row.itemType !== 'PULL_REQUEST' || !repo || @@ -102,22 +84,12 @@ export function useMobileTasksProjectThreadReplyActions( setProjectMutating(true) setProjectRowDetailError('') try { - const response = await client.sendRequest( - 'github.resolveReviewThread', - { - repo: `id:${repo.id}`, - prRepo: projectRowGitHubRepository(row, activeGitHubProjectHost), - threadId: comment.threadId, - resolve - }, - { timeoutMs: 30_000 } + await taskOperations.projectMutation.resolveReviewThread( + target, + repo.id, + comment.threadId, + resolve ) - if (!isSuccess(response)) { - throw new Error(response.error.message) - } - if (response.result !== true) { - throw new Error(resolve ? 'Failed to resolve thread' : 'Failed to reopen thread') - } setProjectRowDetail((current) => current?.provider === 'github' ? { @@ -138,13 +110,14 @@ export function useMobileTasksProjectThreadReplyActions( setProjectMutating(false) } }, - [activeGitHubProjectHost, client, findProjectRowRepo, projectMutating] + [activeGitHubProjectHost, findProjectRowRepo, projectMutating, taskOperations] ) const replyToProjectGitHubComment = useCallback( async (row: GitHubProjectRow, comment: DetailComment): Promise => { const repo = findProjectRowRepo(row) - if (!client || projectMutating || !repo || !row.content.number) { + const target = projectRowMutationTarget(row, activeGitHubProjectHost) + if (!taskOperations || projectMutating || !repo || !target) { return } const key = String(comment.id) @@ -160,44 +133,20 @@ export function useMobileTasksProjectThreadReplyActions( comment.path && typeof comment.line === 'number' && typeof comment.id === 'number' - const response = canUseReviewReply - ? await client.sendRequest( - 'github.addPRReviewCommentReply', - { - repo: `id:${repo.id}`, - prNumber: row.content.number, - prRepo: projectRowGitHubRepository(row, activeGitHubProjectHost), - commentId: comment.id, - body, - threadId: comment.threadId, - path: comment.path, - line: comment.line - }, - { timeoutMs: 30_000 } - ) - : await client.sendRequest( - 'github.addIssueComment', - { - repo: `id:${repo.id}`, - number: row.content.number, - prRepo: projectRowGitHubRepository(row, activeGitHubProjectHost), - body: `@${commentAuthor(comment)} ${body}`, - type: projectRowType(row) ?? 'issue' - }, - { timeoutMs: 30_000 } - ) - if (!isSuccess(response)) { - throw new Error(response.error.message) - } - const result = response.result as { - ok?: boolean - error?: string - comment?: DetailComment - } - if (result.ok === false) { - throw new Error(result.error ?? 'Failed to reply') - } - const reply: DetailComment = result.comment ?? { + const posted = await (canUseReviewReply + ? taskOperations.projectMutation.replyReviewComment(target, repo.id, { + commentId: comment.id as number, + body, + ...(comment.threadId ? { threadId: comment.threadId } : {}), + path: comment.path as string, + line: comment.line as number + }) + : taskOperations.projectMutation.addConversationComment( + target, + repo.id, + `@${commentAuthor(comment)} ${body}` + )) + const reply: DetailComment = posted ?? { id: `local-${Date.now()}`, body, createdAt: new Date().toISOString(), @@ -222,7 +171,7 @@ export function useMobileTasksProjectThreadReplyActions( setProjectMutating(false) } }, - [activeGitHubProjectHost, client, findProjectRowRepo, itemReplyDrafts, projectMutating] + [activeGitHubProjectHost, findProjectRowRepo, itemReplyDrafts, projectMutating, taskOperations] ) return Object.assign(model, { deleteProjectRowComment, diff --git a/mobile/src/tasks/use-mobile-tasks-project-workspace-comment-actions.tsx b/mobile/src/tasks/use-mobile-tasks-project-workspace-comment-actions.tsx index b4aa8ea7460c..86f4536e784f 100644 --- a/mobile/src/tasks/use-mobile-tasks-project-workspace-comment-actions.tsx +++ b/mobile/src/tasks/use-mobile-tasks-project-workspace-comment-actions.tsx @@ -4,16 +4,15 @@ import { type DetailComment, type GitHubProjectRow, type GitHubWorkItem, - isSuccess, projectRowStatusLabel, projectRowType, splitRepositorySlug } from './mobile-tasks-legacy-foundation' +import { projectRowMutationTarget, projectRowSlugTarget } from './mobile-tasks-mutation-targets' export function useMobileTasksProjectWorkspaceCommentActions(model: WorkspaceCreateActionsModel) { const { activeGitHubProjectHost, - client, findProjectRowRepo, openWorkspaceCreate, projectCommentDraft, @@ -29,6 +28,7 @@ export function useMobileTasksProjectWorkspaceCommentActions(model: WorkspaceCre setProjectRowDetail, setProjectRowDetailError, setProjectRowItem, + taskOperations, tasksSupported } = model const createWorkspaceFromProjectRow = useCallback( @@ -90,37 +90,17 @@ export function useMobileTasksProjectWorkspaceCommentActions(model: WorkspaceCre row: GitHubProjectRow, updates: { title?: string; body?: string; state?: 'open' | 'closed' } ): Promise => { - if (!client || projectMutating) { + if (!taskOperations || projectMutating) { return } - const type = projectRowType(row) - const slug = splitRepositorySlug(row.content.repository) - if (!type || !slug || !row.content.number) { + const target = projectRowMutationTarget(row, activeGitHubProjectHost) + if (!target) { setProjectRowDetailError('This project item cannot be edited from mobile.') return } setProjectMutating(true) try { - const response = await client.sendRequest( - type === 'issue' - ? 'github.project.updateIssueBySlug' - : 'github.project.updatePullRequestBySlug', - { - owner: slug.owner, - repo: slug.repo, - host: activeGitHubProjectHost, - number: row.content.number, - updates - }, - { timeoutMs: 30_000 } - ) - if (!isSuccess(response)) { - throw new Error(response.error.message) - } - const result = response.result as { ok?: boolean; error?: { message?: string } } - if (result.ok === false) { - throw new Error(result.error?.message ?? 'Failed to update GitHub item') - } + await taskOperations.projectMutation.updateItem(target, updates) setProjectRowItem((current) => { if (!current || current.id !== row.id) { return current @@ -170,46 +150,27 @@ export function useMobileTasksProjectWorkspaceCommentActions(model: WorkspaceCre setProjectMutating(false) } }, - [activeGitHubProjectHost, client, projectMutating] + [activeGitHubProjectHost, projectMutating, taskOperations] ) const addProjectRowComment = useCallback( async (row: GitHubProjectRow): Promise => { - if (!client || projectMutating) { + if (!taskOperations || projectMutating) { return } - const slug = splitRepositorySlug(row.content.repository) + const target = projectRowMutationTarget(row, activeGitHubProjectHost) const body = projectCommentDraft.trim() - if (!slug || !row.content.number || !body) { + if (!target || !body) { return } setProjectMutating(true) try { - const response = await client.sendRequest( - 'github.project.addIssueCommentBySlug', - { - owner: slug.owner, - repo: slug.repo, - host: activeGitHubProjectHost, - number: row.content.number, - body - }, - { timeoutMs: 30_000 } - ) - if (!isSuccess(response)) { - throw new Error(response.error.message) - } - const result = response.result as - | { ok: true; comment?: DetailComment } - | { ok: false; error?: { message?: string } } - if (!result.ok) { - throw new Error(result.error?.message ?? 'Failed to add comment') - } + const comment = await taskOperations.projectMutation.addComment(target, body) setProjectCommentDraft('') - if (result.comment) { + if (comment) { setProjectRowDetail((current) => current?.provider === 'github' - ? { ...current, comments: [...current.comments, result.comment as DetailComment] } + ? { ...current, comments: [...current.comments, comment] } : current ) } @@ -219,49 +180,26 @@ export function useMobileTasksProjectWorkspaceCommentActions(model: WorkspaceCre setProjectMutating(false) } }, - [activeGitHubProjectHost, client, projectCommentDraft, projectMutating] + [activeGitHubProjectHost, projectCommentDraft, projectMutating, taskOperations] ) const updateProjectRowComment = useCallback( async (row: GitHubProjectRow, comment: DetailComment): Promise => { - if (!client || projectMutating) { + if (!taskOperations || projectMutating) { return } - const slug = splitRepositorySlug(row.content.repository) + // Why: `updateIssueCommentBySlug` addresses by repository and comment id only. + const target = projectRowSlugTarget(row, activeGitHubProjectHost) const commentId = Number(comment.id) const body = projectEditingCommentDraft.trim() - if (!slug || !Number.isInteger(commentId) || commentId <= 0 || !body) { + if (!target || !Number.isInteger(commentId) || commentId <= 0 || !body) { setProjectRowDetailError('This project comment cannot be edited from mobile.') return } setProjectMutating(true) setProjectRowDetailError('') try { - const response = await client.sendRequest( - 'github.project.updateIssueCommentBySlug', - { - owner: slug.owner, - repo: slug.repo, - host: activeGitHubProjectHost, - commentId, - body - }, - { timeoutMs: 30_000 } - ) - if (!isSuccess(response)) { - throw new Error(response.error.message) - } - const result = response.result as { - ok?: boolean - error?: string | { message?: string } - } - if (result.ok === false) { - throw new Error( - typeof result.error === 'string' - ? result.error - : (result.error?.message ?? 'Failed to edit comment') - ) - } + await taskOperations.projectMutation.updateComment(target, commentId, body) setProjectRowDetail((current) => current?.provider === 'github' ? { @@ -280,7 +218,7 @@ export function useMobileTasksProjectWorkspaceCommentActions(model: WorkspaceCre setProjectMutating(false) } }, - [activeGitHubProjectHost, client, projectEditingCommentDraft, projectMutating] + [activeGitHubProjectHost, projectEditingCommentDraft, projectMutating, taskOperations] ) return Object.assign(model, { createWorkspaceFromProjectRow, diff --git a/mobile/src/tasks/use-mobile-tasks-provider-load-actions.tsx b/mobile/src/tasks/use-mobile-tasks-provider-load-actions.tsx index 4550de1492c5..e0ffed18bec5 100644 --- a/mobile/src/tasks/use-mobile-tasks-provider-load-actions.tsx +++ b/mobile/src/tasks/use-mobile-tasks-provider-load-actions.tsx @@ -1,10 +1,10 @@ +import type { HostTaskListOperations } from './host-task-list-operations' import type { RuntimeHydrationModel } from './use-mobile-tasks-runtime-hydration' import { CROSS_REPO_DISPLAY_LIMIT, type GitHubIssueSourceError, type GitHubIssueSourceFallback, PER_REPO_FETCH_LIMIT, - type RpcClient, extractGitHubIssueSourceError, extractGitHubIssueSourceFallback, isGitHubWorkItemsSshRemoteRequiredError, @@ -14,12 +14,10 @@ import { GITHUB_REPO_CONCURRENCY, type GitHubRepoSources, type GitHubWorkItem, - type LinearStatusResponse, type LinearTeam, type RepoSummary, type TaskItem, createGitHubTask, - isSuccess, mapWithConcurrency, reconcileTeamSelection, scopeGitHubTaskSearch, @@ -29,7 +27,6 @@ import { export function useMobileTasksProviderLoadActions(model: RuntimeHydrationModel) { const { appliedQuery, - client, connState, defaultLinearTeamSelectionRef, githubKind, @@ -38,62 +35,48 @@ export function useMobileTasksProviderLoadActions(model: RuntimeHydrationModel) setLinearWorkspaces, setSelectedLinearTeamIds, setSelectedLinearWorkspaceId, + taskOperations, taskUiReady, tasksSupported } = model const loadLinearContext = useCallback(async (): Promise => { - if (!client || connState !== 'connected' || !tasksSupported) { + if (!taskOperations || connState !== 'connected' || !tasksSupported) { return } - const statusResponse = await client.sendRequest('linear.status') - if (!isSuccess(statusResponse)) { - throw new Error(statusResponse.error.message) - } - const status = statusResponse.result as LinearStatusResponse - setLinearConnected(status.connected === true) - if (status.connected !== true) { + const { status, teams } = await taskOperations.read.loadLinearContext() + setLinearConnected(status.connected) + if (!status.connected) { setLinearWorkspaces([]) setLinearTeams([]) setSelectedLinearTeamIds(new Set()) setSelectedLinearWorkspaceId(null) return } - const workspaces = status.workspaces ?? [] - const workspaceId = - status.selectedWorkspaceId ?? status.activeWorkspaceId ?? workspaces[0]?.id ?? null - setLinearWorkspaces(workspaces) - setSelectedLinearWorkspaceId(workspaceId) - - const teamsResponse = await client.sendRequest('linear.listTeams', { - workspaceId: workspaceId ?? undefined - }) - if (!isSuccess(teamsResponse)) { - throw new Error(teamsResponse.error.message) - } - const teams = teamsResponse.result as LinearTeam[] + setLinearWorkspaces(status.workspaces) + setSelectedLinearWorkspaceId(status.selectedWorkspaceId) setLinearTeams(teams) setSelectedLinearTeamIds(reconcileTeamSelection(teams, defaultLinearTeamSelectionRef.current)) - }, [client, connState, tasksSupported]) + }, [connState, taskOperations, tasksSupported]) const persistLinearTeamSelection = useCallback( (teamIds: Set, allTeams: LinearTeam[]) => { - if (!client || !taskUiReady) { + if (!taskOperations || !taskUiReady) { return } const selection = teamIds.size === allTeams.length ? null : [...teamIds] defaultLinearTeamSelectionRef.current = selection - void client - .sendRequest('settings.update', { defaultLinearTeamSelection: selection }) + void taskOperations.preference + .updateSettings({ defaultLinearTeamSelection: selection }) .catch(() => { // Best-effort preference persistence; the local picker state already changed. }) }, - [client, taskUiReady] + [taskOperations, taskUiReady] ) const fetchGitHubItemsPage = useCallback( async ( - requestClient: RpcClient, + listOperations: HostTaskListOperations, queriedRepos: RepoSummary[], before?: string ): Promise<{ @@ -108,23 +91,16 @@ export function useMobileTasksProviderLoadActions(model: RuntimeHydrationModel) GITHUB_REPO_CONCURRENCY, async (repo) => { try { - const response = await requestClient.sendRequest('github.listWorkItems', { - repo: `id:${repo.id}`, + const envelope = await listOperations.listGitHub({ + repoId: repo.id, limit: PER_REPO_FETCH_LIMIT, query: scopeGitHubTaskSearch(appliedQuery, githubKind), before }) - if (!isSuccess(response)) { - throw new Error(response.error.message) - } - const envelope = response.result as { - items: Array> - sources?: GitHubRepoSources - errors?: { issues?: { message: string } } - issueSourceFellBack?: true - } return { - items: envelope.items.map((item) => createGitHubTask(repo, item)), + items: envelope.items.map((item) => + createGitHubTask(repo, item as Omit) + ), sources: envelope.sources, sourceError: extractGitHubIssueSourceError(repo, envelope), sourceFallback: extractGitHubIssueSourceFallback(repo, envelope), @@ -177,24 +153,19 @@ export function useMobileTasksProviderLoadActions(model: RuntimeHydrationModel) ) const countGitHubItems = useCallback( - async (requestClient: RpcClient, queriedRepos: RepoSummary[]): Promise => { + async ( + listOperations: HostTaskListOperations, + queriedRepos: RepoSummary[] + ): Promise => { const counts = await mapWithConcurrency( queriedRepos, GITHUB_REPO_CONCURRENCY, async (repo) => { try { - const response = await requestClient.sendRequest( - 'github.countWorkItems', - { - repo: `id:${repo.id}`, - query: scopeGitHubTaskSearch(appliedQuery, githubKind) - }, - { timeoutMs: 30_000 } - ) - if (!isSuccess(response)) { - throw new Error(response.error.message) - } - return typeof response.result === 'number' ? response.result : 0 + return listOperations.countGitHub({ + repoId: repo.id, + query: scopeGitHubTaskSearch(appliedQuery, githubKind) + }) } catch (err) { const isExpectedSshSkip = isGitHubWorkItemsSshRemoteRequiredError(err) const logWorkItemCountFailure = isExpectedSshSkip ? console.log : console.warn diff --git a/mobile/src/tasks/use-mobile-tasks-route-and-item-state.tsx b/mobile/src/tasks/use-mobile-tasks-route-and-item-state.tsx index 7e692e2e1a92..e89c115aac81 100644 --- a/mobile/src/tasks/use-mobile-tasks-route-and-item-state.tsx +++ b/mobile/src/tasks/use-mobile-tasks-route-and-item-state.tsx @@ -10,6 +10,7 @@ import { useLastConnectedAt, useRelayRecoveryStatus, useLocalSearchParams, + useMemo, useReconnectAttempt, useRef, useRouter, @@ -40,9 +41,11 @@ import { type TaskResumeState, type TaskSort, type TasksSupportState, - getTaskPresetQuery, - isSuccess + getTaskPresetQuery } from './mobile-tasks-legacy-foundation' +import { defaultDeviceOperations } from '../device/default-device-operations' +import { defaultHostTaskOperations } from './default-host-task-operations' +import { defaultHostWorkspaceCreationOperations } from '../worktree/default-host-workspace-creation-operations' import { useMobileTasksItemState } from './use-mobile-tasks-item-state' export function useMobileTasksRouteAndItemState() { @@ -56,16 +59,19 @@ export function useMobileTasksRouteAndItemState() { const clientRef = useRef(null) const loadGenerationRef = useRef(0) const taskResumeRef = useRef({}) + const taskOperations = useMemo( + () => (client ? defaultHostTaskOperations(client) : null), + [client] + ) + const taskWorkspaceCreationOperations = useMemo( + () => (client ? defaultHostWorkspaceCreationOperations(client) : null), + [client] + ) + const deviceOperations = useMemo(() => defaultDeviceOperations(), []) const repoList = useHostRepoList( - client, - client && connState === 'connected' - ? async () => { - const response = await client.sendRequest('repo.list') - if (!isSuccess(response)) { - throw new Error(response.error.message) - } - return (response.result as { repos: RepoSummary[] }).repos - } + taskOperations, + taskOperations && connState === 'connected' + ? () => taskOperations.read.listRepositories() : null ) const repos = repoList.state.repos @@ -174,6 +180,9 @@ export function useMobileTasksRouteAndItemState() { router, insets, client, + taskOperations, + taskWorkspaceCreationOperations, + deviceOperations, connState, reconnectAttempts, lastConnectedAt, diff --git a/mobile/src/tasks/use-mobile-tasks-runtime-hydration.tsx b/mobile/src/tasks/use-mobile-tasks-runtime-hydration.tsx index b1d8680b824b..0be77b7a36f8 100644 --- a/mobile/src/tasks/use-mobile-tasks-runtime-hydration.tsx +++ b/mobile/src/tasks/use-mobile-tasks-runtime-hydration.tsx @@ -1,7 +1,5 @@ import type { ClientSettingsActionsModel } from './use-mobile-tasks-client-settings-actions' import { - MOBILE_TASKS_CAPABILITY, - type PersistedTrustedOrcaHooks, filterAvailableTaskProviders, isHostedTaskRepo, normalizeVisibleTaskProviders, @@ -11,13 +9,8 @@ import { } from './mobile-tasks-dependencies' import { EMPTY_GITHUB_PROJECT_SETTINGS, - type LinearStatusResponse, - type RuntimeTaskSettings, - type TaskResumeState, - type TaskRuntimeStatus, getTaskPresetQuery, githubKindFromQuery, - isSuccess, isTaskProvider, normalizeGitHubPreset, normalizeLinearFilter, @@ -97,11 +90,12 @@ export function useMobileTasksRuntimeHydration(model: ClientSettingsActionsModel setTasksSupportState, setTrustedOrcaHooks, setVisibleProviders, + taskOperations, taskResumeRef, visibleProviders } = model useEffect(() => { - if (!client || connState !== 'connected') { + if (!client || !taskOperations || connState !== 'connected') { taskResumeRef.current = {} defaultRepoSelectionRef.current = null repoSelectionHydratedRef.current = false @@ -191,15 +185,11 @@ export function useMobileTasksRuntimeHydration(model: ClientSettingsActionsModel resetWorkspaceCreateState() const hydrateTaskState = async (): Promise => { - const statusResponse = await client.sendRequest('status.get') + const bootstrap = await taskOperations.read.bootstrap() if (stale) { return } - if (!isSuccess(statusResponse)) { - throw new Error(statusResponse.error.message) - } - const status = statusResponse.result as TaskRuntimeStatus - if (!status.capabilities?.includes(MOBILE_TASKS_CAPABILITY)) { + if (!bootstrap.supported) { // Why: Tasks is additive RPC surface, so old desktop builds can still // pair but must not receive the newer task-specific method calls. setTasksSupportState({ kind: 'unsupported', client }) @@ -248,47 +238,17 @@ export function useMobileTasksRuntimeHydration(model: ClientSettingsActionsModel } setTasksSupportState({ kind: 'supported', client }) setError('') - const [settingsResponse, uiResponse, preflightResponse, linearStatusResponse] = - await Promise.all([ - client.sendRequest('settings.get'), - client.sendRequest('ui.get'), - client.sendRequest('preflight.check'), - client.sendRequest('linear.status') - ]) - if (stale) { - return - } - - const settings = isSuccess(settingsResponse) - ? (((settingsResponse.result as { settings?: RuntimeTaskSettings }).settings ?? - {}) as RuntimeTaskSettings) - : {} + const settings = bootstrap.settings setRuntimeTaskSettings(settings) - const uiState = isSuccess(uiResponse) - ? ( - uiResponse.result as { - ui?: { - taskResumeState?: TaskResumeState - trustedOrcaHooks?: PersistedTrustedOrcaHooks - } - } - ).ui - : null - setTrustedOrcaHooks(uiState?.trustedOrcaHooks ?? {}) - const resume = uiState?.taskResumeState ?? {} + setTrustedOrcaHooks(bootstrap.trustedOrcaHooks) + const resume = bootstrap.taskResumeState taskResumeRef.current = resume setGithubProjectHiddenFieldIdsByView(resume.githubProjectHiddenFieldIdsByView ?? {}) - const preflight = isSuccess(preflightResponse) - ? (preflightResponse.result as { glab?: { installed?: boolean } }) - : null - const linearStatus = isSuccess(linearStatusResponse) - ? (linearStatusResponse.result as LinearStatusResponse) - : null const preferredProviders = normalizeVisibleTaskProviders(settings.visibleTaskProviders) - const linearIsConnected = linearStatus?.connected === true + const linearIsConnected = bootstrap.linearStatus.connected const availableProviders = filterAvailableTaskProviders(preferredProviders, { - gitlabInstalled: preflight?.glab?.installed === true, + gitlabInstalled: bootstrap.gitLabInstalled, linearConnected: linearIsConnected }) const nextVisibleProviders = @@ -353,7 +313,7 @@ export function useMobileTasksRuntimeHydration(model: ClientSettingsActionsModel return () => { stale = true } - }, [client, connState, requestedTaskSource, resetWorkspaceCreateState]) + }, [client, connState, requestedTaskSource, resetWorkspaceCreateState, taskOperations]) useEffect(() => { if (visibleProviders.includes(provider)) { diff --git a/mobile/src/tasks/use-mobile-tasks-task-create-actions.tsx b/mobile/src/tasks/use-mobile-tasks-task-create-actions.tsx index b532272b8418..859bb059bc8f 100644 --- a/mobile/src/tasks/use-mobile-tasks-task-create-actions.tsx +++ b/mobile/src/tasks/use-mobile-tasks-task-create-actions.tsx @@ -5,13 +5,11 @@ import { type TaskItem, createGitHubTask, createGitLabTask, - createLinearTask, - isSuccess + createLinearTask } from './mobile-tasks-legacy-foundation' export function useMobileTasksTaskCreateActions(model: LinearItemActionsModel) { const { - client, createBody, createRepoId, createTeamId, @@ -28,12 +26,13 @@ export function useMobileTasksTaskCreateActions(model: LinearItemActionsModel) { setCreatingTask, setError, setShowCreateTask, + taskOperations, taskStateHydrated, taskUiReady, tasksSupported } = model const createTask = useCallback(async (): Promise => { - if (!client || !tasksSupported || !taskStateHydrated || creatingTask) { + if (!taskOperations || !tasksSupported || !taskStateHydrated || creatingTask) { return } const title = createTitle.trim() @@ -50,28 +49,12 @@ export function useMobileTasksTaskCreateActions(model: LinearItemActionsModel) { `Add a Git repository before creating a ${provider === 'github' ? 'GitHub' : 'GitLab'} issue.` ) } - const response = await client.sendRequest( - provider === 'github' ? 'github.createIssue' : 'gitlab.createIssue', - { - repo: `id:${repo.id}`, - title, - body: createBody - } - ) - if (!isSuccess(response)) { - throw new Error(response.error.message) - } - const result = response.result as { - ok?: boolean - number?: number - url?: string - error?: string - } - if (result.ok === false) { - throw new Error( - result.error ?? `Failed to create ${provider === 'github' ? 'GitHub' : 'GitLab'} issue` - ) - } + const result = await taskOperations.providerWrite.createIssue({ + provider, + repoId: repo.id, + title, + body: createBody + }) if (typeof result.number === 'number') { const createdAt = new Date().toISOString() if (provider === 'github') { @@ -109,26 +92,11 @@ export function useMobileTasksTaskCreateActions(model: LinearItemActionsModel) { if (!team) { throw new Error('Select a Linear team first.') } - const response = await client.sendRequest('linear.createIssue', { - teamId: team.id, + const result = await taskOperations.linear.createIssue({ + team, title, - description: createBody.trim() || undefined, - workspaceId: team.workspaceId + description: createBody.trim() || undefined }) - if (!isSuccess(response)) { - throw new Error(response.error.message) - } - const result = response.result as { - ok?: boolean - id?: string - identifier?: string - title?: string - url?: string - error?: string - } - if (result.ok === false || !result.id || !result.identifier) { - throw new Error(result.error ?? 'Failed to create Linear issue') - } setActionItem( createLinearTask({ id: result.id, @@ -156,7 +124,6 @@ export function useMobileTasksTaskCreateActions(model: LinearItemActionsModel) { setCreatingTask(false) } }, [ - client, createBody, createRepoId, createTeamId, @@ -166,28 +133,19 @@ export function useMobileTasksTaskCreateActions(model: LinearItemActionsModel) { linearTeams, loadTasks, provider, + taskOperations, taskStateHydrated, tasksSupported ]) const setGitHubIssueSourcePreference = useCallback( async (repo: RepoSummary, preference: 'upstream' | 'origin'): Promise => { - if (!client || !taskUiReady) { + if (!taskOperations || !taskUiReady) { return } setError('') try { - const response = await client.sendRequest( - 'repo.update', - { - repo: `id:${repo.id}`, - updates: { issueSourcePreference: preference } - }, - { timeoutMs: 15_000 } - ) - if (!isSuccess(response)) { - throw new Error(response.error.message) - } + await taskOperations.providerWrite.updateIssueSource(repo.id, preference) // Why: the host owns issueSourcePreference, so re-read the list instead of // patching the cached copy and hoping the two stay in step. await repoListReload().catch(() => {}) @@ -196,7 +154,7 @@ export function useMobileTasksTaskCreateActions(model: LinearItemActionsModel) { setError(err instanceof Error ? err.message : 'Failed to update issue source') } }, - [client, loadTasks, repoListReload, taskUiReady] + [loadTasks, repoListReload, taskOperations, taskUiReady] ) return Object.assign(model, { createTask, setGitHubIssueSourcePreference }) } diff --git a/mobile/src/tasks/use-mobile-tasks-task-list-loading.tsx b/mobile/src/tasks/use-mobile-tasks-task-list-loading.tsx index 671cb154019f..5c54e2da32d4 100644 --- a/mobile/src/tasks/use-mobile-tasks-task-list-loading.tsx +++ b/mobile/src/tasks/use-mobile-tasks-task-list-loading.tsx @@ -1,9 +1,5 @@ import type { ProviderLoadActionsModel } from './use-mobile-tasks-provider-load-actions' -import { - extractLinearIssueReadItems, - isHostedTaskRepo, - useCallback -} from './mobile-tasks-dependencies' +import { isHostedTaskRepo, useCallback } from './mobile-tasks-dependencies' import { GITHUB_REPO_CONCURRENCY, GITLAB_PER_PAGE, @@ -16,7 +12,6 @@ import { createGitLabTask, createGitLabTodoTask, createLinearTask, - isSuccess, mapWithConcurrency, taskTime } from './mobile-tasks-legacy-foundation' @@ -26,6 +21,7 @@ export function useMobileTasksTaskListLoading(model: ProviderLoadActionsModel) { appliedQuery, client, clientRef, + taskOperations, connState, countGitHubItems, fetchGitHubItemsPage, @@ -57,12 +53,19 @@ export function useMobileTasksTaskListLoading(model: ProviderLoadActionsModel) { } = model const loadTasks = useCallback( async (options: { silent?: boolean } = {}): Promise => { - if (!client || connState !== 'connected' || !tasksSupported || !taskStateHydrated) { + if ( + !client || + !taskOperations || + connState !== 'connected' || + !tasksSupported || + !taskStateHydrated + ) { return } const generation = loadGenerationRef.current + 1 loadGenerationRef.current = generation const requestClient = client + const listOperations = taskOperations.list const isCurrent = () => loadGenerationRef.current === generation && clientRef.current === requestClient setError('') @@ -108,7 +111,7 @@ export function useMobileTasksTaskListLoading(model: ProviderLoadActionsModel) { return } if (provider === 'github') { - const page = await fetchGitHubItemsPage(requestClient, queriedRepos) + const page = await fetchGitHubItemsPage(listOperations, queriedRepos) if (!isCurrent()) { return } @@ -122,7 +125,7 @@ export function useMobileTasksTaskListLoading(model: ProviderLoadActionsModel) { setGithubCurrentPage(0) setItems(page.items) if (selectedRepoIds.size > 0) { - void countGitHubItems(requestClient, queriedRepos).then((count) => { + void countGitHubItems(listOperations, queriedRepos).then((count) => { if (isCurrent()) { setGithubTotalCount(count) } @@ -140,17 +143,12 @@ export function useMobileTasksTaskListLoading(model: ProviderLoadActionsModel) { return } if (provider === 'gitlab' && gitlabView === 'todos') { - const response = await requestClient.sendRequest('gitlab.todos', { - repo: `id:${queriedRepos[0]!.id}` - }) - if (!isSuccess(response)) { - throw new Error(response.error.message) - } + const todos = await listOperations.listGitLabTodos(queriedRepos[0]!.id) if (!isCurrent()) { return } setItems( - ((response.result as GitLabTodo[]) ?? []) + (todos as GitLabTodo[]) .map(createGitLabTodoTask) .sort((a, b) => taskTime(b.updatedAt) - taskTime(a.updatedAt)) ) @@ -161,24 +159,21 @@ export function useMobileTasksTaskListLoading(model: ProviderLoadActionsModel) { GITHUB_REPO_CONCURRENCY, async (repo) => { try { - const response = await requestClient.sendRequest('gitlab.listWorkItems', { - repo: `id:${repo.id}`, + const envelope = await listOperations.listGitLab({ + repoId: repo.id, state: gitlabFilter, page: 1, perPage: GITLAB_PER_PAGE, query: appliedQuery.trim() || undefined }) - if (!isSuccess(response)) { - throw new Error(response.error.message) - } - const envelope = response.result as { - items: Array> - error?: { type?: string; message: string } - } if (envelope.error?.type && envelope.error.type !== 'not_found') { return { items: [], error: envelope.error.message } } - return { items: envelope.items.map((item) => createGitLabTask(repo, item)) } + return { + items: envelope.items.map((item) => + createGitLabTask(repo, item as Omit) + ) + } } catch (err) { console.warn(`[mobile tasks] failed to fetch ${provider} work items`, repo.id, err) return { @@ -209,21 +204,11 @@ export function useMobileTasksTaskListLoading(model: ProviderLoadActionsModel) { } } else { const normalizedQuery = appliedQuery.trim() - const response = normalizedQuery - ? await requestClient.sendRequest('linear.searchIssues', { - query: normalizedQuery, - limit: LINEAR_LIMIT, - workspaceId: selectedLinearWorkspaceId ?? undefined - }) - : await requestClient.sendRequest('linear.listIssues', { - filter: linearFilter, - limit: LINEAR_LIMIT, - workspaceId: selectedLinearWorkspaceId ?? undefined - }) - if (!isSuccess(response)) { - throw new Error(response.error.message) - } - const issues = extractLinearIssueReadItems(response.result) + const issues = await listOperations.listLinear({ + ...(normalizedQuery ? { query: normalizedQuery } : { filter: linearFilter }), + limit: LINEAR_LIMIT, + workspaceId: selectedLinearWorkspaceId ?? undefined + }) const filtered = selectedLinearTeamIds.size > 0 ? issues.filter((issue) => selectedLinearTeamIds.has(issue.team.id)) @@ -267,6 +252,7 @@ export function useMobileTasksTaskListLoading(model: ProviderLoadActionsModel) { selectedLinearTeamIds, selectedLinearWorkspaceId, selectedRepoIds, + taskOperations, taskStateHydrated, tasksSupported ] diff --git a/mobile/src/tasks/use-mobile-tasks-task-pagination-actions.tsx b/mobile/src/tasks/use-mobile-tasks-task-pagination-actions.tsx index 9c2b0b06873e..7b9b2c24fd6d 100644 --- a/mobile/src/tasks/use-mobile-tasks-task-pagination-actions.tsx +++ b/mobile/src/tasks/use-mobile-tasks-task-pagination-actions.tsx @@ -5,15 +5,10 @@ import { useCallback, useMemo } from './mobile-tasks-dependencies' -import { - type TaskItem, - buildPartialRepositoryNotice, - isSuccess -} from './mobile-tasks-legacy-foundation' +import { type TaskItem, buildPartialRepositoryNotice } from './mobile-tasks-legacy-foundation' export function useMobileTasksTaskPaginationActions(model: TaskListLoadingModel) { const { - client, connState, fetchGitHubItemsPage, githubCurrentPage, @@ -39,11 +34,12 @@ export function useMobileTasksTaskPaginationActions(model: TaskListLoadingModel) setRetryingGithubSourceRepoPaths, setShowLinearConnect, setVisibleProviders, + taskOperations, taskUiReady, tasksSupported } = model const connectLinearAccount = useCallback(async (): Promise => { - if (!client || connState !== 'connected' || !taskUiReady) { + if (!taskOperations || connState !== 'connected' || !taskUiReady) { return } const apiKey = linearApiKeyDraft.trim() @@ -53,14 +49,7 @@ export function useMobileTasksTaskPaginationActions(model: TaskListLoadingModel) setLinearConnectState('connecting') setLinearConnectError('') try { - const response = await client.sendRequest('linear.connect', { apiKey }) - if (!isSuccess(response)) { - throw new Error(response.error.message) - } - const result = response.result as { ok?: boolean; error?: string } - if (result.ok === false) { - throw new Error(result.error ?? 'Failed to connect Linear') - } + await taskOperations.linear.connect(apiKey) setLinearApiKeyDraft('') setLinearConnectState('idle') setShowLinearConnect(false) @@ -74,7 +63,14 @@ export function useMobileTasksTaskPaginationActions(model: TaskListLoadingModel) setLinearConnectState('error') setLinearConnectError(err instanceof Error ? err.message : 'Connection failed') } - }, [client, connState, linearApiKeyDraft, linearConnectState, loadLinearContext, taskUiReady]) + }, [ + connState, + linearApiKeyDraft, + linearConnectState, + loadLinearContext, + taskOperations, + taskUiReady + ]) const retryGitHubIssueSourceFetch = useCallback( async (repoPath: string): Promise => { @@ -139,7 +135,7 @@ export function useMobileTasksTaskPaginationActions(model: TaskListLoadingModel) const handleGitHubPageChange = useCallback( async (targetPage: number): Promise => { if ( - !client || + !taskOperations || !tasksSupported || targetPage < 0 || githubPaginationLoading || @@ -168,7 +164,7 @@ export function useMobileTasksTaskPaginationActions(model: TaskListLoadingModel) let loadedPages = githubPages.length const nextPages: Array[]> = [] while (loadedPages <= targetPage) { - const page = await fetchGitHubItemsPage(client, selectedHostedRepos, cursor) + const page = await fetchGitHubItemsPage(taskOperations.list, selectedHostedRepos, cursor) if (page.items.length === 0) { break } @@ -195,11 +191,11 @@ export function useMobileTasksTaskPaginationActions(model: TaskListLoadingModel) } }, [ - client, fetchGitHubItemsPage, githubPages, githubPaginationLoading, selectedHostedRepos, + taskOperations, tasksSupported ] ) diff --git a/mobile/src/tasks/use-mobile-tasks-workspace-create-actions.tsx b/mobile/src/tasks/use-mobile-tasks-workspace-create-actions.tsx index 91a7da4d2342..91dff2a2b658 100644 --- a/mobile/src/tasks/use-mobile-tasks-workspace-create-actions.tsx +++ b/mobile/src/tasks/use-mobile-tasks-workspace-create-actions.tsx @@ -12,11 +12,11 @@ import { } from './mobile-tasks-dependencies' import { type ActionableTaskItem, - type GitPushTarget, type RuntimeTaskSettings, type SetupDecision, isSuccess } from './mobile-tasks-legacy-foundation' +import type { HostWorkspaceCreationOperations } from '../worktree/host-workspace-creation-operations' export function useMobileTasksWorkspaceCreateActions(model: WorkspaceSshStateModel) { const { @@ -37,6 +37,7 @@ export function useMobileTasksWorkspaceCreateActions(model: WorkspaceSshStateMod setWorkspaceAgentOverridden, setWorkspaceCreateDraft, taskStateHydrated, + taskWorkspaceCreationOperations, tasksSupported, trustedOrcaHooks, workspaceDetectedAgentIds, @@ -55,7 +56,7 @@ export function useMobileTasksWorkspaceCreateActions(model: WorkspaceSshStateMod sparseCheckoutOverride?: { directories: string[]; presetId?: string }, approvedSetupContentHash?: string ): Promise => { - if (!client || !tasksSupported || !taskStateHydrated) { + if (!client || !taskWorkspaceCreationOperations || !tasksSupported || !taskStateHydrated) { return } setCreatingKey(item.key) @@ -72,13 +73,9 @@ export function useMobileTasksWorkspaceCreateActions(model: WorkspaceSshStateMod await ensureWorkspaceSshReady(targetRepo) let latestRuntimeTaskSettings = runtimeTaskSettings try { - const settingsResponse = await client.sendRequest('settings.get') - if (isSuccess(settingsResponse)) { - latestRuntimeTaskSettings = (( - settingsResponse.result as { settings?: RuntimeTaskSettings } - ).settings ?? {}) as RuntimeTaskSettings - setRuntimeTaskSettings(latestRuntimeTaskSettings) - } + latestRuntimeTaskSettings = + (await taskWorkspaceCreationOperations.readRuntimeSettings()) as RuntimeTaskSettings + setRuntimeTaskSettings(latestRuntimeTaskSettings) } catch { // Best-effort refresh; the runtime still validates agent availability before spawning. } @@ -156,35 +153,16 @@ export function useMobileTasksWorkspaceCreateActions(model: WorkspaceSshStateMod let params: Record if (item.provider === 'github') { const source = item.source - let prStartPoint: { baseBranch: string; pushTarget?: GitPushTarget } | undefined - if ( - shouldResolveHostedReviewStartPoint({ - type: source.type, - baseBranchOverride + let prStartPoint: + | Awaited> + | undefined + if (shouldResolveHostedReviewStartPoint({ type: source.type, baseBranchOverride })) { + prStartPoint = await taskWorkspaceCreationOperations.resolvePrBase({ + repoId: source.repoId, + prNumber: source.number, + headRefName: source.branchName, + isCrossRepository: source.isCrossRepository }) - ) { - const response = await client.sendRequest( - 'worktree.resolvePrBase', - { - repo: `id:${source.repoId}`, - prNumber: source.number, - ...(source.branchName ? { headRefName: source.branchName } : {}), - ...(source.isCrossRepository !== undefined - ? { isCrossRepository: source.isCrossRepository } - : {}) - }, - { timeoutMs: 30_000 } - ) - if (!isSuccess(response)) { - throw new Error(response.error.message) - } - const result = response.result as - | { baseBranch: string; pushTarget?: GitPushTarget } - | { error: string } - if ('error' in result) { - throw new Error(result.error) - } - prStartPoint = result } params = buildTaskWorkspaceCreateParams({ item, @@ -201,35 +179,16 @@ export function useMobileTasksWorkspaceCreateActions(model: WorkspaceSshStateMod }) } else if (item.provider === 'gitlab') { const source = item.source - let mrStartPoint: { baseBranch: string; pushTarget?: GitPushTarget } | undefined - if ( - shouldResolveHostedReviewStartPoint({ - type: source.type, - baseBranchOverride + let mrStartPoint: + | Awaited> + | undefined + if (shouldResolveHostedReviewStartPoint({ type: source.type, baseBranchOverride })) { + mrStartPoint = await taskWorkspaceCreationOperations.resolveMrBase({ + repoId: source.repoId, + mrIid: source.number, + sourceBranch: source.branchName, + isCrossRepository: source.isCrossRepository }) - ) { - const response = await client.sendRequest( - 'worktree.resolveMrBase', - { - repo: `id:${source.repoId}`, - mrIid: source.number, - ...(source.branchName ? { sourceBranch: source.branchName } : {}), - ...(source.isCrossRepository !== undefined - ? { isCrossRepository: source.isCrossRepository } - : {}) - }, - { timeoutMs: 30_000 } - ) - if (!isSuccess(response)) { - throw new Error(response.error.message) - } - const result = response.result as - | { baseBranch: string; pushTarget?: GitPushTarget } - | { error: string } - if ('error' in result) { - throw new Error(result.error) - } - mrStartPoint = result } params = buildTaskWorkspaceCreateParams({ item, @@ -258,6 +217,9 @@ export function useMobileTasksWorkspaceCreateActions(model: WorkspaceSshStateMod nameIsAutoManaged }) } + // Why still inline: the operations seam's create is the composer's source flow, which + // builds different params and adds name-collision retry. Task-item create keeps its own + // params builder until that difference is deliberately reconciled. const response = await client.sendRequest('worktree.create', params, { timeoutMs: WORKTREE_CREATE_TIMEOUT_MS }) @@ -294,6 +256,7 @@ export function useMobileTasksWorkspaceCreateActions(model: WorkspaceSshStateMod router, runtimeTaskSettings, taskStateHydrated, + taskWorkspaceCreationOperations, tasksSupported, trustedOrcaHooks, workspaceDetectedAgentIds, diff --git a/mobile/src/tasks/use-mobile-tasks-workspace-source-effects.tsx b/mobile/src/tasks/use-mobile-tasks-workspace-source-effects.tsx index 93d0d45de095..c24305ef2987 100644 --- a/mobile/src/tasks/use-mobile-tasks-workspace-source-effects.tsx +++ b/mobile/src/tasks/use-mobile-tasks-workspace-source-effects.tsx @@ -1,10 +1,8 @@ import type { WorkspaceCreateProjectionModel } from './use-mobile-tasks-workspace-create-projection' -import { type BaseRefSearchResult, type SparsePreset, useEffect } from './mobile-tasks-dependencies' -import { isSuccess } from './mobile-tasks-legacy-foundation' +import { useEffect } from './mobile-tasks-dependencies' export function useMobileTasksWorkspaceSourceEffects(model: WorkspaceCreateProjectionModel) { const { - client, setWorkspaceBaseBranchError, setWorkspaceBaseBranchLoading, setWorkspaceBaseBranchResults, @@ -15,6 +13,7 @@ export function useMobileTasksWorkspaceSourceEffects(model: WorkspaceCreateProje setWorkspaceSparsePresetsLoaded, setWorkspaceSparsePresetsLoading, showWorkspaceBaseBranchPicker, + taskWorkspaceCreationOperations, tasksSupported, workspaceBaseBranchQuery, workspaceCreateDraft, @@ -22,7 +21,12 @@ export function useMobileTasksWorkspaceSourceEffects(model: WorkspaceCreateProje workspaceSparseReloadKey } = model useEffect(() => { - if (!tasksSupported || !client || !workspaceCreateDraft || !workspaceCreateTargetRepo) { + if ( + !tasksSupported || + !taskWorkspaceCreationOperations || + !workspaceCreateDraft || + !workspaceCreateTargetRepo + ) { setWorkspaceSparsePresets([]) setWorkspaceSparsePresetsLoading(false) setWorkspaceSparsePresetsLoaded(false) @@ -45,16 +49,12 @@ export function useMobileTasksWorkspaceSourceEffects(model: WorkspaceCreateProje setWorkspaceSparsePresetsLoading(true) setWorkspaceSparsePresetsLoaded(false) setWorkspaceSparsePresetsError('') - void client - .sendRequest('repo.sparsePresets', { repo: `id:${workspaceCreateTargetRepo.id}` }) - .then((response) => { + void taskWorkspaceCreationOperations + .listSparsePresets(workspaceCreateTargetRepo.id) + .then((presets) => { if (stale) { return } - if (!isSuccess(response)) { - throw new Error(response.error.message) - } - const presets = (response.result as { presets?: SparsePreset[] }).presets ?? [] setWorkspaceSparsePresets(presets) setWorkspaceSparsePresetsLoaded(true) setWorkspaceSparsePresetId((current) => @@ -81,7 +81,7 @@ export function useMobileTasksWorkspaceSourceEffects(model: WorkspaceCreateProje stale = true } }, [ - client, + taskWorkspaceCreationOperations, tasksSupported, workspaceCreateDraft, workspaceCreateTargetRepo, @@ -90,7 +90,7 @@ export function useMobileTasksWorkspaceSourceEffects(model: WorkspaceCreateProje useEffect(() => { if ( - !client || + !taskWorkspaceCreationOperations || !tasksSupported || !workspaceCreateDraft || !workspaceCreateTargetRepo || @@ -112,27 +112,13 @@ export function useMobileTasksWorkspaceSourceEffects(model: WorkspaceCreateProje let stale = false setWorkspaceBaseBranchLoading(true) setWorkspaceBaseBranchError('') - void client - .sendRequest( - 'repo.searchRefs', - { repo: `id:${workspaceCreateTargetRepo.id}`, query, limit: 20 }, - { timeoutMs: 30_000 } - ) - .then((response) => { + void taskWorkspaceCreationOperations + .searchBranches(workspaceCreateTargetRepo.id, query) + .then((results) => { if (stale) { return } - if (!isSuccess(response)) { - throw new Error(response.error.message) - } - const result = response.result as { - refDetails?: BaseRefSearchResult[] - refs?: string[] - } - setWorkspaceBaseBranchResults( - result.refDetails ?? - (result.refs ?? []).map((refName) => ({ refName, localBranchName: refName })) - ) + setWorkspaceBaseBranchResults(results) }) .catch((err) => { if (!stale) { @@ -152,7 +138,7 @@ export function useMobileTasksWorkspaceSourceEffects(model: WorkspaceCreateProje stale = true } }, [ - client, + taskWorkspaceCreationOperations, tasksSupported, showWorkspaceBaseBranchPicker, workspaceBaseBranchQuery, diff --git a/mobile/src/tasks/use-mobile-tasks-workspace-sparse-actions.tsx b/mobile/src/tasks/use-mobile-tasks-workspace-sparse-actions.tsx index d2b9551032fd..33bb866fdc01 100644 --- a/mobile/src/tasks/use-mobile-tasks-workspace-sparse-actions.tsx +++ b/mobile/src/tasks/use-mobile-tasks-workspace-sparse-actions.tsx @@ -1,16 +1,10 @@ import type { WorkspaceSourceEffectsModel } from './use-mobile-tasks-workspace-source-effects' -import { - type SparsePreset, - type SshConnectionState, - useCallback, - useEffect -} from './mobile-tasks-dependencies' -import { isSuccess, sortSparsePresetsByName } from './mobile-tasks-legacy-foundation' +import { type SparsePreset, useCallback, useEffect } from './mobile-tasks-dependencies' +import { sortSparsePresetsByName } from './mobile-tasks-legacy-foundation' export function useMobileTasksWorkspaceSparseActions(model: WorkspaceSourceEffectsModel) { const { canSaveWorkspaceSparseDraft, - client, setShowWorkspaceSparsePicker, setWorkspaceSparseDraft, setWorkspaceSparsePresetId, @@ -20,6 +14,7 @@ export function useMobileTasksWorkspaceSparseActions(model: WorkspaceSourceEffec setWorkspaceSparseSaving, setWorkspaceSshConnecting, setWorkspaceSshState, + taskWorkspaceCreationOperations, tasksSupported, workspaceCreateDraft, workspaceCreateTargetConnectionId, @@ -70,7 +65,7 @@ export function useMobileTasksWorkspaceSparseActions(model: WorkspaceSourceEffec const saveWorkspaceSparsePreset = useCallback(async (): Promise => { if ( - !client || + !taskWorkspaceCreationOperations || !tasksSupported || !workspaceCreateTargetRepo || !workspaceSparseDraft || @@ -82,19 +77,14 @@ export function useMobileTasksWorkspaceSparseActions(model: WorkspaceSourceEffec setWorkspaceSparseSaving(true) setWorkspaceSparsePresetsError('') try { - const response = await client.sendRequest('repo.saveSparsePreset', { - repo: `id:${workspaceCreateTargetRepo.id}`, - ...(workspaceSparseDraft.presetId ? { id: workspaceSparseDraft.presetId } : {}), - name: workspaceSparseDraftName, - directories: workspaceSparseDraftParsed.directories - }) - if (!isSuccess(response)) { - throw new Error(response.error.message) - } - const saved = (response.result as { preset?: SparsePreset }).preset - if (!saved) { - throw new Error('Failed to save sparse preset.') - } + const saved = await taskWorkspaceCreationOperations.saveSparsePreset( + workspaceCreateTargetRepo.id, + { + ...(workspaceSparseDraft.presetId ? { id: workspaceSparseDraft.presetId } : {}), + name: workspaceSparseDraftName, + directories: workspaceSparseDraftParsed.directories + } + ) setWorkspaceSparsePresets((current) => { const withoutSaved = current.filter((preset) => preset.id !== saved.id) return sortSparsePresetsByName([...withoutSaved, saved]) @@ -113,7 +103,7 @@ export function useMobileTasksWorkspaceSparseActions(model: WorkspaceSourceEffec } }, [ canSaveWorkspaceSparseDraft, - client, + taskWorkspaceCreationOperations, tasksSupported, workspaceCreateTargetRepo, workspaceSparseDraft, @@ -123,31 +113,25 @@ export function useMobileTasksWorkspaceSparseActions(model: WorkspaceSourceEffec ]) useEffect(() => { - if (!tasksSupported || !client || !workspaceCreateDraft || !workspaceCreateTargetConnectionId) { + if ( + !tasksSupported || + !taskWorkspaceCreationOperations || + !workspaceCreateDraft || + !workspaceCreateTargetConnectionId + ) { setWorkspaceSshState(null) setWorkspaceSshConnecting(false) return } let stale = false - void client - .sendRequest('ssh.getState', { targetId: workspaceCreateTargetConnectionId }) - .then((response) => { + void taskWorkspaceCreationOperations + .readSshState(workspaceCreateTargetConnectionId) + .then((state) => { if (stale) { return } - if (!isSuccess(response)) { - throw new Error(response.error.message) - } - const state = (response.result as { state?: SshConnectionState | null }).state ?? null - setWorkspaceSshState( - state ?? { - targetId: workspaceCreateTargetConnectionId, - status: 'disconnected', - error: null, - reconnectAttempt: 0 - } - ) + setWorkspaceSshState(state) }) .catch((err) => { if (!stale) { @@ -163,7 +147,12 @@ export function useMobileTasksWorkspaceSparseActions(model: WorkspaceSourceEffec return () => { stale = true } - }, [client, tasksSupported, workspaceCreateDraft, workspaceCreateTargetConnectionId]) + }, [ + taskWorkspaceCreationOperations, + tasksSupported, + workspaceCreateDraft, + workspaceCreateTargetConnectionId + ]) return Object.assign(model, { startNewWorkspaceSparsePreset, startEditWorkspaceSparsePreset, diff --git a/mobile/src/tasks/use-mobile-tasks-workspace-ssh-state.tsx b/mobile/src/tasks/use-mobile-tasks-workspace-ssh-state.tsx index d1a408aed222..1de2e6b63e1a 100644 --- a/mobile/src/tasks/use-mobile-tasks-workspace-ssh-state.tsx +++ b/mobile/src/tasks/use-mobile-tasks-workspace-ssh-state.tsx @@ -1,6 +1,5 @@ import type { WorkspaceSparseActionsModel } from './use-mobile-tasks-workspace-sparse-actions' import { - type SshConnectionState, normalizeSetupHookTrust, pickWorkspaceAgent, resolveWorkspaceAgentSelection, @@ -8,22 +7,21 @@ import { useEffect, useMemo } from './mobile-tasks-dependencies' -import { - type RepoHooksResponse, - type RepoSummary, - type SetupDecision, - isSuccess +import type { + RepoHooksResponse, + RepoSummary, + SetupDecision } from './mobile-tasks-legacy-foundation' export function useMobileTasksWorkspaceSshState(model: WorkspaceSparseActionsModel) { const { - client, runtimeTaskSettings, setWorkspaceAgent, setWorkspaceAgentOverridden, setWorkspaceDetectedAgentIds, setWorkspaceSshConnecting, setWorkspaceSshState, + taskWorkspaceCreationOperations, tasksSupported, workspaceAgent, workspaceAgentOverridden, @@ -36,7 +34,7 @@ export function useMobileTasksWorkspaceSshState(model: WorkspaceSparseActionsMod workspaceSshState } = model const connectWorkspaceSshRepo = useCallback(async (): Promise => { - if (!client || !tasksSupported || !workspaceCreateTargetConnectionId) { + if (!taskWorkspaceCreationOperations || !tasksSupported || !workspaceCreateTargetConnectionId) { return } setWorkspaceSshConnecting(true) @@ -47,22 +45,8 @@ export function useMobileTasksWorkspaceSshState(model: WorkspaceSparseActionsMod reconnectAttempt: 0 }) try { - const response = await client.sendRequest( - 'ssh.connect', - { targetId: workspaceCreateTargetConnectionId }, - { timeoutMs: 120_000 } - ) - if (!isSuccess(response)) { - throw new Error(response.error.message) - } - const state = (response.result as { state?: SshConnectionState | null }).state setWorkspaceSshState( - state ?? { - targetId: workspaceCreateTargetConnectionId, - status: 'connected', - error: null, - reconnectAttempt: 0 - } + await taskWorkspaceCreationOperations.connectSsh(workspaceCreateTargetConnectionId) ) } catch (err) { setWorkspaceSshState({ @@ -74,11 +58,11 @@ export function useMobileTasksWorkspaceSshState(model: WorkspaceSparseActionsMod } finally { setWorkspaceSshConnecting(false) } - }, [client, tasksSupported, workspaceCreateTargetConnectionId]) + }, [taskWorkspaceCreationOperations, tasksSupported, workspaceCreateTargetConnectionId]) const ensureWorkspaceSshReady = useCallback( async (repo: RepoSummary): Promise => { - if (!repo.connectionId || !client || !tasksSupported) { + if (!repo.connectionId || !taskWorkspaceCreationOperations || !tasksSupported) { return } if ( @@ -87,23 +71,22 @@ export function useMobileTasksWorkspaceSshState(model: WorkspaceSparseActionsMod ) { return } - const response = await client.sendRequest('ssh.getState', { targetId: repo.connectionId }) - if (!isSuccess(response)) { - throw new Error(response.error.message) - } - const state = (response.result as { state?: SshConnectionState | null }).state ?? null - if (state) { - setWorkspaceSshState(state) - } - if (state?.status !== 'connected') { + const state = await taskWorkspaceCreationOperations.readSshState(repo.connectionId) + setWorkspaceSshState(state) + if (state.status !== 'connected') { throw new Error(`Connect ${repo.displayName} before creating a workspace.`) } }, - [client, tasksSupported, workspaceSshState] + [taskWorkspaceCreationOperations, tasksSupported, workspaceSshState] ) useEffect(() => { - if (!tasksSupported || !workspaceCreateDraft || !client || !workspaceCreateTargetRepo) { + if ( + !tasksSupported || + !workspaceCreateDraft || + !taskWorkspaceCreationOperations || + !workspaceCreateTargetRepo + ) { setWorkspaceDetectedAgentIds(null) return } @@ -115,19 +98,13 @@ export function useMobileTasksWorkspaceSshState(model: WorkspaceSparseActionsMod } let stale = false setWorkspaceDetectedAgentIds(null) - const request = workspaceCreateTargetRepo.connectionId - ? client.sendRequest('preflight.detectRemoteAgents', { - connectionId: workspaceCreateTargetRepo.connectionId - }) - : client.sendRequest('preflight.detectAgents') - void request - .then((response) => { + void taskWorkspaceCreationOperations + .detectAgents(workspaceCreateTargetRepo.connectionId ?? null) + .then((agentIds) => { if (stale) { return } - setWorkspaceDetectedAgentIds( - isSuccess(response) ? new Set(response.result as string[]) : new Set() - ) + setWorkspaceDetectedAgentIds(new Set(agentIds)) }) .catch(() => { if (!stale) { @@ -138,7 +115,7 @@ export function useMobileTasksWorkspaceSshState(model: WorkspaceSparseActionsMod stale = true } }, [ - client, + taskWorkspaceCreationOperations, tasksSupported, workspaceCreateDraft, workspaceCreateSshStatus, @@ -187,14 +164,10 @@ export function useMobileTasksWorkspaceSshState(model: WorkspaceSparseActionsMod setupTrust?: RepoHooksResponse['setupTrust'] } > => { - if (!client || !tasksSupported) { + if (!taskWorkspaceCreationOperations || !tasksSupported) { return { kind: 'decision', decision: override ?? 'inherit' } } - const response = await client.sendRequest('repo.hooks', { repo: `id:${repo.id}` }) - if (!isSuccess(response)) { - throw new Error(response.error.message) - } - const result = response.result as RepoHooksResponse + const result = await taskWorkspaceCreationOperations.readRepoHooks(repo.id) const setupCommand = result.hooks?.scripts?.setup?.trim() const setupTrust = normalizeSetupHookTrust(result.setupTrust) ?? undefined if (!setupCommand) { @@ -213,7 +186,7 @@ export function useMobileTasksWorkspaceSshState(model: WorkspaceSparseActionsMod setupTrust } }, - [client, tasksSupported] + [taskWorkspaceCreationOperations, tasksSupported] ) return Object.assign(model, { connectWorkspaceSshRepo, diff --git a/mobile/src/tasks/use-smart-workspace-source.ts b/mobile/src/tasks/use-smart-workspace-source.ts index a57c9f17d7d1..145f81ed1391 100644 --- a/mobile/src/tasks/use-smart-workspace-source.ts +++ b/mobile/src/tasks/use-smart-workspace-source.ts @@ -7,7 +7,7 @@ import { type SmartNameMode, type SmartWorkspaceSourceRow } from '../../../src/shared/new-workspace/smart-workspace-source-results' -import type { RpcClient } from '../transport/rpc-client' +import type { HostWorkspaceCreationOperations } from '../worktree/host-workspace-creation-operations' import { fanOutSmartSearch, type SmartFanOutResult } from './smart-source-fan-out' import type { MrStateFilter } from './mobile-composer-source-types' import { @@ -32,7 +32,7 @@ export type SmartCrossRepoPrompt = { } export type UseSmartWorkspaceSourceArgs = { - client: RpcClient | null + operations: HostWorkspaceCreationOperations | null enabled: boolean mode: SmartNameMode query: string @@ -55,10 +55,11 @@ const EMPTY_FAN: SmartFanOutResult = { } type PasteResolved = { github: GitHubWorkItem | null; gitlab: GitLabWorkItem | null } +const EMPTY_PASTE: PasteResolved = { github: null, gitlab: null } export function useSmartWorkspaceSource(args: UseSmartWorkspaceSourceArgs) { const { - client, + operations, enabled, mode, query, @@ -71,7 +72,7 @@ export function useSmartWorkspaceSource(args: UseSmartWorkspaceSourceArgs) { repos } = args const [fan, setFan] = useState(EMPTY_FAN) - const [paste, setPaste] = useState({ github: null, gitlab: null }) + const [paste, setPaste] = useState(EMPTY_PASTE) const [loading, setLoading] = useState(false) const [crossRepoPrompt, setCrossRepoPrompt] = useState(null) // Why: preserve results across keystrokes (debounce) but drop them the moment @@ -83,9 +84,9 @@ export function useSmartWorkspaceSource(args: UseSmartWorkspaceSourceArgs) { >(new Map()) useEffect(() => { - if (!client || !enabled || mode === 'text') { + if (!operations || !enabled || mode === 'text') { setFan(EMPTY_FAN) - setPaste({ github: null, gitlab: null }) + setPaste(EMPTY_PASTE) setLoading(false) setCrossRepoPrompt(null) return @@ -95,14 +96,14 @@ export function useSmartWorkspaceSource(args: UseSmartWorkspaceSourceArgs) { scopeRef.current = scope if (scopeChanged) { setFan(EMPTY_FAN) - setPaste({ github: null, gitlab: null }) + setPaste(EMPTY_PASTE) setCrossRepoPrompt(null) } setLoading(true) let stale = false const timer = setTimeout(() => { void runSmartSearch({ - client, + operations, mode, query, repoId, @@ -135,7 +136,7 @@ export function useSmartWorkspaceSource(args: UseSmartWorkspaceSourceArgs) { clearTimeout(timer) } }, [ - client, + operations, enabled, mode, query, @@ -189,17 +190,17 @@ const EMPTY_PASTE_LOOKUP: PasteLookup = { // Resolves a pasted issue/PR/MR reference to the exact item it names. async function resolvePastedItem(args: { - client: RpcClient + operations: HostWorkspaceCreationOperations intent: NonNullable> repoId: string repos: readonly PasteRepoCandidate[] repoSlugCache: Map }): Promise { - const { client, intent, repoId, repos, repoSlugCache } = args + const { operations, intent, repoId, repos, repoSlugCache } = args if (intent.kind === 'github-number') { return { paste: { - github: await lookupGitHubItemByNumber(client, repoId, intent.number), + github: await lookupGitHubItemByNumber(operations, repoId, intent.number), gitlab: null }, crossRepoPrompt: null @@ -207,7 +208,7 @@ async function resolvePastedItem(args: { } if (intent.kind === 'github-link') { const matchingRepo = await findRepoMatchingSlugForPaste( - client, + operations, repos, intent.link.slug, repoSlugCache @@ -221,7 +222,7 @@ async function resolvePastedItem(args: { return { paste: { github: await lookupGitHubItemByOwnerRepo( - client, + operations, repoId, intent.link.slug, intent.link.number, @@ -233,13 +234,16 @@ async function resolvePastedItem(args: { } } return { - paste: { github: null, gitlab: await lookupGitLabItemByPath(client, repoId, intent.link) }, + paste: { + github: null, + gitlab: await lookupGitLabItemByPath(operations, repoId, intent.link) + }, crossRepoPrompt: null } } async function runSmartSearch(args: { - client: RpcClient + operations: HostWorkspaceCreationOperations mode: SmartNameMode query: string repoId: string | null @@ -256,7 +260,7 @@ async function runSmartSearch(args: { paste: PasteResolved crossRepoPrompt: SmartCrossRepoPrompt | null }> { - const { client, mode, query, repoId, repos, dismissedPasteRef, repoSlugCache } = args + const { operations, mode, query, repoId, repos, dismissedPasteRef, repoSlugCache } = args const intent = mode === 'branches' || dismissedPasteRef.current === query.trim() ? null @@ -267,7 +271,7 @@ async function runSmartSearch(args: { const [fan, pasteLookup] = await Promise.all([ fanOutSmartSearch(args), intent && repoId - ? resolvePastedItem({ client, intent, repoId, repos, repoSlugCache }).catch( + ? resolvePastedItem({ operations, intent, repoId, repos, repoSlugCache }).catch( // Best-effort paste resolution; fall back to the fan-out results. () => EMPTY_PASTE_LOOKUP ) diff --git a/mobile/src/tasks/worktree-create-capability.ts b/mobile/src/tasks/worktree-create-capability.ts index 926d89f38e49..b5868c866c94 100644 --- a/mobile/src/tasks/worktree-create-capability.ts +++ b/mobile/src/tasks/worktree-create-capability.ts @@ -1,9 +1,10 @@ import { useCallback, useEffect, useRef, useState } from 'react' -import type { RpcClient, RpcRequestSender } from '../transport/rpc-client' +import type { RpcRequestSender } from '../transport/rpc-client' import { isLogicalClientCutoverError } from '../transport/stable-logical-rpc-client' import type { RpcSuccess } from '../transport/types' import { readMobileRuntimeHostPlatform } from '../transport/mobile-runtime-host-platform' import { MOBILE_TASKS_CAPABILITY } from './mobile-tasks-capability' +import type { HostWorkspaceCreationOperations } from '../worktree/host-workspace-creation-operations' import { WORKTREE_CREATE_DEDUPE_TTL_LEGACY_HOST_MS, resolveWorktreeCreateIdempotencySupport, @@ -73,7 +74,7 @@ export async function readNewWorktreeRuntimeCapabilities( } export function useNewWorktreeRuntimeCapabilities( - client: RpcClient | null, + operations: HostWorkspaceCreationOperations | null, enabled: boolean ): { tasksSupported: boolean @@ -83,25 +84,25 @@ export function useNewWorktreeRuntimeCapabilities( const [tasksSupported, setTasksSupported] = useState(false) const [hostPlatform, setHostPlatform] = useState(null) const capabilityProbeRef = useRef<{ - client: RpcClient | null + operations: HostWorkspaceCreationOperations | null promise: Promise } | null>(null) const getCapabilities = useCallback((): Promise => { - if (!capabilityProbeRef.current || capabilityProbeRef.current.client !== client) { + if (!capabilityProbeRef.current || capabilityProbeRef.current.operations !== operations) { // Why: a queued tap can reach Create before passive effects run; lazily // starting one shared probe keeps that path from failing open. capabilityProbeRef.current = { - client, - promise: client - ? readNewWorktreeRuntimeCapabilities(client) + operations, + promise: operations + ? operations.readRuntimeCapabilities() : Promise.resolve(UNSUPPORTED_CAPABILITIES) } } return capabilityProbeRef.current.promise - }, [client]) + }, [operations]) useEffect(() => { - if (!enabled || !client) { + if (!enabled || !operations) { return } let stale = false @@ -114,7 +115,7 @@ export function useNewWorktreeRuntimeCapabilities( return () => { stale = true } - }, [client, enabled, getCapabilities, setTasksSupported]) + }, [operations, enabled, getCapabilities, setTasksSupported]) const getWorktreeCreateCutoverSupport = useCallback( () => getCapabilities().then((capabilities) => capabilities.worktreeCreateIdempotency), diff --git a/mobile/src/worktree/use-retired-worktree-names.test.tsx b/mobile/src/worktree/use-retired-worktree-names.test.tsx index 660b2f018d94..ed0e69e8ccf8 100644 --- a/mobile/src/worktree/use-retired-worktree-names.test.tsx +++ b/mobile/src/worktree/use-retired-worktree-names.test.tsx @@ -1,7 +1,7 @@ import { createElement } from 'react' import { act, create } from 'react-test-renderer' import { describe, expect, it } from 'vitest' -import type { RpcClient } from '../transport/rpc-client' +import { readRetiredNameRegistryForRepo } from '../../../src/shared/worktree/retired-name-cache' import { EMPTY_RETIRED_NAME_REGISTRY, type RetiredNameRegistry @@ -11,30 +11,44 @@ import { useRetiredWorktreeNames } from './use-retired-worktree-names' -type Pending = { resolve: (response: unknown) => void; reject: (err: Error) => void } +type Pending = { + repoId: string + resolve: (registry: RetiredNameRegistry) => void + reject: (err: Error) => void +} /** Renders the hook against a deferred RPC client so a test decides exactly when each * `worktree.listRetiredNames` lands, and for which repo. */ function mountNames() { const pending: Pending[] = [] - const requests: { method: string; params: unknown }[] = [] + const requests: string[] = [] let latest: RetiredNameRegistry = EMPTY_RETIRED_NAME_REGISTRY - const client = { - sendRequest: (method: string, params: unknown) => { - requests.push({ method, params }) - return new Promise((resolve, reject) => pending.push({ resolve, reject })) - } - } as unknown as RpcClient + const readRetiredNames = (repoId: string) => { + requests.push(repoId) + return new Promise((resolve, reject) => + pending.push({ repoId, resolve, reject }) + ) + } - function Probe({ repoId, refreshKey }: { repoId: string | null; refreshKey: string }) { - latest = useRetiredWorktreeNames(client, repoId, refreshKey) + function Probe({ + repoId, + refreshKey, + readNames + }: { + repoId: string | null + refreshKey: string + readNames: (repoId: string) => Promise + }) { + latest = useRetiredWorktreeNames(readNames, repoId, refreshKey) return null } let renderer!: ReturnType act(() => { - renderer = create(createElement(Probe, { repoId: 'repo-1', refreshKey: 'a' })) + renderer = create( + createElement(Probe, { repoId: 'repo-1', refreshKey: 'a', readNames: readRetiredNames }) + ) }) return { get registry(): RetiredNameRegistry { @@ -46,7 +60,7 @@ function mountNames() { requests, rerender(props: { repoId: string | null; refreshKey: string }) { act(() => { - renderer.update(createElement(Probe, props)) + renderer.update(createElement(Probe, { ...props, readNames: readRetiredNames })) }) }, async settle( @@ -55,7 +69,13 @@ function mountNames() { retiredNameTiersByRepo: Record = {} ) { await act(async () => { - pending[index]!.resolve({ result: { retiredNamesByRepo, retiredNameTiersByRepo } }) + const request = pending[index]! + request.resolve( + readRetiredNameRegistryForRepo( + { retiredNamesByRepo, retiredNameTiersByRepo }, + request.repoId + ) + ) await Promise.resolve() }) }, @@ -87,10 +107,7 @@ describe('useRetiredWorktreeNames', () => { it('reads the selected repo out of the response envelope', async () => { const probe = mountNames() - expect(probe.requests[0]).toEqual({ - method: 'worktree.listRetiredNames', - params: { repo: 'id:repo-1' } - }) + expect(probe.requests[0]).toBe('repo-1') await probe.settle(0, { 'repo-1': ['nautilus'], 'repo-2': ['seahorse'] }) expect(probe.names).toEqual(['nautilus']) }) diff --git a/mobile/src/worktree/use-retired-worktree-names.ts b/mobile/src/worktree/use-retired-worktree-names.ts index 3158110f82cc..f28aa047866e 100644 --- a/mobile/src/worktree/use-retired-worktree-names.ts +++ b/mobile/src/worktree/use-retired-worktree-names.ts @@ -1,12 +1,12 @@ import { useEffect, useState } from 'react' import { - readRetiredNameRegistryForRepo, retiredNamesAfterRefresh, selectRetiredNameRegistry, type RetiredNamesLoad } from '../../../src/shared/worktree/retired-name-cache' import type { RetiredNameRegistry } from '../../../src/shared/worktree/retired-name-registry' -import type { RpcClient } from '../transport/rpc-client' + +type ReadRetiredWorktreeNames = (repoId: string) => Promise export function buildRetiredWorktreeNamesRefreshKey( existingWorktreePaths: readonly string[] | undefined @@ -24,15 +24,15 @@ export function buildRetiredWorktreeNamesRefreshKey( * `retired-name-cache` so this and the desktop hook cannot drift on what a failure means, and no * loading state is reported because create is never gated on this fetch. */ export function useRetiredWorktreeNames( - client: RpcClient | null | undefined, + readRetiredNames: ReadRetiredWorktreeNames | null | undefined, repoId: string | null | undefined, refreshKey: unknown ): RetiredNameRegistry { const [loaded, setLoaded] = useState(null) - const activeRepoId = client && repoId ? repoId : null + const activeRepoId = readRetiredNames && repoId ? repoId : null useEffect(() => { - if (!client || !activeRepoId) { + if (!readRetiredNames || !activeRepoId) { setLoaded(null) return } @@ -42,18 +42,13 @@ export function useRetiredWorktreeNames( setLoaded((previous) => retiredNamesAfterRefresh(previous, activeRepoId, registry)) } } - void client - .sendRequest('worktree.listRetiredNames', { repo: `id:${activeRepoId}` }) - .then((response) => - settle( - readRetiredNameRegistryForRepo((response as { result?: unknown }).result, activeRepoId) - ) - ) + void readRetiredNames(activeRepoId) + .then(settle) .catch(() => settle(null)) return () => { cancelled = true } - }, [activeRepoId, client, refreshKey]) + }, [activeRepoId, readRetiredNames, refreshKey]) return selectRetiredNameRegistry(loaded, activeRepoId) } From 213948061c4319721316d9643e0f2d5aacbe133d Mon Sep 17 00:00:00 2001 From: Jinwoo-H Date: Tue, 8 Sep 2026 22:49:54 -0400 Subject: [PATCH 03/40] refactor(mobile): route session, file and account screens through operations The session hooks take HostSessionOperations, the file explorer takes HostFileExplorerOperations, and the accounts route takes HostAccountOperations. Terminal, tab, markdown, file, quick-command, browser and native-chat requests now live in their native-host-session-* adapters. Four session RPCs stay inline because no adapter method means the same thing: terminal close, note creation's two calls, and the buffered terminal submit that needs the raw response to classify a partial write. Worker-terminal takeover reporting is re-issued at the call sites the adapter does not report from, so the send-site ratchet still covers all of them. Claude-Session: https://claude.ai/code/session_01JNnE9qzUZMMnqpZWCqM3nb --- mobile/app/h/[hostId]/accounts.tsx | 72 ++++-------- .../src/accounts-route-reset-credit.test.ts | 13 +++ .../native-host-account-operations.ts | 2 + mobile/src/files/MobileFileExplorerPanel.tsx | 80 +++++-------- .../native-host-file-explorer-operations.ts | 2 + mobile/src/session/MobileSessionSheets.tsx | 4 +- mobile/src/session/QuickCommandsSheet.tsx | 11 +- .../src/session/mobile-file-tap-open.test.ts | 92 ++++++++------- mobile/src/session/mobile-file-tap-open.ts | 103 ++++++----------- .../mobile-native-chat-open-file.test.ts | 30 +++-- .../mobile-native-chat-operation-target.ts | 18 +++ .../mobile-session-route-parity.test.ts | 22 ++-- .../mobile-worker-takeover-send-sites.test.ts | 4 + .../use-mobile-file-tap-handlers.test.ts | 12 +- .../session/use-mobile-file-tap-handlers.ts | 21 ++-- .../use-mobile-native-chat-controller.ts | 53 +++------ ...use-mobile-native-chat-file-search.test.ts | 4 +- .../use-mobile-native-chat-file-search.ts | 97 ++++------------ ...use-mobile-native-chat-readability.test.ts | 7 +- .../use-mobile-native-chat-readability.ts | 45 +++----- .../use-mobile-native-chat-session-lane.ts | 8 +- .../use-mobile-native-chat-session.test.ts | 27 ++++- .../session/use-mobile-native-chat-session.ts | 72 ++++++------ .../use-mobile-native-chat-stop.test.ts | 8 +- .../session/use-mobile-native-chat-stop.ts | 87 +++++++------- ...bile-native-chat-terminal-response-lane.ts | 74 ++++++++++++ .../use-mobile-session-close-actions.ts | 23 ++-- ...e-mobile-session-content-create-actions.ts | 40 +++---- .../use-mobile-session-document-readers.ts | 75 ++---------- ...se-mobile-session-feedback-capabilities.ts | 3 + .../use-mobile-session-file-actions.ts | 4 +- .../use-mobile-session-markdown-actions.ts | 22 ++-- ...se-mobile-session-native-chat-dictation.ts | 8 +- .../use-mobile-session-screen-state.ts | 10 +- .../use-mobile-session-terminal-input.ts | 38 +++---- .../use-mobile-session-terminal-runtime.ts | 3 + ...se-mobile-session-terminal-send-actions.ts | 37 +++--- ...-mobile-session-terminal-stream-display.ts | 24 ++-- mobile/src/session/use-quick-commands.test.ts | 42 ++++++- mobile/src/session/use-quick-commands.ts | 107 +++++------------- .../terminal-input-connection-gate.test.ts | 14 ++- 41 files changed, 678 insertions(+), 740 deletions(-) create mode 100644 mobile/src/session/mobile-native-chat-operation-target.ts create mode 100644 mobile/src/session/use-mobile-native-chat-terminal-response-lane.ts diff --git a/mobile/app/h/[hostId]/accounts.tsx b/mobile/app/h/[hostId]/accounts.tsx index b107f34da975..cb14566df8be 100644 --- a/mobile/app/h/[hostId]/accounts.tsx +++ b/mobile/app/h/[hostId]/accounts.tsx @@ -1,4 +1,4 @@ -import { useEffect, useState, useCallback } from 'react' +import { useEffect, useMemo, useState, useCallback } from 'react' import { View, Text, @@ -20,7 +20,6 @@ import { ClaudeIcon, OpenAIIcon } from '../../../src/components/AgentIcons' import { type AccountsSnapshot, type ProviderKey, - decodeAccountsSnapshot, getActiveProviderRateLimits, getInactiveProviderUsage, getUsageBarState, @@ -34,6 +33,7 @@ import { } from '../../../src/components/codex-reset-credit' import { CodexResetCreditAction } from '../../../src/components/CodexResetCreditAction' import { useCodexResetCreditAction } from '../../../src/components/use-codex-reset-credit-action' +import { defaultHostAccountOperations } from '../../../src/accounts/default-host-account-operations' export default function AccountsScreen() { const router = useRouter() @@ -42,6 +42,10 @@ export default function AccountsScreen() { // Why: shared client per host. See docs/mobile-shared-client-per-host.md. const { client, state: connState } = useHostClient(hostId) + const operations = useMemo( + () => (client && hostId ? defaultHostAccountOperations(client, hostId) : null), + [client, hostId] + ) const [hostName, setHostName] = useState('') const [snapshot, setSnapshot] = useState(null) const [error, setError] = useState(null) @@ -66,6 +70,8 @@ export default function AccountsScreen() { scopeLabel: resetScopeLabel, confirmReset: confirmCodexReset } = useCodexResetCreditAction({ + // Why: still the client — the capability probe behind this hook retries a failed + // status.get, which a one-shot operations read cannot reproduce. client, connected: connState === 'connected', hostId, @@ -88,6 +94,8 @@ export default function AccountsScreen() { return } let stale = false + // Why: the local host catalog, not the adapter — `operations` is null in exactly the + // host-missing case this reports, so routing it there would show a blank screen instead. void loadHosts().then((hosts) => { if (stale) { return @@ -109,37 +117,19 @@ export default function AccountsScreen() { // when the user switches accounts. Falls back to a one-shot accounts.list // if the subscription stream errors. useEffect(() => { - if (!client || connState !== 'connected') { + if (!operations || connState !== 'connected') { return } - const unsubscribe = client.subscribe('accounts.subscribe', null, (payload) => { - if (!payload || typeof payload !== 'object') { - return - } - const evt = payload as { type?: string; snapshot?: unknown } - if (evt.type === 'ready' || evt.type === 'snapshot') { - try { - acceptSnapshot(decodeAccountsSnapshot(evt.snapshot)) - } catch { - rejectInvalidSnapshot() - } - } - }) - return unsubscribe - }, [acceptSnapshot, client, connState, rejectInvalidSnapshot]) + return operations.subscribe(acceptSnapshot, rejectInvalidSnapshot) + }, [acceptSnapshot, connState, operations, rejectInvalidSnapshot]) const refresh = useCallback(async () => { - if (!client) { + if (!operations) { return } setRefreshing(true) try { - const res = await client.sendRequest('accounts.list') - if (res.ok) { - acceptSnapshot(decodeAccountsSnapshot(res.result)) - } else { - setError(res.error.message) - } + acceptSnapshot(await operations.snapshot()) } catch (e) { if (e instanceof Error && e.message === 'Invalid accounts snapshot from host') { rejectInvalidSnapshot() @@ -149,11 +139,11 @@ export default function AccountsScreen() { } finally { setRefreshing(false) } - }, [acceptSnapshot, client, rejectInvalidSnapshot]) + }, [acceptSnapshot, operations, rejectInvalidSnapshot]) const selectAccount = useCallback( async (provider: ProviderKey, accountId: string | null) => { - if (!client) { + if (!operations) { return } const codexTarget = provider === 'codex' ? snapshot?.rateLimits.codexTarget : null @@ -161,33 +151,19 @@ export default function AccountsScreen() { return } setBusyAccountId(accountId ?? `${provider}:default`) - const method = - provider === 'claude' - ? 'accounts.selectClaude' - : codexTarget?.runtime === 'wsl' - ? 'accounts.selectCodexForTarget' - : 'accounts.selectCodex' try { - // Why: old hosts silently strip unknown target fields. Use the distinct - // targeted RPC for WSL so version skew fails before mutating host state. - const params = - codexTarget?.runtime === 'wsl' ? { accountId, target: codexTarget } : { accountId } - const res = await client.sendRequest(method, params) - if (!res.ok) { - Alert.alert('Could not switch account', res.error.message) - } else { - // Why: optimistic refresh — the streaming subscription will also - // emit, but a one-shot keeps the UI responsive even if the stream - // is temporarily disconnected. - await refresh() - } + await operations.select(provider, accountId, codexTarget) + // Why: optimistic refresh — the streaming subscription will also + // emit, but a one-shot keeps the UI responsive even if the stream + // is temporarily disconnected. + await refresh() } catch (e) { Alert.alert('Could not switch account', e instanceof Error ? e.message : String(e)) } finally { setBusyAccountId(null) } }, - [client, refresh, snapshot] + [operations, refresh, snapshot] ) const renderProviderSection = (provider: ProviderKey, title: string) => { @@ -343,7 +319,7 @@ export default function AccountsScreen() { {refreshing ? ( diff --git a/mobile/src/accounts-route-reset-credit.test.ts b/mobile/src/accounts-route-reset-credit.test.ts index 2de1e96881d4..09019809bcc1 100644 --- a/mobile/src/accounts-route-reset-credit.test.ts +++ b/mobile/src/accounts-route-reset-credit.test.ts @@ -54,6 +54,19 @@ vi.mock('expo-router', async () => { vi.mock('expo-crypto', () => ({ randomUUID: dependencies.randomUUID })) +// The account adapter reaches device operations for its idempotency nonce, which pulls the +// native expo modules into this module graph. +vi.mock('expo-clipboard', () => ({ setStringAsync: vi.fn() })) +vi.mock('expo-haptics', () => ({ + AndroidHaptics: {}, + ImpactFeedbackStyle: {}, + NotificationFeedbackType: {}, + impactAsync: vi.fn(), + notificationAsync: vi.fn(), + performAndroidHapticsAsync: vi.fn(), + selectionAsync: vi.fn() +})) + vi.mock('lucide-react-native', () => ({ Check: 'Check', ChevronLeft: 'ChevronLeft', diff --git a/mobile/src/accounts/native-host-account-operations.ts b/mobile/src/accounts/native-host-account-operations.ts index 76b41ee55ea2..5f5dd27a54a7 100644 --- a/mobile/src/accounts/native-host-account-operations.ts +++ b/mobile/src/accounts/native-host-account-operations.ts @@ -25,6 +25,8 @@ export function nativeHostAccountOperations( return decodeAccountsSnapshot((response as RpcSuccess).result) }, async select(provider, accountId, codexTarget) { + // Why: old hosts silently strip unknown target fields. Use the distinct + // targeted RPC for WSL so version skew fails before mutating host state. const method = selectionMethod(provider, codexTarget) const params = provider === 'codex' && codexTarget?.runtime === 'wsl' diff --git a/mobile/src/files/MobileFileExplorerPanel.tsx b/mobile/src/files/MobileFileExplorerPanel.tsx index 7e67bf81b5f9..503030b0eddd 100644 --- a/mobile/src/files/MobileFileExplorerPanel.tsx +++ b/mobile/src/files/MobileFileExplorerPanel.tsx @@ -16,10 +16,8 @@ import { flattenDirectoryCache, getDirectoryCacheState, type DirectoryCache, - type FileExplorerRow, - type MobileDirEntry + type FileExplorerRow } from './file-tree' -import type { RpcSuccess } from '../transport/types' import { colors } from '../theme/mobile-theme' import { beginDirectoryLoad, @@ -28,14 +26,11 @@ import { resetDirectoryLoadRevisions, type DirectoryLoadRevisions } from './directory-load-revisions' -import { - directoryCacheFromFileList, - isMobileMethodUnavailableError, - type LegacyFilesListResult -} from './file-list-fallback' +import { directoryCacheFromFileList } from './file-list-fallback' import { fileExplorerStyles as styles } from './mobile-file-explorer-styles' import { MobileFileExplorerRow } from './mobile-file-explorer-row' import { navigateToMobileFilePreview } from './mobile-file-preview-navigation' +import { defaultHostFileExplorerOperations } from './default-host-file-explorer-operations' export function MobileFileExplorerPanel(props: { hostId: string @@ -48,6 +43,16 @@ export function MobileFileExplorerPanel(props: { const router = useRouter() const { client, state: connState } = useHostClient(hostId) const forceReconnect = useForceReconnect() + const operations = useMemo( + () => (client ? defaultHostFileExplorerOperations(client, () => forceReconnect(hostId)) : null), + [client, forceReconnect, hostId] + ) + // Why: `operations` is null in exactly the disconnected state Retry exists for + // (no client), so the revive path cannot hang off it (#5049). + const reconnect = useCallback( + () => (operations ? operations.reconnect() : forceReconnect(hostId)), + [forceReconnect, hostId, operations] + ) const scopeRef = useRef('') const scope = `${hostId}:${worktreeId}` scopeRef.current = scope @@ -67,7 +72,7 @@ export function MobileFileExplorerPanel(props: { const loadToken = beginDirectoryLoad(directoryLoadRevisionsRef.current, scope, relativePath) const rootLoad = relativePath === '' - if (!client || connState !== 'connected') { + if (!operations || connState !== 'connected') { const message = connState === 'connected' ? 'Connecting to desktop...' : 'Waiting for desktop...' if (rootLoad) { @@ -107,56 +112,25 @@ export function MobileFileExplorerPanel(props: { })) try { - const response = await client.sendRequest('files.readDir', { - worktree: `id:${worktreeId}`, - relativePath - }) - if (!response.ok) { - // Why: desktops that predate the files.readDir mobile allowlist - // entry still serve the capped files.list; fall back so the Files - // tab keeps working until the desktop updates. - if ( - rootLoad && - isMobileMethodUnavailableError(response.error?.code, response.error?.message) - ) { - const legacy = await client.sendRequest('files.list', { - worktree: `id:${worktreeId}` - }) - if (legacy.ok) { - if ( - !isCurrentDirectoryLoad( - directoryLoadRevisionsRef.current, - scopeRef.current, - loadToken - ) - ) { - return - } - const legacyResult = (legacy as RpcSuccess).result as LegacyFilesListResult - setDirectoryCache(directoryCacheFromFileList(legacyResult.files)) - // Why: the capped list silently omits files past the cap — keep - // the legacy explorer's "Showing first 5000" note. - setLegacyListTruncated(legacyResult.truncated) - return - } - throw new Error( - legacy.error?.message || response.error?.message || 'Unable to load files' - ) - } - throw new Error(response.error?.message || 'Unable to load files') - } + const result = await operations.readDirectory(worktreeId, relativePath) if ( !isCurrentDirectoryLoad(directoryLoadRevisionsRef.current, scopeRef.current, loadToken) ) { return } - const entries = (response as RpcSuccess).result as MobileDirEntry[] + if (result.kind === 'legacy-list') { + setDirectoryCache(directoryCacheFromFileList(result.files)) + // Why: the capped list silently omits files past the cap — keep + // the legacy explorer's "Showing first 5000" note. + setLegacyListTruncated(result.truncated) + return + } if (rootLoad) { setLegacyListTruncated(false) } setDirectoryCache((prev) => ({ ...prev, - [relativePath]: { entries } + [relativePath]: { entries: result.entries } })) } catch (err) { if ( @@ -187,7 +161,7 @@ export function MobileFileExplorerPanel(props: { } } }, - [client, connState, worktreeId] + [connState, operations, worktreeId] ) useEffect(() => { @@ -249,12 +223,12 @@ export function MobileFileExplorerPanel(props: { (relativePath: string) => { if (connState !== 'connected' && hostId) { pendingDirectoryRetriesRef.current.add(relativePath) - void forceReconnect(hostId) + void reconnect() return } void loadDirectory(relativePath) }, - [connState, forceReconnect, hostId, loadDirectory] + [connState, hostId, loadDirectory, reconnect] ) const previewFile = useCallback( @@ -332,7 +306,7 @@ export function MobileFileExplorerPanel(props: { - connState !== 'connected' && hostId ? void forceReconnect(hostId) : void loadDirectory('') + connState !== 'connected' && hostId ? void reconnect() : void loadDirectory('') } > Retry diff --git a/mobile/src/files/native-host-file-explorer-operations.ts b/mobile/src/files/native-host-file-explorer-operations.ts index 50b74b37f74f..bd6113bf8ab9 100644 --- a/mobile/src/files/native-host-file-explorer-operations.ts +++ b/mobile/src/files/native-host-file-explorer-operations.ts @@ -23,6 +23,8 @@ export function nativeHostFileExplorerOperations( truncated: false } } + // Why: desktops that predate the files.readDir mobile allowlist entry still serve the + // capped files.list; fall back so the Files tab keeps working until the desktop updates. if ( relativePath === '' && isMobileMethodUnavailableError(response.error?.code, response.error?.message) diff --git a/mobile/src/session/MobileSessionSheets.tsx b/mobile/src/session/MobileSessionSheets.tsx index 0aac2bb9d42e..e24c7e5bd4e4 100644 --- a/mobile/src/session/MobileSessionSheets.tsx +++ b/mobile/src/session/MobileSessionSheets.tsx @@ -23,6 +23,7 @@ export function MobileSessionSheets({ controller }: { controller: MobileSessionC isFolderWorkspaceRoute, isFloatingWorkspaceRoute, client, + sessionOperations, worktreeName, sessionTabs, pendingDiffNotesDelivery, @@ -103,7 +104,8 @@ export function MobileSessionSheets({ controller }: { controller: MobileSessionC setShowQuickCommands(false)} - client={client} + operations={sessionOperations?.quickCommand ?? null} + workspaceId={worktreeId} repoId={ isFolderWorkspaceRoute || isFloatingWorkspaceRoute ? null diff --git a/mobile/src/session/QuickCommandsSheet.tsx b/mobile/src/session/QuickCommandsSheet.tsx index 3342f1226653..fac2b212f40a 100644 --- a/mobile/src/session/QuickCommandsSheet.tsx +++ b/mobile/src/session/QuickCommandsSheet.tsx @@ -3,7 +3,7 @@ import { Alert, View, Text, Pressable, StyleSheet } from 'react-native' import { ChevronLeft } from 'lucide-react-native' import { colors, spacing } from '../theme/mobile-theme' import { BottomDrawer } from '../components/BottomDrawer' -import type { RpcClient } from '../transport/rpc-client' +import type { HostSessionQuickCommandOperations } from './host-session-quick-command-operations' import type { TerminalQuickCommand } from '../../../src/shared/terminal-quick-command-types' import { getQuickCommandPreview, @@ -23,7 +23,8 @@ import { type Props = { visible: boolean onClose: () => void - client: RpcClient | null + operations: HostSessionQuickCommandOperations | null + workspaceId: string repoId: string | null repoName: string | null onLaunch: (command: TerminalQuickCommand) => boolean @@ -34,13 +35,15 @@ type SheetView = 'list' | 'editor' | 'agent' export function QuickCommandsSheet({ visible, onClose, - client, + operations, + workspaceId, repoId, repoName, onLaunch }: Props) { const { commands, loading, ready, error, persist } = useQuickCommands({ - client, + operations, + workspaceId, enabled: visible }) const [view, setView] = useState('list') diff --git a/mobile/src/session/mobile-file-tap-open.test.ts b/mobile/src/session/mobile-file-tap-open.test.ts index 732db327e082..e6771e8f8e0b 100644 --- a/mobile/src/session/mobile-file-tap-open.test.ts +++ b/mobile/src/session/mobile-file-tap-open.test.ts @@ -1,14 +1,28 @@ import { describe, expect, it, vi } from 'vitest' +import type { RpcClient } from '../transport/rpc-client' +import { defaultHostSessionOperations } from './default-host-session-operations' import { openMobileFileTap } from './mobile-file-tap-open' +/** The operations provider awaits its own RPC before the tap resumes, so drain + * more than one microtask before asserting. */ +async function settle(): Promise { + for (let tick = 0; tick < 6; tick += 1) { + await Promise.resolve() + } +} + function ok(result: unknown) { return { ok: true, result, _meta: { runtimeId: 'runtime-1' } } } function createClient(responses: unknown[]) { - return { + const client = { sendRequest: vi.fn(async () => responses.shift()) } + return { + ...client, + operations: defaultHostSessionOperations(client as unknown as RpcClient).terminalFile + } } function activeTerminalState(activated: boolean) { @@ -43,7 +57,7 @@ describe('openMobileFileTap', () => { const triggerOpenFeedback = vi.fn() openMobileFileTap({ - client, + operations: client.operations, hostId: 'host-1', worktreeId: 'wt-1', pathText: '/tmp/result.json', @@ -60,7 +74,7 @@ describe('openMobileFileTap', () => { switchSessionTab: vi.fn(), scheduleDelayedAction: vi.fn() }) - await Promise.resolve() + await settle() expect(client.sendRequest).toHaveBeenCalledWith( 'files.resolveTerminalPath', @@ -112,7 +126,7 @@ describe('openMobileFileTap', () => { const switchSessionTab = vi.fn() openMobileFileTap({ - client, + operations: client.operations, hostId: 'host-1', worktreeId: 'wt-1', pathText: 'src/index.ts', @@ -128,8 +142,8 @@ describe('openMobileFileTap', () => { switchSessionTab, scheduleDelayedAction }) - await Promise.resolve() - await Promise.resolve() + await settle() + await settle() await new Promise((resolve) => setTimeout(resolve, 0)) expect(client.sendRequest).toHaveBeenCalledWith( @@ -159,7 +173,7 @@ describe('openMobileFileTap', () => { const pushPreviewRoute = vi.fn() openMobileFileTap({ - client, + operations: client.operations, hostId: 'host-1', worktreeId: 'wt-1', pathText: '/repo-b/docs/readme.md', @@ -175,8 +189,8 @@ describe('openMobileFileTap', () => { switchSessionTab: vi.fn(), scheduleDelayedAction: vi.fn() }) - await Promise.resolve() - await Promise.resolve() + await settle() + await settle() expect(pushPreviewRoute).toHaveBeenCalledWith({ pathname: '/h/[hostId]/files/preview/[worktreeId]', @@ -210,7 +224,7 @@ describe('openMobileFileTap', () => { const triggerOpenFeedback = vi.fn() openMobileFileTap({ - client, + operations: client.operations, hostId: 'host-1', worktreeId: 'wt-1', worktreeName: 'Orca', @@ -227,7 +241,7 @@ describe('openMobileFileTap', () => { switchSessionTab: vi.fn(), scheduleDelayedAction: vi.fn() }) - await Promise.resolve() + await settle() expect(pushPreviewRoute).toHaveBeenCalledWith({ pathname: '/h/[hostId]/files/preview/[worktreeId]', @@ -264,7 +278,7 @@ describe('openMobileFileTap', () => { const openBrowser = vi.fn() openMobileFileTap({ - client, + operations: client.operations, hostId: 'host-1', worktreeId: 'wt-1', pathText: 'public/report #1?.html', @@ -280,7 +294,7 @@ describe('openMobileFileTap', () => { switchSessionTab: vi.fn(), scheduleDelayedAction: vi.fn() }) - await Promise.resolve() + await settle() expect(openBrowser).toHaveBeenCalledWith('file:///repo/public/report%20%231%3F.html') expect(client.sendRequest).not.toHaveBeenCalledWith('files.open', expect.anything()) @@ -305,7 +319,7 @@ describe('openMobileFileTap', () => { ]) openMobileFileTap({ - client, + operations: client.operations, hostId: 'host-1', worktreeId: 'wt-1', pathText: 'index.ts', @@ -323,7 +337,7 @@ describe('openMobileFileTap', () => { switchSessionTab: vi.fn(), scheduleDelayedAction: vi.fn() }) - await Promise.resolve() + await settle() expect(client.sendRequest).toHaveBeenCalledWith( 'files.resolveTerminalPath', @@ -358,7 +372,7 @@ describe('openMobileFileTap', () => { const openBrowser = vi.fn() openMobileFileTap({ - client, + operations: client.operations, hostId: 'host-1', worktreeId: 'wt-1', pathText: 'report.html', @@ -374,8 +388,8 @@ describe('openMobileFileTap', () => { switchSessionTab: vi.fn(), scheduleDelayedAction: vi.fn() }) - await Promise.resolve() - await Promise.resolve() + await settle() + await settle() expect(openBrowser).not.toHaveBeenCalled() expect(client.sendRequest).toHaveBeenCalledWith( @@ -399,7 +413,7 @@ describe('openMobileFileTap', () => { const pushPreviewRoute = vi.fn() openMobileFileTap({ - client, + operations: client.operations, hostId: 'host-1', worktreeId: 'wt-1', pathText: '/tmp/result.json', @@ -436,8 +450,8 @@ describe('openMobileFileTap', () => { } }) ) - await Promise.resolve() - await Promise.resolve() + await settle() + await settle() expect(pushPreviewRoute).not.toHaveBeenCalled() }) @@ -462,7 +476,7 @@ describe('openMobileFileTap', () => { const onOpenFailed = vi.fn() openMobileFileTap({ - client, + operations: client.operations, hostId: 'host-1', worktreeId: 'wt-1', pathText: 'src/index.ts', @@ -479,9 +493,9 @@ describe('openMobileFileTap', () => { scheduleDelayedAction: vi.fn(), onOpenFailed }) - await Promise.resolve() - await Promise.resolve() - await Promise.resolve() + await settle() + await settle() + await settle() expect(onOpenFailed).toHaveBeenCalledTimes(1) }) @@ -507,7 +521,7 @@ describe('openMobileFileTap', () => { const scheduleDelayedAction = vi.fn() openMobileFileTap({ - client, + operations: client.operations, hostId: 'host-1', worktreeId: 'wt-1', pathText: 'dist/app.zip', @@ -524,9 +538,9 @@ describe('openMobileFileTap', () => { scheduleDelayedAction, onOpenFailed }) - await Promise.resolve() - await Promise.resolve() - await Promise.resolve() + await settle() + await settle() + await settle() expect(onOpenFailed).toHaveBeenCalledTimes(1) expect(scheduleDelayedAction).not.toHaveBeenCalled() @@ -545,7 +559,7 @@ describe('openMobileFileTap', () => { const onOpenFailed = vi.fn() openMobileFileTap({ - client, + operations: client.operations, hostId: 'host-1', worktreeId: 'wt-1', pathText: 'gone/missing.ts', @@ -565,8 +579,8 @@ describe('openMobileFileTap', () => { scheduleDelayedAction: vi.fn(), onOpenFailed }) - await Promise.resolve() - await Promise.resolve() + await settle() + await settle() expect(onOpenFailed).not.toHaveBeenCalled() }) @@ -590,7 +604,7 @@ describe('openMobileFileTap', () => { const onOpenFailed = vi.fn() openMobileFileTap({ - client, + operations: client.operations, hostId: 'host-1', worktreeId: 'wt-1', pathText: 'src/index.ts', @@ -610,8 +624,8 @@ describe('openMobileFileTap', () => { scheduleDelayedAction: vi.fn(), onOpenFailed }) - await Promise.resolve() - await Promise.resolve() + await settle() + await settle() expect(onOpenFailed).not.toHaveBeenCalled() }) @@ -638,7 +652,7 @@ describe('openMobileFileTap', () => { const switchSessionTab = vi.fn() openMobileFileTap({ - client, + operations: client.operations, hostId: 'host-1', worktreeId: 'wt-1', pathText: 'src/index.ts', @@ -657,10 +671,10 @@ describe('openMobileFileTap', () => { switchSessionTab, scheduleDelayedAction: (callback) => callbacks.push(callback) }) - await Promise.resolve() - await Promise.resolve() + await settle() + await settle() callbacks.forEach((callback) => callback()) - await Promise.resolve() + await settle() expect(switchSessionTab).not.toHaveBeenCalled() }) diff --git a/mobile/src/session/mobile-file-tap-open.ts b/mobile/src/session/mobile-file-tap-open.ts index 9c25dd215ca6..91c1c1316424 100644 --- a/mobile/src/session/mobile-file-tap-open.ts +++ b/mobile/src/session/mobile-file-tap-open.ts @@ -1,13 +1,8 @@ -import type { - RuntimeFileOpenResult, - RuntimeNativeChatFileContext, - RuntimeTerminalPathResolution -} from '../../../src/shared/runtime-types' +import type { RuntimeNativeChatFileContext } from '../../../src/shared/runtime-types' import { filesystemPathToFileUri } from '../../../src/shared/file-uri-path' import { createMobileFilePreviewHref } from '../files/mobile-file-preview-route' import { classifyMobileArtifact } from './mobile-artifact-kind' -import type { RpcClient } from '../transport/rpc-client' -import type { RpcSuccess } from '../transport/types' +import type { HostSessionTerminalFileOperations } from './host-session-terminal-file-operations' import { shouldActivateOpenedMobileSessionTab } from './opened-mobile-session-tab' export type FileTapSessionTab = { @@ -16,7 +11,7 @@ export type FileTapSessionTab = { } export type OpenMobileFileTapOptions = { - client: Pick + operations: HostSessionTerminalFileOperations hostId: string worktreeId: string worktreeName?: string @@ -73,28 +68,25 @@ function reportOpenFailure( async function openMobileFileTapAsync( options: OpenMobileFileTapOptions ): Promise { - const worktree = `id:${options.worktreeId}` - const response = await options.client.sendRequest( - 'files.resolveTerminalPath', - { - worktree, - pathText: options.pathText, - // Why: opts into sibling-workspace resolutions; this caller honors resolved.worktree. - crossWorkspace: true, - ...(options.terminalHandle && options.terminalHandle.trim().length > 0 - ? { terminal: options.terminalHandle } - : {}), - ...(options.cwd && options.cwd.trim().length > 0 ? { cwd: options.cwd } : {}), - ...(options.nativeChatContext ? { nativeChatContext: options.nativeChatContext } : {}) - }, - { timeoutMs: 10_000 } - ) - if (!response.ok) { - reportOpenFailure(options) - return - } - const resolved = (response as RpcSuccess).result as RuntimeTerminalPathResolution - if (!resolved.exists || resolved.isDirectory) { + // Keep the raw values on the wire; only their emptiness decides whether they are sent. + const terminalHandle = options.terminalHandle?.trim() ? options.terminalHandle : null + const cwd = options.cwd?.trim() ? options.cwd : null + const activation = options.getActivationState(false) + // Structured agent-session chat has no backing terminal; its tab id anchors the resolve. + const sourceTabId = + terminalHandle ?? activation.sourceTerminalHandle ?? activation.sourceSessionTabId ?? '' + // Why: resolution opts into sibling-workspace hits; this caller honors resolved.workspaceId. + const resolved = await options.operations.resolveTerminalPath({ + workspaceId: options.worktreeId, + tabId: sourceTabId, + terminalHandle, + pathText: options.pathText, + cwd, + nativeChatContext: options.nativeChatContext ?? null, + line: options.line, + column: options.column + }) + if (!resolved) { reportOpenFailure(options) return } @@ -102,32 +94,29 @@ async function openMobileFileTapAsync( if (!shouldActivateOpenedMobileSessionTab(options.getActivationState(false))) { return } - const resolvedWorktreeId = resolved.worktree?.trim() || options.worktreeId - const resolvedWorktree = `id:${resolvedWorktreeId}` + const resolvedWorktreeId = resolved.workspaceId?.trim() || options.worktreeId const resolvedWorktreeName = resolvedWorktreeId === options.worktreeId ? options.worktreeName : undefined - if (resolved.openTarget?.kind === 'absolute-file') { + if (resolved.kind === 'native-artifact') { options.triggerOpenFeedback() options.pushPreviewRoute( createMobileFilePreviewHref({ hostId: options.hostId, worktreeId: resolvedWorktreeId, source: 'terminalArtifact', - absolutePath: resolved.openTarget.absolutePath, - grantId: resolved.openTarget.grantId, + absolutePath: resolved.absolutePath, + grantId: resolved.grantId, pathText: options.pathText, - ...(options.cwd && options.cwd.trim().length > 0 ? { cwd: options.cwd } : {}), - ...(options.terminalHandle && options.terminalHandle.trim().length > 0 - ? { terminal: options.terminalHandle } - : {}), + ...(cwd ? { cwd } : {}), + ...(terminalHandle ? { terminal: terminalHandle } : {}), ...(options.nativeChatContext ? { nativeChatTab: options.nativeChatContext.tabId, nativeChatSession: options.nativeChatContext.sessionId } : {}), - name: displayNameFromPath(resolved.openTarget.absolutePath), + name: displayNameFromPath(resolved.absolutePath), ...(options.line !== null ? { line: String(options.line) } : {}), ...(options.column !== null ? { column: String(options.column) } : {}), ...(resolvedWorktreeName ? { worktreeName: resolvedWorktreeName } : {}) @@ -135,15 +124,13 @@ async function openMobileFileTapAsync( ) return } - - const openedPath = - resolved.openTarget?.kind === 'worktree-file' - ? resolved.openTarget.relativePath - : resolved.relativePath - if (!openedPath) { + // The native host never resolves a non-worktree, non-absolute target. + if (resolved.kind !== 'worktree-file') { reportOpenFailure(options) return } + + const openedPath = resolved.relativePath options.triggerOpenFeedback() if ( resolvedWorktreeId !== options.worktreeId || @@ -164,28 +151,12 @@ async function openMobileFileTapAsync( ) return } - if ( - classifyMobileArtifact(openedPath) === 'html' && - resolved.openTarget?.kind === 'worktree-file' && - resolved.openTarget.provider === 'local' - ) { - options.openBrowser(filesystemPathToFileUri(resolved.openTarget.absolutePath)) - return - } - const openResponse = await options.client.sendRequest( - 'files.open', - { worktree: resolvedWorktree, relativePath: openedPath }, - { timeoutMs: 15_000 } - ) - if (!openResponse.ok) { - reportOpenFailure(options) - return - } - const openResult = (openResponse as RpcSuccess).result as RuntimeFileOpenResult - if (!openResult.opened) { - reportOpenFailure(options) + if (classifyMobileArtifact(openedPath) === 'html' && resolved.localAbsolutePath) { + options.openBrowser(filesystemPathToFileUri(resolved.localAbsolutePath)) return } + // A failed open throws; openMobileFileTap's catch reports it. + await options.operations.openWorktreeFile(resolvedWorktreeId, openedPath) scheduleOpenedWorktreeTabActivation(options, openedPath) } diff --git a/mobile/src/session/mobile-native-chat-open-file.test.ts b/mobile/src/session/mobile-native-chat-open-file.test.ts index bef222721ac9..7ed7f26991ec 100644 --- a/mobile/src/session/mobile-native-chat-open-file.test.ts +++ b/mobile/src/session/mobile-native-chat-open-file.test.ts @@ -1,6 +1,16 @@ import { describe, expect, it, vi } from 'vitest' +import type { RpcClient } from '../transport/rpc-client' +import { defaultHostSessionOperations } from './default-host-session-operations' import { openMobileNativeChatFileTap } from './mobile-native-chat-open-file' +/** The operations provider awaits its own RPC before the tap resumes, so drain + * more than one microtask before asserting. */ +async function settle(): Promise { + for (let tick = 0; tick < 6; tick += 1) { + await Promise.resolve() + } +} + function ok(result: unknown) { return { ok: true, result, _meta: { runtimeId: 'runtime-1' } } } @@ -18,7 +28,7 @@ function activationState(activated: boolean) { function baseOptions(client: { sendRequest: ReturnType }) { return { - client, + operations: defaultHostSessionOperations(client as unknown as RpcClient).terminalFile, hostId: 'host-1', worktreeId: 'wt-1', pushPreviewRoute: vi.fn(), @@ -56,7 +66,7 @@ describe('openMobileNativeChatFileTap', () => { const options = baseOptions({ sendRequest }) openMobileNativeChatFileTap({ ...options, pathText: 'src/app.ts' }) - await Promise.resolve() + await settle() expect(sendRequest).toHaveBeenCalledWith( 'files.resolveTerminalPath', @@ -89,7 +99,7 @@ describe('openMobileNativeChatFileTap', () => { pathText: '~/orca-plans/result.html', nativeChatContext: { tabId: 'tab-1', sessionId: 'session-1' } }) - await Promise.resolve() + await settle() expect(sendRequest).toHaveBeenCalledWith( 'files.resolveTerminalPath', @@ -118,7 +128,7 @@ describe('openMobileNativeChatFileTap', () => { const options = baseOptions({ sendRequest }) openMobileNativeChatFileTap({ ...options, pathText: 'src/app.ts:120:7' }) - await Promise.resolve() + await settle() expect(sendRequest).toHaveBeenCalledWith( 'files.resolveTerminalPath', @@ -151,8 +161,8 @@ describe('openMobileNativeChatFileTap', () => { const options = baseOptions({ sendRequest }) openMobileNativeChatFileTap({ ...options, pathText: 'gone/missing.ts' }) - await Promise.resolve() - await Promise.resolve() + await settle() + await settle() expect(options.onOpenFailed).toHaveBeenCalledTimes(1) expect(options.pushPreviewRoute).not.toHaveBeenCalled() @@ -166,8 +176,8 @@ describe('openMobileNativeChatFileTap', () => { const options = baseOptions({ sendRequest }) openMobileNativeChatFileTap({ ...options, pathText: 'src/app.ts' }) - await Promise.resolve() - await Promise.resolve() + await settle() + await settle() expect(options.onOpenFailed).toHaveBeenCalledTimes(1) }) @@ -186,8 +196,8 @@ describe('openMobileNativeChatFileTap', () => { } openMobileNativeChatFileTap({ ...options, pathText: 'src/app.ts' }) - await Promise.resolve() - await Promise.resolve() + await settle() + await settle() await new Promise((resolve) => setTimeout(resolve, 0)) expect(sendRequest).toHaveBeenCalledWith( diff --git a/mobile/src/session/mobile-native-chat-operation-target.ts b/mobile/src/session/mobile-native-chat-operation-target.ts new file mode 100644 index 000000000000..403ae8e03824 --- /dev/null +++ b/mobile/src/session/mobile-native-chat-operation-target.ts @@ -0,0 +1,18 @@ +import type { HostSessionNativeChatTarget } from './host-session-native-chat-operations' + +/** Addresses one native-chat operation. Each operation reads only the coordinates + * it needs — a workspace-wide file search carries no transcript, a stop carries no + * session — so callers name what their call actually addresses and the rest stays + * empty rather than being invented. */ +export function mobileNativeChatOperationTarget( + args: Partial & { workspaceId: string } +): HostSessionNativeChatTarget { + return { + workspaceId: args.workspaceId, + agent: args.agent ?? '', + sessionId: args.sessionId ?? '', + transcriptPath: args.transcriptPath ?? null, + terminalId: args.terminalId ?? null, + clientId: args.clientId ?? null + } +} diff --git a/mobile/src/session/mobile-session-route-parity.test.ts b/mobile/src/session/mobile-session-route-parity.test.ts index 3a6b04661dec..bccdf4082533 100644 --- a/mobile/src/session/mobile-session-route-parity.test.ts +++ b/mobile/src/session/mobile-session-route-parity.test.ts @@ -62,15 +62,15 @@ const HOST_COMPONENT_NAMES = new Set([ 'View' ]) -const HEAD_MAIN_HOOK_SHA256 = '10071240ef9edafc2b9c8bed73be83dceaf7828e3b29f17dab55da020a7697a6' -const HEAD_HOOK_BINDING_SHA256 = '1dadb8c3dc0573ea20659ce7251629669e618dd0effaeac3a4536b29c2e865a1' +const HEAD_MAIN_HOOK_SHA256 = 'ff61336b8c99fa1b03691869c55ea8874ffefd523551c30efaeb702b7a006db6' +const HEAD_HOOK_BINDING_SHA256 = '8c58d9d8176322073aba394bc3121934b32eea9e358724870ac8567d913bc7b3' const HEAD_CALLBACK_IDENTITY_SHA256 = - '2a9e4825df007f6ef53b81aa5004991d6318eee7507b44d625c07e630be432eb' -const HEAD_CALLBACK_BODY_SHA256 = 'af7f3c62954250d4be7ee432ecd10dc2689792aad8230fed2d1d68bbc892d776' + '8fdd1bf011123fc3cd502d47a2eb915934bd359d3510c5c19d8ab26eb0950152' +const HEAD_CALLBACK_BODY_SHA256 = 'e66e6436cdb9a66e870c06fdfc140106502fbeddd8db48b170263d863fee9ef8' const HEAD_EFFECT_SHA256 = 'd9ebfaabc1e79773cdada7ab370b20459ed972f1f8edce1652199f4d0391cd13' const HEAD_CONTENT_HOOK_SHA256 = '9c3b612fef3f370d66873aefdbe1d701f20cb64ded31fef5cc45fde6f8189581' const HEAD_NESTED_FUNCTION_SHA256 = - 'fde6679349ab2b8c30c7e627841ff99bd1dd24441ee95323d0aa70230422ae24' + '5042c3622cbf32166e5a2af5a534ff0305ee9446e8fd607a4baf7ec3e485b7ba' const HEAD_NATIVE_REGISTRATION_SHA256 = 'cab85e4e4a3f43289ba93ddea9ccce57aea83e0bf14fd1620a965aad0c1cb49e' const HEAD_NATIVE_REMOVAL_SHA256 = @@ -79,13 +79,13 @@ const HEAD_TIMER_CREATION_SHA256 = '1a31b625e2174c3db77272249843196d2b6b06ab1e654a96d8f7858e3082e66b' const HEAD_TIMER_CLEANUP_SHA256 = 'c73f1d1c2cc89642f3d727d6f3b6b81860a9d6f34234541a2065ec3d1a8cd116' const HEAD_RUNTIME_STRING_SHA256 = - '31951b0b83be01ebfa659c4b94df9ad7eaff6404df5338fbade89eb7473a3cb4' + 'd5cf66745d014a3848798f7fe388d2d3370e657451dd8353e19e972b07eec324' const HEAD_HOST_JSX_SHA256 = '390405926b1695fa3a33686f0bc192b432f5468d8576499d7cafbb4922defbb5' -const HEAD_LEAF_JSX_SHA256 = '21dba981875e173f692590bf910d60964660c5f4cbb79f3a377c7e54f6a1f016' +const HEAD_LEAF_JSX_SHA256 = 'd5f1ef0db57c63eb3e4ee7c98e8483bc21882a151ce0ca24e42c7d1234e1dace' const HEAD_STYLE_REFERENCE_SHA256 = '295a3501c2c6d7bea7c8bbf38b3f3534f01344cd7e1b91bb8e07c040821d596a' const HEAD_IDENTITY_FIELD_SHA256 = - '91146853930a34dd1f3d80e5c97fbacd7cf19fb93dd26fe8fc6f29169622f9d6' + 'c5c6eaa5c161e842e66077dc2e934bb5871c6267f38d2f3046f902c92ae55f7b' const HEAD_NAVIGATION_SHA256 = '9d96f5dad7de555d6553eac39c0fab00efad507470fd562cb9beaa32db16f512' const HEAD_CAPABILITY_SHA256 = 'ca219f7909a091717110b823d5b94a20770ad3ae51894e0fa765e8628309392d' @@ -472,7 +472,7 @@ describe('mobile session route extraction parity', () => { const contentBindings = CONTENT_COMPONENT_NAMES.flatMap( (name) => readHookFacts(name, definitions).bindings ) - expect(main.hooks).toHaveLength(266) + expect(main.hooks).toHaveLength(268) expect(hash(main.hooks)).toBe(HEAD_MAIN_HOOK_SHA256) expect(hash(main.bindings)).toBe(HEAD_HOOK_BINDING_SHA256) expect(main.callbacks).toHaveLength(77) @@ -507,7 +507,7 @@ describe('mobile session route extraction parity', () => { ) expect(hash(native.cleanups)).toBe(HEAD_TIMER_CLEANUP_SHA256) const compatibility = readCompatibilityFacts(definitions) - expect(compatibility.identityFields).toHaveLength(14) + expect(compatibility.identityFields).toHaveLength(11) expect(hash(compatibility.identityFields)).toBe(HEAD_IDENTITY_FIELD_SHA256) expect(compatibility.navigation).toHaveLength(6) expect(hash(compatibility.navigation)).toBe(HEAD_NAVIGATION_SHA256) @@ -517,7 +517,7 @@ describe('mobile session route extraction parity', () => { it('preserves runtime strings, styles, and the expanded JSX tree', () => { const strings = readRuntimeStrings() - expect(strings).toHaveLength(546) + expect(strings).toHaveLength(523) expect(hash(strings)).toBe(HEAD_RUNTIME_STRING_SHA256) const jsx = readJsxFacts(readDefinitions()) expect(jsx.host).toHaveLength(124) diff --git a/mobile/src/session/mobile-worker-takeover-send-sites.test.ts b/mobile/src/session/mobile-worker-takeover-send-sites.test.ts index 2700d8d24fe0..1bf2ef82c140 100644 --- a/mobile/src/session/mobile-worker-takeover-send-sites.test.ts +++ b/mobile/src/session/mobile-worker-takeover-send-sites.test.ts @@ -3,6 +3,7 @@ import { act, create, type ReactTestRenderer } from 'react-test-renderer' import { beforeEach, afterEach, expect, it, vi } from 'vitest' import type { RpcClient } from '../transport/rpc-client' import { resetWorkerTerminalTakeoverReportsForTest } from '../terminal/worker-terminal-takeover-report' +import { defaultHostSessionOperations } from './default-host-session-operations' import { useMobileSessionTerminalSendActions } from './use-mobile-session-terminal-send-actions' import { useMobileSessionTerminalInput } from './use-mobile-session-terminal-input' import { useMobileTerminalPaste } from './use-mobile-terminal-paste' @@ -45,9 +46,12 @@ function mountSendSites(client: ReturnType, handle = 'term const activeHandleRef = ref(handle) const activeSessionTabTypeRef = ref('terminal') const sendLiveTerminalInputRef = ref(async (_handle: string, _text: string) => false) + const sessionOperations = defaultHostSessionOperations(client as unknown as RpcClient) const scope = { client, clientRef: ref(client), + sessionOperations, + sessionOperationsRef: ref(sessionOperations), activeHandle: handle, activeHandleRef, activeSessionTabTypeRef, diff --git a/mobile/src/session/use-mobile-file-tap-handlers.test.ts b/mobile/src/session/use-mobile-file-tap-handlers.test.ts index 6d0adbbf8df4..236b93a5bd89 100644 --- a/mobile/src/session/use-mobile-file-tap-handlers.test.ts +++ b/mobile/src/session/use-mobile-file-tap-handlers.test.ts @@ -1,6 +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 { RpcClient } from '../transport/rpc-client' +import { defaultHostSessionOperations } from './default-host-session-operations' import { useMobileFileTapHandlers } from './use-mobile-file-tap-handlers' const push = vi.fn() @@ -30,7 +32,8 @@ describe('useMobileFileTapHandlers', () => { function createOptions(sendRequest: ReturnType) { return { - client: { sendRequest }, + operations: defaultHostSessionOperations({ sendRequest } as unknown as RpcClient) + .terminalFile, hostId: 'host-1', worktreeId: 'wt-1', worktreeName: 'Orca', @@ -77,7 +80,12 @@ describe('useMobileFileTapHandlers', () => { act(() => { renderer!.update( createElement(Harness, { - options: { ...firstOptions, client: { sendRequest: latestSendRequest } } + options: { + ...firstOptions, + operations: defaultHostSessionOperations({ + sendRequest: latestSendRequest + } as unknown as RpcClient).terminalFile + } }) ) }) diff --git a/mobile/src/session/use-mobile-file-tap-handlers.ts b/mobile/src/session/use-mobile-file-tap-handlers.ts index 5bfe71f839bf..d75dfe53e3ac 100644 --- a/mobile/src/session/use-mobile-file-tap-handlers.ts +++ b/mobile/src/session/use-mobile-file-tap-handlers.ts @@ -1,12 +1,12 @@ import { useCallback, useLayoutEffect, useRef, type MutableRefObject } from 'react' import { useRouter } from 'expo-router' import { triggerSelection } from '../platform/haptics' -import type { RpcClient } from '../transport/rpc-client' +import type { HostSessionTerminalFileOperations } from './host-session-terminal-file-operations' import { openMobileFileTap, type FileTapSessionTab } from './mobile-file-tap-open' import { openMobileNativeChatFileTap } from './mobile-native-chat-open-file' type MobileFileTapHandlerOptions = { - client: Pick | null + operations: HostSessionTerminalFileOperations | null hostId: string worktreeId: string worktreeName?: string @@ -43,7 +43,7 @@ export function useMobileFileTapHandlers( } { const { activeHandleRef, - client, + operations, fetchSessionTabs, getActiveSessionTabId, getActiveSessionTabType, @@ -67,7 +67,7 @@ export function useMobileFileTapHandlers( routerRef.current = router optionsRef.current = { activeHandleRef, - client, + operations, fetchSessionTabs, getActiveSessionTabId, getActiveSessionTabType, @@ -84,7 +84,7 @@ export function useMobileFileTapHandlers( } }, [ activeHandleRef, - client, + operations, fetchSessionTabs, getActiveSessionTabId, getActiveSessionTabType, @@ -104,12 +104,12 @@ export function useMobileFileTapHandlers( const handleFileTap = useCallback( (handle: string, pathText: string, line: number | null, column: number | null) => { const current = optionsRef.current - if (handle !== current.activeHandleRef.current || !current.client) { + if (handle !== current.activeHandleRef.current || !current.operations) { return } const activationSeq = ++activationSeqRef.current openMobileFileTap({ - client: current.client, + operations: current.operations, hostId: current.hostId, worktreeId: current.worktreeId, worktreeName: current.worktreeName, @@ -144,12 +144,15 @@ export function useMobileFileTapHandlers( const sourceTerminalHandle = current.activeHandleRef.current const nativeChatSessionId = current.nativeChatSessionId const nativeChatTabId = current.getActiveSessionTabId() - if (!current.client || (!sourceTerminalHandle && !(nativeChatSessionId && nativeChatTabId))) { + if ( + !current.operations || + (!sourceTerminalHandle && !(nativeChatSessionId && nativeChatTabId)) + ) { return } const activationSeq = ++activationSeqRef.current openMobileNativeChatFileTap({ - client: current.client, + operations: current.operations, hostId: current.hostId, worktreeId: current.worktreeId, worktreeName: current.worktreeName, diff --git a/mobile/src/session/use-mobile-native-chat-controller.ts b/mobile/src/session/use-mobile-native-chat-controller.ts index 729cec302c13..7e815da75e51 100644 --- a/mobile/src/session/use-mobile-native-chat-controller.ts +++ b/mobile/src/session/use-mobile-native-chat-controller.ts @@ -1,11 +1,9 @@ import { useLayoutEffect, useRef, type MutableRefObject } from 'react' import type { RpcClient } from '../transport/rpc-client' import type { ConnectionState } from '../transport/types' +import type { HostSessionNativeChatOperations } from './host-session-native-chat-operations' import type { MobileNativeChatTab } from './mobile-native-chat-eligibility' -import { useMobileNativeChatPermissionSend } from './mobile-native-chat-permission-send' -import { useMobileNativeChatAnswerSend } from './use-mobile-native-chat-answer-send' import { useMobileNativeChatAskDismiss } from './use-mobile-native-chat-ask-dismiss' -import { useMobileNativeChatCancelAsk } from './use-mobile-native-chat-cancel-ask' import { useMobileNativeChatDrafts } from './use-mobile-native-chat-drafts' import { useMobileNativeChatFileSearch } from './use-mobile-native-chat-file-search' import { useMobileNativeChatMessageSend } from './use-mobile-native-chat-message-send' @@ -14,7 +12,7 @@ import { useMobileNativeChatSessionOptionController } from './use-mobile-native- import { useMobileNativeChatSessionLane } from './use-mobile-native-chat-session-lane' import { useMobileStructuredNativeChatSendBridge } from './use-mobile-structured-native-chat-send-bridge' import { useMobileNativeChatPrompts } from './use-mobile-native-chat-prompts' -import { useMobileNativeChatStop } from './use-mobile-native-chat-stop' +import { useMobileNativeChatTerminalResponseLane } from './use-mobile-native-chat-terminal-response-lane' import { useNativeChatAcceptedAction } from './use-native-chat-action-outcomes' import { useThrottledLatestValue } from './use-throttled-latest-value' import type { MobileNativeChatController } from './mobile-native-chat-controller-contract' @@ -28,6 +26,7 @@ const NATIVE_CHAT_STREAM_THROTTLE_MS = 50 * route. The route remains responsible only for choosing and rendering the view. */ export function useMobileNativeChatController(args: { client: RpcClient | null + nativeChatOperations: HostSessionNativeChatOperations | null hostId: string worktreeId: string activeSessionTab: MobileNativeChatTab | null @@ -45,6 +44,7 @@ export function useMobileNativeChatController(args: { }): MobileNativeChatController { const { client, + nativeChatOperations, hostId, worktreeId, activeSessionTab, @@ -84,6 +84,8 @@ export function useMobileNativeChatController(args: { const { structuredSession: structuredNativeChat, session: nativeChatSession } = useMobileNativeChatSessionLane({ client, + nativeChatOperations, + workspaceId: worktreeId, structured: activeChatStructured, agent: activeChatAgent, resolvedAgent: activeChatResolution?.agent ?? null, @@ -172,47 +174,26 @@ export function useMobileNativeChatController(args: { ? client != null && activeChatSessionId != null && connState === 'connected' : nativeChatInputLeaseReady && connState === 'connected' - const { answerAsk: handleNativeChatAnswerAsk, cancelPending: cancelNativeChatAnswer } = - useMobileNativeChatAnswerSend({ - client, - enabled: inputSendable && !activeChatStructured, - handleRef: activeHandleRef, - deviceTokenRef, - agentRef: activeChatAgentRef, - sessionId: activeChatSessionId, - streamIdentity, - onSendError - }) - - const handleNativeChatCancelAsk = useMobileNativeChatCancelAsk({ - client, - enabled: inputSendable && !activeChatStructured, - handleRef: activeHandleRef, - deviceTokenRef, - cancelPending: cancelNativeChatAnswer, - onSendError - }) - - const legacyHandleNativeChatRespondPermission = useMobileNativeChatPermissionSend({ - client, - enabled: inputSendable && !activeChatStructured, - handleRef: activeHandleRef, - deviceTokenRef, - onSendError - }) - - const handleNativeChatStop = useMobileNativeChatStop({ + const { + answerAsk: handleNativeChatAnswerAsk, + cancelAsk: handleNativeChatCancelAsk, + respondPermission: legacyHandleNativeChatRespondPermission, + stop: handleNativeChatStop + } = useMobileNativeChatTerminalResponseLane({ client, + operations: nativeChatOperations, + workspaceId: worktreeId, enabled: inputSendable && !activeChatStructured, handleRef: activeHandleRef, deviceTokenRef, + agentRef: activeChatAgentRef, + sessionId: activeChatSessionId, streamIdentity, - cancelPending: cancelNativeChatAnswer, onSendError }) const { nativeChatFilePaths, loadNativeChatFiles } = useMobileNativeChatFileSearch({ - client, + operations: nativeChatOperations, worktreeId }) diff --git a/mobile/src/session/use-mobile-native-chat-file-search.test.ts b/mobile/src/session/use-mobile-native-chat-file-search.test.ts index 93db87c8b324..a9d180f74b19 100644 --- a/mobile/src/session/use-mobile-native-chat-file-search.test.ts +++ b/mobile/src/session/use-mobile-native-chat-file-search.test.ts @@ -2,6 +2,7 @@ import { createElement } from 'react' import { act, create, type ReactTestRenderer } from 'react-test-renderer' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import type { RpcClient } from '../transport/rpc-client' +import { defaultHostSessionOperations } from './default-host-session-operations' import { useMobileNativeChatFileSearch } from './use-mobile-native-chat-file-search' type SearchState = ReturnType @@ -20,8 +21,9 @@ describe('useMobileNativeChatFileSearch', () => { let state: SearchState | null = null async function mount(client: RpcClient): Promise { + const operations = defaultHostSessionOperations(client).nativeChat function Harness(): null { - state = useMobileNativeChatFileSearch({ client, worktreeId: 'wt-1' }) + state = useMobileNativeChatFileSearch({ operations, worktreeId: 'wt-1' }) return null } await act(async () => { diff --git a/mobile/src/session/use-mobile-native-chat-file-search.ts b/mobile/src/session/use-mobile-native-chat-file-search.ts index 53df98e3ee0c..4b9f321e8100 100644 --- a/mobile/src/session/use-mobile-native-chat-file-search.ts +++ b/mobile/src/session/use-mobile-native-chat-file-search.ts @@ -1,41 +1,31 @@ -import { useCallback, useEffect, useRef, useState } from 'react' -import type { RpcClient } from '../transport/rpc-client' -import { rankSuggestions } from './mobile-native-chat-autocomplete' +import { useCallback, useEffect, useMemo, useRef, useState } from 'react' +import type { HostSessionNativeChatOperations } from './host-session-native-chat-operations' +import { mobileNativeChatOperationTarget } from './mobile-native-chat-operation-target' const FILE_SEARCH_DEBOUNCE_MS = 120 const FILE_SEARCH_RESULT_LIMIT = 16 const FILE_SEARCH_QUERY_CACHE_LIMIT = 20 -function extractPaths(result: unknown): string[] { - const files = (result as { files?: Array<{ relativePath?: string }> }).files ?? [] - return files - .map((file) => file.relativePath ?? '') - .filter((path): path is string => path.length > 0) -} - -/** Debounces current-host path searches, bounds the mobile result/cache, and - * falls back to the legacy one-time full list when paired to an older host. */ +/** Debounces current-host path searches and bounds the mobile result/cache. The + * legacy full-list fallback for older hosts lives in the operations provider. */ export function useMobileNativeChatFileSearch(args: { - client: RpcClient | null + operations: HostSessionNativeChatOperations | null worktreeId: string }): { nativeChatFilePaths: string[]; loadNativeChatFiles: (query: string) => void } { - const { client, worktreeId } = args + const { operations, worktreeId } = args + // Path search is scoped to the workspace alone; no transcript coordinates apply. + const target = useMemo( + () => mobileNativeChatOperationTarget({ workspaceId: worktreeId }), + [worktreeId] + ) const [nativeChatFilePaths, setNativeChatFilePaths] = useState([]) const timerRef = useRef | null>(null) const sequenceRef = useRef(0) - const generationRef = useRef(0) const queryCacheRef = useRef(new Map()) - const legacyPathsRef = useRef(null) - const legacyLoadRef = useRef | null>(null) - const searchSupportedRef = useRef(null) useEffect(() => { sequenceRef.current++ - generationRef.current++ queryCacheRef.current.clear() - legacyPathsRef.current = null - legacyLoadRef.current = null - searchSupportedRef.current = null setNativeChatFilePaths([]) return () => { if (timerRef.current) { @@ -43,11 +33,11 @@ export function useMobileNativeChatFileSearch(args: { timerRef.current = null } } - }, [client, worktreeId]) + }, [operations, worktreeId]) const loadNativeChatFiles = useCallback( (query: string) => { - if (!client) { + if (!operations) { return } const normalizedQuery = query.trim().toLowerCase().slice(0, 256) @@ -67,7 +57,6 @@ export function useMobileNativeChatFileSearch(args: { clearTimeout(timerRef.current) } const sequence = ++sequenceRef.current - const generation = generationRef.current setNativeChatFilePaths([]) timerRef.current = setTimeout(() => { timerRef.current = null @@ -85,61 +74,13 @@ export function useMobileNativeChatFileSearch(args: { } setNativeChatFilePaths(paths) } - const loadLegacyPaths = async (): Promise => { - if (!legacyPathsRef.current) { - if (!legacyLoadRef.current) { - const request = client - .sendRequest('files.list', { worktree: `id:${worktreeId}` }) - .then((response) => { - if (!response.ok || generationRef.current !== generation) { - return null - } - const paths = extractPaths(response.result) - legacyPathsRef.current = paths - return paths - }) - .finally(() => { - if (legacyLoadRef.current === request && !legacyPathsRef.current) { - legacyLoadRef.current = null - } - }) - // Why: older hosts expose only the full inventory RPC; queries that - // overlap its slow local/SSH read must share one request. - legacyLoadRef.current = request - } - const paths = await legacyLoadRef.current - if (!paths) { - return - } - } - const legacyPaths = legacyPathsRef.current - if (legacyPaths) { - applyPaths(rankSuggestions(legacyPaths, normalizedQuery, FILE_SEARCH_RESULT_LIMIT)) - } - } - void (async () => { - if (searchSupportedRef.current === false) { - await loadLegacyPaths() - return - } - const response = await client.sendRequest('files.searchPaths', { - worktree: `id:${worktreeId}`, - query: normalizedQuery, - limit: FILE_SEARCH_RESULT_LIMIT - }) - if (response.ok) { - searchSupportedRef.current = true - applyPaths(extractPaths(response.result)) - return - } - if (response.error.code === 'method_not_found') { - searchSupportedRef.current = false - await loadLegacyPaths() - } - })().catch(() => {}) + void operations + .searchFiles(target, normalizedQuery) + .then((paths) => applyPaths(paths.slice(0, FILE_SEARCH_RESULT_LIMIT))) + .catch(() => {}) }, FILE_SEARCH_DEBOUNCE_MS) }, - [client, worktreeId] + [operations, target] ) return { nativeChatFilePaths, loadNativeChatFiles } diff --git a/mobile/src/session/use-mobile-native-chat-readability.test.ts b/mobile/src/session/use-mobile-native-chat-readability.test.ts index b7e2c5daab32..2b20ecd0413c 100644 --- a/mobile/src/session/use-mobile-native-chat-readability.test.ts +++ b/mobile/src/session/use-mobile-native-chat-readability.test.ts @@ -2,6 +2,7 @@ import { createElement } from 'react' import { act, create, type ReactTestRenderer } from 'react-test-renderer' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import type { RpcClient } from '../transport/rpc-client' +import { defaultHostSessionOperations } from './default-host-session-operations' import { FLOATING_WORKSPACE_WORKTREE_ID } from './floating-workspace' import { useMobileNativeChatReadability } from './use-mobile-native-chat-readability' @@ -29,8 +30,9 @@ describe('useMobileNativeChatReadability', () => { const client = { sendRequest } as unknown as RpcClient + const operations = defaultHostSessionOperations(client).nativeChat function Harness(): null { - readable = useMobileNativeChatReadability(client, worktreeId) + readable = useMobileNativeChatReadability(operations, worktreeId) return null } await act(async () => { @@ -73,8 +75,9 @@ describe('useMobileNativeChatReadability', () => { }) .mockImplementationOnce(() => new Promise((resolve) => (resolveNext = resolve))) } as unknown as RpcClient + const operations = defaultHostSessionOperations(client).nativeChat function Harness({ worktreeId }: { worktreeId: string }): null { - readable = useMobileNativeChatReadability(client, worktreeId) + readable = useMobileNativeChatReadability(operations, worktreeId) return null } await act(async () => { diff --git a/mobile/src/session/use-mobile-native-chat-readability.ts b/mobile/src/session/use-mobile-native-chat-readability.ts index e3729022d38c..91a0e003518b 100644 --- a/mobile/src/session/use-mobile-native-chat-readability.ts +++ b/mobile/src/session/use-mobile-native-chat-readability.ts @@ -1,19 +1,20 @@ import { useEffect, useState } from 'react' -import type { RpcClient } from '../transport/rpc-client' import { isFloatingWorkspaceWorktreeId } from './floating-workspace' -import { isMobileNativeChatTranscriptReadable } from './mobile-native-chat-eligibility' -import { getRepoIdFromMobileWorktreeId } from './mobile-session-route-helpers' +import type { HostSessionNativeChatOperations } from './host-session-native-chat-operations' -type RepoSummary = { id: string; connectionId?: string | null } -type ReadabilityState = { client: RpcClient | null; worktreeId: string; readable: boolean } +type ReadabilityState = { + operations: HostSessionNativeChatOperations | null + worktreeId: string + readable: boolean +} export function useMobileNativeChatReadability( - client: RpcClient | null, + operations: HostSessionNativeChatOperations | null, worktreeId: string ): boolean { const isFloatingWorkspace = isFloatingWorkspaceWorktreeId(worktreeId) const [state, setState] = useState({ - client: null, + operations: null, worktreeId: '', readable: false }) @@ -23,40 +24,30 @@ export function useMobileNativeChatReadability( return } let active = true - if (!client) { - setState({ client, worktreeId, readable: false }) + if (!operations) { + setState({ operations, worktreeId, readable: false }) return } - void client - .sendRequest('repo.list') - .then((response) => { - if (!active) { - return + void operations + .readability(worktreeId) + .then((readable) => { + if (active) { + setState({ operations, worktreeId, readable }) } - const repos = response.ok - ? ((response.result as { repos?: RepoSummary[] }).repos ?? []) - : [] - const repoId = getRepoIdFromMobileWorktreeId(worktreeId) - const repo = repos.find((candidate) => candidate.id === repoId) - setState({ - client, - worktreeId, - readable: repo ? isMobileNativeChatTranscriptReadable(repo.connectionId ?? null) : false - }) }) .catch(() => { if (active) { - setState({ client, worktreeId, readable: false }) + setState({ operations, worktreeId, readable: false }) } }) return () => { active = false } - }, [client, isFloatingWorkspace, worktreeId]) + }, [operations, isFloatingWorkspace, worktreeId]) if (isFloatingWorkspace) { return true } // Why: route reuse renders before its new effect resolves; never expose the // previous repo's readability under a different client/worktree key. - return state.client === client && state.worktreeId === worktreeId ? state.readable : false + return state.operations === operations && state.worktreeId === worktreeId ? state.readable : false } diff --git a/mobile/src/session/use-mobile-native-chat-session-lane.ts b/mobile/src/session/use-mobile-native-chat-session-lane.ts index fc465de902b0..57c6a262cf84 100644 --- a/mobile/src/session/use-mobile-native-chat-session-lane.ts +++ b/mobile/src/session/use-mobile-native-chat-session-lane.ts @@ -1,5 +1,6 @@ import type { RpcClient } from '../transport/rpc-client' import type { ConnectionState } from '../transport/types' +import type { HostSessionNativeChatOperations } from './host-session-native-chat-operations' import { useMobileNativeChatSession } from './use-mobile-native-chat-session' import { useMobileStructuredAgentSession } from './use-mobile-structured-agent-session' @@ -8,6 +9,8 @@ import { useMobileStructuredAgentSession } from './use-mobile-structured-agent-s * its identity inputs rather than unmounted, so a lane flip keeps its cache. */ export function useMobileNativeChatSessionLane({ client, + nativeChatOperations, + workspaceId, structured, agent, resolvedAgent, @@ -19,6 +22,8 @@ export function useMobileNativeChatSessionLane({ onSendError }: { client: RpcClient | null + nativeChatOperations: HostSessionNativeChatOperations | null + workspaceId: string structured: boolean /** Agent id for the structured provider session. */ agent: string | null @@ -35,7 +40,8 @@ export function useMobileNativeChatSessionLane({ session: ReturnType } { const bridgeSession = useMobileNativeChatSession({ - client, + operations: nativeChatOperations, + workspaceId, sourceIdentity, agent: structured ? null : resolvedAgent, sessionId: structured ? null : sessionId, diff --git a/mobile/src/session/use-mobile-native-chat-session.test.ts b/mobile/src/session/use-mobile-native-chat-session.test.ts index ed2f66c42bff..165f6b948c4e 100644 --- a/mobile/src/session/use-mobile-native-chat-session.test.ts +++ b/mobile/src/session/use-mobile-native-chat-session.test.ts @@ -3,11 +3,32 @@ import { act, create, type ReactTestRenderer } from 'react-test-renderer' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import type { NativeChatMessage } from '../../../src/shared/native-chat-types' import type { RpcClient } from '../transport/rpc-client' +import { defaultHostSessionOperations } from './default-host-session-operations' import { useMobileNativeChatSession, type MobileNativeChatSession } from './use-mobile-native-chat-session' +/** The hook now takes the operations provider; tests still drive a fake client so + * they keep asserting the wire params the native provider actually sends. One + * provider per client, exactly as the session model memoizes it. */ +const chatOperationsByClient = new WeakMap< + RpcClient, + ReturnType['nativeChat'] +>() +function chatOperations(client: RpcClient | null) { + if (!client) { + return null + } + const cached = chatOperationsByClient.get(client) + if (cached) { + return cached + } + const operations = defaultHostSessionOperations(client).nativeChat + chatOperationsByClient.set(client, operations) + return operations +} + function message(id: string): NativeChatMessage { return { id, @@ -34,7 +55,8 @@ describe('useMobileNativeChatSession', () => { function Harness({ client }: { client: RpcClient | null }): null { state = useMobileNativeChatSession({ - client, + operations: chatOperations(client), + workspaceId: 'workspace-a', sourceIdentity: 'host-a\0workspace-a', agent: 'claude', sessionId: 'session', @@ -456,7 +478,8 @@ describe('useMobileNativeChatSession transcriptLoading', () => { sourceIdentity?: string }): null { const session = useMobileNativeChatSession({ - client, + operations: chatOperations(client), + workspaceId: 'workspace-a', sourceIdentity, agent, sessionId, diff --git a/mobile/src/session/use-mobile-native-chat-session.ts b/mobile/src/session/use-mobile-native-chat-session.ts index e509b202c2a7..86873816db7a 100644 --- a/mobile/src/session/use-mobile-native-chat-session.ts +++ b/mobile/src/session/use-mobile-native-chat-session.ts @@ -5,8 +5,8 @@ import { } from '../../../src/shared/native-chat-transcript-retention' import { createNativeChatMerger, replaceList } from '../../../src/shared/native-chat-merge' import type { NativeChatMessage } from '../../../src/shared/native-chat-types' -import { buildNativeChatSubscriptionId } from '../../../src/shared/native-chat-stream-unsubscribe' -import type { RpcClient } from '../transport/rpc-client' +import type { HostSessionNativeChatOperations } from './host-session-native-chat-operations' +import { mobileNativeChatOperationTarget } from './mobile-native-chat-operation-target' import { applyMobileNativeChatStreamFrame, type MobileNativeChatStreamFrame @@ -54,14 +54,15 @@ type ReadSessionResult = * and pages in older history on demand. Read results replace the list (they are * an ordered tail); live appends merge by id so order stays stable. */ export function useMobileNativeChatSession(args: { - client: RpcClient | null - /** Stable host/workspace source; unlike `client`, it survives manual reconnect. */ + operations: HostSessionNativeChatOperations | null + workspaceId: string + /** Stable host/workspace source; unlike the provider, it survives manual reconnect. */ sourceIdentity: string agent: string | null sessionId: string | null transcriptPath: string | null }): MobileNativeChatSession { - const { client, sourceIdentity, agent, sessionId, transcriptPath } = args + const { operations, workspaceId, sourceIdentity, agent, sessionId, transcriptPath } = args const [messages, setMessages] = useState([]) const identity = encodeNativeChatTranscriptIdentity([ sourceIdentity, @@ -72,13 +73,13 @@ export function useMobileNativeChatSession(args: { // Pre-read status is a pure function of the props, so derive it rather than // letting the effect write it a commit later. const initialStatus: MobileNativeChatStatus = - !client || !agent ? 'idle' : !sessionId ? 'waiting-session' : 'loading' + !operations || !agent ? 'idle' : !sessionId ? 'waiting-session' : 'loading' // Only the settled outcome is genuinely async, and it is tagged with the // identity it describes so a just-switched tab is never judged by the // previous tab's transcript — the effect that clears `messages` is passive // and lands a commit late. const [read, setRead] = useState<{ - client: RpcClient + operations: HostSessionNativeChatOperations identity: string status: MobileNativeChatStatus } | null>(null) @@ -87,7 +88,7 @@ export function useMobileNativeChatSession(args: { // Without this a toggle out of chat view and back (agent null, then the same // identity again) would resurface a settled 'ready' over an emptied list. let current = read - if (current !== null && (current.identity !== identity || current.client !== client)) { + if (current !== null && (current.identity !== identity || current.operations !== operations)) { current = null setRead(null) } @@ -140,23 +141,24 @@ export function useMobileNativeChatSession(args: { setError(undefined) setHasMore(false) beforeOffsetRef.current = null - if (!client || !agent) { + if (!operations || !agent) { return } if (!sessionId) { return } - const unsubscribe = client.subscribe( - 'nativeChat.subscribe', - { - agent, - sessionId, - limit: limitRef.current, - subscriptionId: buildNativeChatSubscriptionId(agent, sessionId), - capabilities: { transcriptPending: 1 }, - ...(transcriptPath ? { transcriptPath } : {}) - }, + // Terminal-scoped reads are the send lane's business; the transcript reader + // addresses the session alone, exactly as it did over the raw subscription. + const target = mobileNativeChatOperationTarget({ + workspaceId, + agent, + sessionId, + transcriptPath + }) + const unsubscribe = operations.subscribe( + target, + limitRef.current, (raw) => { if (cancelled) { return @@ -172,7 +174,7 @@ export function useMobileNativeChatSession(args: { return } if (applied.kind === 'error') { - setRead({ client, identity, status: 'error' }) + setRead({ operations, identity, status: 'error' }) setError(applied.error) return } @@ -210,7 +212,13 @@ export function useMobileNativeChatSession(args: { setLoadingEarlier(false) beforeOffsetRef.current = null } - setRead({ client, identity, status: applied.pending ? 'awaiting-transcript' : 'ready' }) + setRead({ operations, identity, status: applied.pending ? 'awaiting-transcript' : 'ready' }) + }, + () => { + if (!cancelled) { + setRead({ operations, identity, status: 'error' }) + setError('Transcript stream failed') + } } ) @@ -218,10 +226,10 @@ export function useMobileNativeChatSession(args: { cancelled = true unsubscribe() } - }, [client, agent, sessionId, transcriptPath, identity, setList]) + }, [operations, workspaceId, agent, sessionId, transcriptPath, identity, setList]) const loadEarlier = useCallback(() => { - if (!client || !agent || !sessionId || loadingEarlierRef.current || !hasMore) { + if (!operations || !agent || !sessionId || loadingEarlierRef.current || !hasMore) { return } // Capture the session this page belongs to; a swap underneath us must not @@ -239,17 +247,11 @@ export function useMobileNativeChatSession(args: { setLoadingEarlier(true) void (async () => { try { - const response = await client.sendRequest('nativeChat.readSession', { - agent, - sessionId, - limit: beforeOffset === null ? nextLimit : pageLimit, - ...(beforeOffset === null ? {} : { beforeOffset }), - ...(transcriptPath ? { transcriptPath } : {}) - }) - if (!response.ok) { - return - } - const result = response.result as ReadSessionResult + const result = (await operations.read( + mobileNativeChatOperationTarget({ workspaceId, agent, sessionId, transcriptPath }), + beforeOffset === null ? nextLimit : pageLimit, + beforeOffset === null ? undefined : beforeOffset + )) as ReadSessionResult if ('error' in result) { return } @@ -283,7 +285,7 @@ export function useMobileNativeChatSession(args: { } } })() - }, [client, agent, sessionId, transcriptPath, hasMore, setList]) + }, [operations, workspaceId, agent, sessionId, transcriptPath, hasMore, setList]) // Held for any unsettled read, not just an in-flight one: a stream error or a // dropped client would otherwise trade the conversation for an error card. diff --git a/mobile/src/session/use-mobile-native-chat-stop.test.ts b/mobile/src/session/use-mobile-native-chat-stop.test.ts index a1ee9ab4dd98..6b7ce22b5bf1 100644 --- a/mobile/src/session/use-mobile-native-chat-stop.test.ts +++ b/mobile/src/session/use-mobile-native-chat-stop.test.ts @@ -3,6 +3,7 @@ import { act, create, type ReactTestRenderer } from 'react-test-renderer' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import type { RpcClient } from '../transport/rpc-client' import { markRpcDeliveryUnknown } from '../transport/rpc-delivery-ambiguity' +import { defaultHostSessionOperations } from './default-host-session-operations' import { MOBILE_NATIVE_CHAT_SEND_TIMEOUT_MS } from './mobile-native-chat-send' import { useMobileNativeChatStop } from './use-mobile-native-chat-stop' @@ -17,6 +18,10 @@ describe('useMobileNativeChatStop', () => { let stop: (() => void) | null = null const sendRequest = vi.fn() const onSendError = vi.fn() + // One provider for the whole suite, exactly as the session model memoizes it per client. + const operations = defaultHostSessionOperations({ + sendRequest + } as unknown as RpcClient).nativeChat beforeEach(() => { vi.useFakeTimers() @@ -43,7 +48,8 @@ describe('useMobileNativeChatStop', () => { streamIdentity: string }): null { stop = useMobileNativeChatStop({ - client: { sendRequest } as unknown as RpcClient, + operations, + workspaceId: 'workspace-a', enabled, handleRef: { current: 'terminal-1' }, deviceTokenRef: { current: 'mobile-1' }, diff --git a/mobile/src/session/use-mobile-native-chat-stop.ts b/mobile/src/session/use-mobile-native-chat-stop.ts index 69d2d8e73e85..2b66a860d947 100644 --- a/mobile/src/session/use-mobile-native-chat-stop.ts +++ b/mobile/src/session/use-mobile-native-chat-stop.ts @@ -1,13 +1,11 @@ import { useCallback, useEffect, useRef, type MutableRefObject } from 'react' -import type { RpcClient } from '../transport/rpc-client' -import { isRpcDeliveryUnknown } from '../transport/rpc-delivery-ambiguity' -import { isLogicalClientCutoverError } from '../transport/stable-logical-rpc-client' -import { isTerminalSendRpcAccepted } from '../terminal/terminal-send-rpc-response' -import { reportWorkerTerminalUserInput } from '../terminal/worker-terminal-takeover-report' +import type { HostSessionNativeChatOperations } from './host-session-native-chat-operations' +import { mobileNativeChatOperationTarget } from './mobile-native-chat-operation-target' import { openMobileNativeChatSendBudget } from './mobile-native-chat-send' export function useMobileNativeChatStop(args: { - client: RpcClient | null + operations: HostSessionNativeChatOperations | null + workspaceId: string enabled: boolean handleRef: MutableRefObject deviceTokenRef: MutableRefObject @@ -15,16 +13,24 @@ export function useMobileNativeChatStop(args: { cancelPending: () => void onSendError: (message: string) => void }): () => void { - const { client, enabled, handleRef, deviceTokenRef, streamIdentity, cancelPending, onSendError } = - args + const { + operations, + workspaceId, + enabled, + handleRef, + deviceTokenRef, + streamIdentity, + cancelPending, + onSendError + } = args const timerRef = useRef | null>(null) const generationRef = useRef(0) /** Settles the paced second Escape when it is cancelled rather than sent, so a * first-Escape failure still reports instead of waiting on a write that will * never happen. */ const dropSecondEscapeRef = useRef<(() => void) | null>(null) - const activeRouteRef = useRef({ client, enabled, streamIdentity }) - activeRouteRef.current = { client, enabled, streamIdentity } + const activeRouteRef = useRef({ operations, enabled, streamIdentity }) + activeRouteRef.current = { operations, enabled, streamIdentity } const cancelSecondEscape = useCallback(() => { if (timerRef.current) { clearTimeout(timerRef.current) @@ -39,11 +45,11 @@ export function useMobileNativeChatStop(args: { generationRef.current += 1 cancelSecondEscape() }, - [cancelSecondEscape, client, enabled, streamIdentity] + [cancelSecondEscape, operations, enabled, streamIdentity] ) return useCallback(() => { const handle = handleRef.current - if (!client || !handle || !enabled) { + if (!operations || !handle || !enabled) { onSendError('Stop not sent (terminal not ready)') return } @@ -80,52 +86,38 @@ export function useMobileNativeChatStop(args: { const activeRoute = activeRouteRef.current if ( !activeRoute.enabled || - activeRoute.client !== client || + activeRoute.operations !== operations || activeRoute.streamIdentity !== stopStreamIdentity || handleRef.current !== handle ) { return } pending += 1 - const timeoutMs = deadline - Date.now() - if (timeoutMs <= 0) { - sawRejected = true - pending -= 1 - reportIfSettled() - return - } - void client - .sendRequest( - 'terminal.send', - { - terminal: handle, - text: String.fromCharCode(27), - ...(deviceTokenRef.current - ? { client: { id: deviceTokenRef.current, type: 'mobile' as const } } - : {}) - }, - // Why: without this the call parks indefinitely on reconnect, so "Stop not - // sent" never appears and a stale Escape can land minutes later — into a - // composer that by then holds fresh text. - { timeoutMs, budgetSpansConnect: true } + // The shared budget bounds the write so a stale Escape cannot land minutes + // later into a composer that by then holds fresh text. + void operations + .stop( + mobileNativeChatOperationTarget({ + workspaceId, + terminalId: handle, + clientId: deviceTokenRef.current + }), + deadline ) - .then((response) => { - if (isTerminalSendRpcAccepted(response)) { + .then((outcome) => { + if (outcome === 'accepted') { sawAccepted = true - // A deliberate Stop is human input; it takes the worker over like any other key. - reportWorkerTerminalUserInput(client, handle) + } else if (outcome === 'unknown') { + // Delivery-ambiguous: the Escape may still have stopped the agent. + sawUnknown = true } else { sawRejected = true } }) // Why: disconnect can race either fire-and-forget Escape; record one verdict - // instead of leaking an unhandled RPC rejection. - .catch((error: unknown) => { - if (isRpcDeliveryUnknown(error) || isLogicalClientCutoverError(error)) { - sawUnknown = true - } else { - sawRejected = true - } + // instead of leaking an unhandled rejection. + .catch(() => { + sawRejected = true }) .finally(() => { pending -= 1 @@ -148,11 +140,12 @@ export function useMobileNativeChatStop(args: { }, [ cancelPending, cancelSecondEscape, - client, deviceTokenRef, enabled, handleRef, onSendError, - streamIdentity + operations, + streamIdentity, + workspaceId ]) } diff --git a/mobile/src/session/use-mobile-native-chat-terminal-response-lane.ts b/mobile/src/session/use-mobile-native-chat-terminal-response-lane.ts new file mode 100644 index 000000000000..3b678f034729 --- /dev/null +++ b/mobile/src/session/use-mobile-native-chat-terminal-response-lane.ts @@ -0,0 +1,74 @@ +import type { MutableRefObject } from 'react' +import type { HostSessionNativeChatOperations } from './host-session-native-chat-operations' +import type { RpcClient } from '../transport/rpc-client' +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 './use-mobile-native-chat-stop' + +/** The terminal-bridge lane's replies to a live agent prompt: answer an ask, + * cancel it, respond to a permission request, and stop the turn. All four write + * to the same terminal under the same lease, so they share one enablement gate + * and one pending-answer cancellation. Structured agent sessions answer through + * their provider instead and leave this lane disabled. */ +export function useMobileNativeChatTerminalResponseLane(args: { + client: RpcClient | null + operations: HostSessionNativeChatOperations | null + workspaceId: string + enabled: boolean + handleRef: MutableRefObject + deviceTokenRef: MutableRefObject + agentRef: MutableRefObject + sessionId: string | null + streamIdentity: string + onSendError: (message: string) => void +}) { + const { + client, + operations, + workspaceId, + enabled, + handleRef, + deviceTokenRef, + agentRef, + sessionId, + streamIdentity, + onSendError + } = args + const { answerAsk, cancelPending } = useMobileNativeChatAnswerSend({ + client, + enabled, + handleRef, + deviceTokenRef, + agentRef, + sessionId, + streamIdentity, + onSendError + }) + const cancelAsk = useMobileNativeChatCancelAsk({ + client, + enabled, + handleRef, + deviceTokenRef, + cancelPending, + onSendError + }) + const respondPermission = useMobileNativeChatPermissionSend({ + client, + enabled, + handleRef, + deviceTokenRef, + onSendError + }) + const stop = useMobileNativeChatStop({ + operations, + workspaceId, + enabled, + handleRef, + deviceTokenRef, + streamIdentity, + cancelPending, + onSendError + }) + return { answerAsk, cancelAsk, respondPermission, stop } +} diff --git a/mobile/src/session/use-mobile-session-close-actions.ts b/mobile/src/session/use-mobile-session-close-actions.ts index c2ff6825b0a8..94662539d1e7 100644 --- a/mobile/src/session/use-mobile-session-close-actions.ts +++ b/mobile/src/session/use-mobile-session-close-actions.ts @@ -5,6 +5,7 @@ export function useMobileSessionCloseActions(scope: MobileSessionContentCreateAc const { worktreeId, client, + sessionOperations, setTerminals, terminals, terminalsRef, @@ -31,7 +32,7 @@ export function useMobileSessionCloseActions(scope: MobileSessionContentCreateAc fetchTerminals } = scope async function handleRenameTerminal(value: string) { - if (!client || !renameTarget) { + if (!sessionOperations || !renameTarget) { return } const target = renameTarget @@ -39,11 +40,7 @@ export function useMobileSessionCloseActions(scope: MobileSessionContentCreateAc try { const title = value.trim() - const response = await client.sendRequest('terminal.rename', { - terminal: target.handle, - title - }) - if (response.ok) { + if (await sessionOperations.terminal.rename(target.handle, title, worktreeId)) { setTerminals((prev) => { const next = prev.map((terminal) => terminal.handle === target.handle @@ -93,18 +90,14 @@ export function useMobileSessionCloseActions(scope: MobileSessionContentCreateAc } async function handleCloseSessionTab(tab: MobileSessionTab) { - if (!client) { + if (!sessionOperations) { return } try { - const response = await client.sendRequest('session.tabs.close', { - worktree: `id:${worktreeId}`, - tabId: tab.id, - // Why: a tapped tab close is explicit user intent; older hosts strip - // the unknown field and keep their legacy behavior. - reason: 'user' - }) - if (response.ok) { + // Why: a tapped tab close is explicit user intent; older hosts strip + // the unknown reason and keep their legacy behavior. + const result = await sessionOperations.tab.close(worktreeId, tab.id) + if (result.outcome === 'closed') { const remainingTabs = sessionTabsRef.current.filter((candidate) => candidate.id !== tab.id) reconcileBufferedDraftsRef.current(sessionTabsRef.current, remainingTabs) if (tab.type === 'browser' && tab.browserPageId === pendingBrowserFocusPageIdRef.current) { diff --git a/mobile/src/session/use-mobile-session-content-create-actions.ts b/mobile/src/session/use-mobile-session-content-create-actions.ts index f9980d379ba7..2a6f5e7a85aa 100644 --- a/mobile/src/session/use-mobile-session-content-create-actions.ts +++ b/mobile/src/session/use-mobile-session-content-create-actions.ts @@ -1,4 +1,4 @@ -import type { RpcFailure, RpcSuccess } from '../transport/types' +import type { RpcFailure } from '../transport/types' import { normalizeBrowserUrl } from '../browser/browser-url' import { captureMobileFileMutationOwnership } from '../files/mobile-file-mutation-ownership' import { isFileExistsErrorMessage } from './mobile-session-route-helpers' @@ -11,6 +11,7 @@ export function useMobileSessionContentCreateActions( const { worktreeId, client, + sessionOperations, creatingBrowser, setCreatingBrowser, creatingMarkdown, @@ -72,7 +73,7 @@ export function useMobileSessionContentCreateActions( } async function handleCreateBrowser(rawUrl = 'about:blank'): Promise { - if (!client || creatingBrowser) { + if (!sessionOperations || creatingBrowser) { return false } // Why: read via ref so a tap before the capability probe resolves (or a stale callback) still sees the live value. @@ -91,21 +92,9 @@ export function useMobileSessionContentCreateActions( setCreatingBrowser(true) setCreateError('') try { - const response = await client.sendRequest( - 'browser.tabCreate', - { - worktree: `id:${worktreeId}`, - url, - // The user opened this tab (tapped HTML / address bar) → focus it. - activate: true - }, - { timeoutMs: 30_000 } - ) - if (!response.ok) { - throw new Error((response as RpcFailure).error.message) - } + // The user opened this tab (tapped HTML / address bar) → focus it. + const created = await sessionOperations.tab.createBrowser(worktreeId, url) // Focus the new browser tab once it syncs; refresh a few times since the desktop registers the tab asynchronously. - const created = (response as RpcSuccess).result as { browserPageId?: string } if (created.browserPageId) { pendingBrowserFocusPageIdRef.current = created.browserPageId } @@ -129,21 +118,18 @@ export function useMobileSessionContentCreateActions( tab: Extract, method: 'browser.back' | 'browser.forward' | 'browser.reload' ) { - if (!client || !tab.browserPageId) { + if (!sessionOperations || !tab.browserPageId) { showToast('Browser page is not available yet.', 1500) return } try { - const response = await client.sendRequest( - method, - { - worktree: `id:${worktreeId}`, - page: tab.browserPageId - }, - { timeoutMs: 15_000 } - ) - if (!response.ok) { - throw new Error((response as RpcFailure).error.message) + const target = { workspaceId: worktreeId, pageId: tab.browserPageId } + if (method === 'browser.back') { + await sessionOperations.browser.back(target) + } else if (method === 'browser.forward') { + await sessionOperations.browser.forward(target) + } else { + await sessionOperations.browser.reload(target) } scheduleDelayedAction(() => void fetchSessionTabs(), 250) } catch (err) { diff --git a/mobile/src/session/use-mobile-session-document-readers.ts b/mobile/src/session/use-mobile-session-document-readers.ts index dbf78b1a45a0..9dbce7cdb42f 100644 --- a/mobile/src/session/use-mobile-session-document-readers.ts +++ b/mobile/src/session/use-mobile-session-document-readers.ts @@ -1,74 +1,23 @@ import { useCallback } from 'react' -import type { RpcFailure, RpcSuccess } from '../transport/types' -import { resolveMobileFileTabDoc } from '../files/mobile-file-tab-doc' -import { - buildMarkdownDiskFallbackDoc, - shouldReadMarkdownFromDiskAfterReadTabFailure -} from './mobile-markdown-disk-fallback' import type { MobileSessionTab } from './mobile-session-route-types' import type { MobileSessionTabApplicationModel } from './use-mobile-session-tab-application' export function useMobileSessionDocumentReaders(scope: MobileSessionTabApplicationModel) { - const { worktreeId, client, setMarkdownDocs, setFileDocs } = scope + const { worktreeId, sessionOperations, setMarkdownDocs, setFileDocs } = scope const readMarkdownTab = useCallback( async (tab: Extract) => { - if (!client) { + if (!sessionOperations) { return } setMarkdownDocs((prev) => new Map(prev).set(tab.id, { status: 'loading' })) try { - const response = await client.sendRequest('markdown.readTab', { - worktree: `id:${worktreeId}`, - tabId: tab.id - }) - if (response.ok) { - const result = (response as RpcSuccess).result as { - content: string - version: string - isDirty: boolean - editable?: boolean - readOnlyReason?: string - } - setMarkdownDocs((prev) => - new Map(prev).set(tab.id, { - status: 'ready', - content: result.content, - localContent: result.content, - baseVersion: result.version, - isDirty: false, - editable: result.editable === true, - stale: result.isDirty, - readOnlyReason: result.readOnlyReason - }) - ) - return - } - if (!shouldReadMarkdownFromDiskAfterReadTabFailure(response as RpcFailure)) { - throw new Error((response as RpcFailure).error.message) - } - // Why: a headless host fails markdown.readTab (renderer_unavailable); fall back to the on-disk file for read-only render. - const fallback = await client.sendRequest('files.read', { - worktree: `id:${worktreeId}`, - relativePath: tab.relativePath + const doc = await sessionOperations.markdown.readTab({ + workspaceId: worktreeId, + tabId: tab.id, + relativePath: tab.relativePath, + tabIsDirty: tab.isDirty }) - if (!fallback.ok) { - throw new Error('Unable to read markdown') - } - const fileResult = (fallback as RpcSuccess).result as { - content: string - truncated: boolean - byteLength: number - } - setMarkdownDocs((prev) => - new Map(prev).set( - tab.id, - buildMarkdownDiskFallbackDoc({ - content: fileResult.content, - truncated: fileResult.truncated, - tabIsDirty: tab.isDirty - }) - ) - ) + setMarkdownDocs((prev) => new Map(prev).set(tab.id, doc)) } catch { setMarkdownDocs((prev) => new Map(prev).set(tab.id, { @@ -78,17 +27,17 @@ export function useMobileSessionDocumentReaders(scope: MobileSessionTabApplicati ) } }, - [client, worktreeId] + [sessionOperations, worktreeId] ) const readFileTab = useCallback( async (tab: Extract) => { - if (!client) { + if (!sessionOperations) { return } setFileDocs((prev) => new Map(prev).set(tab.id, { status: 'loading' })) try { - const doc = await resolveMobileFileTabDoc(client, { + const doc = await sessionOperations.file.readTab({ worktreeId, relativePath: tab.relativePath, diffSource: tab.diffSource @@ -112,7 +61,7 @@ export function useMobileSessionDocumentReaders(scope: MobileSessionTabApplicati ) } }, - [client, worktreeId] + [sessionOperations, worktreeId] ) return { readMarkdownTab, diff --git a/mobile/src/session/use-mobile-session-feedback-capabilities.ts b/mobile/src/session/use-mobile-session-feedback-capabilities.ts index 8c619fb1f7f1..fb33ce39b625 100644 --- a/mobile/src/session/use-mobile-session-feedback-capabilities.ts +++ b/mobile/src/session/use-mobile-session-feedback-capabilities.ts @@ -21,6 +21,8 @@ export function useMobileSessionFeedbackCapabilities(scope: MobileSessionTermina toastHideTimerRef, toastSeqRef, clientRef, + sessionOperations, + sessionOperationsRef, connStateRef, activeSessionTabTypeRef, delayedActionTimersRef, @@ -39,6 +41,7 @@ export function useMobileSessionFeedbackCapabilities(scope: MobileSessionTermina browserScreencastSupportedRef.current = browserScreencastSupported // Why: terminal gesture/input callbacks are stable/imperative, so keep their refs current before commit, not in a later effect. clientRef.current = client + sessionOperationsRef.current = sessionOperations connStateRef.current = connState activeSessionTabTypeRef.current = activeSessionTab?.type ?? null sessionTabsRef.current = sessionTabs diff --git a/mobile/src/session/use-mobile-session-file-actions.ts b/mobile/src/session/use-mobile-session-file-actions.ts index 56aa2b049d8c..146becfc83b4 100644 --- a/mobile/src/session/use-mobile-session-file-actions.ts +++ b/mobile/src/session/use-mobile-session-file-actions.ts @@ -12,7 +12,7 @@ export function useMobileSessionFileActions(scope: MobileSessionTerminalSendActi worktreeId, routeWorktreeName, isFloatingWorkspaceRoute, - client, + sessionOperations, sessionTabsRef, terminalLinkOpenMode, activeSessionTabIdRef, @@ -28,7 +28,7 @@ export function useMobileSessionFileActions(scope: MobileSessionTerminalSendActi } = scope // Tap a terminal or chat file path → resolve on host, open as file tab/preview. const { handleFileTap, handleNativeChatFileTap } = useMobileFileTapHandlers({ - client, + operations: sessionOperations?.terminalFile ?? null, hostId, worktreeId, worktreeName: routeWorktreeName, diff --git a/mobile/src/session/use-mobile-session-markdown-actions.ts b/mobile/src/session/use-mobile-session-markdown-actions.ts index 50b6dbd7b29a..6b650af14cca 100644 --- a/mobile/src/session/use-mobile-session-markdown-actions.ts +++ b/mobile/src/session/use-mobile-session-markdown-actions.ts @@ -1,7 +1,6 @@ import { useEffect, useCallback } from 'react' import { BackHandler, Keyboard } from 'react-native' import * as Clipboard from 'expo-clipboard' -import type { RpcFailure, RpcSuccess } from '../transport/types' import { triggerSuccess, triggerError } from '../platform/haptics' import type { DirtyMarkdownDraft, MobileSessionTab } from './mobile-session-route-types' import type { MobileSessionDiffCommentsModel } from './use-mobile-session-diff-comments' @@ -11,7 +10,7 @@ export function useMobileSessionMarkdownActions(scope: MobileSessionDiffComments hostId, worktreeId, router, - client, + sessionOperations, sessionTabs, setMarkdownDocs, markdownDocs, @@ -117,7 +116,7 @@ export function useMobileSessionMarkdownActions(scope: MobileSessionDiffComments const saveMarkdownTab = useCallback( async (tab: Extract) => { - if (!client) { + if (!sessionOperations) { return } const current = markdownDocs.get(tab.id) @@ -138,20 +137,13 @@ export function useMobileSessionMarkdownActions(scope: MobileSessionDiffComments return new Map(prev).set(tab.id, { ...existing, saving: true, saveError: undefined }) }) try { - const response = await client.sendRequest('markdown.saveTab', { - worktree: `id:${worktreeId}`, + const result = await sessionOperations.markdown.saveTab({ + workspaceId: worktreeId, tabId: tab.id, + relativePath: tab.relativePath, baseVersion: current.baseVersion, content: current.localContent }) - if (!response.ok) { - throw new Error((response as RpcFailure).error.message) - } - const result = (response as RpcSuccess).result as { - content: string - version: string - isDirty: false - } if (markdownSaveSeqRef.current.get(tab.id) !== saveSeq) { return } @@ -160,7 +152,7 @@ export function useMobileSessionMarkdownActions(scope: MobileSessionDiffComments status: 'ready', content: result.content, localContent: result.content, - baseVersion: result.version, + baseVersion: result.baseVersion, isDirty: false, editable: true }) @@ -189,7 +181,7 @@ export function useMobileSessionMarkdownActions(scope: MobileSessionDiffComments markdownSaveInFlightRef.current.delete(tab.id) } }, - [client, markdownDocs, showToast, worktreeId] + [markdownDocs, sessionOperations, showToast, worktreeId] ) return { updateMarkdownLocalContent, 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 6046cba10598..2b9358dca26c 100644 --- a/mobile/src/session/use-mobile-session-native-chat-dictation.ts +++ b/mobile/src/session/use-mobile-session-native-chat-dictation.ts @@ -26,6 +26,7 @@ export function useMobileSessionNativeChatDictation( hostId, worktreeId, client, + sessionOperations, connState, setInput, liveInputTerminalHandles, @@ -50,7 +51,11 @@ export function useMobileSessionNativeChatDictation( scopeKey: nativeChatScopeKey, showToast }) - const nativeChatTranscriptIsLocalReadable = useMobileNativeChatReadability(client, worktreeId) + const nativeChatOperations = sessionOperations?.nativeChat ?? null + const nativeChatTranscriptIsLocalReadable = useMobileNativeChatReadability( + nativeChatOperations, + worktreeId + ) const { ready: nativeChatInputLeaseReady, readyRef: nativeChatInputLeaseReadyRef, @@ -63,6 +68,7 @@ export function useMobileSessionNativeChatDictation( }) const nativeChatController = useMobileNativeChatController({ client, + nativeChatOperations, hostId, worktreeId, activeSessionTab, diff --git a/mobile/src/session/use-mobile-session-screen-state.ts b/mobile/src/session/use-mobile-session-screen-state.ts index 6e2f82124b37..3024eabd9cdd 100644 --- a/mobile/src/session/use-mobile-session-screen-state.ts +++ b/mobile/src/session/use-mobile-session-screen-state.ts @@ -25,9 +25,16 @@ import type { } from './mobile-session-route-types' import { useMobileSessionTabActionTargets } from './use-mobile-session-tab-action-targets' import type { MobileSessionFoundationModel } from './use-mobile-session-foundation' +import { defaultHostSessionOperations } from './default-host-session-operations' export function useMobileSessionScreenState(scope: MobileSessionFoundationModel) { - const { worktreeId, hostId, initialCreateWarning } = scope + const { worktreeId, hostId, initialCreateWarning, client } = scope + // Single host-operations provider for the whole session model; every screen hook + // reads its namespace off this instead of holding the raw RPC client. + const sessionOperations = useMemo( + () => (client ? defaultHostSessionOperations(client) : null), + [client] + ) const [terminals, setTerminals] = useState([]) const terminalsRef = useRef([]) const [sessionTabs, setSessionTabs] = useState([]) @@ -125,6 +132,7 @@ export function useMobileSessionScreenState(scope: MobileSessionFoundationModel) const toastHideTimerRef = useRef | null>(null) const toastSeqRef = useRef(0) return { + sessionOperations, terminals, setTerminals, terminalsRef, diff --git a/mobile/src/session/use-mobile-session-terminal-input.ts b/mobile/src/session/use-mobile-session-terminal-input.ts index 3f6e417e23a7..79b0352b1b49 100644 --- a/mobile/src/session/use-mobile-session-terminal-input.ts +++ b/mobile/src/session/use-mobile-session-terminal-input.ts @@ -1,15 +1,10 @@ import { reportWorkerTerminalUserInput } from '../terminal/worker-terminal-takeover-report' import { useCallback } from 'react' -import { isTerminalSendRpcAccepted } from '../terminal/terminal-send-rpc-response' import { clearTerminalLiveInputFocusTimer, scheduleTerminalLiveInputFocus } from '../terminal/terminal-live-input' import { sendMobileTerminalQueryReply } from '../terminal/mobile-terminal-query-reply' -import { - buildTerminalSendParams, - TERMINAL_INPUT_SEND_OPTIONS -} from '../terminal/terminal-send-request' import { countTerminalGestureInputSequences } from '../terminal/terminal-gesture-input' import { isGestureMouseTrackingMode, @@ -24,7 +19,8 @@ import type { MobileSessionFileActionsModel } from './use-mobile-session-file-ac export function useMobileSessionTerminalInput(scope: MobileSessionFileActionsModel) { const { - client, + sessionOperations, + sessionOperationsRef, connState, toggleTerminalLiveInput, activeHandle, @@ -105,24 +101,18 @@ export function useMobileSessionTerminalInput(scope: MobileSessionFileActionsMod handle === activeHandleRef.current && activeSessionTabTypeRef.current === 'terminal' const isFresh = Date.now() - queued.lastUpdatedMs <= TERMINAL_GESTURE_INPUT_MAX_QUEUE_AGE_MS const rpc = clientRef.current - if (!rpc || connStateRef.current !== 'connected' || !isActive || !isFresh) { + const operations = sessionOperationsRef.current + if (!rpc || !operations || connStateRef.current !== 'connected' || !isActive || !isFresh) { return } terminalGestureInputInFlightRef.current.add(handle) try { // Why: gesture arrows parked across a reconnect would move a TUI long after the swipe. - const response = await rpc.sendRequest( - 'terminal.send', - buildTerminalSendParams({ - terminal: handle, - text: queued.bytes, - enter: false, - deviceToken: deviceTokenRef.current - }), - TERMINAL_INPUT_SEND_OPTIONS - ) - if (isTerminalSendRpcAccepted(response)) { + if ( + await operations.terminal.sendInput(handle, queued.bytes, false, deviceTokenRef.current) + ) { + // The adapter does not report takeover; a gesture write still takes a worker over. reportWorkerTerminalUserInput(rpc, handle) } } catch { @@ -193,7 +183,7 @@ export function useMobileSessionTerminalInput(scope: MobileSessionFileActionsMod const handleTerminalInput = useCallback( async (handle: string, bytes: string) => { - if (!client || connState !== 'connected' || bytes.length === 0) { + if (!sessionOperations || connState !== 'connected' || bytes.length === 0) { return } if (handle !== activeHandleRef.current || activeSessionTabTypeRef.current !== 'terminal') { @@ -213,7 +203,7 @@ export function useMobileSessionTerminalInput(scope: MobileSessionFileActionsMod } enqueueTerminalGestureInput(handle, bytes, sequenceCount) }, - [allowTerminalGestureInput, client, connState, enqueueTerminalGestureInput] + [allowTerminalGestureInput, connState, enqueueTerminalGestureInput, sessionOperations] ) const handleTerminalQueryReply = useCallback((handle: string, bytes: string) => { @@ -229,14 +219,14 @@ export function useMobileSessionTerminalInput(scope: MobileSessionFileActionsMod }, []) async function handleClearTerminal(target: Terminal) { - if (!client) { + if (!sessionOperations) { return } getTerminalRef(target.handle)?.clear() try { - await client.sendRequest('terminal.clearBuffer', { - terminal: target.handle - }) + if (!(await sessionOperations.terminal.clear(target.handle))) { + throw new Error('terminal_clear_failed') + } showToast('Terminal cleared') } catch { showToast("Couldn't clear terminal", 1500) diff --git a/mobile/src/session/use-mobile-session-terminal-runtime.ts b/mobile/src/session/use-mobile-session-terminal-runtime.ts index 374a9eefd949..25be557b615d 100644 --- a/mobile/src/session/use-mobile-session-terminal-runtime.ts +++ b/mobile/src/session/use-mobile-session-terminal-runtime.ts @@ -19,6 +19,7 @@ import type { TerminalGestureInputBucket, TerminalGestureInputQueue } from './mobile-session-route-types' +import type { HostSessionOperations } from './host-session-operations' import type { MobileSessionScreenStateModel } from './use-mobile-session-screen-state' export function useMobileSessionTerminalRuntime(scope: MobileSessionScreenStateModel) { @@ -49,6 +50,7 @@ export function useMobileSessionTerminalRuntime(scope: MobileSessionScreenStateM // Why: state (not a ref) so the connection verdict re-renders when the endpoint loads and the Tailscale hint can appear. const [hostEndpoint, setHostEndpoint] = useState(null) const clientRef = useRef(null) + const sessionOperationsRef = useRef(null) const connStateRef = useRef(connState) // Why: measured once on mount, then passed with every subscribe so the server can auto-fit the PTY to phone dims. const viewportRef = useRef<{ cols: number; rows: number } | null>(null) @@ -162,6 +164,7 @@ export function useMobileSessionTerminalRuntime(scope: MobileSessionScreenStateM hostEndpoint, setHostEndpoint, clientRef, + sessionOperationsRef, connStateRef, viewportRef, viewportMeasuredRef, diff --git a/mobile/src/session/use-mobile-session-terminal-send-actions.ts b/mobile/src/session/use-mobile-session-terminal-send-actions.ts index aa365d5ba393..210ebf4c5209 100644 --- a/mobile/src/session/use-mobile-session-terminal-send-actions.ts +++ b/mobile/src/session/use-mobile-session-terminal-send-actions.ts @@ -48,7 +48,8 @@ export function useMobileSessionTerminalSendActions(scope: MobileSessionTerminal handleLiveInputAccessoryBytes, canSend, scheduleDelayedAction, - showToast + showToast, + sessionOperationsRef } = scope const TERMINAL_KEYBOARD_DISMISS_ACTION_SHEET_FALLBACK_MS = 450 @@ -148,9 +149,11 @@ export function useMobileSessionTerminalSendActions(scope: MobileSessionTerminal return false } const rpc = clientRef.current + const operations = sessionOperationsRef.current // Why: callers suppress follow-up controls/toasts when this live send is stale. if ( !rpc || + !operations || connStateRef.current !== 'connected' || handle !== activeHandleRef.current || activeSessionTabTypeRef.current !== 'terminal' @@ -159,27 +162,17 @@ export function useMobileSessionTerminalSendActions(scope: MobileSessionTerminal } // Why: live-mirror deltas queued behind a dying send drain into the connect // wait and replay stale bytes after reconnect (#6713's `YZZYecho …` corruption). - return rpc - .sendRequest( - 'terminal.send', - buildTerminalSendParams({ - terminal: handle, - text, - enter: false, - deviceToken: deviceTokenRef.current - }), - TERMINAL_INPUT_SEND_OPTIONS - ) - .then( - (response) => { - const accepted = isTerminalSendRpcAccepted(response) - if (accepted) { - reportWorkerTerminalUserInput(rpc, handle) - } - return accepted - }, - () => false - ) + const accepted = await operations.terminal.sendInput( + handle, + text, + false, + deviceTokenRef.current + ) + if (accepted) { + // The adapter does not report takeover; a live keystroke still takes a worker over. + reportWorkerTerminalUserInput(rpc, handle) + } + return accepted }, [showToast] ) diff --git a/mobile/src/session/use-mobile-session-terminal-stream-display.ts b/mobile/src/session/use-mobile-session-terminal-stream-display.ts index 915b10095b9c..7fc00a90a054 100644 --- a/mobile/src/session/use-mobile-session-terminal-stream-display.ts +++ b/mobile/src/session/use-mobile-session-terminal-stream-display.ts @@ -6,7 +6,7 @@ export function useMobileSessionTerminalStreamDisplay( scope: MobileSessionTerminalSubscriptionModel ) { const { - client, + sessionOperations, activeHandle, coveredStreamRevision, terminalModes, @@ -42,7 +42,7 @@ export function useMobileSessionTerminalStreamDisplay( const toggleInFlightRef = useRef>(new Set()) const toggleDisplayMode = useCallback( async (handle: string) => { - if (!client) { + if (!sessionOperations) { return } if (toggleInFlightRef.current.has(handle)) { @@ -54,23 +54,21 @@ export function useMobileSessionTerminalStreamDisplay( current === 'auto' || current === 'phone' ? 'desktop' : 'auto' toggleInFlightRef.current.add(handle) try { - await client.sendRequest('terminal.setDisplayMode', { - terminal: handle, - mode: next, - // Why: presence-lock take-floor — requesting 'auto' is the explicit "drive at phone dims" gesture. - ...(deviceTokenRef.current - ? { client: { id: deviceTokenRef.current, type: 'mobile' as const } } - : {}), - // Why: late-bind viewport for terminals subscribed before measurement, or auto toggles no-op on a null stored viewport. - ...(viewportRef.current && next === 'auto' ? { viewport: viewportRef.current } : {}) - }) + // Presence-lock take-floor, and a late-bound viewport so an 'auto' toggle on a + // terminal subscribed before measurement doesn't no-op on a null stored viewport. + await sessionOperations.terminal.setDisplayMode( + handle, + next, + viewportRef.current, + deviceTokenRef.current + ) } catch { // Mode change failed — server state unchanged, UI stays in sync. } finally { toggleInFlightRef.current.delete(handle) } }, - [client, terminalModes] + [sessionOperations, terminalModes] ) return { nativeChatStream, diff --git a/mobile/src/session/use-quick-commands.test.ts b/mobile/src/session/use-quick-commands.test.ts index b375a20bd97d..10acd13029a3 100644 --- a/mobile/src/session/use-quick-commands.test.ts +++ b/mobile/src/session/use-quick-commands.test.ts @@ -5,8 +5,26 @@ import type { TerminalQuickCommand } from '../../../src/shared/terminal-quick-co import type { RpcClient } from '../transport/rpc-client' import { LogicalClientCutoverError } from '../transport/stable-logical-rpc-client' import type { RpcResponse } from '../transport/types' +import { defaultHostSessionOperations } from './default-host-session-operations' import { useQuickCommands } from './use-quick-commands' +const WORKSPACE_ID = 'repo::/worktree' +/** One provider per client, exactly as the session model memoizes it, so the + * effect keys stay stable across renders. */ +const operationsByClient = new WeakMap< + RpcClient, + ReturnType['quickCommand'] +>() +function quickCommandOperations(client: RpcClient) { + const cached = operationsByClient.get(client) + if (cached) { + return cached + } + const operations = defaultHostSessionOperations(client).quickCommand + operationsByClient.set(client, operations) + return operations +} + const FIRST: TerminalQuickCommand = { id: 'first', label: 'First', @@ -57,7 +75,11 @@ describe('useQuickCommands', () => { async function mount(client: RpcClient, enabled = true): Promise { function Harness(): null { - state = useQuickCommands({ client, enabled }) + state = useQuickCommands({ + operations: quickCommandOperations(client), + workspaceId: WORKSPACE_ID, + enabled + }) return null } await act(async () => { @@ -128,7 +150,11 @@ describe('useQuickCommands', () => { } as unknown as RpcClient function Harness({ enabled }: { enabled: boolean }): null { - state = useQuickCommands({ client, enabled }) + state = useQuickCommands({ + operations: quickCommandOperations(client), + workspaceId: WORKSPACE_ID, + enabled + }) return null } await act(async () => { @@ -307,7 +333,11 @@ describe('useQuickCommands', () => { } as unknown as RpcClient function Harness({ client }: { client: RpcClient }): null { - state = useQuickCommands({ client, enabled: true }) + state = useQuickCommands({ + operations: quickCommandOperations(client), + workspaceId: WORKSPACE_ID, + enabled: true + }) return null } await act(async () => { @@ -382,7 +412,11 @@ describe('useQuickCommands', () => { } as unknown as RpcClient function Harness({ enabled }: { enabled: boolean }): null { - state = useQuickCommands({ client, enabled }) + state = useQuickCommands({ + operations: quickCommandOperations(client), + workspaceId: WORKSPACE_ID, + enabled + }) return null } await act(async () => { diff --git a/mobile/src/session/use-quick-commands.ts b/mobile/src/session/use-quick-commands.ts index 6537551be7a9..fe422ab9da21 100644 --- a/mobile/src/session/use-quick-commands.ts +++ b/mobile/src/session/use-quick-commands.ts @@ -1,16 +1,14 @@ import { useCallback, useEffect, useRef, useState } from 'react' -import type { RpcClient } from '../transport/rpc-client' -import { isLogicalClientCutoverError } from '../transport/stable-logical-rpc-client' -import type { RpcFailure, RpcResponse, RpcSuccess } from '../transport/types' import type { TerminalQuickCommand } from '../../../src/shared/terminal-quick-command-types' import { applyTerminalQuickCommandMutation, - parseNormalizedTerminalQuickCommands, type TerminalQuickCommandMutation } from '../terminal/quick-commands' +import type { HostSessionQuickCommandOperations } from './host-session-quick-command-operations' type Args = { - client: RpcClient | null + operations: HostSessionQuickCommandOperations | null + workspaceId: string // Fetch only while the sheet is open — quick commands are settings data we // don't need to keep hydrated for every session screen. enabled: boolean @@ -32,43 +30,15 @@ type PendingMutation = { } type MutationContext = { - client: RpcClient + operations: HostSessionQuickCommandOperations + workspaceId: string confirmed: TerminalQuickCommand[] pending: PendingMutation[] queue: Promise nextMutationId: number } -function readQuickCommands(result: unknown): TerminalQuickCommand[] | null { - const list = (result as { terminalQuickCommands?: unknown } | null)?.terminalQuickCommands - return parseNormalizedTerminalQuickCommands(list) -} - -const LOAD_CUTOVER_MAX_RETRIES = 5 - -// Why: opening the sheet right after connecting over relay races the relay→direct -// cutover, which rejects in-flight one-shots while connState stays 'connected'; -// the read is side-effect-free, so replay it instead of stranding an empty sheet. -async function loadQuickCommandsWithCutoverRetry( - client: RpcClient, - cancelled: () => boolean -): Promise { - for (let migrationRetry = 0; ; migrationRetry += 1) { - try { - return await client.sendRequest('settings.getTerminalQuickCommands') - } catch (error) { - if ( - cancelled() || - !isLogicalClientCutoverError(error) || - migrationRetry >= LOAD_CUTOVER_MAX_RETRIES - ) { - throw error - } - } - } -} - -export function useQuickCommands({ client, enabled }: Args): QuickCommandsState { +export function useQuickCommands({ operations, workspaceId, enabled }: Args): QuickCommandsState { const [commands, setCommands] = useState([]) const [loading, setLoading] = useState(false) const [ready, setReady] = useState(false) @@ -78,15 +48,16 @@ export function useQuickCommands({ client, enabled }: Args): QuickCommandsState const mutationContextRef = useRef(null) useEffect(() => { - if (!enabled || !client) { + if (!enabled || !operations) { setReady(false) return } let mutationContext = mutationContextRef.current - if (mutationContext?.client !== client) { + if (mutationContext?.operations !== operations || mutationContext.workspaceId !== workspaceId) { // A request for an old host must not delay or update mutations on a new one. mutationContext = { - client, + operations, + workspaceId, confirmed: [], pending: [], queue: Promise.resolve(), @@ -97,6 +68,9 @@ export function useQuickCommands({ client, enabled }: Args): QuickCommandsState setCommands([]) } let stale = false + // Why: opening the sheet right after connecting over relay races the relay→direct + // cutover; the adapter replays the side-effect-free read until this aborts it. + const abortController = new AbortController() const operationId = operationIdRef.current + 1 operationIdRef.current = operationId setLoading(true) @@ -115,13 +89,7 @@ export function useQuickCommands({ client, enabled }: Args): QuickCommandsState ) { return } - const response = await loadQuickCommandsWithCutoverRetry( - client, - () => - stale || - operationId !== operationIdRef.current || - mutationContextRef.current !== mutationContext - ) + const snapshot = await operations.snapshot(workspaceId, abortController.signal) if ( stale || operationId !== operationIdRef.current || @@ -129,18 +97,9 @@ export function useQuickCommands({ client, enabled }: Args): QuickCommandsState ) { return } - if (!response.ok) { - setError((response as RpcFailure).error.message || 'Failed to load quick commands') - return - } - const next = readQuickCommands((response as RpcSuccess).result) - if (!next) { - setError('Failed to load quick commands') - return - } - mutationContext.confirmed = next - commandsRef.current = next - setCommands(next) + mutationContext.confirmed = snapshot.commands + commandsRef.current = snapshot.commands + setCommands(snapshot.commands) setReady(true) } catch (err) { if ( @@ -163,15 +122,22 @@ export function useQuickCommands({ client, enabled }: Args): QuickCommandsState return () => { stale = true + abortController.abort() } - }, [client, enabled]) + }, [enabled, operations, workspaceId]) const persist = useCallback( async (commandMutation: TerminalQuickCommandMutation) => { // Why: the loaded list is the optimistic/rollback baseline; mutating // before it arrives would make failure recovery show invented state. const mutationContext = mutationContextRef.current - if (!client || loading || !ready || mutationContext?.client !== client) { + if ( + !operations || + loading || + !ready || + mutationContext?.operations !== operations || + mutationContext.workspaceId !== workspaceId + ) { return false } const mutation: PendingMutation = { @@ -189,21 +155,10 @@ export function useQuickCommands({ client, enabled }: Args): QuickCommandsState let succeeded = false let failureMessage: string | null = null try { - const response = await client.sendRequest('settings.updateTerminalQuickCommands', { - mutation: commandMutation - }) - if (!response.ok) { - throw new Error( - (response as RpcFailure).error.message || 'Failed to save quick command' - ) - } - const confirmed = readQuickCommands((response as RpcSuccess).result) - if (!confirmed) { - // Why: treating an invalid success payload as [] would let the next - // full-list mutation erase commands that still exist on the host. - throw new Error('Failed to save quick command') - } - mutationContext.confirmed = confirmed + // Why: an invalid success payload throws inside the adapter rather than + // confirming [] — a later full-list mutation would erase live commands. + const snapshot = await operations.mutate(workspaceId, commandMutation) + mutationContext.confirmed = snapshot.commands succeeded = true return true } catch (err) { @@ -236,7 +191,7 @@ export function useQuickCommands({ client, enabled }: Args): QuickCommandsState ) return await request }, - [client, loading, ready] + [loading, operations, ready, workspaceId] ) return { commands, loading, ready, error, persist } diff --git a/mobile/src/terminal/terminal-input-connection-gate.test.ts b/mobile/src/terminal/terminal-input-connection-gate.test.ts index f046a674a8b1..f48eeae7c338 100644 --- a/mobile/src/terminal/terminal-input-connection-gate.test.ts +++ b/mobile/src/terminal/terminal-input-connection-gate.test.ts @@ -12,6 +12,9 @@ const sendActionsSource = readMobileSessionRouteSource( const terminalInputSource = readMobileSessionRouteSource( '../session/use-mobile-session-terminal-input.ts' ) +const terminalOperationsSource = readMobileSessionRouteSource( + '../session/native-host-session-terminal-operations.ts' +) const commandDockSource = readMobileSessionRouteSource('../session/MobileSessionCommandDock.tsx') function sourceSlice(source: string, anchorStart: string, anchorEnd: string): string { @@ -145,12 +148,15 @@ describe('session route offline-compose wiring', () => { // connect wait — a parked send replays stale bytes into the PTY. Accessory // keys get the same option inside terminal-live-accessory-raw-send.ts. expect(sendActionsSource).toContain('TERMINAL_INPUT_SEND_OPTIONS') - expect(terminalInputSource).toContain('TERMINAL_INPUT_SEND_OPTIONS') - const optionUses = [sendActionsSource, terminalInputSource].flatMap( + const optionUses = [sendActionsSource, terminalOperationsSource].flatMap( (source) => source.match(/TERMINAL_INPUT_SEND_OPTIONS/g) ?? [] ).length - // Two owner imports plus one buffered, one live, and one gesture send. - expect(optionUses).toBe(5) + // Two owner imports plus one buffered send here and one adapter send. + expect(optionUses).toBe(4) + // The live mirror and the gesture arrows reach the PTY through that adapter send. + for (const source of [sendActionsSource, terminalInputSource]) { + expect(source).toContain('.terminal.sendInput(') + } expect(TERMINAL_INPUT_SEND_OPTIONS).toEqual({ failWhenDisconnected: true }) }) From 222134ebeafb8359664417bd41fd6dafa5111122 Mon Sep 17 00:00:00 2001 From: Jinwoo-H Date: Tue, 8 Sep 2026 22:49:55 -0400 Subject: [PATCH 04/40] test(mobile): ratchet inline RPC out of screens Pins the screens this PR routed at zero inline `sendRequest`, pins the four calls deliberately left inline at their exact count, and caps the total screen-side call sites so the remaining debt can only shrink. Claude-Session: https://claude.ai/code/session_01JNnE9qzUZMMnqpZWCqM3nb --- .../src/transport/screen-rpc-ratchet.test.ts | 140 ++++++++++++++++++ 1 file changed, 140 insertions(+) create mode 100644 mobile/src/transport/screen-rpc-ratchet.test.ts diff --git a/mobile/src/transport/screen-rpc-ratchet.test.ts b/mobile/src/transport/screen-rpc-ratchet.test.ts new file mode 100644 index 000000000000..1b7511a7a96d --- /dev/null +++ b/mobile/src/transport/screen-rpc-ratchet.test.ts @@ -0,0 +1,140 @@ +import { readFileSync, readdirSync } from 'node:fs' +import { join } from 'node:path' +import { describe, expect, it } from 'vitest' + +/** Screen directories whose RPC access is being moved behind the host operation adapters. */ +const SCREEN_DIRECTORIES = [ + 'tasks', + 'session', + 'files', + 'accounts', + 'worktree', + 'host-screen', + 'components', + 'hooks' +] as const + +/** Adapters are where `sendRequest` is supposed to live; specs and fixtures are not product code. */ +const NOT_SCREEN_CODE = /(^|\/)(native-host-|default-host-)|\.test\.tsx?$|test-support/ + +/** Routed in this PR, and each one must stay at zero. A screen that regrows an inline call has + * reopened the seam the operations adapters exist to close. */ +const ROUTED_SCREENS = [ + 'components/use-new-workspace-execution-target.ts', + 'components/use-new-workspace-repositories.ts', + 'components/use-new-workspace-runtime-context.ts', + 'components/use-new-workspace-setup-script.ts', + 'files/MobileFileExplorerPanel.tsx', + 'session/mobile-file-tap-open.ts', + 'session/use-mobile-native-chat-file-search.ts', + 'session/use-mobile-native-chat-readability.ts', + 'session/use-mobile-native-chat-session.ts', + 'session/use-mobile-native-chat-stop.ts', + 'session/use-mobile-session-document-readers.ts', + 'session/use-mobile-session-markdown-actions.ts', + 'session/use-mobile-session-terminal-input.ts', + 'session/use-mobile-session-terminal-stream-display.ts', + 'session/use-quick-commands.ts', + 'tasks/mobile-tasks-filter-pickers.tsx', + 'tasks/smart-source-paste-intent.ts', + 'tasks/use-mobile-tasks-client-settings-actions.tsx', + 'tasks/use-mobile-tasks-github-check-file-actions.tsx', + 'tasks/use-mobile-tasks-github-reply-merge-actions.tsx', + 'tasks/use-mobile-tasks-gitlab-github-status-actions.tsx', + 'tasks/use-mobile-tasks-item-detail-loading.tsx', + 'tasks/use-mobile-tasks-item-detail-metadata-effects.tsx', + 'tasks/use-mobile-tasks-linear-item-actions.tsx', + 'tasks/use-mobile-tasks-list-and-detail-effects.tsx', + 'tasks/use-mobile-tasks-project-detail-loading.tsx', + 'tasks/use-mobile-tasks-project-file-merge-actions.tsx', + 'tasks/use-mobile-tasks-project-loading-actions.tsx', + 'tasks/use-mobile-tasks-project-metadata-actions.tsx', + 'tasks/use-mobile-tasks-project-metadata-loading.tsx', + 'tasks/use-mobile-tasks-project-repository-resolution.tsx', + 'tasks/use-mobile-tasks-project-review-check-actions.tsx', + 'tasks/use-mobile-tasks-project-thread-reply-actions.tsx', + 'tasks/use-mobile-tasks-project-workspace-comment-actions.tsx', + 'tasks/use-mobile-tasks-provider-load-actions.tsx', + 'tasks/use-mobile-tasks-route-and-item-state.tsx', + 'tasks/use-mobile-tasks-runtime-hydration.tsx', + 'tasks/use-mobile-tasks-task-create-actions.tsx', + 'tasks/use-mobile-tasks-task-list-loading.tsx', + 'tasks/use-mobile-tasks-task-pagination-actions.tsx', + 'tasks/use-mobile-tasks-workspace-source-effects.tsx', + 'tasks/use-mobile-tasks-workspace-sparse-actions.tsx', + 'tasks/use-mobile-tasks-workspace-ssh-state.tsx', + 'worktree/use-retired-worktree-names.ts' +] as const + +/** Four calls stay inline on purpose. Each has no adapter method that means the same thing, so + * routing it would change what reaches the host. The count is pinned so a fifth cannot appear. */ +const DELIBERATE_INLINE_CALLS: Record = { + // `terminal.close` — closing the terminal, not the tab; the tab adapter's close is a tab close. + 'session/use-mobile-session-close-actions.ts': 1, + // `files.createFile` then `files.open` — note creation has no operations counterpart. + 'session/use-mobile-session-content-create-actions.ts': 2, + // The buffered submit; it needs the raw response to classify a partial write. + 'session/use-mobile-session-terminal-send-actions.ts': 1, + // `worktree.create` from a task item; the creation adapter builds the composer's params instead. + 'tasks/use-mobile-tasks-workspace-create-actions.tsx': 1 +} + +/** Every remaining inline call site under the screen directories. Lower is the only allowed + * direction: later PRs move the rest, and nothing may add a new one. */ +const REMAINING_INLINE_CALL_SITES = 112 + +const SOURCE_ROOT = join(__dirname, '..') +const APP_ROOT = join(__dirname, '../..', 'app') + +/** Route files live outside `src/`, so the account screen is checked by its own path. */ +const ROUTED_APP_SCREENS = ['h/[hostId]/accounts.tsx'] as const + +function screenSources(): Array<{ path: string; source: string }> { + const found: Array<{ path: string; source: string }> = [] + const walk = (directory: string, prefix: string): void => { + for (const entry of readdirSync(directory, { withFileTypes: true })) { + const relative = `${prefix}${entry.name}` + if (entry.isDirectory()) { + walk(join(directory, entry.name), `${relative}/`) + continue + } + if (!/\.tsx?$/.test(entry.name) || NOT_SCREEN_CODE.test(relative)) { + continue + } + found.push({ path: relative, source: readFileSync(join(directory, entry.name), 'utf8') }) + } + } + for (const directory of SCREEN_DIRECTORIES) { + walk(join(SOURCE_ROOT, directory), `${directory}/`) + } + return found +} + +const countCalls = (source: string): number => (source.match(/sendRequest\(/g) ?? []).length + +describe('screen RPC ratchet', () => { + it('keeps every routed screen free of inline sendRequest', () => { + const regrown = [ + ...ROUTED_SCREENS.map((path) => [path, join(SOURCE_ROOT, path)] as const), + ...ROUTED_APP_SCREENS.map((path) => [path, join(APP_ROOT, path)] as const) + ] + .filter(([, absolute]) => countCalls(readFileSync(absolute, 'utf8')) > 0) + .map(([path]) => path) + expect(regrown).toEqual([]) + }) + + it('pins the calls left inline on purpose', () => { + const actual = Object.fromEntries( + Object.keys(DELIBERATE_INLINE_CALLS).map((path) => [ + path, + countCalls(readFileSync(join(SOURCE_ROOT, path), 'utf8')) + ]) + ) + expect(actual).toEqual(DELIBERATE_INLINE_CALLS) + }) + + it('never grows the screen-side RPC surface', () => { + const total = screenSources().reduce((sum, file) => sum + countCalls(file.source), 0) + expect(total).toBeLessThanOrEqual(REMAINING_INLINE_CALL_SITES) + }) +}) From 538bfd2bdd56bfd788f95fd90f24ab2ede3e2223 Mon Sep 17 00:00:00 2001 From: Jinwoo-H Date: Tue, 8 Sep 2026 23:07:36 -0400 Subject: [PATCH 05/40] fix(mobile): match main's observable behavior in the host adapters An adapter body has to be the inline call it replaced, so each place where a carried adapter answered differently from main is corrected here: - Linear: per-method timeouts and error strings as main sent them, no result check on selectWorkspace or updateIssue, "Sub-issue not found" and "Failed to create sub-issue" restored. - browser.tabCreate: the host's error message, main's 30s budget, and a tolerated missing page id. - terminal.clearBuffer: an ok:false reply keeps main's success toast. - Quick commands: only the load retries a logical cutover, and an empty error message falls back to main's per-operation copy. - Project rows: the pull-request mutations no longer require a repository slug; a row without one forwards prRepo: null, as main did. - worktree.listRetiredNames: a refused read reads as an empty registry again. - repo.hooks: the create sheet keeps its state on a refused read, while task create still fails on one. The paced-Escape route ref moves from render into a layout effect so the changed-code React Doctor gate passes; a timer cannot observe the ref between commit and layout, so the guard's timing is unchanged. Claude-Session: https://claude.ai/code/session_01JNnE9qzUZMMnqpZWCqM3nb --- .../use-new-workspace-setup-script.ts | 4 +- .../session/host-session-tab-operations.ts | 2 +- .../host-session-terminal-operations.ts | 2 + .../mobile-session-route-parity.test.ts | 6 +- ...e-host-session-quick-command-operations.ts | 36 ++++----- ...native-host-session-tab-operations.test.ts | 5 +- .../native-host-session-tab-operations.ts | 19 +++-- .../session/use-mobile-native-chat-stop.ts | 8 +- .../use-mobile-session-terminal-input.ts | 6 +- ...github-project-host-routing-source.test.ts | 12 ++- .../tasks/mobile-tasks-mutation-targets.ts | 1 + .../tasks/mobile-tasks-project-row-targets.ts | 22 ++++++ .../mobile-tasks-refactor-parity.test.ts | 8 +- ...tive-host-task-item-mutation-operations.ts | 15 +++- .../native-host-task-linear-operations.ts | 71 +++++++++++------- ...ative-host-task-project-file-operations.ts | 6 +- ...e-host-task-project-mutation-operations.ts | 73 +++++++++++++------ ...obile-tasks-project-file-merge-actions.tsx | 11 ++- ...ile-tasks-project-review-check-actions.tsx | 10 +-- .../host-workspace-catalog-operations.ts | 4 +- .../host-workspace-creation-operations.ts | 3 + ...host-workspace-creation-read-operations.ts | 15 +++- .../rpc-workspace-creation-operations.ts | 6 +- 23 files changed, 225 insertions(+), 120 deletions(-) diff --git a/mobile/src/components/use-new-workspace-setup-script.ts b/mobile/src/components/use-new-workspace-setup-script.ts index db81043210f3..233ff9ec080e 100644 --- a/mobile/src/components/use-new-workspace-setup-script.ts +++ b/mobile/src/components/use-new-workspace-setup-script.ts @@ -35,9 +35,9 @@ export function useNewWorkspaceSetupScript(args: { } let stale = false void operations - .readRepoHooks(selectedRepo.id) + .readRepoHooksIfAvailable(selectedRepo.id) .then((result) => { - if (stale) { + if (stale || !result) { return } const command = result.hooks?.scripts?.setup?.trim() || null diff --git a/mobile/src/session/host-session-tab-operations.ts b/mobile/src/session/host-session-tab-operations.ts index 8b8418ff80ab..554df8f6718f 100644 --- a/mobile/src/session/host-session-tab-operations.ts +++ b/mobile/src/session/host-session-tab-operations.ts @@ -31,7 +31,7 @@ export type HostSessionTabOperations = { workspaceId: string, commandId: string ): Promise - createBrowser(workspaceId: string, url: string): Promise<{ browserPageId: string }> + createBrowser(workspaceId: string, url: string): Promise<{ browserPageId?: string }> activate(workspaceId: string, tabId: string, leafId?: string): Promise close(workspaceId: string, tabId: string): Promise } diff --git a/mobile/src/session/host-session-terminal-operations.ts b/mobile/src/session/host-session-terminal-operations.ts index 6457df719cd2..10e3799e6465 100644 --- a/mobile/src/session/host-session-terminal-operations.ts +++ b/mobile/src/session/host-session-terminal-operations.ts @@ -64,6 +64,8 @@ export type HostSessionTerminalOperations = { enter: boolean, clientId: string | null ): Promise + /** Answers only for a terminal this same instance subscribed: the reply is dropped otherwise. + * A caller that routes query replies must route `subscribe` through the same instance too. */ sendQueryReply( terminalId: string, bytes: string, diff --git a/mobile/src/session/mobile-session-route-parity.test.ts b/mobile/src/session/mobile-session-route-parity.test.ts index bccdf4082533..dbf204dcd96c 100644 --- a/mobile/src/session/mobile-session-route-parity.test.ts +++ b/mobile/src/session/mobile-session-route-parity.test.ts @@ -70,7 +70,7 @@ const HEAD_CALLBACK_BODY_SHA256 = 'e66e6436cdb9a66e870c06fdfc140106502fbeddd8db4 const HEAD_EFFECT_SHA256 = 'd9ebfaabc1e79773cdada7ab370b20459ed972f1f8edce1652199f4d0391cd13' const HEAD_CONTENT_HOOK_SHA256 = '9c3b612fef3f370d66873aefdbe1d701f20cb64ded31fef5cc45fde6f8189581' const HEAD_NESTED_FUNCTION_SHA256 = - '5042c3622cbf32166e5a2af5a534ff0305ee9446e8fd607a4baf7ec3e485b7ba' + 'd0aada4091de4551fcb5edabad4aa84249799d2fd3244c0f7493eadb4fe3ba58' const HEAD_NATIVE_REGISTRATION_SHA256 = 'cab85e4e4a3f43289ba93ddea9ccce57aea83e0bf14fd1620a965aad0c1cb49e' const HEAD_NATIVE_REMOVAL_SHA256 = @@ -79,7 +79,7 @@ const HEAD_TIMER_CREATION_SHA256 = '1a31b625e2174c3db77272249843196d2b6b06ab1e654a96d8f7858e3082e66b' const HEAD_TIMER_CLEANUP_SHA256 = 'c73f1d1c2cc89642f3d727d6f3b6b81860a9d6f34234541a2065ec3d1a8cd116' const HEAD_RUNTIME_STRING_SHA256 = - 'd5cf66745d014a3848798f7fe388d2d3370e657451dd8353e19e972b07eec324' + 'f7e7d7a99d506589d1b620b86f39bbce97223ab7ad4143b1f06a6a8d8ab81f5b' const HEAD_HOST_JSX_SHA256 = '390405926b1695fa3a33686f0bc192b432f5468d8576499d7cafbb4922defbb5' const HEAD_LEAF_JSX_SHA256 = 'd5f1ef0db57c63eb3e4ee7c98e8483bc21882a151ce0ca24e42c7d1234e1dace' const HEAD_STYLE_REFERENCE_SHA256 = @@ -517,7 +517,7 @@ describe('mobile session route extraction parity', () => { it('preserves runtime strings, styles, and the expanded JSX tree', () => { const strings = readRuntimeStrings() - expect(strings).toHaveLength(523) + expect(strings).toHaveLength(522) expect(hash(strings)).toBe(HEAD_RUNTIME_STRING_SHA256) const jsx = readJsxFacts(readDefinitions()) expect(jsx.host).toHaveLength(124) diff --git a/mobile/src/session/native-host-session-quick-command-operations.ts b/mobile/src/session/native-host-session-quick-command-operations.ts index ad5e4f85c340..36a7ce9906da 100644 --- a/mobile/src/session/native-host-session-quick-command-operations.ts +++ b/mobile/src/session/native-host-session-quick-command-operations.ts @@ -1,7 +1,4 @@ -import { - parseNormalizedTerminalQuickCommands, - type TerminalQuickCommandMutation -} from '../terminal/quick-commands' +import { parseNormalizedTerminalQuickCommands } from '../terminal/quick-commands' import type { RpcClient } from '../transport/rpc-client' import { isLogicalClientCutoverError } from '../transport/stable-logical-rpc-client' import type { @@ -19,36 +16,31 @@ export function nativeHostSessionQuickCommandOperations( return { async snapshot(workspaceId, signal) { return quickCommandSnapshot( - await quickCommandRequest(client, 'settings.getTerminalQuickCommands', undefined, signal), + await loadWithCutoverRetry(client, signal), workspaceId, 'Failed to load quick commands' ) }, async mutate(workspaceId, mutation) { - return quickCommandSnapshot( - await quickCommandRequest(client, 'settings.updateTerminalQuickCommands', { - mutation - }), - workspaceId, - 'Failed to save quick command' - ) + // Why no cutover retry here: a quick-command mutation is not idempotent, so a replay + // after a logical cutover could apply the same edit twice. + const response = await client.sendRequest('settings.updateTerminalQuickCommands', { + mutation + }) + if (!response.ok) { + throw new Error(response.error.message || 'Failed to save quick command') + } + return quickCommandSnapshot(response.result, workspaceId, 'Failed to save quick command') } } } -async function quickCommandRequest( - client: RpcClient, - method: 'settings.getTerminalQuickCommands' | 'settings.updateTerminalQuickCommands', - params?: { mutation: TerminalQuickCommandMutation }, - signal?: AbortSignal -) { +async function loadWithCutoverRetry(client: RpcClient, signal?: AbortSignal) { for (let retry = 0; ; retry += 1) { try { - const response = params - ? await client.sendRequest(method, params) - : await client.sendRequest(method) + const response = await client.sendRequest('settings.getTerminalQuickCommands') if (!response.ok) { - throw new Error(response.error.message || 'quick_commands_failed') + throw new Error(response.error.message || 'Failed to load quick commands') } return response.result } catch (error) { diff --git a/mobile/src/session/native-host-session-tab-operations.test.ts b/mobile/src/session/native-host-session-tab-operations.test.ts index d064b683853d..59e55b0a57d5 100644 --- a/mobile/src/session/native-host-session-tab-operations.test.ts +++ b/mobile/src/session/native-host-session-tab-operations.test.ts @@ -74,7 +74,10 @@ describe('native host session tab operations', () => { worktree: 'id:workspace-1', url: 'https://example.com', activate: true - } + }, + // The caller carried this budget before the seam existed; a browser create that parks on + // reconnect leaves the composer spinning with no error. + { timeoutMs: 30_000 } ], [ 'session.tabs.activate', diff --git a/mobile/src/session/native-host-session-tab-operations.ts b/mobile/src/session/native-host-session-tab-operations.ts index c35f8b1ca316..084bdc9aed96 100644 --- a/mobile/src/session/native-host-session-tab-operations.ts +++ b/mobile/src/session/native-host-session-tab-operations.ts @@ -83,19 +83,18 @@ export function nativeHostSessionTabOperations(client: RpcClient): HostSessionTa ) }, async createBrowser(workspaceId, url) { - const response = await client.sendRequest('browser.tabCreate', { - worktree: `id:${workspaceId}`, - url, - activate: true - }) + const response = await client.sendRequest( + 'browser.tabCreate', + { worktree: `id:${workspaceId}`, url, activate: true }, + { timeoutMs: 30_000 } + ) if (!response.ok) { - throw new Error('browser_create_failed') + throw new Error(response.error.message) } + // A host that answers without a page id still created the tab; the caller only loses the + // focus hint, so this is not a create failure. const result = (response as RpcSuccess).result as { browserPageId?: unknown } - if (typeof result.browserPageId !== 'string') { - throw new Error('browser_create_failed') - } - return { browserPageId: result.browserPageId } + return typeof result.browserPageId === 'string' ? { browserPageId: result.browserPageId } : {} }, async activate(workspaceId, tabId, leafId) { // Why: a relay-to-direct cutover rejects the in-flight request; activation is idempotent, diff --git a/mobile/src/session/use-mobile-native-chat-stop.ts b/mobile/src/session/use-mobile-native-chat-stop.ts index 2b66a860d947..8dd8aa4f6545 100644 --- a/mobile/src/session/use-mobile-native-chat-stop.ts +++ b/mobile/src/session/use-mobile-native-chat-stop.ts @@ -1,4 +1,4 @@ -import { useCallback, useEffect, useRef, type MutableRefObject } from 'react' +import { useCallback, useEffect, useLayoutEffect, useRef, type MutableRefObject } from 'react' import type { HostSessionNativeChatOperations } from './host-session-native-chat-operations' import { mobileNativeChatOperationTarget } from './mobile-native-chat-operation-target' import { openMobileNativeChatSendBudget } from './mobile-native-chat-send' @@ -30,7 +30,11 @@ export function useMobileNativeChatStop(args: { * never happen. */ const dropSecondEscapeRef = useRef<(() => void) | null>(null) const activeRouteRef = useRef({ operations, enabled, streamIdentity }) - activeRouteRef.current = { operations, enabled, streamIdentity } + // Layout, not render or a passive Effect: the paced Escape fires from a timer, and only a + // synchronous post-commit write guarantees it never reads a route the render discarded. + useLayoutEffect(() => { + activeRouteRef.current = { operations, enabled, streamIdentity } + }, [operations, enabled, streamIdentity]) const cancelSecondEscape = useCallback(() => { if (timerRef.current) { clearTimeout(timerRef.current) diff --git a/mobile/src/session/use-mobile-session-terminal-input.ts b/mobile/src/session/use-mobile-session-terminal-input.ts index 79b0352b1b49..db31020ca3b1 100644 --- a/mobile/src/session/use-mobile-session-terminal-input.ts +++ b/mobile/src/session/use-mobile-session-terminal-input.ts @@ -224,9 +224,9 @@ export function useMobileSessionTerminalInput(scope: MobileSessionFileActionsMod } getTerminalRef(target.handle)?.clear() try { - if (!(await sessionOperations.terminal.clear(target.handle))) { - throw new Error('terminal_clear_failed') - } + // Why the result is ignored: a host that answers `ok: false` still cleared the local + // buffer above, and only a transport failure told the user the clear did not happen. + await sessionOperations.terminal.clear(target.handle) showToast('Terminal cleared') } catch { showToast("Couldn't clear terminal", 1500) diff --git a/mobile/src/tasks/github-project-host-routing-source.test.ts b/mobile/src/tasks/github-project-host-routing-source.test.ts index be992ed4558c..92e80628b6a6 100644 --- a/mobile/src/tasks/github-project-host-routing-source.test.ts +++ b/mobile/src/tasks/github-project-host-routing-source.test.ts @@ -45,13 +45,19 @@ describe('mobile GitHub Project host routing boundary', () => { it('pins Project-row PR actions to the row repository identity', () => { // Every Project-row action resolves its target from the row plus the active Project host. - const targets = [...compositionSource.matchAll(/projectRowMutationTarget\(([^)]*)\)/g)] + const targets = [ + ...compositionSource.matchAll(/projectRow(?:Mutation|PullRequest)Target\(([^)]*)\)/g) + ] expect(targets.length).toBeGreaterThan(10) for (const target of targets) { expect(target[1].replace(/\s+/g, ' ').trim()).toBe('row, activeGitHubProjectHost') } - // The target type carries the host that the PR mutations forward as prRepo. - expect(projectMutationAdapter).toContain('prRepo: slugPayload(target)') + // The target type carries the host that the PR mutations forward as prRepo, and a row with + // no slug forwards null rather than being refused. + expect(projectMutationAdapter).toContain('prRepo: prRepoPayload(target)') + expect(projectMutationAdapter).toMatch( + /function prRepoPayload\(target: HostTaskProjectItemTarget\) \{\s*return target\.owner && target\.repo/ + ) for (const method of [ 'fetchResolveReviewThread', 'fetchAddPRReviewCommentReply', diff --git a/mobile/src/tasks/mobile-tasks-mutation-targets.ts b/mobile/src/tasks/mobile-tasks-mutation-targets.ts index cf82d2d5112c..851b0ec7e28f 100644 --- a/mobile/src/tasks/mobile-tasks-mutation-targets.ts +++ b/mobile/src/tasks/mobile-tasks-mutation-targets.ts @@ -9,6 +9,7 @@ import type { TaskItem } from './mobile-tasks-project-workspace-types' export { projectRowIdentityTarget, projectRowMutationTarget, + projectRowPullRequestTarget, projectRowSlugTarget } from './mobile-tasks-project-row-targets' diff --git a/mobile/src/tasks/mobile-tasks-project-row-targets.ts b/mobile/src/tasks/mobile-tasks-project-row-targets.ts index e24f73b22e3a..25b2442711e3 100644 --- a/mobile/src/tasks/mobile-tasks-project-row-targets.ts +++ b/mobile/src/tasks/mobile-tasks-project-row-targets.ts @@ -24,6 +24,28 @@ export function projectRowMutationTarget( : null } +/** + * For the pull-request mutations the host addresses by number, carrying the slug only as + * optional `prRepo` decoration: reviewers, check reruns, merges and file-viewed state. The slug + * is not required, because a row without one still names a pull request the host can act on. + */ +export function projectRowPullRequestTarget( + row: GitHubProjectRow, + host: string +): HostTaskProjectItemTarget | null { + const slug = splitRepositorySlug(row.content.repository) + const type = projectRowType(row) + return type && row.content.number + ? { + owner: slug?.owner ?? '', + repo: slug?.repo ?? '', + host, + number: row.content.number, + type + } + : null +} + /** * For mutations the host addresses by repository slug and comment id — the `*BySlug` comment * edits. They read no issue number and no issue/PR kind, so requiring those refused rows diff --git a/mobile/src/tasks/mobile-tasks-refactor-parity.test.ts b/mobile/src/tasks/mobile-tasks-refactor-parity.test.ts index 9f5844bbb5c2..63eb851d792d 100644 --- a/mobile/src/tasks/mobile-tasks-refactor-parity.test.ts +++ b/mobile/src/tasks/mobile-tasks-refactor-parity.test.ts @@ -25,11 +25,11 @@ const hash = (parts: string[] | string): string => * plus the row-target locals the adapters take in place of inline slug/number checks. Diff hooks, * declarations and styles are untouched. */ -const SCREEN_HOOKS = 'e7c47c8624d0c51100d1704cd7865a022d1ea372ad659c1f9d2581afa9e0de6a' +const SCREEN_HOOKS = 'b5d85ab1cd2996a6986604caf497c8a577dc118b095c49d555c576d98f48148f' const DIFF_HOOKS = '93c7189b32bed8456cc51814fffa8ce80cf62011ef968a9d53ddec2b9686f58f' -const STATEMENTS = '268d9cebe985c14b35052128ce985e81306d4507aae49a6301c165dc65d93337' +const STATEMENTS = '1d059c8359400f2aedb16c94a7dba0c8a21b5a06edb45e2b0b7ff0317250d564' const DECLARATIONS = 'cff54172af17a877789be1479c2eb6ca97d83c3e31dd831cd59395962f2b4c4a' -const SEMANTICS = '69cfc4f59322d1050b47f7028171ef5c9cbda6c3e51878676ecf9be68122affa' +const SEMANTICS = 'f767906884b93537f2c6369d6d0bd2d4cb39b4314c31cca9d8f9e5e9b78a75ee' const STYLES = '1db6af69c791d9963928541ad5310942fcbda6d984b422c90b6eb92b6816579a' const RENDER_TREE = 'a959c6712c70024127a429a47ae7689c629393752fa99a1ac6ba311d0bf13ca6' @@ -58,7 +58,7 @@ describe('Mobile Tasks refactor parity', () => { it('preserves RPC calls, runtime strings, and JSX host signatures', () => { const semantics = readMobileTasksSemanticSource() - expect(semantics.split('\n')).toHaveLength(3_276) + expect(semantics.split('\n')).toHaveLength(3_278) expect(hash(semantics)).toBe(SEMANTICS) }) diff --git a/mobile/src/tasks/native-host-task-item-mutation-operations.ts b/mobile/src/tasks/native-host-task-item-mutation-operations.ts index 59f385bee777..7f30a1efa8cb 100644 --- a/mobile/src/tasks/native-host-task-item-mutation-operations.ts +++ b/mobile/src/tasks/native-host-task-item-mutation-operations.ts @@ -14,14 +14,25 @@ export function nativeHostTaskItemMutationOperations( target.provider === 'github' ? await setGitHubClosed(client, target, closed) : await setGitLabClosed(client, target, closed) - assertMutation(response, 'Failed to update task status') + // Provider-keyed, because each caller reported its own provider's wording before the seam. + assertMutation( + response, + target.provider === 'github' + ? 'Failed to update GitHub status' + : 'Failed to update GitLab item' + ) }, async updateMetadata(target, updates) { const response = target.provider === 'github' ? await updateGitHubMetadata(client, target, updates) : await updateGitLabMetadata(client, target, updates) - assertMutation(response, 'Failed to update task') + assertMutation( + response, + target.provider === 'github' + ? 'Failed to update GitHub issue' + : 'Failed to update GitLab item' + ) } } } diff --git a/mobile/src/tasks/native-host-task-linear-operations.ts b/mobile/src/tasks/native-host-task-linear-operations.ts index 4f2fd3c2679e..1f763b583936 100644 --- a/mobile/src/tasks/native-host-task-linear-operations.ts +++ b/mobile/src/tasks/native-host-task-linear-operations.ts @@ -1,5 +1,10 @@ import type { HostTaskLinearOperations } from './host-task-linear-operations' import type { RpcRequestSender } from '../transport/rpc-client' +import type { SendRequestOptions } from '../transport/rpc-client' + +/** The interactive Linear writes carry their own budget; the reads that only feed a picker do + * not, so a slow host degrades the picker instead of the whole screen. */ +const INTERACTIVE: SendRequestOptions = { timeoutMs: 30_000 } export function nativeHostTaskLinearOperations(client: RpcRequestSender): HostTaskLinearOperations { return { @@ -16,26 +21,23 @@ export function nativeHostTaskLinearOperations(client: RpcRequestSender): HostTa workspaceId: target.workspaceId }), async selectWorkspace(workspaceId) { - assertMutation( - await request(client, 'linear.selectWorkspace', { workspaceId }), - 'Failed to select workspace' - ) + // Why no result check: the picker already switched, and it reloads the Linear context next. + // A rejected switch surfaces through that reload, not as a second error on the same tap. + await client.sendRequest('linear.selectWorkspace', { workspaceId }) }, async updateState(target, stateId) { - assertMutation( - await request(client, 'linear.updateIssue', { - id: target.issueId, - workspaceId: target.workspaceId, - updates: { stateId } - }), - 'Failed to update Linear issue' - ) + await request(client, 'linear.updateIssue', { + id: target.issueId, + workspaceId: target.workspaceId, + updates: { stateId } + }) }, async addComment(target, body) { const result = await request<{ ok?: boolean; id?: string; error?: string }>( client, 'linear.addIssueComment', - { issueId: target.issueId, workspaceId: target.workspaceId, body } + { issueId: target.issueId, workspaceId: target.workspaceId, body }, + INTERACTIVE ) assertMutation(result, 'Failed to add comment') return result.id @@ -43,21 +45,32 @@ export function nativeHostTaskLinearOperations(client: RpcRequestSender): HostTa async loadIssue(target) { const issue = await request - > | null>(client, 'linear.getIssue', { id: target.issueId, workspaceId: target.workspaceId }) + > | null>( + client, + 'linear.getIssue', + { id: target.issueId, workspaceId: target.workspaceId }, + INTERACTIVE + ) if (!issue) { - throw new Error('Linear issue not found') + throw new Error('Sub-issue not found') } return issue }, async createSubIssue(target, title) { return createdIssue( - await request(client, 'linear.createIssue', { - teamId: target.teamId, - title, - workspaceId: target.workspaceId, - parentIssueId: target.issueId, - projectId: target.projectId ?? null - }) + await request( + client, + 'linear.createIssue', + { + teamId: target.teamId, + title, + workspaceId: target.workspaceId, + parentIssueId: target.issueId, + projectId: target.projectId ?? null + }, + INTERACTIVE + ), + 'Failed to create sub-issue' ) }, async createIssue(payload) { @@ -67,7 +80,8 @@ export function nativeHostTaskLinearOperations(client: RpcRequestSender): HostTa title: payload.title, description: payload.description, workspaceId: payload.team.workspaceId - }) + }), + 'Failed to create Linear issue' ) } } @@ -76,9 +90,12 @@ export function nativeHostTaskLinearOperations(client: RpcRequestSender): HostTa async function request( client: RpcRequestSender, method: string, - payload?: object + payload?: object, + options?: SendRequestOptions ): Promise { - const response = await client.sendRequest(method, payload, { timeoutMs: 30_000 }) + const response = options + ? await client.sendRequest(method, payload, options) + : await client.sendRequest(method, payload) if (!response.ok) { throw new Error(response.error?.message ?? 'Task request failed') } @@ -94,7 +111,7 @@ function assertMutation( } } -function createdIssue(result: unknown) { +function createdIssue(result: unknown, fallback: string) { const issue = result as { ok?: boolean id?: string @@ -104,7 +121,7 @@ function createdIssue(result: unknown) { error?: string } if (issue.ok === false || !issue.id || !issue.identifier) { - throw new Error(issue.error ?? 'Failed to create Linear issue') + throw new Error(issue.error ?? fallback) } return { id: issue.id, diff --git a/mobile/src/tasks/native-host-task-project-file-operations.ts b/mobile/src/tasks/native-host-task-project-file-operations.ts index 126bbf0eae3a..978fb9250275 100644 --- a/mobile/src/tasks/native-host-task-project-file-operations.ts +++ b/mobile/src/tasks/native-host-task-project-file-operations.ts @@ -55,7 +55,11 @@ export function nativeHostTaskProjectFileOperations( function repoPayload(target: HostTaskProjectItemTarget, repoId: string) { return { repo: `id:${repoId}`, - prRepo: { owner: target.owner, repo: target.repo, host: target.host } + // Null when the row carries no slug: that is what the screens sent before this seam. + prRepo: + target.owner && target.repo + ? { owner: target.owner, repo: target.repo, host: target.host } + : null } } diff --git a/mobile/src/tasks/native-host-task-project-mutation-operations.ts b/mobile/src/tasks/native-host-task-project-mutation-operations.ts index 3f2f5dd339cf..a7e304da850d 100644 --- a/mobile/src/tasks/native-host-task-project-mutation-operations.ts +++ b/mobile/src/tasks/native-host-task-project-mutation-operations.ts @@ -86,10 +86,11 @@ export function nativeHostTaskProjectMutationOperations( await fetchResolveReviewThread(client, repoId, { threadId, resolve, - // Why: `prRepo` is fork/GHES decoration the host treats as optional, and a draft row + // Why: a draft row // has no slug — send it only when one resolved rather than an empty pair. - prRepo: target.owner && target.repo ? slugPayload(target) : null - }) + prRepo: prRepoPayload(target) + }), + 'Failed to resolve thread' ) }, async replyReviewComment(target, repoId, payload) { @@ -97,8 +98,9 @@ export function nativeHostTaskProjectMutationOperations( await fetchAddPRReviewCommentReply(client, repoId, { prNumber: target.number, ...payload, - prRepo: slugPayload(target) - }) + prRepo: prRepoPayload(target) + }), + 'Failed to reply' ) }, async addConversationComment(target, repoId, body) { @@ -106,9 +108,10 @@ export function nativeHostTaskProjectMutationOperations( await fetchAddIssueComment(client, repoId, { prNumber: target.number, body, - prRepo: slugPayload(target), + prRepo: prRepoPayload(target), type: target.type - }) + }), + 'Failed to reply' ) }, async requestReviewers(target, repoId, reviewers) { @@ -116,8 +119,9 @@ export function nativeHostTaskProjectMutationOperations( await fetchRequestPRReviewers(client, repoId, { prNumber: target.number, reviewers, - prRepo: slugPayload(target) - }) + prRepo: prRepoPayload(target) + }), + 'Failed to request reviewers' ) }, async rerunChecks(target, repoId, payload) { @@ -125,10 +129,11 @@ export function nativeHostTaskProjectMutationOperations( await fetchRerunPRChecks( client, repoId, - { prNumber: target.number, ...payload, prRepo: slugPayload(target) }, + { prNumber: target.number, ...payload, prRepo: prRepoPayload(target) }, // A CI rerun and a merge both routinely outrun the 30s default. { timeoutMs: PROJECT_PR_MUTATION_TIMEOUT_MS } - ) + ), + 'Failed to rerun checks' ) }, async merge(target, repoId, method) { @@ -136,14 +141,23 @@ export function nativeHostTaskProjectMutationOperations( await fetchMergePR( client, repoId, - { prNumber: target.number, method, prRepo: slugPayload(target) }, + { prNumber: target.number, method, prRepo: prRepoPayload(target) }, { timeoutMs: PROJECT_PR_MUTATION_TIMEOUT_MS } - ) + ), + 'Failed to merge pull request' ) } } } +/** Fork/GHES decoration the host treats as optional. A row with no repository slug sent `null` + * before this seam existed, so refusing the whole call here would lose a working path. */ +function prRepoPayload(target: HostTaskProjectItemTarget) { + return target.owner && target.repo + ? { owner: target.owner, repo: target.repo, host: target.host } + : null +} + function slugPayload(target: HostTaskProjectItemTarget) { return { owner: target.owner, @@ -153,35 +167,52 @@ function slugPayload(target: HostTaskProjectItemTarget) { } } +/** The wording each caller reported for a refused mutation before these calls moved behind the + * seam. A host that refuses without a message must still name the action that failed. */ +const PROJECT_MUTATION_FALLBACKS: Record = { + 'github.project.updateIssueBySlug': 'Failed to update GitHub item', + 'github.project.updatePullRequestBySlug': 'Failed to update GitHub item', + 'github.project.addIssueCommentBySlug': 'Failed to add comment', + 'github.project.updateIssueCommentBySlug': 'Failed to edit comment', + 'github.project.deleteIssueCommentBySlug': 'Failed to delete comment', + 'github.project.updateItemField': 'Failed to update project field', + 'github.project.clearItemField': 'Failed to update project field', + 'github.project.updateIssueTypeBySlug': 'Failed to update issue type' +} + async function projectMutation( client: RpcRequestSender, method: string, payload: object ): Promise { + const fallback = PROJECT_MUTATION_FALLBACKS[method] ?? 'GitHub Project request failed' const response = (await client.sendRequest(method, payload, { timeoutMs: 30_000 })) as { ok: boolean result?: { ok?: boolean; error?: string | { message?: string } } error?: { message?: string } } if (!response.ok) { - throw new Error(response.error?.message ?? 'GitHub Project request failed') + throw new Error(response.error?.message ?? fallback) } if (response.result?.ok === false) { const error = response.result.error - throw new Error( - typeof error === 'string' ? error : (error?.message ?? 'GitHub Project request failed') - ) + throw new Error(typeof error === 'string' ? error : (error?.message ?? fallback)) } return (response.result ?? {}) as T } -function requirePrMutation(result: GitHubPrMutationOutcome): void { +function requirePrMutation(result: GitHubPrMutationOutcome, fallback: string): void { if (!result.ok) { - throw new Error(result.error) + // The wrapper mints `Request failed: ` when the host says nothing; the caller's own + // wording is what the user read before these calls moved behind the seam. + throw new Error(result.error.startsWith('Request failed: ') ? fallback : result.error) } } -function prMutationComment(result: GitHubPrMutationOutcome): DetailComment | undefined { - requirePrMutation(result) +function prMutationComment( + result: GitHubPrMutationOutcome, + fallback: string +): DetailComment | undefined { + requirePrMutation(result, fallback) return (result as { comment?: DetailComment }).comment } diff --git a/mobile/src/tasks/use-mobile-tasks-project-file-merge-actions.tsx b/mobile/src/tasks/use-mobile-tasks-project-file-merge-actions.tsx index a8cfff17a079..4c5125dc3d7b 100644 --- a/mobile/src/tasks/use-mobile-tasks-project-file-merge-actions.tsx +++ b/mobile/src/tasks/use-mobile-tasks-project-file-merge-actions.tsx @@ -7,7 +7,10 @@ import type { HostedReviewMergeMethod, TaskItem } from './mobile-tasks-legacy-foundation' -import { projectRowMutationTarget, taskItemMutationTarget } from './mobile-tasks-mutation-targets' +import { + projectRowPullRequestTarget, + taskItemMutationTarget +} from './mobile-tasks-mutation-targets' export function useMobileTasksProjectFileMergeActions(model: ProjectReviewCheckActionsModel) { const { @@ -45,7 +48,7 @@ export function useMobileTasksProjectFileMergeActions(model: ProjectReviewCheckA return } const repo = findProjectRowRepo(row) - const target = projectRowMutationTarget(row, activeGitHubProjectHost) + const target = projectRowPullRequestTarget(row, activeGitHubProjectHost) if ( !taskOperations || row.itemType !== 'PULL_REQUEST' || @@ -90,7 +93,7 @@ export function useMobileTasksProjectFileMergeActions(model: ProjectReviewCheckA const addProjectGitHubFileReviewComment = useCallback( async (row: GitHubProjectRow, file: GitHubDetailFile, line: number): Promise => { const repo = findProjectRowRepo(row) - const target = projectRowMutationTarget(row, activeGitHubProjectHost) + const target = projectRowPullRequestTarget(row, activeGitHubProjectHost) if ( !taskOperations || projectMutating || @@ -157,7 +160,7 @@ export function useMobileTasksProjectFileMergeActions(model: ProjectReviewCheckA const mergeProjectGitHubPullRequest = useCallback( async (row: GitHubProjectRow, method: HostedReviewMergeMethod): Promise => { const repo = findProjectRowRepo(row) - const target = projectRowMutationTarget(row, activeGitHubProjectHost) + const target = projectRowPullRequestTarget(row, activeGitHubProjectHost) if ( !taskOperations || projectMutating || diff --git a/mobile/src/tasks/use-mobile-tasks-project-review-check-actions.tsx b/mobile/src/tasks/use-mobile-tasks-project-review-check-actions.tsx index 6f8621db38d8..e5b739dc0f66 100644 --- a/mobile/src/tasks/use-mobile-tasks-project-review-check-actions.tsx +++ b/mobile/src/tasks/use-mobile-tasks-project-review-check-actions.tsx @@ -6,7 +6,7 @@ import { type GitHubProjectRow, splitReviewerList } from './mobile-tasks-legacy-foundation' -import { projectRowMutationTarget } from './mobile-tasks-mutation-targets' +import { projectRowPullRequestTarget } from './mobile-tasks-mutation-targets' export function useMobileTasksProjectReviewCheckActions(model: ProjectMetadataActionsModel) { const { @@ -25,7 +25,7 @@ export function useMobileTasksProjectReviewCheckActions(model: ProjectMetadataAc const requestProjectGitHubReviewers = useCallback( async (row: GitHubProjectRow, logins?: string[]): Promise => { const repo = findProjectRowRepo(row) - const target = projectRowMutationTarget(row, activeGitHubProjectHost) + const target = projectRowPullRequestTarget(row, activeGitHubProjectHost) if ( !taskOperations || projectMutating || @@ -92,7 +92,7 @@ export function useMobileTasksProjectReviewCheckActions(model: ProjectMetadataAc const refreshProjectGitHubChecks = useCallback( async (row: GitHubProjectRow): Promise => { const repo = findProjectRowRepo(row) - const target = projectRowMutationTarget(row, activeGitHubProjectHost) + const target = projectRowPullRequestTarget(row, activeGitHubProjectHost) if ( !taskOperations || projectMutating || @@ -125,7 +125,7 @@ export function useMobileTasksProjectReviewCheckActions(model: ProjectMetadataAc const rerunProjectGitHubChecks = useCallback( async (row: GitHubProjectRow, failedOnly: boolean): Promise => { const repo = findProjectRowRepo(row) - const target = projectRowMutationTarget(row, activeGitHubProjectHost) + const target = projectRowPullRequestTarget(row, activeGitHubProjectHost) if ( !taskOperations || projectMutating || @@ -157,7 +157,7 @@ export function useMobileTasksProjectReviewCheckActions(model: ProjectMetadataAc const toggleProjectGitHubFileViewed = useCallback( async (row: GitHubProjectRow, file: GitHubDetailFile): Promise => { const repo = findProjectRowRepo(row) - const target = projectRowMutationTarget(row, activeGitHubProjectHost) + const target = projectRowPullRequestTarget(row, activeGitHubProjectHost) if ( !taskOperations || projectMutating || diff --git a/mobile/src/worktree/host-workspace-catalog-operations.ts b/mobile/src/worktree/host-workspace-catalog-operations.ts index d63bfbd6f3d2..ac43f47f6adf 100644 --- a/mobile/src/worktree/host-workspace-catalog-operations.ts +++ b/mobile/src/worktree/host-workspace-catalog-operations.ts @@ -33,7 +33,7 @@ export type HostWorkspaceCatalogOperations = { sleepWorkspace(workspaceId: string): Promise notifyForeground(): void subscribeChanges(listener: (event: HostWorkspaceChange) => void): () => void - // Why: a hosted page reads `connected` from the shell's relayed snapshot, so it can issue its - // first catalog request a beat before that socket serves one. A direct socket omits this. + // Why: a provider that relays connection state can report `connected` a beat before its + // socket serves a catalog request. A direct socket omits this, so the flag is optional. readonly connectionStateIsRelayed?: boolean } diff --git a/mobile/src/worktree/host-workspace-creation-operations.ts b/mobile/src/worktree/host-workspace-creation-operations.ts index 5fee7251d743..4ca39de323e5 100644 --- a/mobile/src/worktree/host-workspace-creation-operations.ts +++ b/mobile/src/worktree/host-workspace-creation-operations.ts @@ -89,6 +89,9 @@ export type HostWorkspaceCreationOperations = { connectSsh(targetId: string): Promise detectAgents(connectionId: string | null): Promise readRepoHooks(repoId: string): Promise + /** Null when the host refuses the read. The create sheet keeps whatever it already showed + * rather than replacing it with a "no setup script" answer it cannot stand behind. */ + readRepoHooksIfAvailable(repoId: string): Promise readRuntimeCapabilities(): Promise listSparsePresets(repoId: string): Promise saveSparsePreset( diff --git a/mobile/src/worktree/native-host-workspace-creation-read-operations.ts b/mobile/src/worktree/native-host-workspace-creation-read-operations.ts index cb13a1caae0f..ab1800349093 100644 --- a/mobile/src/worktree/native-host-workspace-creation-read-operations.ts +++ b/mobile/src/worktree/native-host-workspace-creation-read-operations.ts @@ -23,6 +23,7 @@ type ReadOperations = Pick< | 'connectSsh' | 'detectAgents' | 'readRepoHooks' + | 'readRepoHooksIfAvailable' | 'readRuntimeCapabilities' > @@ -37,10 +38,12 @@ export function nativeHostWorkspaceCreationReadOperations( return result.repos }, async readRetiredWorktreeNames(repoId) { - const result = await successfulResult( - client.sendRequest('worktree.listRetiredNames', { repo: `id:${repoId}` }) - ) - return readRetiredNameRegistryForRepo(result, repoId) + // Why no ok check: a refused read must read as an empty registry, not as a failure. The + // caller holds its previous answer on a failure, which would keep offering a spent name. + const response = await client.sendRequest('worktree.listRetiredNames', { + repo: `id:${repoId}` + }) + return readRetiredNameRegistryForRepo((response as { result?: unknown }).result, repoId) }, async readRuntimeSettings() { const result = await successfulResult<{ settings: NewWorkspaceRuntimeSettings }>( @@ -90,6 +93,10 @@ export function nativeHostWorkspaceCreationReadOperations( client.sendRequest('repo.hooks', { repo: `id:${repoId}` }) ) }, + async readRepoHooksIfAvailable(repoId) { + const response = await client.sendRequest('repo.hooks', { repo: `id:${repoId}` }) + return response.ok ? ((response as RpcSuccess).result as NewWorkspaceRepoHooks) : null + }, readRuntimeCapabilities() { return readNewWorktreeRuntimeCapabilities(client) } diff --git a/mobile/src/worktree/rpc-workspace-creation-operations.ts b/mobile/src/worktree/rpc-workspace-creation-operations.ts index 0a411d65fc43..051deca5ba1a 100644 --- a/mobile/src/worktree/rpc-workspace-creation-operations.ts +++ b/mobile/src/worktree/rpc-workspace-creation-operations.ts @@ -9,9 +9,9 @@ export type RpcWorkspaceCreationOperations = Omit< 'createBlankWorkspace' | 'createWorkspaceFromSource' > -/** Every workspace-creation call that is a plain desktop request. The native app passes its socket - * and the hosted page passes a bridge-backed sender, so neither side owns a second copy. Creation - * itself is excluded: it needs connection state for its retry, which a sender cannot report. */ +/** Every workspace-creation call that is a plain desktop request, written against a bare request + * sender so any non-socket provider can supply one without a second copy. Creation itself is + * excluded: it needs connection state for its retry, which a sender cannot report. */ export function rpcWorkspaceCreationOperations( client: RpcRequestSender ): RpcWorkspaceCreationOperations { From 654db50c0eec209a005c1079bd78aa4f681241e3 Mon Sep 17 00:00:00 2001 From: Jinwoo-H Date: Tue, 8 Sep 2026 23:15:50 -0400 Subject: [PATCH 06/40] fix(mobile): keep two adapter improvements over the calls they replaced Two refusals the old inline calls dropped are now reported, because dropping them is a bug rather than behavior worth preserving: - linear.selectWorkspace: a refused switch reaches the picker's error instead of leaving it showing a workspace the host never selected. - worktree.listRetiredNames: a refused read fails rather than reading as an empty registry, so the create sheet keeps its previous answer instead of offering a name that is already spent. This is the policy src/shared/worktree/retired-name-cache.ts documents. Every other adapter still answers exactly as the call it replaced did. Claude-Session: https://claude.ai/code/session_01JNnE9qzUZMMnqpZWCqM3nb --- .../src/tasks/native-host-task-linear-operations.ts | 9 ++++++--- ...ative-host-workspace-creation-read-operations.ts | 13 +++++++------ 2 files changed, 13 insertions(+), 9 deletions(-) diff --git a/mobile/src/tasks/native-host-task-linear-operations.ts b/mobile/src/tasks/native-host-task-linear-operations.ts index 1f763b583936..53e6bd98ad59 100644 --- a/mobile/src/tasks/native-host-task-linear-operations.ts +++ b/mobile/src/tasks/native-host-task-linear-operations.ts @@ -21,9 +21,12 @@ export function nativeHostTaskLinearOperations(client: RpcRequestSender): HostTa workspaceId: target.workspaceId }), async selectWorkspace(workspaceId) { - // Why no result check: the picker already switched, and it reloads the Linear context next. - // A rejected switch surfaces through that reload, not as a second error on the same tap. - await client.sendRequest('linear.selectWorkspace', { workspaceId }) + // Deliberate improvement over the call this replaced: that one dropped a refusal on the + // floor, leaving the picker showing a workspace the host never switched to. + assertMutation( + await request(client, 'linear.selectWorkspace', { workspaceId }), + 'Failed to select workspace' + ) }, async updateState(target, stateId) { await request(client, 'linear.updateIssue', { diff --git a/mobile/src/worktree/native-host-workspace-creation-read-operations.ts b/mobile/src/worktree/native-host-workspace-creation-read-operations.ts index ab1800349093..199135303550 100644 --- a/mobile/src/worktree/native-host-workspace-creation-read-operations.ts +++ b/mobile/src/worktree/native-host-workspace-creation-read-operations.ts @@ -38,12 +38,13 @@ export function nativeHostWorkspaceCreationReadOperations( return result.repos }, async readRetiredWorktreeNames(repoId) { - // Why no ok check: a refused read must read as an empty registry, not as a failure. The - // caller holds its previous answer on a failure, which would keep offering a spent name. - const response = await client.sendRequest('worktree.listRetiredNames', { - repo: `id:${repoId}` - }) - return readRetiredNameRegistryForRepo((response as { result?: unknown }).result, repoId) + // Deliberate improvement over the call this replaced: that one read a refusal as an empty + // registry, so a failed poll offered a spent name back. Failing lets the caller keep its + // previous answer, which is the policy `retired-name-cache` documents. + const result = await successfulResult( + client.sendRequest('worktree.listRetiredNames', { repo: `id:${repoId}` }) + ) + return readRetiredNameRegistryForRepo(result, repoId) }, async readRuntimeSettings() { const result = await successfulResult<{ settings: NewWorkspaceRuntimeSettings }>( From 1b86a6842bae02eef83e9ee81333f6dd3b619c0d Mon Sep 17 00:00:00 2001 From: Jinwoo-H Date: Wed, 9 Sep 2026 00:32:31 -0400 Subject: [PATCH 07/40] fix(mobile): close the seven defects the adapter review found - Clear terminal consumes the boolean the adapter returns, so a clear that never reached the host no longer toasts success. - A refused `@`-autocomplete search returns null instead of an empty list, so the failure is not cached and the next keystroke retries. - The Linear workspace picker reloads the host's context on both outcomes, and `selectWorkspace` detects a refusal by the id the host echoes back, since it answers a refusal with its unchanged status and no `ok` field. - `read.loadLinearContext` splits into `linearStatus` and `linearTeams`, so the screen commits the workspace list and the resolved selection before it asks for teams, as it did before the seam existed. - Resolving a review thread reports the host's message for a transport failure and the caller's wording only for a refusal, in both the item and the Projects lane. - The RPC ratchet matches the identifier rather than `sendRequest(`, counts client subscriptions, walks every source directory and all of `mobile/app`, classifies adapters by path, and pins each remaining site by file. Verified against bind, bracket access, a space before the paren, an aliased client, a helper in another directory and an adapter-shaped new file. - Deletes the adapter families nothing constructs (file preview, workspace catalog and the workspace group), the dead device wiring, and the three methods that shadowed a live call with different behavior. Claude-Session: https://claude.ai/code/session_01JNnE9qzUZMMnqpZWCqM3nb --- mobile/src/device/device-operations.ts | 22 +- mobile/src/device/native-device-operations.ts | 40 -- .../src/files/default-host-file-operations.ts | 10 - .../default-host-file-preview-operations.ts | 10 - mobile/src/files/host-file-operations.ts | 9 - .../src/files/host-file-preview-operations.ts | 27 -- .../src/files/native-host-file-operations.ts | 14 - .../native-host-file-preview-operations.ts | 25 -- .../host-session-native-chat-operations.ts | 4 +- .../session/host-session-tab-operations.ts | 5 - .../host-session-terminal-operations.ts | 8 - .../mobile-session-route-parity.test.ts | 2 +- .../native-host-session-browser-operations.ts | 11 +- ...ive-host-session-native-chat-operations.ts | 6 +- ...native-host-session-tab-operations.test.ts | 30 +- .../native-host-session-tab-operations.ts | 39 -- ...e-host-session-terminal-operations.test.ts | 26 -- ...native-host-session-terminal-operations.ts | 19 +- ...use-mobile-native-chat-file-search.test.ts | 28 ++ .../use-mobile-native-chat-file-search.ts | 6 +- .../use-mobile-session-terminal-input.ts | 7 +- mobile/src/tasks/host-task-read-operations.ts | 10 +- .../src/tasks/host-task-runtime-payloads.ts | 5 +- mobile/src/tasks/linear-status-projection.ts | 13 + .../src/tasks/mobile-tasks-filter-pickers.tsx | 10 +- .../mobile-tasks-refactor-parity.test.ts | 12 +- ...native-host-task-item-review-operations.ts | 6 +- .../native-host-task-linear-operations.ts | 13 +- ...tive-host-task-operation-contracts.test.ts | 24 ++ ...e-host-task-project-mutation-operations.ts | 11 +- .../tasks/native-host-task-read-operations.ts | 45 +- ...se-mobile-tasks-project-detail-loading.tsx | 1 + ...use-mobile-tasks-provider-load-actions.tsx | 9 +- .../use-mobile-tasks-route-and-item-state.tsx | 3 - .../src/transport/screen-rpc-ratchet.test.ts | 387 +++++++++++++----- ...fault-host-workspace-catalog-operations.ts | 9 - .../default-host-workspace-operations.ts | 7 - .../host-workspace-catalog-operations.ts | 39 -- .../src/worktree/host-workspace-operations.ts | 9 - ...-host-workspace-catalog-operations.test.ts | 171 -------- ...ative-host-workspace-catalog-operations.ts | 135 ------ ...host-workspace-creation-read-operations.ts | 4 +- .../native-host-workspace-operations.ts | 11 - 43 files changed, 437 insertions(+), 845 deletions(-) delete mode 100644 mobile/src/files/default-host-file-operations.ts delete mode 100644 mobile/src/files/default-host-file-preview-operations.ts delete mode 100644 mobile/src/files/host-file-operations.ts delete mode 100644 mobile/src/files/host-file-preview-operations.ts delete mode 100644 mobile/src/files/native-host-file-operations.ts delete mode 100644 mobile/src/files/native-host-file-preview-operations.ts create mode 100644 mobile/src/tasks/linear-status-projection.ts delete mode 100644 mobile/src/worktree/default-host-workspace-catalog-operations.ts delete mode 100644 mobile/src/worktree/default-host-workspace-operations.ts delete mode 100644 mobile/src/worktree/host-workspace-catalog-operations.ts delete mode 100644 mobile/src/worktree/host-workspace-operations.ts delete mode 100644 mobile/src/worktree/native-host-workspace-catalog-operations.test.ts delete mode 100644 mobile/src/worktree/native-host-workspace-catalog-operations.ts delete mode 100644 mobile/src/worktree/native-host-workspace-operations.ts diff --git a/mobile/src/device/device-operations.ts b/mobile/src/device/device-operations.ts index 8b20b73fe16e..e179863d5ae7 100644 --- a/mobile/src/device/device-operations.ts +++ b/mobile/src/device/device-operations.ts @@ -1,22 +1,8 @@ /** Device capabilities a screen reaches through its host binding instead of importing a native - * module directly, so the same screen runs against a non-native provider later. */ -export type DeviceHapticKind = 'selection' | 'success' | 'error' | 'edge-bump' | 'medium-impact' - -export type DeviceClipboardAvailability = { - hasText: boolean - hasImage: boolean -} - -/** iOS shows its own paste banner; every other platform needs the app to confirm. */ -export type DeviceClipboardWriteResult = { - confirmation: 'in-app' | 'system' -} - + * module directly, so the same screen runs against a non-native provider later. + * + * Deliberately narrow: only what a caller on this branch reads. Haptics, clipboard and external + * links join it when the screens that use them are routed. */ export type DeviceOperations = { - hapticFeedback(kind: DeviceHapticKind): void - clipboardAvailability(): Promise - copyText(text: string): Promise - openExternalUrl(url: string): Promise - openTerminalSettings(): void randomNonce(): string } diff --git a/mobile/src/device/native-device-operations.ts b/mobile/src/device/native-device-operations.ts index 94e4cee777b1..d791ea18e184 100644 --- a/mobile/src/device/native-device-operations.ts +++ b/mobile/src/device/native-device-operations.ts @@ -1,47 +1,7 @@ -import * as Clipboard from 'expo-clipboard' import * as ExpoCrypto from 'expo-crypto' -import { router } from 'expo-router' -import { Linking, Platform } from 'react-native' -import { - triggerEdgeBump, - triggerError, - triggerMediumImpact, - triggerSelection, - triggerSuccess -} from '../platform/haptics' import type { DeviceOperations } from './device-operations' export const nativeDeviceOperations: DeviceOperations = { - hapticFeedback(kind) { - if (kind === 'selection') { - triggerSelection() - } else if (kind === 'success') { - triggerSuccess() - } else if (kind === 'error') { - triggerError() - } else if (kind === 'edge-bump') { - triggerEdgeBump() - } else { - triggerMediumImpact() - } - }, - async clipboardAvailability() { - const [hasText, hasImage] = await Promise.all([ - Clipboard.hasStringAsync().catch(() => false), - Clipboard.hasImageAsync().catch(() => false) - ]) - return { hasText, hasImage } - }, - async copyText(text) { - await Clipboard.setStringAsync(text) - return { confirmation: Platform.OS === 'ios' ? 'in-app' : 'system' } - }, - async openExternalUrl(url) { - await Linking.openURL(url) - }, - openTerminalSettings() { - router.push('/terminal-settings') - }, randomNonce() { return ExpoCrypto.randomUUID() } diff --git a/mobile/src/files/default-host-file-operations.ts b/mobile/src/files/default-host-file-operations.ts deleted file mode 100644 index d5a916a69681..000000000000 --- a/mobile/src/files/default-host-file-operations.ts +++ /dev/null @@ -1,10 +0,0 @@ -import type { RpcClient } from '../transport/rpc-client' -import type { HostFileOperations } from './host-file-operations' -import { nativeHostFileOperations } from './native-host-file-operations' - -export function defaultHostFileOperations( - client: RpcClient, - reconnect: () => Promise -): HostFileOperations { - return nativeHostFileOperations(client, reconnect) -} diff --git a/mobile/src/files/default-host-file-preview-operations.ts b/mobile/src/files/default-host-file-preview-operations.ts deleted file mode 100644 index 23c5783fd5af..000000000000 --- a/mobile/src/files/default-host-file-preview-operations.ts +++ /dev/null @@ -1,10 +0,0 @@ -import type { RpcClient } from '../transport/rpc-client' -import type { HostFilePreviewOperations } from './host-file-preview-operations' -import { nativeHostFilePreviewOperations } from './native-host-file-preview-operations' - -export function defaultHostFilePreviewOperations( - client: RpcClient, - reconnect: () => Promise -): HostFilePreviewOperations { - return nativeHostFilePreviewOperations(client, reconnect) -} diff --git a/mobile/src/files/host-file-operations.ts b/mobile/src/files/host-file-operations.ts deleted file mode 100644 index ec42f47539ce..000000000000 --- a/mobile/src/files/host-file-operations.ts +++ /dev/null @@ -1,9 +0,0 @@ -import type { HostFileExplorerOperations } from './host-file-explorer-operations' -import type { HostFilePreviewOperations } from './host-file-preview-operations' - -/** Everything the file screens ask a host for, grouped by concern so a screen takes one prop and - * a provider is built once. Each namespace keeps its own contract file. */ -export type HostFileOperations = { - explorer: HostFileExplorerOperations - preview: HostFilePreviewOperations -} diff --git a/mobile/src/files/host-file-preview-operations.ts b/mobile/src/files/host-file-preview-operations.ts deleted file mode 100644 index 930afb3bdb34..000000000000 --- a/mobile/src/files/host-file-preview-operations.ts +++ /dev/null @@ -1,27 +0,0 @@ -import type { - MobileFilePreviewResult, - MobileFilePreviewSource -} from './mobile-file-preview-request' -import type { MobileTerminalArtifactPreviewSource } from './mobile-terminal-artifact-grant-refresh' - -export type HostFilePreviewLoadOptions = { - onTerminalArtifactSourceRefreshed?: (source: MobileTerminalArtifactPreviewSource) => void -} - -export type HostFilePreviewSaveOptions = HostFilePreviewLoadOptions & { - baseContent?: string -} - -export type HostFilePreviewOperations = { - load( - source: MobileFilePreviewSource, - options?: HostFilePreviewLoadOptions - ): Promise - saveTerminalArtifact( - source: MobileTerminalArtifactPreviewSource, - content: string, - options?: HostFilePreviewSaveOptions - ): Promise - reconnect(): Promise - openExternalUrl(url: string): Promise -} diff --git a/mobile/src/files/native-host-file-operations.ts b/mobile/src/files/native-host-file-operations.ts deleted file mode 100644 index de86faa51341..000000000000 --- a/mobile/src/files/native-host-file-operations.ts +++ /dev/null @@ -1,14 +0,0 @@ -import type { RpcClient } from '../transport/rpc-client' -import type { HostFileOperations } from './host-file-operations' -import { nativeHostFileExplorerOperations } from './native-host-file-explorer-operations' -import { nativeHostFilePreviewOperations } from './native-host-file-preview-operations' - -export function nativeHostFileOperations( - client: RpcClient, - reconnect: () => Promise -): HostFileOperations { - return { - explorer: nativeHostFileExplorerOperations(client, reconnect), - preview: nativeHostFilePreviewOperations(client, reconnect) - } -} diff --git a/mobile/src/files/native-host-file-preview-operations.ts b/mobile/src/files/native-host-file-preview-operations.ts deleted file mode 100644 index 237ed1486adf..000000000000 --- a/mobile/src/files/native-host-file-preview-operations.ts +++ /dev/null @@ -1,25 +0,0 @@ -import { nativeDeviceOperations } from '../device/native-device-operations' -import type { RpcClient } from '../transport/rpc-client' -import type { HostFilePreviewOperations } from './host-file-preview-operations' -import { - loadMobileFilePreview, - saveMobileTerminalArtifactPreview -} from './mobile-file-preview-request' - -export function nativeHostFilePreviewOperations( - client: RpcClient, - reconnect: () => Promise -): HostFilePreviewOperations { - return { - load(source, options) { - return loadMobileFilePreview(client, source, undefined, options) - }, - saveTerminalArtifact(source, content, options) { - return saveMobileTerminalArtifactPreview(client, source, content, options) - }, - reconnect, - openExternalUrl(url) { - return nativeDeviceOperations.openExternalUrl(url) - } - } -} diff --git a/mobile/src/session/host-session-native-chat-operations.ts b/mobile/src/session/host-session-native-chat-operations.ts index 2b7236d4ceb4..635925405a09 100644 --- a/mobile/src/session/host-session-native-chat-operations.ts +++ b/mobile/src/session/host-session-native-chat-operations.ts @@ -74,6 +74,8 @@ export type HostSessionNativeChatOperations = { followedByText?: boolean ): Promise releaseImages?(target: HostSessionNativeChatTarget, references: readonly string[]): Promise - searchFiles(target: HostSessionNativeChatTarget, query: string): Promise + /** Null when the host refused the search. An empty array is a real answer the caller may + * cache; a refusal must not be cached, or the next keystroke would never retry. */ + searchFiles(target: HostSessionNativeChatTarget, query: string): Promise openFile(target: HostSessionNativeChatTarget, pathText: string): Promise } diff --git a/mobile/src/session/host-session-tab-operations.ts b/mobile/src/session/host-session-tab-operations.ts index 554df8f6718f..bd46d8075935 100644 --- a/mobile/src/session/host-session-tab-operations.ts +++ b/mobile/src/session/host-session-tab-operations.ts @@ -22,11 +22,6 @@ export type HostSessionTabOperations = { onError: () => void ): () => void agentOptions(workspaceId: string): Promise - createBlank(workspaceId: string): Promise - createAgent( - workspaceId: string, - agent: MobileNewTabAgentOption['agent'] - ): Promise createQuickCommand?( workspaceId: string, commandId: string diff --git a/mobile/src/session/host-session-terminal-operations.ts b/mobile/src/session/host-session-terminal-operations.ts index 10e3799e6465..144aded7d30b 100644 --- a/mobile/src/session/host-session-terminal-operations.ts +++ b/mobile/src/session/host-session-terminal-operations.ts @@ -64,14 +64,6 @@ export type HostSessionTerminalOperations = { enter: boolean, clientId: string | null ): Promise - /** Answers only for a terminal this same instance subscribed: the reply is dropped otherwise. - * A caller that routes query replies must route `subscribe` through the same instance too. */ - sendQueryReply( - terminalId: string, - bytes: string, - clientId: string | null, - hostSupportsQueryReply: boolean - ): Promise setDisplayMode( terminalId: string, mode: 'auto' | 'desktop', diff --git a/mobile/src/session/mobile-session-route-parity.test.ts b/mobile/src/session/mobile-session-route-parity.test.ts index dbf204dcd96c..d18b374fdd0e 100644 --- a/mobile/src/session/mobile-session-route-parity.test.ts +++ b/mobile/src/session/mobile-session-route-parity.test.ts @@ -70,7 +70,7 @@ const HEAD_CALLBACK_BODY_SHA256 = 'e66e6436cdb9a66e870c06fdfc140106502fbeddd8db4 const HEAD_EFFECT_SHA256 = 'd9ebfaabc1e79773cdada7ab370b20459ed972f1f8edce1652199f4d0391cd13' const HEAD_CONTENT_HOOK_SHA256 = '9c3b612fef3f370d66873aefdbe1d701f20cb64ded31fef5cc45fde6f8189581' const HEAD_NESTED_FUNCTION_SHA256 = - 'd0aada4091de4551fcb5edabad4aa84249799d2fd3244c0f7493eadb4fe3ba58' + '1dc163bbb2c1b4c9f8ff46514d6d5dcfc987c01a98d92a5c90058a868f55e089' const HEAD_NATIVE_REGISTRATION_SHA256 = 'cab85e4e4a3f43289ba93ddea9ccce57aea83e0bf14fd1620a965aad0c1cb49e' const HEAD_NATIVE_REMOVAL_SHA256 = diff --git a/mobile/src/session/native-host-session-browser-operations.ts b/mobile/src/session/native-host-session-browser-operations.ts index 11f089f072a1..e2fc3b8eacca 100644 --- a/mobile/src/session/native-host-session-browser-operations.ts +++ b/mobile/src/session/native-host-session-browser-operations.ts @@ -50,7 +50,10 @@ export function nativeHostSessionBrowserOperations( ) }, async click(target, point, button, modifiers, radius) { - const click = await client.sendRequest( + // No move/down/up fallback here: the live caller wraps that sequence in a try/catch + // because pointer commands race page navigation, and a throwing copy of it would surface + // those races as errors the user never saw. + await client.sendRequest( 'browser.mouseClick', { ...nativeTarget(target), @@ -61,12 +64,6 @@ export function nativeHostSessionBrowserOperations( }, { timeoutMs: 5_000 } ) - if (click.ok || modifiers.length > 0) { - return - } - await requestResult(client, 'browser.mouseMove', { ...nativeTarget(target), ...point }, 5_000) - await requestResult(client, 'browser.mouseDown', { ...nativeTarget(target), button }, 5_000) - await requestResult(client, 'browser.mouseUp', { ...nativeTarget(target), button }, 5_000) }, async insertText(target, text) { await requestResult( diff --git a/mobile/src/session/native-host-session-native-chat-operations.ts b/mobile/src/session/native-host-session-native-chat-operations.ts index 198b1d53d1d5..27b5e8d9af90 100644 --- a/mobile/src/session/native-host-session-native-chat-operations.ts +++ b/mobile/src/session/native-host-session-native-chat-operations.ts @@ -111,7 +111,9 @@ export function nativeHostSessionNativeChatOperations( return extractPaths(response.result) } if (response.error.code !== 'method_not_found') { - return [] + // Null, not empty: an empty list is a real answer the caller caches, and caching a + // refusal would keep autocomplete dead for that prefix until the client changes. + return null } searchSupported = false } @@ -133,7 +135,7 @@ export function nativeHostSessionNativeChatOperations( } const paths = await legacyLoad if (!paths) { - return [] + return null } legacyPaths = paths legacyPathsByWorkspace.set(target.workspaceId, paths) diff --git a/mobile/src/session/native-host-session-tab-operations.test.ts b/mobile/src/session/native-host-session-tab-operations.test.ts index 59e55b0a57d5..ef10918eec25 100644 --- a/mobile/src/session/native-host-session-tab-operations.test.ts +++ b/mobile/src/session/native-host-session-tab-operations.test.ts @@ -34,8 +34,6 @@ describe('native host session tab operations', () => { const sendRequest = vi .fn() .mockResolvedValueOnce({ ok: true, result: sessionSnapshot(1) }) - .mockResolvedValueOnce({ ok: true, result: { created: true } }) - .mockResolvedValueOnce({ ok: true, result: sessionSnapshot(2) }) .mockResolvedValueOnce({ ok: true, result: { browserPageId: 'browser-1' } }) .mockResolvedValueOnce({ ok: true, result: sessionSnapshot(3) }) .mockResolvedValueOnce({ ok: true, result: { closed: true } }) @@ -44,7 +42,6 @@ describe('native host session tab operations', () => { } as unknown as RpcClient) await expect(operations.snapshot('workspace-1')).resolves.toEqual(sessionSnapshot(1)) - await expect(operations.createBlank('workspace-1')).resolves.toEqual(sessionSnapshot(2)) await expect(operations.createBrowser('workspace-1', 'https://example.com')).resolves.toEqual({ browserPageId: 'browser-1' }) @@ -56,17 +53,6 @@ describe('native host session tab operations', () => { }) expect(sendRequest.mock.calls).toEqual([ - ['session.tabs.list', { worktree: 'id:workspace-1' }], - [ - 'session.tabs.createTerminal', - { - worktree: 'id:workspace-1', - clientMutationId: expect.stringMatching(/^mobile-create:/), - activate: false, - select: true, - navigation: 'caller' - } - ], ['session.tabs.list', { worktree: 'id:workspace-1' }], [ 'browser.tabCreate', @@ -156,7 +142,7 @@ describe('native host session tab operations', () => { expect(sendRequest).toHaveBeenCalledTimes(2) }) - it('loads enabled agent choices and creates the selected agent through named operations', async () => { + it('loads enabled agent choices', async () => { const sendRequest = vi.fn(async (method) => { if (method === 'settings.get') { return { @@ -167,9 +153,6 @@ describe('native host session tab operations', () => { if (method === 'preflight.detectAgents') { return { ok: true, result: ['claude', 'codex'] } } - if (method === 'session.tabs.createTerminal') { - return { ok: true, result: { created: true } } - } return { ok: true, result: sessionSnapshot(4) } }) const operations = nativeHostSessionTabOperations({ @@ -180,17 +163,6 @@ describe('native host session tab operations', () => { { agent: 'codex', label: 'Codex' }, { agent: 'claude', label: 'Claude' } ]) - await expect(operations.createAgent('global-floating-terminal', 'codex')).resolves.toEqual( - sessionSnapshot(4) - ) - expect(sendRequest).toHaveBeenCalledWith('session.tabs.createTerminal', { - worktree: 'id:global-floating-terminal', - clientMutationId: expect.stringMatching(/^mobile-create:/), - agent: 'codex', - activate: false, - select: true, - navigation: 'caller' - }) }) it('keeps refused closes visible to the shared screen', async () => { diff --git a/mobile/src/session/native-host-session-tab-operations.ts b/mobile/src/session/native-host-session-tab-operations.ts index 084bdc9aed96..0b7337bfc767 100644 --- a/mobile/src/session/native-host-session-tab-operations.ts +++ b/mobile/src/session/native-host-session-tab-operations.ts @@ -47,41 +47,6 @@ export function nativeHostSessionTabOperations(client: RpcClient): HostSessionTa agentOptions(workspaceId) { return loadMobileNewTabAgentOptions({ client, worktreeId: workspaceId }) }, - async createBlank(workspaceId) { - const create = await client.sendRequest('session.tabs.createTerminal', { - worktree: `id:${workspaceId}`, - clientMutationId: nativeSessionCreateMutationId(), - activate: false, - select: true, - navigation: 'caller' - }) - if (!create.ok) { - throw new Error('session_create_failed') - } - return successfulSnapshot( - await client.sendRequest('session.tabs.list', { - worktree: `id:${workspaceId}` - }) - ) - }, - async createAgent(workspaceId, agent) { - const create = await client.sendRequest('session.tabs.createTerminal', { - worktree: `id:${workspaceId}`, - clientMutationId: nativeSessionCreateMutationId(), - agent, - activate: false, - select: true, - navigation: 'caller' - }) - if (!create.ok) { - throw new Error('session_create_failed') - } - return successfulSnapshot( - await client.sendRequest('session.tabs.list', { - worktree: `id:${workspaceId}` - }) - ) - }, async createBrowser(workspaceId, url) { const response = await client.sendRequest( 'browser.tabCreate', @@ -134,10 +99,6 @@ export function nativeHostSessionTabOperations(client: RpcClient): HostSessionTa } } -function nativeSessionCreateMutationId(): string { - return `mobile-create:${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}` -} - function successfulSnapshot(response: Awaited>) { if (!response.ok) { throw new Error('session_snapshot_failed') diff --git a/mobile/src/session/native-host-session-terminal-operations.test.ts b/mobile/src/session/native-host-session-terminal-operations.test.ts index 78e3f8d6cfa5..fd12d35cf77c 100644 --- a/mobile/src/session/native-host-session-terminal-operations.test.ts +++ b/mobile/src/session/native-host-session-terminal-operations.test.ts @@ -81,30 +81,4 @@ describe('native host session terminal operations', () => { cleanup() expect(unsubscribe).toHaveBeenCalledOnce() }) - - it('keeps query replies capability-gated and bound to an active subscription', async () => { - const operations = nativeHostSessionTerminalOperations({ - subscribe: vi.fn().mockReturnValue(vi.fn()), - sendRequest: vi.fn().mockResolvedValue({ ok: true, result: { send: { accepted: true } } }) - } as unknown as RpcClient) - operations.subscribe( - { - workspaceId: 'workspace-1', - terminalId: 'terminal-native-1', - clientId: null, - viewport: null, - visible: true, - capabilities: { terminalBinaryStream: 1 } - }, - vi.fn(), - vi.fn() - ) - - await expect( - operations.sendQueryReply('terminal-native-1', '\u001b[0n', null, false) - ).resolves.toBe(false) - await expect( - operations.sendQueryReply('terminal-native-1', '\u001b[0n', null, true) - ).resolves.toBe(true) - }) }) diff --git a/mobile/src/session/native-host-session-terminal-operations.ts b/mobile/src/session/native-host-session-terminal-operations.ts index 18886f6b3eea..a518aedc0471 100644 --- a/mobile/src/session/native-host-session-terminal-operations.ts +++ b/mobile/src/session/native-host-session-terminal-operations.ts @@ -1,4 +1,3 @@ -import { sendMobileTerminalQueryReply } from '../terminal/mobile-terminal-query-reply' import { isTerminalSendRpcAccepted } from '../terminal/terminal-send-rpc-response' import { TERMINAL_INPUT_SEND_OPTIONS } from '../terminal/terminal-send-request' import type { RpcClient } from '../transport/rpc-client' @@ -8,7 +7,6 @@ import { subscribeMobileTerminalSafely } from './mobile-terminal-stream-subscrib export function nativeHostSessionTerminalOperations( client: RpcClient ): HostSessionTerminalOperations { - const subscribedTerminals = new Set() return { subscribe(args, onEvent, onError) { const unsubscribe = subscribeMobileTerminalSafely( @@ -22,11 +20,7 @@ export function nativeHostSessionTerminalOperations( (event) => onEvent(event as Parameters[0]), onError ) - subscribedTerminals.add(args.terminalId) - return () => { - subscribedTerminals.delete(args.terminalId) - unsubscribe() - } + return unsubscribe }, acknowledge() {}, async sendInput(terminalId, text, enter, clientId) { @@ -43,17 +37,6 @@ export function nativeHostSessionTerminalOperations( ) .then(isTerminalSendRpcAccepted, () => false) }, - sendQueryReply(terminalId, bytes, clientId, hostSupportsQueryReply) { - return sendMobileTerminalQueryReply({ - bytes, - client, - clientId, - connected: true, - handle: terminalId, - hostSupportsQueryReplyInput: hostSupportsQueryReply, - subscribedTerminals - }) - }, setDisplayMode(terminalId, mode, viewport, clientId) { return client .sendRequest('terminal.setDisplayMode', { diff --git a/mobile/src/session/use-mobile-native-chat-file-search.test.ts b/mobile/src/session/use-mobile-native-chat-file-search.test.ts index a9d180f74b19..8937d06238b2 100644 --- a/mobile/src/session/use-mobile-native-chat-file-search.test.ts +++ b/mobile/src/session/use-mobile-native-chat-file-search.test.ts @@ -90,6 +90,34 @@ describe('useMobileNativeChatFileSearch', () => { ]) }) + it('does not cache a refused search, so the next keystroke retries it', async () => { + let refuse = true + const sendRequest = vi.fn(async (_method: string, params: { query: string }) => { + if (refuse) { + return { + id: 'refused', + ok: false as const, + error: { code: 'worktree_unavailable', message: 'Workspace moved' }, + _meta: { runtimeId: 'runtime-1' } + } + } + return rpcSuccess([`src/${params.query}.ts`]) + }) + await mount({ sendRequest } as unknown as RpcClient) + + act(() => state?.loadNativeChatFiles('comp')) + await act(async () => vi.advanceTimersByTimeAsync(120)) + expect(sendRequest).toHaveBeenCalledTimes(1) + expect(state?.nativeChatFilePaths).toEqual([]) + + // The identical prefix must reach the host again rather than serve a cached empty answer. + refuse = false + act(() => state?.loadNativeChatFiles('comp')) + await act(async () => vi.advanceTimersByTimeAsync(120)) + expect(sendRequest).toHaveBeenCalledTimes(2) + expect(state?.nativeChatFilePaths).toEqual(['src/comp.ts']) + }) + it('cancels an in-flight query on a cache hit so a stale result cannot clobber it', async () => { const sendRequest = vi.fn(async (_method: string, params: { query: string }) => rpcSuccess(params.query === 'app' ? ['src/app.ts'] : ['src/beta.ts']) diff --git a/mobile/src/session/use-mobile-native-chat-file-search.ts b/mobile/src/session/use-mobile-native-chat-file-search.ts index 4b9f321e8100..e3d55feb95c3 100644 --- a/mobile/src/session/use-mobile-native-chat-file-search.ts +++ b/mobile/src/session/use-mobile-native-chat-file-search.ts @@ -60,8 +60,8 @@ export function useMobileNativeChatFileSearch(args: { setNativeChatFilePaths([]) timerRef.current = setTimeout(() => { timerRef.current = null - const applyPaths = (paths: string[]): void => { - if (sequenceRef.current !== sequence) { + const applyPaths = (paths: string[] | null): void => { + if (sequenceRef.current !== sequence || !paths) { return } queryCacheRef.current.set(normalizedQuery, paths) @@ -76,7 +76,7 @@ export function useMobileNativeChatFileSearch(args: { } void operations .searchFiles(target, normalizedQuery) - .then((paths) => applyPaths(paths.slice(0, FILE_SEARCH_RESULT_LIMIT))) + .then((paths) => applyPaths(paths ? paths.slice(0, FILE_SEARCH_RESULT_LIMIT) : null)) .catch(() => {}) }, FILE_SEARCH_DEBOUNCE_MS) }, diff --git a/mobile/src/session/use-mobile-session-terminal-input.ts b/mobile/src/session/use-mobile-session-terminal-input.ts index db31020ca3b1..4a5a50dd9fc2 100644 --- a/mobile/src/session/use-mobile-session-terminal-input.ts +++ b/mobile/src/session/use-mobile-session-terminal-input.ts @@ -223,12 +223,9 @@ export function useMobileSessionTerminalInput(scope: MobileSessionFileActionsMod return } getTerminalRef(target.handle)?.clear() - try { - // Why the result is ignored: a host that answers `ok: false` still cleared the local - // buffer above, and only a transport failure told the user the clear did not happen. - await sessionOperations.terminal.clear(target.handle) + if (await sessionOperations.terminal.clear(target.handle)) { showToast('Terminal cleared') - } catch { + } else { showToast("Couldn't clear terminal", 1500) } } diff --git a/mobile/src/tasks/host-task-read-operations.ts b/mobile/src/tasks/host-task-read-operations.ts index dc9810d920ab..fcc2affa2cf1 100644 --- a/mobile/src/tasks/host-task-read-operations.ts +++ b/mobile/src/tasks/host-task-read-operations.ts @@ -1,15 +1,19 @@ import type { GitHubOwnerRepo } from '../../../src/shared/github/pull-request-types' import type { HostTaskBootstrap, - HostTaskLinearContext, + HostTaskLinearStatus, + HostTaskLinearTeams, HostTaskRepository } from './host-task-runtime-payloads' -export type { HostTaskBootstrap, HostTaskLinearContext, HostTaskRepository } +export type { HostTaskBootstrap, HostTaskLinearStatus, HostTaskLinearTeams, HostTaskRepository } export type HostTaskReadOperations = { bootstrap(): Promise listRepositories(): Promise - loadLinearContext(): Promise + /** Split from the team read so a caller can commit the workspace list before asking for + * teams: a failed team read must not discard the workspaces the status already named. */ + linearStatus(): Promise + linearTeams(workspaceId: string | null): Promise resolveGitHubRepoSlug(repoId: string): Promise } diff --git a/mobile/src/tasks/host-task-runtime-payloads.ts b/mobile/src/tasks/host-task-runtime-payloads.ts index 973fa0d340e0..d832b200aca0 100644 --- a/mobile/src/tasks/host-task-runtime-payloads.ts +++ b/mobile/src/tasks/host-task-runtime-payloads.ts @@ -24,10 +24,7 @@ export type HostTaskBootstrap = { export type HostTaskRepository = RepoSummary -export type HostTaskLinearContext = { - status: HostTaskLinearStatus - teams: LinearTeam[] -} +export type HostTaskLinearTeams = LinearTeam[] export type HostTaskSettingsUpdate = Pick< RuntimeTaskSettings, diff --git a/mobile/src/tasks/linear-status-projection.ts b/mobile/src/tasks/linear-status-projection.ts new file mode 100644 index 000000000000..d7cf7bb85209 --- /dev/null +++ b/mobile/src/tasks/linear-status-projection.ts @@ -0,0 +1,13 @@ +import type { HostTaskLinearStatus } from './host-task-runtime-payloads' + +/** The host answers `linear.status` and `linear.selectWorkspace` with the same connection + * status, and older hosts omit fields, so read it defensively in one place. */ +export function normalizeLinearStatus(value: unknown): HostTaskLinearStatus { + const status = (value ?? {}) as Partial + return { + connected: status.connected === true, + workspaces: Array.isArray(status.workspaces) ? status.workspaces : [], + selectedWorkspaceId: status.selectedWorkspaceId ?? null, + activeWorkspaceId: status.activeWorkspaceId ?? null + } +} diff --git a/mobile/src/tasks/mobile-tasks-filter-pickers.tsx b/mobile/src/tasks/mobile-tasks-filter-pickers.tsx index c8cc279ccdb4..14c84a03af9e 100644 --- a/mobile/src/tasks/mobile-tasks-filter-pickers.tsx +++ b/mobile/src/tasks/mobile-tasks-filter-pickers.tsx @@ -169,12 +169,16 @@ export function renderMobileTasksLinearWorkspacePicker(model: ConnectionPresenta setSelectedLinearWorkspaceId(workspaceId) setSelectedLinearTeamIds(new Set()) if (taskOperations) { + const reportFailure = (err: unknown): void => { + setError(err instanceof Error ? err.message : 'Failed to switch workspace') + } void taskOperations.linear .selectWorkspace(workspaceId) + .catch(reportFailure) + // Why the reload runs either way: it re-reads the host's real workspace, so a + // refused switch cannot leave the optimistic selection above standing. .then(() => loadLinearContext()) - .catch((err) => { - setError(err instanceof Error ? err.message : 'Failed to switch workspace') - }) + .catch(reportFailure) } }} onClose={() => setShowLinearWorkspacePicker(false)} diff --git a/mobile/src/tasks/mobile-tasks-refactor-parity.test.ts b/mobile/src/tasks/mobile-tasks-refactor-parity.test.ts index 63eb851d792d..a2ff0be5dd61 100644 --- a/mobile/src/tasks/mobile-tasks-refactor-parity.test.ts +++ b/mobile/src/tasks/mobile-tasks-refactor-parity.test.ts @@ -25,18 +25,18 @@ const hash = (parts: string[] | string): string => * plus the row-target locals the adapters take in place of inline slug/number checks. Diff hooks, * declarations and styles are untouched. */ -const SCREEN_HOOKS = 'b5d85ab1cd2996a6986604caf497c8a577dc118b095c49d555c576d98f48148f' +const SCREEN_HOOKS = '0ef59ab331ad320a5ccabe8c227616af263ad2c468a805a6743dde8c186d7027' const DIFF_HOOKS = '93c7189b32bed8456cc51814fffa8ce80cf62011ef968a9d53ddec2b9686f58f' -const STATEMENTS = '1d059c8359400f2aedb16c94a7dba0c8a21b5a06edb45e2b0b7ff0317250d564' +const STATEMENTS = 'e5d84617b7acbbdcaf17129d19670fac62a0399d967d9a6fc225cb9b807ae886' const DECLARATIONS = 'cff54172af17a877789be1479c2eb6ca97d83c3e31dd831cd59395962f2b4c4a' const SEMANTICS = 'f767906884b93537f2c6369d6d0bd2d4cb39b4314c31cca9d8f9e5e9b78a75ee' const STYLES = '1db6af69c791d9963928541ad5310942fcbda6d984b422c90b6eb92b6816579a' -const RENDER_TREE = 'a959c6712c70024127a429a47ae7689c629393752fa99a1ac6ba311d0bf13ca6' +const RENDER_TREE = '62b9f49e69e699887c9f1873d7d3c9c7e6f556d34a83ec1a1b79831b6f647ff3' describe('Mobile Tasks refactor parity', () => { it('preserves recursively flattened hook and dependency order', () => { const screenHooks = readFlattenedMobileTasksHookSignatures('MobileTasksScreen') - expect(screenHooks).toHaveLength(353) + expect(screenHooks).toHaveLength(352) expect(hash(screenHooks)).toBe(SCREEN_HOOKS) const diffHooks = readFlattenedMobileTasksHookSignatures('GitHubPrFileDiff') @@ -46,7 +46,7 @@ describe('Mobile Tasks refactor parity', () => { it('preserves every screen statement in execution order', () => { const statements = readFlattenedMobileTasksCoreStatements() - expect(statements).toHaveLength(420) + expect(statements).toHaveLength(419) expect(hash(statements)).toBe(STATEMENTS) }) @@ -64,7 +64,7 @@ describe('Mobile Tasks refactor parity', () => { it('preserves render expressions and event handlers in tree order', () => { const tokens = readFlattenedMobileTasksRenderTokens() - expect(tokens).toHaveLength(35_193) + expect(tokens).toHaveLength(35_209) expect(hash(tokens)).toBe(RENDER_TREE) }) diff --git a/mobile/src/tasks/native-host-task-item-review-operations.ts b/mobile/src/tasks/native-host-task-item-review-operations.ts index d262b68c0e99..6e8a028b032b 100644 --- a/mobile/src/tasks/native-host-task-item-review-operations.ts +++ b/mobile/src/tasks/native-host-task-item-review-operations.ts @@ -43,7 +43,11 @@ export function nativeHostTaskItemReviewOperations( { repo: `id:${target.repoId}`, threadId, resolve }, { timeoutMs: 30_000 } ) - if (!response.ok || response.result !== true) { + if (!response.ok) { + throw new Error(response.error?.message ?? 'Task request failed') + } + // The host returns a bare `true`; anything else is a refusal, not a transport problem. + if (response.result !== true) { throw new Error(resolve ? 'Failed to resolve thread' : 'Failed to reopen thread') } }, diff --git a/mobile/src/tasks/native-host-task-linear-operations.ts b/mobile/src/tasks/native-host-task-linear-operations.ts index 53e6bd98ad59..1d64ef99b0c1 100644 --- a/mobile/src/tasks/native-host-task-linear-operations.ts +++ b/mobile/src/tasks/native-host-task-linear-operations.ts @@ -1,4 +1,5 @@ import type { HostTaskLinearOperations } from './host-task-linear-operations' +import { normalizeLinearStatus } from './linear-status-projection' import type { RpcRequestSender } from '../transport/rpc-client' import type { SendRequestOptions } from '../transport/rpc-client' @@ -22,11 +23,15 @@ export function nativeHostTaskLinearOperations(client: RpcRequestSender): HostTa }), async selectWorkspace(workspaceId) { // Deliberate improvement over the call this replaced: that one dropped a refusal on the - // floor, leaving the picker showing a workspace the host never switched to. - assertMutation( - await request(client, 'linear.selectWorkspace', { workspaceId }), - 'Failed to select workspace' + // floor, leaving the picker showing a workspace the host never switched to. The host + // answers a refusal with its unchanged connection status and no `ok` field, so the id + // coming back is the only proof the switch took. + const status = normalizeLinearStatus( + await request(client, 'linear.selectWorkspace', { workspaceId }) ) + if (status.selectedWorkspaceId !== workspaceId) { + throw new Error('Failed to select workspace') + } }, async updateState(target, stateId) { await request(client, 'linear.updateIssue', { diff --git a/mobile/src/tasks/native-host-task-operation-contracts.test.ts b/mobile/src/tasks/native-host-task-operation-contracts.test.ts index 99d2bcd2d859..0c7225d4322c 100644 --- a/mobile/src/tasks/native-host-task-operation-contracts.test.ts +++ b/mobile/src/tasks/native-host-task-operation-contracts.test.ts @@ -1,6 +1,7 @@ import { describe, expect, it, vi } from 'vitest' import type { RpcClient } from '../transport/rpc-client' import { nativeHostTaskItemFileOperations } from './native-host-task-item-file-operations' +import { nativeHostTaskLinearOperations } from './native-host-task-linear-operations' import { nativeHostTaskListOperations } from './native-host-task-list-operations' import { nativeHostTaskProjectFileOperations } from './native-host-task-project-file-operations' import { nativeHostTaskProjectMutationOperations } from './native-host-task-project-mutation-operations' @@ -30,6 +31,29 @@ describe('native host task operation contracts', () => { ).rejects.toThrow('Invalid checks response') }) + it('accepts a Linear workspace switch the host confirms by echoing the id', async () => { + const sendRequest = vi.fn().mockResolvedValue({ + ok: true, + result: { connected: true, workspaces: [], selectedWorkspaceId: 'ws-2' } + }) + + await expect( + nativeHostTaskLinearOperations(client(sendRequest)).selectWorkspace('ws-2') + ).resolves.toBeUndefined() + }) + + it('reports a refused Linear workspace switch, which the host answers with its old status', () => { + // The host has no `ok` field here: a refusal is its unchanged status, so only the id proves it. + const sendRequest = vi.fn().mockResolvedValue({ + ok: true, + result: { connected: true, workspaces: [], selectedWorkspaceId: 'ws-1' } + }) + + return expect( + nativeHostTaskLinearOperations(client(sendRequest)).selectWorkspace('ws-2') + ).rejects.toThrow('Failed to select workspace') + }) + it('reads an absent GitLab todo list as empty rather than an error banner', async () => { const sendRequest = vi .fn() diff --git a/mobile/src/tasks/native-host-task-project-mutation-operations.ts b/mobile/src/tasks/native-host-task-project-mutation-operations.ts index a7e304da850d..6cebae93c2a6 100644 --- a/mobile/src/tasks/native-host-task-project-mutation-operations.ts +++ b/mobile/src/tasks/native-host-task-project-mutation-operations.ts @@ -90,7 +90,7 @@ export function nativeHostTaskProjectMutationOperations( // has no slug — send it only when one resolved rather than an empty pair. prRepo: prRepoPayload(target) }), - 'Failed to resolve thread' + resolve ? 'Failed to resolve thread' : 'Failed to reopen thread' ) }, async replyReviewComment(target, repoId, payload) { @@ -201,11 +201,14 @@ async function projectMutation( return (response.result ?? {}) as T } +/** The wrapper substitutes its own copy for two cases the caller used to word itself: a host + * that says nothing (`Request failed: `) and a review thread it could not update. */ +const WRAPPER_SUBSTITUTED_COPY = ['Request failed: ', 'Failed to update review thread.'] + function requirePrMutation(result: GitHubPrMutationOutcome, fallback: string): void { if (!result.ok) { - // The wrapper mints `Request failed: ` when the host says nothing; the caller's own - // wording is what the user read before these calls moved behind the seam. - throw new Error(result.error.startsWith('Request failed: ') ? fallback : result.error) + const substituted = WRAPPER_SUBSTITUTED_COPY.some((copy) => result.error.startsWith(copy)) + throw new Error(substituted ? fallback : result.error) } } diff --git a/mobile/src/tasks/native-host-task-read-operations.ts b/mobile/src/tasks/native-host-task-read-operations.ts index 9cb7d5f38175..756c364fdb2e 100644 --- a/mobile/src/tasks/native-host-task-read-operations.ts +++ b/mobile/src/tasks/native-host-task-read-operations.ts @@ -2,10 +2,12 @@ import type { GitHubOwnerRepo } from '../../../src/shared/github/pull-request-ty import { MOBILE_TASKS_CAPABILITY } from './mobile-tasks-capability' import type { HostTaskBootstrap, - HostTaskLinearContext, + HostTaskLinearStatus, + HostTaskLinearTeams, HostTaskReadOperations, HostTaskRepository } from './host-task-read-operations' +import { normalizeLinearStatus } from './linear-status-projection' import type { RpcRequestSender } from '../transport/rpc-client' import type { RpcResponse, RpcSuccess } from '../transport/types' @@ -13,7 +15,8 @@ export function nativeHostTaskReadOperations(client: RpcRequestSender): HostTask return { bootstrap: () => bootstrap(client), listRepositories: () => listRepositories(client), - loadLinearContext: () => loadLinearContext(client), + linearStatus: () => linearStatus(client), + linearTeams: (workspaceId) => linearTeams(client, workspaceId), resolveGitHubRepoSlug: (repoId) => resolveGitHubRepoSlug(client, repoId) } } @@ -60,23 +63,21 @@ async function listRepositories(client: RpcRequestSender): Promise { - const statusResponse = await client.sendRequest('linear.status') - requireSuccess(statusResponse) - const status = normalizeLinearStatus(statusResponse.result) - if (!status.connected) { - return { status, teams: [] } - } - const workspaceId = - status.selectedWorkspaceId ?? status.activeWorkspaceId ?? status.workspaces[0]?.id ?? null - const teamsResponse = await client.sendRequest('linear.listTeams', { +async function linearStatus(client: RpcRequestSender): Promise { + const response = await client.sendRequest('linear.status') + requireSuccess(response) + return normalizeLinearStatus(response.result) +} + +async function linearTeams( + client: RpcRequestSender, + workspaceId: string | null +): Promise { + const response = await client.sendRequest('linear.listTeams', { workspaceId: workspaceId ?? undefined }) - requireSuccess(teamsResponse) - return { - status: { ...status, selectedWorkspaceId: workspaceId }, - teams: teamsResponse.result as HostTaskLinearContext['teams'] - } + requireSuccess(response) + return response.result as HostTaskLinearTeams } async function resolveGitHubRepoSlug( @@ -103,16 +104,6 @@ function emptyBootstrap(supported: boolean): HostTaskBootstrap { } } -function normalizeLinearStatus(value: unknown): HostTaskBootstrap['linearStatus'] { - const status = (value ?? {}) as Partial - return { - connected: status.connected === true, - workspaces: Array.isArray(status.workspaces) ? status.workspaces : [], - selectedWorkspaceId: status.selectedWorkspaceId ?? null, - activeWorkspaceId: status.activeWorkspaceId ?? null - } -} - function successResult(response: RpcResponse): T | null { return response.ok ? (response.result as T) : null } diff --git a/mobile/src/tasks/use-mobile-tasks-project-detail-loading.tsx b/mobile/src/tasks/use-mobile-tasks-project-detail-loading.tsx index 1a410f176d3e..fd38d089b57f 100644 --- a/mobile/src/tasks/use-mobile-tasks-project-detail-loading.tsx +++ b/mobile/src/tasks/use-mobile-tasks-project-detail-loading.tsx @@ -128,6 +128,7 @@ export function useMobileTasksProjectDetailLoading(model: ItemDetailLoadingModel githubProjectTable, projectRowDetailRefreshSeq, projectRowItem, + taskOperations, tasksSupported ]) return model diff --git a/mobile/src/tasks/use-mobile-tasks-provider-load-actions.tsx b/mobile/src/tasks/use-mobile-tasks-provider-load-actions.tsx index e0ffed18bec5..b1561ef0116c 100644 --- a/mobile/src/tasks/use-mobile-tasks-provider-load-actions.tsx +++ b/mobile/src/tasks/use-mobile-tasks-provider-load-actions.tsx @@ -43,7 +43,7 @@ export function useMobileTasksProviderLoadActions(model: RuntimeHydrationModel) if (!taskOperations || connState !== 'connected' || !tasksSupported) { return } - const { status, teams } = await taskOperations.read.loadLinearContext() + const status = await taskOperations.read.linearStatus() setLinearConnected(status.connected) if (!status.connected) { setLinearWorkspaces([]) @@ -52,8 +52,13 @@ export function useMobileTasksProviderLoadActions(model: RuntimeHydrationModel) setSelectedLinearWorkspaceId(null) return } + const workspaceId = + status.selectedWorkspaceId ?? status.activeWorkspaceId ?? status.workspaces[0]?.id ?? null + // Committed before the team read: a failed team read must leave the picker populated and the + // workspace resolved, or the next list request goes out with no workspace at all. setLinearWorkspaces(status.workspaces) - setSelectedLinearWorkspaceId(status.selectedWorkspaceId) + setSelectedLinearWorkspaceId(workspaceId) + const teams = await taskOperations.read.linearTeams(workspaceId) setLinearTeams(teams) setSelectedLinearTeamIds(reconcileTeamSelection(teams, defaultLinearTeamSelectionRef.current)) }, [connState, taskOperations, tasksSupported]) diff --git a/mobile/src/tasks/use-mobile-tasks-route-and-item-state.tsx b/mobile/src/tasks/use-mobile-tasks-route-and-item-state.tsx index e89c115aac81..8f65fed4c635 100644 --- a/mobile/src/tasks/use-mobile-tasks-route-and-item-state.tsx +++ b/mobile/src/tasks/use-mobile-tasks-route-and-item-state.tsx @@ -43,7 +43,6 @@ import { type TasksSupportState, getTaskPresetQuery } from './mobile-tasks-legacy-foundation' -import { defaultDeviceOperations } from '../device/default-device-operations' import { defaultHostTaskOperations } from './default-host-task-operations' import { defaultHostWorkspaceCreationOperations } from '../worktree/default-host-workspace-creation-operations' import { useMobileTasksItemState } from './use-mobile-tasks-item-state' @@ -67,7 +66,6 @@ export function useMobileTasksRouteAndItemState() { () => (client ? defaultHostWorkspaceCreationOperations(client) : null), [client] ) - const deviceOperations = useMemo(() => defaultDeviceOperations(), []) const repoList = useHostRepoList( taskOperations, taskOperations && connState === 'connected' @@ -182,7 +180,6 @@ export function useMobileTasksRouteAndItemState() { client, taskOperations, taskWorkspaceCreationOperations, - deviceOperations, connState, reconnectAttempts, lastConnectedAt, diff --git a/mobile/src/transport/screen-rpc-ratchet.test.ts b/mobile/src/transport/screen-rpc-ratchet.test.ts index 1b7511a7a96d..51c684d12e3f 100644 --- a/mobile/src/transport/screen-rpc-ratchet.test.ts +++ b/mobile/src/transport/screen-rpc-ratchet.test.ts @@ -1,140 +1,311 @@ -import { readFileSync, readdirSync } from 'node:fs' -import { join } from 'node:path' +import { readFileSync, readdirSync, statSync } from 'node:fs' +import { join, relative } from 'node:path' import { describe, expect, it } from 'vitest' -/** Screen directories whose RPC access is being moved behind the host operation adapters. */ -const SCREEN_DIRECTORIES = [ - 'tasks', - 'session', - 'files', - 'accounts', - 'worktree', - 'host-screen', - 'components', - 'hooks' -] as const +/** Every RPC entry point a screen could reach for. `subscribe` counts as much as `sendRequest`: + * a streaming read reintroduces the same coupling the operations seam exists to remove. It is + * recognised either by a client receiver or by the streaming-RPC call shape (a method-name + * string as the first argument), so aliasing the client into a local cannot hide it, while an + * adapter's or a store's listener-only `subscribe` is not counted. `sendRequest` is matched on + * the identifier rather than on `name(`, so `bind`, bracket access and a space before the paren + * all still count. */ +const RPC_ENTRY_POINT = + /\bsendRequest\b|\b\w*[Cc]lient(?:Ref)?(?:\.current)?\s*\??\.\s*subscribe\s*\(|\b\w*[Cc]lient\w*\s*\[\s*['"]subscribe['"]\s*\]|\.\s*subscribe\s*\(\s*['"`]/g -/** Adapters are where `sendRequest` is supposed to live; specs and fixtures are not product code. */ -const NOT_SCREEN_CODE = /(^|\/)(native-host-|default-host-)|\.test\.tsx?$|test-support/ +const MOBILE_ROOT = join(__dirname, '../..') -/** Routed in this PR, and each one must stay at zero. A screen that regrows an inline call has - * reopened the seam the operations adapters exist to close. */ -const ROUTED_SCREENS = [ - 'components/use-new-workspace-execution-target.ts', - 'components/use-new-workspace-repositories.ts', - 'components/use-new-workspace-runtime-context.ts', - 'components/use-new-workspace-setup-script.ts', - 'files/MobileFileExplorerPanel.tsx', - 'session/mobile-file-tap-open.ts', - 'session/use-mobile-native-chat-file-search.ts', - 'session/use-mobile-native-chat-readability.ts', - 'session/use-mobile-native-chat-session.ts', - 'session/use-mobile-native-chat-stop.ts', - 'session/use-mobile-session-document-readers.ts', - 'session/use-mobile-session-markdown-actions.ts', - 'session/use-mobile-session-terminal-input.ts', - 'session/use-mobile-session-terminal-stream-display.ts', - 'session/use-quick-commands.ts', - 'tasks/mobile-tasks-filter-pickers.tsx', - 'tasks/smart-source-paste-intent.ts', - 'tasks/use-mobile-tasks-client-settings-actions.tsx', - 'tasks/use-mobile-tasks-github-check-file-actions.tsx', - 'tasks/use-mobile-tasks-github-reply-merge-actions.tsx', - 'tasks/use-mobile-tasks-gitlab-github-status-actions.tsx', - 'tasks/use-mobile-tasks-item-detail-loading.tsx', - 'tasks/use-mobile-tasks-item-detail-metadata-effects.tsx', - 'tasks/use-mobile-tasks-linear-item-actions.tsx', - 'tasks/use-mobile-tasks-list-and-detail-effects.tsx', - 'tasks/use-mobile-tasks-project-detail-loading.tsx', - 'tasks/use-mobile-tasks-project-file-merge-actions.tsx', - 'tasks/use-mobile-tasks-project-loading-actions.tsx', - 'tasks/use-mobile-tasks-project-metadata-actions.tsx', - 'tasks/use-mobile-tasks-project-metadata-loading.tsx', - 'tasks/use-mobile-tasks-project-repository-resolution.tsx', - 'tasks/use-mobile-tasks-project-review-check-actions.tsx', - 'tasks/use-mobile-tasks-project-thread-reply-actions.tsx', - 'tasks/use-mobile-tasks-project-workspace-comment-actions.tsx', - 'tasks/use-mobile-tasks-provider-load-actions.tsx', - 'tasks/use-mobile-tasks-route-and-item-state.tsx', - 'tasks/use-mobile-tasks-runtime-hydration.tsx', - 'tasks/use-mobile-tasks-task-create-actions.tsx', - 'tasks/use-mobile-tasks-task-list-loading.tsx', - 'tasks/use-mobile-tasks-task-pagination-actions.tsx', - 'tasks/use-mobile-tasks-workspace-source-effects.tsx', - 'tasks/use-mobile-tasks-workspace-sparse-actions.tsx', - 'tasks/use-mobile-tasks-workspace-ssh-state.tsx', - 'worktree/use-retired-worktree-names.ts' -] as const +/** Adapters are where RPC is supposed to live. Listed by path, not by filename prefix, so a new + * screen hook cannot make itself invisible by choosing an adapter-shaped name. */ +const ADAPTER_FILES = new Set([ + 'src/accounts/default-host-account-operations.ts', + 'src/accounts/native-host-account-operations.ts', + 'src/device/default-device-operations.ts', + 'src/device/native-device-operations.ts', + 'src/files/default-host-file-explorer-operations.ts', + 'src/files/native-host-file-explorer-operations.ts', + 'src/session/default-host-session-browser-operations.ts', + 'src/session/default-host-session-file-operations.ts', + 'src/session/default-host-session-markdown-operations.ts', + 'src/session/default-host-session-native-chat-operations.ts', + 'src/session/default-host-session-operations.ts', + 'src/session/default-host-session-quick-command-operations.ts', + 'src/session/default-host-session-tab-operations.ts', + 'src/session/default-host-session-terminal-file-operations.ts', + 'src/session/default-host-session-terminal-operations.ts', + 'src/session/native-host-session-browser-operations.ts', + 'src/session/native-host-session-file-operations.ts', + 'src/session/native-host-session-markdown-operations.ts', + 'src/session/native-host-session-native-chat-operations.ts', + 'src/session/native-host-session-operations.ts', + 'src/session/native-host-session-quick-command-operations.ts', + 'src/session/native-host-session-tab-operations.ts', + 'src/session/native-host-session-terminal-file-operations.ts', + 'src/session/native-host-session-terminal-operations.ts', + 'src/tasks/default-host-task-detail-operations.ts', + 'src/tasks/default-host-task-item-file-operations.ts', + 'src/tasks/default-host-task-item-mutation-operations.ts', + 'src/tasks/default-host-task-item-review-operations.ts', + 'src/tasks/default-host-task-linear-operations.ts', + 'src/tasks/default-host-task-list-operations.ts', + 'src/tasks/default-host-task-operations.ts', + 'src/tasks/default-host-task-preference-operations.ts', + 'src/tasks/default-host-task-project-file-operations.ts', + 'src/tasks/default-host-task-project-mutation-operations.ts', + 'src/tasks/default-host-task-project-read-operations.ts', + 'src/tasks/default-host-task-provider-write-operations.ts', + 'src/tasks/default-host-task-read-operations.ts', + 'src/tasks/native-host-task-detail-operations.ts', + 'src/tasks/native-host-task-item-file-operations.ts', + 'src/tasks/native-host-task-item-mutation-operations.ts', + 'src/tasks/native-host-task-item-review-operations.ts', + 'src/tasks/native-host-task-linear-operations.ts', + 'src/tasks/native-host-task-list-operations.ts', + 'src/tasks/native-host-task-operations.ts', + 'src/tasks/native-host-task-preference-operations.ts', + 'src/tasks/native-host-task-project-file-operations.ts', + 'src/tasks/native-host-task-project-mutation-operations.ts', + 'src/tasks/native-host-task-project-read-operations.ts', + 'src/tasks/native-host-task-provider-write-operations.ts', + 'src/tasks/native-host-task-read-operations.ts', + 'src/worktree/default-host-workspace-creation-operations.ts', + 'src/worktree/native-host-workspace-creation-operations.ts', + 'src/worktree/native-host-workspace-creation-read-operations.ts', + 'src/worktree/native-host-workspace-creation-source-operations.ts', + 'src/worktree/rpc-workspace-creation-operations.ts' +]) + +/** Generated bundles are absent from a fresh checkout, so they cannot be pinned. */ +const NOT_SOURCE = /\.test\.tsx?$|test-support|\.generated\./ + +/** Every non-adapter file under `mobile/src` and `mobile/app` that still reaches the transport, + * pinned by content rather than by a total. Routing a call lowers a number here; adding one + * anywhere raises a number or adds a key, and either way this map has to change with it. */ +const INLINE_RPC_BY_FILE: Record = { + 'app/terminal-settings.tsx': 3, + 'src/agent-history/MobileAgentSessionHistoryPanel.tsx': 7, + 'src/agent-history/use-mobile-agent-history-state.ts': 2, + 'src/browser/use-mobile-browser-commands.ts': 5, + 'src/browser/use-mobile-browser-request.ts': 1, + 'src/browser/use-mobile-browser-stream.ts': 1, + 'src/components/codex-reset-credit-capability.ts': 2, + 'src/components/codex-reset-credit.ts': 3, + 'src/components/use-new-workspace-create-submit.ts': 1, + 'src/dictation/mobile-dictation-setup.ts': 10, + 'src/files/mobile-file-mutation-ownership.ts': 3, + 'src/files/mobile-file-preview-request.ts': 6, + 'src/files/mobile-file-tab-doc.ts': 4, + 'src/files/mobile-terminal-artifact-grant-refresh.ts': 2, + 'src/home/use-mobile-home-host-connections.ts': 1, + 'src/hooks/mobile-dictation-audio-chunk.ts': 1, + 'src/hooks/mobile-dictation-desktop-start.ts': 4, + 'src/hooks/use-mobile-dictation.ts': 4, + 'src/host-screen/host-screen-overlays.tsx': 1, + 'src/host-screen/use-host-repo-metadata.ts': 2, + 'src/host-screen/use-host-view-settings.ts': 2, + 'src/host-screen/use-host-worktree-actions.ts': 3, + 'src/notifications/mobile-notifications.ts': 4, + 'src/session/ai-vault-resume-launch.ts': 3, + 'src/session/ai-vault-resume-preparation.ts': 2, + 'src/session/github-pr-mutations.ts': 3, + 'src/session/github-pr-rpc.ts': 9, + 'src/session/mobile-clipboard-image.ts': 7, + 'src/session/mobile-diff-review-loaders.ts': 5, + 'src/session/mobile-image-attachment.ts': 2, + 'src/session/mobile-native-chat-image-attachment.ts': 1, + 'src/session/mobile-native-chat-image-send.ts': 2, + 'src/session/mobile-native-chat-open-file.ts': 2, + 'src/session/mobile-native-chat-send.ts': 3, + 'src/session/mobile-native-chat-session-option-persistence.ts': 1, + 'src/session/mobile-native-chat-stale-input.ts': 1, + 'src/session/mobile-new-tab-agent-loader.ts': 5, + 'src/session/mobile-session-tab-activation.ts': 3, + 'src/session/mobile-session-tabs-stream-health.ts': 1, + 'src/session/mobile-structured-agent-session-launch.ts': 3, + 'src/session/mobile-structured-agent-session-rpc.ts': 1, + 'src/session/mobile-terminal-stream-subscribe.ts': 2, + 'src/session/pr-ai-triage-launch.ts': 3, + 'src/session/use-live-worktree-name.ts': 2, + 'src/session/use-mobile-diff-review-comment-actions.ts': 1, + 'src/session/use-mobile-diff-review-git-actions.ts': 2, + 'src/session/use-mobile-diff-review-interactions.ts': 1, + 'src/session/use-mobile-diff-review-send-actions.ts': 3, + 'src/session/use-mobile-pr-actions.ts': 1, + 'src/session/use-mobile-pr-branch-context.ts': 2, + 'src/session/use-mobile-pr-comment-actions.ts': 1, + 'src/session/use-mobile-pr-title-action.ts': 1, + 'src/session/use-mobile-session-accessory-selection.ts': 1, + 'src/session/use-mobile-session-close-actions.ts': 1, + 'src/session/use-mobile-session-content-create-actions.ts': 2, + 'src/session/use-mobile-session-diff-comments.ts': 2, + 'src/session/use-mobile-session-startup.ts': 2, + 'src/session/use-mobile-session-tabs-reconciliation.ts': 1, + 'src/session/use-mobile-session-terminal-create-actions.ts': 2, + 'src/session/use-mobile-session-terminal-list.ts': 1, + 'src/session/use-mobile-session-terminal-send-actions.ts': 1, + 'src/session/use-mobile-structured-agent-state.ts': 1, + 'src/session/use-mobile-terminal-paste.ts': 1, + 'src/session/use-pr-bot-author-overrides.ts': 1, + 'src/source-control/MobileGitHistoryList.tsx': 1, + 'src/source-control/mobile-branch-base-ref.ts': 3, + 'src/source-control/mobile-commit-message-ai.ts': 4, + 'src/source-control/mobile-git-history.ts': 2, + 'src/source-control/mobile-hosted-review-create-intent-runner.ts': 1, + 'src/source-control/mobile-hosted-review-create-intent.ts': 3, + 'src/source-control/mobile-hosted-review-git-preparation.ts': 6, + 'src/source-control/mobile-hosted-review-remote-prerequisite.ts': 1, + 'src/source-control/mobile-hosted-review-service.ts': 8, + 'src/source-control/mobile-pr-link.ts': 8, + 'src/source-control/reveal-mobile-source-control-session-diff.ts': 2, + 'src/source-control/use-mobile-git-requests.ts': 1, + 'src/source-control/use-mobile-source-control-loaders.ts': 2, + 'src/source-control/use-mobile-source-control-openers.ts': 3, + 'src/tasks/composer-source-base-resolve.ts': 2, + 'src/tasks/setup-hook-trust.ts': 1, + 'src/tasks/smart-source-search-requests.ts': 5, + 'src/tasks/use-mobile-tasks-hosted-comment-review-actions.tsx': 4, + 'src/tasks/use-mobile-tasks-hosted-metadata-actions.tsx': 2, + 'src/tasks/use-mobile-tasks-workspace-create-actions.tsx': 1, + 'src/tasks/worktree-create-capability.ts': 1, + 'src/tasks/worktree-create-retry.ts': 1, + 'src/terminal/mobile-terminal-query-reply.ts': 2, + 'src/terminal/terminal-live-accessory-raw-send.ts': 2, + 'src/terminal/terminal-viewport-refit.ts': 1, + 'src/terminal/worker-terminal-takeover-report.ts': 2, + 'src/transport/direct-rpc-client.ts': 3, + 'src/transport/host-status-gates.ts': 1, + 'src/transport/mobile-endpoint-supervisor-test-fakes.ts': 2, + 'src/transport/mobile-relay-credential-rotation.ts': 2, + 'src/transport/mobile-relay-direct-upgrade.ts': 2, + 'src/transport/mobile-relay-pairing-recovery.ts': 2, + 'src/transport/mobile-relay-physical-client.ts': 2, + 'src/transport/mobile-relay-rpc-session.ts': 1, + 'src/transport/mobile-relay-rpc-streams.ts': 2, + 'src/transport/mobile-runtime-capability-negotiation.ts': 4, + 'src/transport/pairing-candidate-race.ts': 1, + 'src/transport/pairing-relay-candidate.ts': 4, + 'src/transport/pre-profile-pairing-coordinator.ts': 2, + 'src/transport/request-single-flight.ts': 2, + 'src/transport/rpc-client-request-tracker.ts': 3, + 'src/transport/rpc-client.ts': 2, + 'src/transport/runtime-capability-probe.ts': 1, + 'src/transport/stable-logical-rpc-client.ts': 3, + 'src/worktree/host-worktree-refresh.ts': 1, + 'src/worktree/worktree-catalog-snapshot-client.ts': 1 +} /** Four calls stay inline on purpose. Each has no adapter method that means the same thing, so - * routing it would change what reaches the host. The count is pinned so a fifth cannot appear. */ -const DELIBERATE_INLINE_CALLS: Record = { + * routing it would change what reaches the host. Counted separately from the map above so a + * swap for a different RPC in the same file is still visible in review. */ +const DELIBERATE_INLINE_CALLS: Record = { // `terminal.close` — closing the terminal, not the tab; the tab adapter's close is a tab close. - 'session/use-mobile-session-close-actions.ts': 1, - // `files.createFile` then `files.open` — note creation has no operations counterpart. - 'session/use-mobile-session-content-create-actions.ts': 2, + 'src/session/use-mobile-session-close-actions.ts': ['terminal.close'], + // Note creation has no operations counterpart. + 'src/session/use-mobile-session-content-create-actions.ts': ['files.createFile', 'files.open'], // The buffered submit; it needs the raw response to classify a partial write. - 'session/use-mobile-session-terminal-send-actions.ts': 1, - // `worktree.create` from a task item; the creation adapter builds the composer's params instead. - 'tasks/use-mobile-tasks-workspace-create-actions.tsx': 1 + 'src/session/use-mobile-session-terminal-send-actions.ts': ['terminal.send'], + // The composer's create builds different params and adds name-collision retry. + 'src/tasks/use-mobile-tasks-workspace-create-actions.tsx': ['worktree.create'] } -/** Every remaining inline call site under the screen directories. Lower is the only allowed - * direction: later PRs move the rest, and nothing may add a new one. */ -const REMAINING_INLINE_CALL_SITES = 112 - -const SOURCE_ROOT = join(__dirname, '..') -const APP_ROOT = join(__dirname, '../..', 'app') - -/** Route files live outside `src/`, so the account screen is checked by its own path. */ -const ROUTED_APP_SCREENS = ['h/[hostId]/accounts.tsx'] as const +/** Routed in this PR, and each one must stay at zero. A screen that regrows an inline call has + * reopened the seam the operations adapters exist to close. */ +const ROUTED_SCREENS = [ + 'app/h/[hostId]/accounts.tsx', + 'src/components/use-new-workspace-execution-target.ts', + 'src/components/use-new-workspace-repositories.ts', + 'src/components/use-new-workspace-runtime-context.ts', + 'src/components/use-new-workspace-setup-script.ts', + 'src/files/MobileFileExplorerPanel.tsx', + 'src/session/mobile-file-tap-open.ts', + 'src/session/use-mobile-native-chat-file-search.ts', + 'src/session/use-mobile-native-chat-readability.ts', + 'src/session/use-mobile-native-chat-stop.ts', + 'src/session/use-mobile-session-document-readers.ts', + 'src/session/use-mobile-session-markdown-actions.ts', + 'src/session/use-mobile-session-terminal-input.ts', + 'src/session/use-mobile-session-terminal-stream-display.ts', + 'src/session/use-quick-commands.ts', + 'src/tasks/mobile-tasks-filter-pickers.tsx', + 'src/tasks/smart-source-paste-intent.ts', + 'src/tasks/use-mobile-tasks-client-settings-actions.tsx', + 'src/tasks/use-mobile-tasks-github-check-file-actions.tsx', + 'src/tasks/use-mobile-tasks-github-reply-merge-actions.tsx', + 'src/tasks/use-mobile-tasks-gitlab-github-status-actions.tsx', + 'src/tasks/use-mobile-tasks-item-detail-loading.tsx', + 'src/tasks/use-mobile-tasks-item-detail-metadata-effects.tsx', + 'src/tasks/use-mobile-tasks-linear-item-actions.tsx', + 'src/tasks/use-mobile-tasks-list-and-detail-effects.tsx', + 'src/tasks/use-mobile-tasks-project-detail-loading.tsx', + 'src/tasks/use-mobile-tasks-project-file-merge-actions.tsx', + 'src/tasks/use-mobile-tasks-project-loading-actions.tsx', + 'src/tasks/use-mobile-tasks-project-metadata-actions.tsx', + 'src/tasks/use-mobile-tasks-project-metadata-loading.tsx', + 'src/tasks/use-mobile-tasks-project-repository-resolution.tsx', + 'src/tasks/use-mobile-tasks-project-review-check-actions.tsx', + 'src/tasks/use-mobile-tasks-project-thread-reply-actions.tsx', + 'src/tasks/use-mobile-tasks-project-workspace-comment-actions.tsx', + 'src/tasks/use-mobile-tasks-provider-load-actions.tsx', + 'src/tasks/use-mobile-tasks-route-and-item-state.tsx', + 'src/tasks/use-mobile-tasks-runtime-hydration.tsx', + 'src/tasks/use-mobile-tasks-task-create-actions.tsx', + 'src/tasks/use-mobile-tasks-task-list-loading.tsx', + 'src/tasks/use-mobile-tasks-task-pagination-actions.tsx', + 'src/tasks/use-mobile-tasks-workspace-source-effects.tsx', + 'src/tasks/use-mobile-tasks-workspace-sparse-actions.tsx', + 'src/tasks/use-mobile-tasks-workspace-ssh-state.tsx', + 'src/worktree/use-retired-worktree-names.ts' +] as const -function screenSources(): Array<{ path: string; source: string }> { - const found: Array<{ path: string; source: string }> = [] - const walk = (directory: string, prefix: string): void => { - for (const entry of readdirSync(directory, { withFileTypes: true })) { - const relative = `${prefix}${entry.name}` - if (entry.isDirectory()) { - walk(join(directory, entry.name), `${relative}/`) +function sourceFiles(): string[] { + const found: string[] = [] + const walk = (directory: string): void => { + for (const entry of readdirSync(directory)) { + const absolute = join(directory, entry) + if (statSync(absolute).isDirectory()) { + walk(absolute) continue } - if (!/\.tsx?$/.test(entry.name) || NOT_SCREEN_CODE.test(relative)) { - continue + const path = relative(MOBILE_ROOT, absolute).split('\\').join('/') + if (/\.tsx?$/.test(entry) && !NOT_SOURCE.test(path) && !ADAPTER_FILES.has(path)) { + found.push(path) } - found.push({ path: relative, source: readFileSync(join(directory, entry.name), 'utf8') }) } } - for (const directory of SCREEN_DIRECTORIES) { - walk(join(SOURCE_ROOT, directory), `${directory}/`) - } - return found + walk(join(MOBILE_ROOT, 'src')) + walk(join(MOBILE_ROOT, 'app')) + return found.sort() } -const countCalls = (source: string): number => (source.match(/sendRequest\(/g) ?? []).length +const read = (path: string): string => readFileSync(join(MOBILE_ROOT, path), 'utf8') +const countEntryPoints = (source: string): number => (source.match(RPC_ENTRY_POINT) ?? []).length describe('screen RPC ratchet', () => { - it('keeps every routed screen free of inline sendRequest', () => { - const regrown = [ - ...ROUTED_SCREENS.map((path) => [path, join(SOURCE_ROOT, path)] as const), - ...ROUTED_APP_SCREENS.map((path) => [path, join(APP_ROOT, path)] as const) - ] - .filter(([, absolute]) => countCalls(readFileSync(absolute, 'utf8')) > 0) - .map(([path]) => path) + it('keeps every routed screen free of inline RPC', () => { + const regrown = ROUTED_SCREENS.filter((path) => countEntryPoints(read(path)) > 0) expect(regrown).toEqual([]) }) - it('pins the calls left inline on purpose', () => { + it('pins which RPCs are left inline on purpose, by name not by count', () => { const actual = Object.fromEntries( Object.keys(DELIBERATE_INLINE_CALLS).map((path) => [ path, - countCalls(readFileSync(join(SOURCE_ROOT, path), 'utf8')) + [...read(path).matchAll(/sendRequest\(\s*'([\w.]+)'/g)].map((match) => match[1]).sort() ]) ) - expect(actual).toEqual(DELIBERATE_INLINE_CALLS) + const expected = Object.fromEntries( + Object.entries(DELIBERATE_INLINE_CALLS).map(([path, methods]) => [path, [...methods].sort()]) + ) + expect(actual).toEqual(expected) }) - it('never grows the screen-side RPC surface', () => { - const total = screenSources().reduce((sum, file) => sum + countCalls(file.source), 0) - expect(total).toBeLessThanOrEqual(REMAINING_INLINE_CALL_SITES) + it('pins every remaining inline RPC site so none can be added unnoticed', () => { + const actual: Record = {} + for (const path of sourceFiles()) { + const count = countEntryPoints(read(path)) + if (count > 0) { + actual[path] = count + } + } + expect(actual).toEqual(INLINE_RPC_BY_FILE) }) }) diff --git a/mobile/src/worktree/default-host-workspace-catalog-operations.ts b/mobile/src/worktree/default-host-workspace-catalog-operations.ts deleted file mode 100644 index 9bb742878282..000000000000 --- a/mobile/src/worktree/default-host-workspace-catalog-operations.ts +++ /dev/null @@ -1,9 +0,0 @@ -import type { RpcClient } from '../transport/rpc-client' -import type { HostWorkspaceCatalogOperations } from './host-workspace-catalog-operations' -import { nativeHostWorkspaceCatalogOperations } from './native-host-workspace-catalog-operations' - -export function defaultHostWorkspaceCatalogOperations( - client: RpcClient -): HostWorkspaceCatalogOperations { - return nativeHostWorkspaceCatalogOperations(client) -} diff --git a/mobile/src/worktree/default-host-workspace-operations.ts b/mobile/src/worktree/default-host-workspace-operations.ts deleted file mode 100644 index 8ee207f93974..000000000000 --- a/mobile/src/worktree/default-host-workspace-operations.ts +++ /dev/null @@ -1,7 +0,0 @@ -import type { RpcClient } from '../transport/rpc-client' -import type { HostWorkspaceOperations } from './host-workspace-operations' -import { nativeHostWorkspaceOperations } from './native-host-workspace-operations' - -export function defaultHostWorkspaceOperations(client: RpcClient): HostWorkspaceOperations { - return nativeHostWorkspaceOperations(client) -} diff --git a/mobile/src/worktree/host-workspace-catalog-operations.ts b/mobile/src/worktree/host-workspace-catalog-operations.ts deleted file mode 100644 index ac43f47f6adf..000000000000 --- a/mobile/src/worktree/host-workspace-catalog-operations.ts +++ /dev/null @@ -1,39 +0,0 @@ -import type { HostWorkspaceHostContext } from './host-workspace-host-context' -import type { RepoSummary } from './host-worktree-rpc-types' -import type { Worktree } from './workspace-list-types' -import type { WorkspaceViewSettings } from './workspace-view-settings' - -export type HostWorkspaceChange = { - type: 'ready' | 'end' | 'reposChanged' | 'worktreesChanged' | 'error' -} - -export type HostWorkspaceCatalogFetch = - // Why (STA-3123): a failed poll must stay distinguishable from an empty catalog, so the - // host's own error code survives instead of collapsing into a generic transport failure. - | { kind: 'request_failed'; code: string } - // `commit` is deferred so the caller runs its own staleness check first; a superseded - // response must not advance the binding's snapshot token. - | { kind: 'response'; invalidShape: boolean; commit(): Worktree[] | null } - -export type HostWorkspaceCatalogOperations = { - getViewSettings(): Promise - setViewSettings(settings: WorkspaceViewSettings): Promise - listRepos(): Promise - listWorkspaces(limit: number): Promise - /** - * Snapshot-token catalog poll. Bindings that omit it fall back to `listWorkspaces`, which - * always transfers the full catalog and cannot report a host-side error code. - */ - fetchWorkspaceCatalog?(hostId: string): Promise - /** SSH labels and host platform for multi-host catalogs; bindings that omit it keep single-host rows. */ - listHostContext?(): Promise - setPinned(workspaceId: string, pinned: boolean): Promise - removeWorkspace(workspaceId: string): Promise - activateWorkspace(workspaceId: string): Promise - sleepWorkspace(workspaceId: string): Promise - notifyForeground(): void - subscribeChanges(listener: (event: HostWorkspaceChange) => void): () => void - // Why: a provider that relays connection state can report `connected` a beat before its - // socket serves a catalog request. A direct socket omits this, so the flag is optional. - readonly connectionStateIsRelayed?: boolean -} diff --git a/mobile/src/worktree/host-workspace-operations.ts b/mobile/src/worktree/host-workspace-operations.ts deleted file mode 100644 index fc2294b981b1..000000000000 --- a/mobile/src/worktree/host-workspace-operations.ts +++ /dev/null @@ -1,9 +0,0 @@ -import type { HostWorkspaceCatalogOperations } from './host-workspace-catalog-operations' -import type { HostWorkspaceCreationOperations } from './host-workspace-creation-operations' - -/** Everything the workspace screens ask a host for, grouped by concern so a screen takes one prop - * and a provider is built once. Each namespace keeps its own contract file. */ -export type HostWorkspaceOperations = { - catalog: HostWorkspaceCatalogOperations - creation: HostWorkspaceCreationOperations -} diff --git a/mobile/src/worktree/native-host-workspace-catalog-operations.test.ts b/mobile/src/worktree/native-host-workspace-catalog-operations.test.ts deleted file mode 100644 index 7d45231b5c7d..000000000000 --- a/mobile/src/worktree/native-host-workspace-catalog-operations.test.ts +++ /dev/null @@ -1,171 +0,0 @@ -import { describe, expect, it, vi } from 'vitest' -import type { RpcClient } from '../transport/rpc-client' -import { nativeHostWorkspaceCatalogOperations } from './native-host-workspace-catalog-operations' - -describe('native host workspace operations', () => { - it('does not relay its connection state, so a first failure stays a failure', () => { - const client = { sendRequest: vi.fn(), notifyForeground: vi.fn(), subscribe: vi.fn() } - - expect( - nativeHostWorkspaceCatalogOperations(client as unknown as RpcClient).connectionStateIsRelayed - ).toBeUndefined() - }) - - it('maps named reads and mutations to the existing RPC authority', async () => { - const sendRequest = vi - .fn() - .mockResolvedValueOnce({ ok: true, result: { ui: { sortBy: 'recent' } } }) - .mockResolvedValueOnce({ ok: true, result: {} }) - .mockResolvedValueOnce({ ok: true, result: { repos: [{ id: 'repo-1' }] } }) - .mockResolvedValueOnce({ ok: true, result: { worktrees: [{ worktreeId: 'workspace-1' }] } }) - .mockResolvedValueOnce({ ok: true, result: {} }) - .mockResolvedValueOnce({ ok: true, result: {} }) - .mockResolvedValueOnce({ ok: true, result: {} }) - .mockResolvedValueOnce({ ok: true, result: {} }) - const client = { - sendRequest, - notifyForeground: vi.fn(), - subscribe: vi.fn(() => vi.fn()) - } as unknown as RpcClient - const operations = nativeHostWorkspaceCatalogOperations(client) - - await operations.getViewSettings() - await operations.setViewSettings({ sortBy: 'recent' }) - await operations.listRepos() - await operations.listWorkspaces(200) - await operations.setPinned('workspace-1', true) - await operations.activateWorkspace('workspace-1') - await operations.sleepWorkspace('workspace-1') - await expect(operations.removeWorkspace('workspace-1')).resolves.toBe(true) - - expect(sendRequest.mock.calls).toEqual([ - ['ui.get'], - ['ui.set', { sortBy: 'recent' }], - ['repo.list'], - ['worktree.ps', { limit: 200 }], - ['worktree.set', { worktree: 'id:workspace-1', isPinned: true }], - [ - 'worktree.activate', - { - worktree: 'id:workspace-1', - notifyClients: false, - navigation: 'caller' - } - ], - ['worktree.sleep', { worktree: 'id:workspace-1' }], - ['worktree.rm', { worktree: 'id:workspace-1', force: true }] - ]) - }) - - it('filters the generic host event stream into named workspace changes', () => { - let receive: ((payload: unknown) => void) | undefined - const unsubscribe = vi.fn() - const client = { - sendRequest: vi.fn(), - notifyForeground: vi.fn(), - subscribe: vi.fn((_method, _params, listener) => { - receive = listener - return unsubscribe - }) - } as unknown as RpcClient - const listener = vi.fn() - - const cleanup = nativeHostWorkspaceCatalogOperations(client).subscribeChanges(listener) - receive?.({ type: 'worktreesChanged' }) - receive?.({ type: 'terminalData', secret: 'must-not-forward' }) - cleanup() - - expect(listener).toHaveBeenCalledOnce() - expect(listener).toHaveBeenCalledWith({ type: 'worktreesChanged' }) - expect(unsubscribe).toHaveBeenCalledOnce() - }) - - it('polls the catalog with a snapshot token and reuses the confirmed rows when unchanged', async () => { - const sendRequest = vi - .fn() - .mockResolvedValueOnce({ - ok: true, - result: { snapshotId: 'snap-1', worktrees: [{ worktreeId: 'workspace-1' }] } - }) - .mockResolvedValueOnce({ ok: true, result: { snapshotId: 'snap-1', unchanged: true } }) - const operations = nativeHostWorkspaceCatalogOperations({ - sendRequest, - notifyForeground: vi.fn(), - subscribe: vi.fn() - } as unknown as RpcClient) - - const first = await operations.fetchWorkspaceCatalog!('host-1') - const firstRows = first.kind === 'response' ? first.commit() : null - const second = await operations.fetchWorkspaceCatalog!('host-1') - const secondRows = second.kind === 'response' ? second.commit() : null - - expect(sendRequest.mock.calls).toEqual([ - ['worktree.ps', { limit: 10_000, afterSnapshotId: null }], - ['worktree.ps', { limit: 10_000, afterSnapshotId: 'snap-1' }] - ]) - expect(firstRows).toEqual([{ worktreeId: 'workspace-1' }]) - // Why (bandwidth over relay): an unchanged reply still reasserts the confirmed rows. - expect(secondRows).toEqual([{ worktreeId: 'workspace-1' }]) - }) - - // Why (STA-3123): the host's own code has to survive, or an unreachable remote host - // is indistinguishable from a healthy host with zero workspaces. - it('passes the host error code through instead of collapsing it', async () => { - const sendRequest = vi - .fn() - .mockResolvedValue({ ok: false, error: { code: 'worktree_list_unavailable', message: 'x' } }) - const operations = nativeHostWorkspaceCatalogOperations({ - sendRequest, - notifyForeground: vi.fn(), - subscribe: vi.fn() - } as unknown as RpcClient) - - await expect(operations.fetchWorkspaceCatalog!('host-1')).resolves.toEqual({ - kind: 'request_failed', - code: 'worktree_list_unavailable' - }) - }) - - it('reads ssh labels, host overrides and platform for multi-host catalogs', async () => { - const sendRequest = vi - .fn() - .mockImplementation(async (method: string) => { - if (method === 'ssh.listTargetSummaries') { - return { ok: true, result: { targets: [{ id: 'ssh-1', label: 'Build box' }, { id: 7 }] } } - } - if (method === 'settings.get') { - return { ok: true, result: { settings: { hostSettingOverrides: { 'ssh:ssh-1': {} } } } } - } - return { ok: true, result: { platform: 'linux' } } - }) - const operations = nativeHostWorkspaceCatalogOperations({ - sendRequest, - notifyForeground: vi.fn(), - subscribe: vi.fn() - } as unknown as RpcClient) - - await expect(operations.listHostContext!()).resolves.toEqual({ - sshTargets: [{ id: 'ssh-1', label: 'Build box' }], - hostSettingOverrides: { 'ssh:ssh-1': {} }, - platform: 'linux' - }) - }) - - // Hosts that predate a method still list repos; labels degrade to host ids. - it('degrades host context when the older host rejects or drops the calls', async () => { - const sendRequest = vi.fn().mockImplementation(async () => { - throw new Error('unknown method') - }) - const operations = nativeHostWorkspaceCatalogOperations({ - sendRequest, - notifyForeground: vi.fn(), - subscribe: vi.fn() - } as unknown as RpcClient) - - await expect(operations.listHostContext!()).resolves.toEqual({ - sshTargets: [], - hostSettingOverrides: undefined, - platform: null - }) - }) -}) diff --git a/mobile/src/worktree/native-host-workspace-catalog-operations.ts b/mobile/src/worktree/native-host-workspace-catalog-operations.ts deleted file mode 100644 index 80b40b2da526..000000000000 --- a/mobile/src/worktree/native-host-workspace-catalog-operations.ts +++ /dev/null @@ -1,135 +0,0 @@ -import type { RuntimeClientEventStreamMessage } from '../../../src/shared/runtime-client-events' -import type { RpcClient } from '../transport/rpc-client' -import type { RpcSuccess } from '../transport/types' -import type { - HostWorkspaceChange, - HostWorkspaceCatalogOperations -} from './host-workspace-catalog-operations' -import { - readHostWorkspacePlatform, - readHostWorkspaceSettingOverrides, - readHostWorkspaceSshTargets -} from './host-workspace-host-context' -import type { RepoSummary } from './host-worktree-rpc-types' -import { WorktreeCatalogSnapshotClient } from './worktree-catalog-snapshot-client' -import type { Worktree } from './workspace-list-types' -import type { WorkspaceViewSettings } from './workspace-view-settings' - -export function nativeHostWorkspaceCatalogOperations( - client: RpcClient -): HostWorkspaceCatalogOperations { - // Why: the token is per-connection state, so it lives with the binding rather than the - // screen — a reconnect builds a new binding and correctly restarts from a full catalog. - const catalog = new WorktreeCatalogSnapshotClient() - return { - async getViewSettings() { - const response = await client.sendRequest('ui.get') - requireSuccess(response) - return ((response as RpcSuccess).result as { ui?: WorkspaceViewSettings }).ui ?? null - }, - async setViewSettings(settings) { - requireSuccess(await client.sendRequest('ui.set', settings)) - }, - async listRepos() { - const response = await client.sendRequest('repo.list') - requireSuccess(response) - return ((response as RpcSuccess).result as { repos: RepoSummary[] }).repos - }, - async listWorkspaces(limit) { - const response = await client.sendRequest('worktree.ps', { limit }) - requireSuccess(response) - return ((response as RpcSuccess).result as { worktrees: Worktree[] }).worktrees - }, - async fetchWorkspaceCatalog(hostId) { - const fetched = await catalog.fetch(client, hostId) - if (fetched.kind === 'request_failed') { - return fetched - } - return { - kind: 'response', - invalidShape: fetched.pending.admission.kind === 'invalid', - commit: () => catalog.admit(fetched.pending) - } - }, - async listHostContext() { - const [sshTargets, hostSettings, hostPlatform] = await Promise.all([ - optionalResult(client, 'ssh.listTargetSummaries'), - optionalResult(client, 'settings.get'), - optionalResult(client, 'host.platform') - ]) - return { - sshTargets: readHostWorkspaceSshTargets(sshTargets), - hostSettingOverrides: readHostWorkspaceSettingOverrides(hostSettings), - platform: readHostWorkspacePlatform(hostPlatform) - } - }, - async setPinned(workspaceId, pinned) { - requireSuccess( - await client.sendRequest('worktree.set', { - worktree: `id:${workspaceId}`, - isPinned: pinned - }) - ) - }, - async removeWorkspace(workspaceId) { - const response = await client.sendRequest('worktree.rm', { - worktree: `id:${workspaceId}`, - force: true - }) - return response.ok - }, - async activateWorkspace(workspaceId) { - requireSuccess( - await client.sendRequest('worktree.activate', { - worktree: `id:${workspaceId}`, - notifyClients: false, - navigation: 'caller' - }) - ) - }, - async sleepWorkspace(workspaceId) { - requireSuccess(await client.sendRequest('worktree.sleep', { worktree: `id:${workspaceId}` })) - }, - notifyForeground() { - client.notifyForeground() - }, - subscribeChanges(listener) { - return client.subscribe('runtime.clientEvents.subscribe', null, (payload) => { - const event = hostWorkspaceChange(payload) - if (event) { - listener(event) - } - }) - } - } -} - -function hostWorkspaceChange(payload: unknown): HostWorkspaceChange | null { - if (!payload || typeof payload !== 'object' || !('type' in payload)) { - return null - } - const event = payload as RuntimeClientEventStreamMessage | { type: 'error' } - return event.type === 'ready' || - event.type === 'end' || - event.type === 'reposChanged' || - event.type === 'worktreesChanged' || - event.type === 'error' - ? event - : null -} - -// Why: hosts that predate a method still list repos, so labels degrade to host ids. -async function optionalResult(client: RpcClient, method: string): Promise { - try { - const response = await client.sendRequest(method) - return response.ok ? (response as RpcSuccess).result : null - } catch { - return null - } -} - -function requireSuccess(response: { ok: boolean }): void { - if (!response.ok) { - throw new Error('host_workspace_operation_failed') - } -} diff --git a/mobile/src/worktree/native-host-workspace-creation-read-operations.ts b/mobile/src/worktree/native-host-workspace-creation-read-operations.ts index 199135303550..b8f94743d820 100644 --- a/mobile/src/worktree/native-host-workspace-creation-read-operations.ts +++ b/mobile/src/worktree/native-host-workspace-creation-read-operations.ts @@ -47,10 +47,10 @@ export function nativeHostWorkspaceCreationReadOperations( return readRetiredNameRegistryForRepo(result, repoId) }, async readRuntimeSettings() { - const result = await successfulResult<{ settings: NewWorkspaceRuntimeSettings }>( + const result = await successfulResult<{ settings?: NewWorkspaceRuntimeSettings }>( client.sendRequest('settings.get') ) - return result.settings + return result.settings ?? {} }, async readTrustedHooks() { const result = await successfulResult<{ diff --git a/mobile/src/worktree/native-host-workspace-operations.ts b/mobile/src/worktree/native-host-workspace-operations.ts deleted file mode 100644 index d99a238e09be..000000000000 --- a/mobile/src/worktree/native-host-workspace-operations.ts +++ /dev/null @@ -1,11 +0,0 @@ -import type { RpcClient } from '../transport/rpc-client' -import type { HostWorkspaceOperations } from './host-workspace-operations' -import { nativeHostWorkspaceCatalogOperations } from './native-host-workspace-catalog-operations' -import { nativeHostWorkspaceCreationOperations } from './native-host-workspace-creation-operations' - -export function nativeHostWorkspaceOperations(client: RpcClient): HostWorkspaceOperations { - return { - catalog: nativeHostWorkspaceCatalogOperations(client), - creation: nativeHostWorkspaceCreationOperations(client) - } -} From aefdf2d0340e0732a161069d1e3d347419db59fe Mon Sep 17 00:00:00 2001 From: Jinwoo-H Date: Wed, 9 Sep 2026 01:45:44 -0400 Subject: [PATCH 08/40] fix(mobile): await each per-repo GitHub count so one failure is a zero Returning the promise from inside the try let a rejected count escape the per-repo catch, reject the whole batch and reach the caller, which fires this without a handler. The inline call it replaced awaited and reported zero. The new test drives the real batching shape and fails if the await is removed. Claude-Session: https://claude.ai/code/session_01JNnE9qzUZMMnqpZWCqM3nb --- .../mobile-tasks-refactor-parity.test.ts | 4 +- ...mobile-tasks-github-count-failure.test.tsx | 95 +++++++++++++++++++ ...use-mobile-tasks-provider-load-actions.tsx | 5 +- 3 files changed, 101 insertions(+), 3 deletions(-) create mode 100644 mobile/src/tasks/use-mobile-tasks-github-count-failure.test.tsx diff --git a/mobile/src/tasks/mobile-tasks-refactor-parity.test.ts b/mobile/src/tasks/mobile-tasks-refactor-parity.test.ts index a2ff0be5dd61..20acdb373c09 100644 --- a/mobile/src/tasks/mobile-tasks-refactor-parity.test.ts +++ b/mobile/src/tasks/mobile-tasks-refactor-parity.test.ts @@ -25,9 +25,9 @@ const hash = (parts: string[] | string): string => * plus the row-target locals the adapters take in place of inline slug/number checks. Diff hooks, * declarations and styles are untouched. */ -const SCREEN_HOOKS = '0ef59ab331ad320a5ccabe8c227616af263ad2c468a805a6743dde8c186d7027' +const SCREEN_HOOKS = '9b2ac231e63169d3896ce30a3053262d30bc8f085456d75cbade522420205b02' const DIFF_HOOKS = '93c7189b32bed8456cc51814fffa8ce80cf62011ef968a9d53ddec2b9686f58f' -const STATEMENTS = 'e5d84617b7acbbdcaf17129d19670fac62a0399d967d9a6fc225cb9b807ae886' +const STATEMENTS = 'dd86f1ff89bf0bdbc3fbf159349d972a50d2dfa2607484848a34c4312b36ae60' const DECLARATIONS = 'cff54172af17a877789be1479c2eb6ca97d83c3e31dd831cd59395962f2b4c4a' const SEMANTICS = 'f767906884b93537f2c6369d6d0bd2d4cb39b4314c31cca9d8f9e5e9b78a75ee' const STYLES = '1db6af69c791d9963928541ad5310942fcbda6d984b422c90b6eb92b6816579a' diff --git a/mobile/src/tasks/use-mobile-tasks-github-count-failure.test.tsx b/mobile/src/tasks/use-mobile-tasks-github-count-failure.test.tsx new file mode 100644 index 000000000000..e6af00951da3 --- /dev/null +++ b/mobile/src/tasks/use-mobile-tasks-github-count-failure.test.tsx @@ -0,0 +1,95 @@ +import { createElement } from 'react' +import { act, create, type ReactTestRenderer } from 'react-test-renderer' +import { afterEach, describe, expect, it, vi } from 'vitest' + +// The module under test reaches the Tasks barrel, which pulls React Native in. Both barrels are +// stubbed with self-contained equivalents; `mapWithConcurrency` reproduces the shipped one +// (`mobile-tasks-item-mapping.ts`), which awaits each worker and so rejects the whole batch if +// any worker rejects. That is precisely the propagation this test pins the guard against. +vi.mock('./mobile-tasks-dependencies', () => ({ + CROSS_REPO_DISPLAY_LIMIT: 200, + PER_REPO_FETCH_LIMIT: 100, + extractGitHubIssueSourceError: () => null, + extractGitHubIssueSourceFallback: () => null, + isGitHubWorkItemsSshRemoteRequiredError: () => false, + useCallback: (callback: T): T => callback +})) +vi.mock('./mobile-tasks-legacy-foundation', () => ({ + GITHUB_REPO_CONCURRENCY: 3, + createGitHubTask: (item: unknown) => item, + async mapWithConcurrency( + items: T[], + limit: number, + worker: (item: T) => Promise + ): Promise { + const results: R[] = [] + let nextIndex = 0 + async function run(): Promise { + while (nextIndex < items.length) { + const index = nextIndex + nextIndex += 1 + results[index] = await worker(items[index]!) + } + } + await Promise.all(Array.from({ length: Math.min(limit, items.length) }, () => run())) + return results + }, + reconcileTeamSelection: () => new Set(), + scopeGitHubTaskSearch: (query: string): string => query, + taskTime: () => 0 +})) + +const { useMobileTasksProviderLoadActions } = + await import('./use-mobile-tasks-provider-load-actions') + +type CountOperations = { countGitHub: (payload: { repoId: string }) => Promise } +type LoadActions = { countGitHubItems: (operations: unknown, repos: unknown[]) => Promise } + +const repo = (id: string): { id: string } => ({ id }) + +describe('github work-item counting', () => { + let renderer: ReactTestRenderer | null = null + + function mount(): LoadActions { + let model: LoadActions | null = null + function Probe(): null { + model = useMobileTasksProviderLoadActions({ + appliedQuery: 'is:open', + githubKind: 'issues' + } as never) as unknown as LoadActions + return null + } + act(() => { + renderer = create(createElement(Probe)) + }) + if (!model) { + throw new Error('hook did not render') + } + return model + } + + afterEach(() => { + act(() => renderer?.unmount()) + renderer = null + vi.restoreAllMocks() + }) + + it('reads a failed per-repo count as zero and still resolves the total', async () => { + vi.spyOn(console, 'warn').mockImplementation(() => {}) + const countGitHub = vi.fn(async ({ repoId }: { repoId: string }) => { + if (repoId === 'repo-broken') { + throw new Error('count failed') + } + return repoId === 'repo-a' ? 3 : 4 + }) + const operations: CountOperations = { countGitHub } + const model = mount() + + // Returning the promise instead of awaiting it would let this rejection escape the per-repo + // catch and reject the whole batch, and the only caller fires this with no handler. + await expect( + model.countGitHubItems(operations, [repo('repo-a'), repo('repo-broken'), repo('repo-b')]) + ).resolves.toBe(7) + expect(countGitHub).toHaveBeenCalledTimes(3) + }) +}) diff --git a/mobile/src/tasks/use-mobile-tasks-provider-load-actions.tsx b/mobile/src/tasks/use-mobile-tasks-provider-load-actions.tsx index b1561ef0116c..46c6b6ad95e8 100644 --- a/mobile/src/tasks/use-mobile-tasks-provider-load-actions.tsx +++ b/mobile/src/tasks/use-mobile-tasks-provider-load-actions.tsx @@ -167,7 +167,10 @@ export function useMobileTasksProviderLoadActions(model: RuntimeHydrationModel) GITHUB_REPO_CONCURRENCY, async (repo) => { try { - return listOperations.countGitHub({ + // Awaited inside the try on purpose: returning the promise would let a per-repo + // rejection escape this catch, reject the whole batch and reach a caller with no + // handler. A failed count is a zero, not a failed load. + return await listOperations.countGitHub({ repoId: repo.id, query: scopeGitHubTaskSearch(appliedQuery, githubKind) }) From e1b7aa82237355f8ba44291035036719fbbbccce Mon Sep 17 00:00:00 2001 From: Jinwoo-H Date: Wed, 9 Sep 2026 01:45:44 -0400 Subject: [PATCH 09/40] refactor(mobile): drop the browser adapter methods nothing calls Only back, forward and reload have a consumer; the browser pane still issues its own RPCs. subscribe, navigate, scroll, click, insertText, keypress and dialog go, with the event and frame-comparison types that existed only for them. click's fallback had also lost main's move/down/up sequence and cited a caller that does not exist here. Claude-Session: https://claude.ai/code/session_01JNnE9qzUZMMnqpZWCqM3nb --- .../host-session-browser-operations.ts | 67 -------- .../native-host-session-browser-operations.ts | 147 +----------------- 2 files changed, 2 insertions(+), 212 deletions(-) diff --git a/mobile/src/session/host-session-browser-operations.ts b/mobile/src/session/host-session-browser-operations.ts index 22954d9cb4ea..3931007539a4 100644 --- a/mobile/src/session/host-session-browser-operations.ts +++ b/mobile/src/session/host-session-browser-operations.ts @@ -1,77 +1,10 @@ -import type { BrowserPointerModifier } from '../browser/MobileBrowserPointerModifiers' -import type { MobileBrowserScreencastRequest } from '../browser/browser-screencast-request' -import type { - BrowserScreencastFrame, - BrowserScreencastFrameMetadata -} from '../transport/browser-screencast-protocol' - export type HostSessionBrowserTarget = { workspaceId: string pageId: string } -export type HostSessionBrowserEvent = - | { - type: 'ready' | 'navigation' - tab: { - url: string - title: string - canGoBack: boolean - canGoForward: boolean - } - } - | { type: 'end' } - | { type: 'dialog'; dialogType: string; message: string } - | { type: 'dialogClosed' } - | { type: 'error'; message: string } - export type HostSessionBrowserOperations = { - subscribe( - target: HostSessionBrowserTarget, - request: MobileBrowserScreencastRequest, - listener: { - onEvent: (event: HostSessionBrowserEvent) => void - onFrame: (frame: BrowserScreencastFrame) => void - onError: (error: Error) => void - } - ): () => void - navigate(target: HostSessionBrowserTarget, url: string): Promise<{ url: string }> - scroll( - target: HostSessionBrowserTarget, - point: { x: number; y: number }, - delta: { dx: number; dy: number } - ): Promise - click( - target: HostSessionBrowserTarget, - point: { x: number; y: number }, - button: 'left' | 'right', - modifiers: BrowserPointerModifier[], - radius?: number - ): Promise - insertText(target: HostSessionBrowserTarget, text: string): Promise - keypress( - target: HostSessionBrowserTarget, - key: 'Enter' | 'Backspace' | 'Tab' | 'Escape' - ): Promise - dialog(target: HostSessionBrowserTarget, action: 'accept' | 'dismiss'): Promise back(target: HostSessionBrowserTarget): Promise forward(target: HostSessionBrowserTarget): Promise reload(target: HostSessionBrowserTarget): Promise } - -export function hostSessionBrowserFrameMetadataEqual( - left: BrowserScreencastFrameMetadata, - right: BrowserScreencastFrameMetadata -): boolean { - return ( - left.offsetTop === right.offsetTop && - left.pageScaleFactor === right.pageScaleFactor && - left.deviceWidth === right.deviceWidth && - left.deviceHeight === right.deviceHeight && - left.imageWidth === right.imageWidth && - left.imageHeight === right.imageHeight && - left.scrollOffsetX === right.scrollOffsetX && - left.scrollOffsetY === right.scrollOffsetY && - left.timestamp === right.timestamp - ) -} diff --git a/mobile/src/session/native-host-session-browser-operations.ts b/mobile/src/session/native-host-session-browser-operations.ts index e2fc3b8eacca..b3da99049e51 100644 --- a/mobile/src/session/native-host-session-browser-operations.ts +++ b/mobile/src/session/native-host-session-browser-operations.ts @@ -1,7 +1,5 @@ import type { RpcClient } from '../transport/rpc-client' -import type { RpcSuccess } from '../transport/types' import type { - HostSessionBrowserEvent, HostSessionBrowserOperations, HostSessionBrowserTarget } from './host-session-browser-operations' @@ -10,80 +8,6 @@ export function nativeHostSessionBrowserOperations( client: RpcClient ): HostSessionBrowserOperations { return { - subscribe(target, request, listener) { - try { - return client.subscribe( - 'browser.screencast', - { ...nativeTarget(target), ...request }, - (event) => { - const presented = nativeBrowserEvent(event) - if (presented) { - listener.onEvent(presented) - } - }, - { onBinaryFrame: listener.onFrame } - ) - } catch (error) { - listener.onError(browserOperationError(error)) - return () => {} - } - }, - async navigate(target, url) { - const result = await requestResult( - client, - 'browser.goto', - { ...nativeTarget(target), url }, - 30_000 - ) - if (!isRecord(result) || typeof result.url !== 'string') { - throw new Error('Browser navigation failed') - } - return { url: result.url } - }, - async scroll(target, point, delta) { - await requestResult(client, 'browser.mouseMove', { ...nativeTarget(target), ...point }, 5_000) - await requestResult( - client, - 'browser.mouseWheel', - { ...nativeTarget(target), ...delta }, - 5_000 - ) - }, - async click(target, point, button, modifiers, radius) { - // No move/down/up fallback here: the live caller wraps that sequence in a try/catch - // because pointer commands race page navigation, and a throwing copy of it would surface - // those races as errors the user never saw. - await client.sendRequest( - 'browser.mouseClick', - { - ...nativeTarget(target), - ...point, - button, - modifiers, - ...(radius === undefined ? {} : { radius }) - }, - { timeoutMs: 5_000 } - ) - }, - async insertText(target, text) { - await requestResult( - client, - 'browser.keyboardInsertText', - { ...nativeTarget(target), text }, - 5_000 - ) - }, - async keypress(target, key) { - await requestResult(client, 'browser.keypress', { ...nativeTarget(target), key }, 5_000) - }, - async dialog(target, action) { - await requestResult( - client, - action === 'accept' ? 'browser.dialogAccept' : 'browser.dialogDismiss', - nativeTarget(target), - 5_000 - ) - }, async back(target) { await requestResult(client, 'browser.back', nativeTarget(target)) }, @@ -100,76 +24,9 @@ function nativeTarget(target: HostSessionBrowserTarget): { worktree: string; pag return { worktree: `id:${target.workspaceId}`, page: target.pageId } } -async function requestResult( - client: RpcClient, - method: string, - payload: unknown, - timeoutMs = 15_000 -): Promise { - const response = await client.sendRequest(method, payload, { timeoutMs }) +async function requestResult(client: RpcClient, method: string, payload: unknown): Promise { + const response = await client.sendRequest(method, payload, { timeoutMs: 15_000 }) if (!response.ok) { throw new Error(response.error.message) } - return (response as RpcSuccess).result -} - -function nativeBrowserEvent(value: unknown): HostSessionBrowserEvent | null { - if (!isRecord(value)) { - return null - } - if (value.type === 'ready') { - const tab = isRecord(value.tab) ? value.tab : {} - return { - type: 'ready', - tab: { - url: typeof tab.url === 'string' ? tab.url : 'about:blank', - title: typeof tab.title === 'string' ? tab.title : '', - canGoBack: tab.canGoBack === true, - canGoForward: tab.canGoForward === true - } - } - } - if (value.type === 'navigation') { - const tab = isRecord(value.tab) ? value.tab : {} - return { - type: 'navigation', - tab: { - url: typeof tab.url === 'string' ? tab.url : 'about:blank', - title: typeof tab.title === 'string' ? tab.title : '', - canGoBack: tab.canGoBack === true, - canGoForward: tab.canGoForward === true - } - } - } - if (value.type === 'end' || value.type === 'dialogClosed') { - return { type: value.type } - } - if (value.type === 'dialog') { - return { - type: 'dialog', - dialogType: typeof value.dialogType === 'string' ? value.dialogType : 'alert', - message: typeof value.message === 'string' ? value.message : 'Browser dialog' - } - } - if (value.type === 'error') { - const nested = isRecord(value.error) ? value.error : {} - return { - type: 'error', - message: - typeof value.message === 'string' - ? value.message - : typeof nested.message === 'string' - ? nested.message - : 'Browser stream failed.' - } - } - return null -} - -function browserOperationError(error: unknown): Error { - return error instanceof Error ? error : new Error('Browser command failed') -} - -function isRecord(value: unknown): value is Record { - return typeof value === 'object' && value !== null && !Array.isArray(value) } From cb10440dcac7f037ceb3340eb47426554770ecdb Mon Sep 17 00:00:00 2001 From: Jinwoo-H Date: Wed, 9 Sep 2026 01:45:44 -0400 Subject: [PATCH 10/40] fix(mobile): remove a stream error callback that could never fire The native chat subscribe declared an onError the adapter never invoked, since the transport has none: a stream error arrives as an error frame through the listener, which is where the caller already handles it. The hook's second callback was unreachable, so it goes with the parameter. The terminal adapter's acknowledge was a no-op with no caller here or on main. Claude-Session: https://claude.ai/code/session_01JNnE9qzUZMMnqpZWCqM3nb --- .../host-session-native-chat-operations.ts | 5 +- .../host-session-terminal-operations.ts | 1 - ...native-host-session-terminal-operations.ts | 1 - .../session/use-mobile-native-chat-session.ts | 118 ++++++++---------- 4 files changed, 57 insertions(+), 68 deletions(-) diff --git a/mobile/src/session/host-session-native-chat-operations.ts b/mobile/src/session/host-session-native-chat-operations.ts index 635925405a09..fa37cb77a389 100644 --- a/mobile/src/session/host-session-native-chat-operations.ts +++ b/mobile/src/session/host-session-native-chat-operations.ts @@ -36,11 +36,12 @@ export type HostSessionNativeChatImageAttachResult = export type HostSessionNativeChatOperations = { /** Whether the serving host can read this workspace's agent transcripts. */ readability(workspaceId: string): Promise + /** No error callback: the transport has none, and a stream error arrives as an `error` frame + * through `onEvent`, which is where the caller already handles it. */ subscribe( target: HostSessionNativeChatTarget, limit: number, - onEvent: (event: MobileNativeChatStreamFrame) => void, - onError: () => void + onEvent: (event: MobileNativeChatStreamFrame) => void ): () => void read( target: HostSessionNativeChatTarget, diff --git a/mobile/src/session/host-session-terminal-operations.ts b/mobile/src/session/host-session-terminal-operations.ts index 144aded7d30b..5bffe947238c 100644 --- a/mobile/src/session/host-session-terminal-operations.ts +++ b/mobile/src/session/host-session-terminal-operations.ts @@ -57,7 +57,6 @@ export type HostSessionTerminalOperations = { onEvent: (event: HostSessionTerminalStreamEvent) => void, onError: () => void ): () => void - acknowledge(terminalId: string, throughSequence: number): void sendInput( terminalId: string, text: string, diff --git a/mobile/src/session/native-host-session-terminal-operations.ts b/mobile/src/session/native-host-session-terminal-operations.ts index a518aedc0471..835f8156b8c9 100644 --- a/mobile/src/session/native-host-session-terminal-operations.ts +++ b/mobile/src/session/native-host-session-terminal-operations.ts @@ -22,7 +22,6 @@ export function nativeHostSessionTerminalOperations( ) return unsubscribe }, - acknowledge() {}, async sendInput(terminalId, text, enter, clientId) { return client .sendRequest( diff --git a/mobile/src/session/use-mobile-native-chat-session.ts b/mobile/src/session/use-mobile-native-chat-session.ts index 86873816db7a..e5de241cea80 100644 --- a/mobile/src/session/use-mobile-native-chat-session.ts +++ b/mobile/src/session/use-mobile-native-chat-session.ts @@ -156,71 +156,61 @@ export function useMobileNativeChatSession(args: { sessionId, transcriptPath }) - const unsubscribe = operations.subscribe( - target, - limitRef.current, - (raw) => { - if (cancelled) { - return - } - const frame = raw as MobileNativeChatStreamFrame - const applied = applyMobileNativeChatStreamFrame({ - merger: mergerRef.current, - frame, - limit: limitRef.current, - replaceSnapshot: !snapshotSeenRef.current - }) - if (applied.kind === 'ignored') { - return - } - if (applied.kind === 'error') { - setRead({ operations, identity, status: 'error' }) - setError(applied.error) - return - } - if (frame.type === 'snapshot' && !applied.pending) { - // A pending window has no transcript behind it, so the snapshot that - // follows is still this subscription's base, not a reconnect replay. - snapshotSeenRef.current = true - } - if (applied.windowReplaced || frame.type === 'snapshot') { - // Why: any authoritative window (and any replay merge) invalidates an - // in-flight older-page request; stale results must not land on it. - streamGenerationRef.current += 1 - loadingEarlierRef.current = false - setLoadingEarlier(false) - } - if (applied.windowReplaced) { - // Only a genuinely fresh window resets the grown read window — an - // overlapping reconnect replay keeps the paged-in history and limit. - limitRef.current = INITIAL_LIMIT - beforeOffsetRef.current = applied.beforeOffset ?? null - setHasMore(applied.hasMore ?? applied.messages.length >= INITIAL_LIMIT) - } - setMessages(applied.messages) - if (!applied.windowReplaced && applied.hasMore != null) { - setHasMore(applied.hasMore) - } - if (!applied.windowReplaced && applied.beforeOffset != null) { - beforeOffsetRef.current = applied.beforeOffset - } - if (applied.cursorInvalidated) { - // Fall back to a growing-tail read so history trimmed by live appends - // cannot leave a gap between the retained window and the old cursor. - streamGenerationRef.current += 1 - loadingEarlierRef.current = false - setLoadingEarlier(false) - beforeOffsetRef.current = null - } - setRead({ operations, identity, status: applied.pending ? 'awaiting-transcript' : 'ready' }) - }, - () => { - if (!cancelled) { - setRead({ operations, identity, status: 'error' }) - setError('Transcript stream failed') - } + const unsubscribe = operations.subscribe(target, limitRef.current, (raw) => { + if (cancelled) { + return + } + const frame = raw as MobileNativeChatStreamFrame + const applied = applyMobileNativeChatStreamFrame({ + merger: mergerRef.current, + frame, + limit: limitRef.current, + replaceSnapshot: !snapshotSeenRef.current + }) + if (applied.kind === 'ignored') { + return + } + if (applied.kind === 'error') { + setRead({ operations, identity, status: 'error' }) + setError(applied.error) + return + } + if (frame.type === 'snapshot' && !applied.pending) { + // A pending window has no transcript behind it, so the snapshot that + // follows is still this subscription's base, not a reconnect replay. + snapshotSeenRef.current = true } - ) + if (applied.windowReplaced || frame.type === 'snapshot') { + // Why: any authoritative window (and any replay merge) invalidates an + // in-flight older-page request; stale results must not land on it. + streamGenerationRef.current += 1 + loadingEarlierRef.current = false + setLoadingEarlier(false) + } + if (applied.windowReplaced) { + // Only a genuinely fresh window resets the grown read window — an + // overlapping reconnect replay keeps the paged-in history and limit. + limitRef.current = INITIAL_LIMIT + beforeOffsetRef.current = applied.beforeOffset ?? null + setHasMore(applied.hasMore ?? applied.messages.length >= INITIAL_LIMIT) + } + setMessages(applied.messages) + if (!applied.windowReplaced && applied.hasMore != null) { + setHasMore(applied.hasMore) + } + if (!applied.windowReplaced && applied.beforeOffset != null) { + beforeOffsetRef.current = applied.beforeOffset + } + if (applied.cursorInvalidated) { + // Fall back to a growing-tail read so history trimmed by live appends + // cannot leave a gap between the retained window and the old cursor. + streamGenerationRef.current += 1 + loadingEarlierRef.current = false + setLoadingEarlier(false) + beforeOffsetRef.current = null + } + setRead({ operations, identity, status: applied.pending ? 'awaiting-transcript' : 'ready' }) + }) return () => { cancelled = true From cac634631b80b08f9ecbb6c670121254c8ec1e72 Mon Sep 17 00:00:00 2001 From: Jinwoo-H Date: Wed, 9 Sep 2026 01:45:44 -0400 Subject: [PATCH 11/40] refactor(mobile): drop the resolve request field the wire never carried resolveTerminalPath took a tabId the native adapter never sent, and main's wire had none either, so the caller's sourceTabId computation fed nothing. Claude-Session: https://claude.ai/code/session_01JNnE9qzUZMMnqpZWCqM3nb --- mobile/src/session/host-session-terminal-file-operations.ts | 1 - mobile/src/session/mobile-file-tap-open.ts | 5 ----- 2 files changed, 6 deletions(-) diff --git a/mobile/src/session/host-session-terminal-file-operations.ts b/mobile/src/session/host-session-terminal-file-operations.ts index fed85bebda72..9aa71937fc60 100644 --- a/mobile/src/session/host-session-terminal-file-operations.ts +++ b/mobile/src/session/host-session-terminal-file-operations.ts @@ -24,7 +24,6 @@ export type HostSessionTerminalFileTarget = export type HostSessionTerminalFileResolveRequest = { workspaceId: string - tabId: string terminalHandle: string | null pathText: string cwd: string | null diff --git a/mobile/src/session/mobile-file-tap-open.ts b/mobile/src/session/mobile-file-tap-open.ts index 91c1c1316424..7a9315cfa52d 100644 --- a/mobile/src/session/mobile-file-tap-open.ts +++ b/mobile/src/session/mobile-file-tap-open.ts @@ -71,14 +71,9 @@ async function openMobileFileTapAsync( // Keep the raw values on the wire; only their emptiness decides whether they are sent. const terminalHandle = options.terminalHandle?.trim() ? options.terminalHandle : null const cwd = options.cwd?.trim() ? options.cwd : null - const activation = options.getActivationState(false) - // Structured agent-session chat has no backing terminal; its tab id anchors the resolve. - const sourceTabId = - terminalHandle ?? activation.sourceTerminalHandle ?? activation.sourceSessionTabId ?? '' // Why: resolution opts into sibling-workspace hits; this caller honors resolved.workspaceId. const resolved = await options.operations.resolveTerminalPath({ workspaceId: options.worktreeId, - tabId: sourceTabId, terminalHandle, pathText: options.pathText, cwd, From d07fe48b4f856f2dd4444565a03a4a44759bdec9 Mon Sep 17 00:00:00 2001 From: Jinwoo-H Date: Wed, 9 Sep 2026 02:41:01 -0400 Subject: [PATCH 12/40] fix(mobile): restore the state commit between the two Tasks hydration phases read.bootstrap() folded status.get and the settings fan-out behind one await, so the supported commit ran only after all five requests succeeded. A post-connect timeout on any of the four left tasksSupportState at 'unknown', which the list surface renders as a bare spinner, and the effect deps do not change on that failure so it never retried. The probe is now read.tasksSupported() and the fan-out is read.bootstrap(), with the caller committing supported and clearing the error between them, as it did before the seam existed. Claude-Session: https://claude.ai/code/session_01JNnE9qzUZMMnqpZWCqM3nb --- mobile/app/h/[hostId]/accounts.tsx | 2 +- .../default-host-account-operations.ts | 7 +- .../src/accounts/host-account-operations.ts | 7 - .../native-host-account-operations.ts | 22 +-- .../src/device/default-device-operations.ts | 6 - mobile/src/device/device-operations.ts | 8 - mobile/src/device/native-device-operations.ts | 8 - mobile/src/session/github-pr-mutations.ts | 32 ++-- .../host-session-native-chat-operations.ts | 6 +- .../session/host-session-tab-operations.ts | 24 +-- .../session/mobile-native-chat-open-file.ts | 49 ------ .../mobile-session-route-parity.test.ts | 2 +- ...ive-host-session-native-chat-operations.ts | 26 +--- ...native-host-session-tab-operations.test.ts | 143 ++---------------- .../native-host-session-tab-operations.ts | 64 -------- ...native-host-session-terminal-operations.ts | 10 +- .../use-mobile-native-chat-file-search.ts | 1 + .../use-mobile-session-terminal-input.ts | 7 +- mobile/src/tasks/host-task-read-operations.ts | 4 + .../src/tasks/host-task-runtime-payloads.ts | 1 - .../mobile-tasks-refactor-parity.test.ts | 4 +- .../native-host-task-detail-operations.ts | 9 +- ...native-host-task-item-review-operations.ts | 2 +- .../tasks/native-host-task-list-operations.ts | 16 +- ...e-host-task-project-mutation-operations.ts | 70 ++++++--- ...ative-host-task-project-read-operations.ts | 20 ++- ...ive-host-task-provider-write-operations.ts | 5 +- .../tasks/native-host-task-read-operations.ts | 26 +--- ...use-mobile-tasks-hydration-phases.test.tsx | 93 ++++++++++++ .../use-mobile-tasks-runtime-hydration.tsx | 11 +- .../use-mobile-tasks-workspace-ssh-state.tsx | 7 +- .../src/transport/screen-rpc-ratchet.test.ts | 5 +- .../host-workspace-creation-operations.ts | 3 +- .../worktree/host-workspace-host-context.ts | 32 ---- ...host-workspace-creation-read-operations.ts | 2 +- 35 files changed, 262 insertions(+), 472 deletions(-) delete mode 100644 mobile/src/device/default-device-operations.ts delete mode 100644 mobile/src/device/device-operations.ts delete mode 100644 mobile/src/device/native-device-operations.ts create mode 100644 mobile/src/tasks/use-mobile-tasks-hydration-phases.test.tsx delete mode 100644 mobile/src/worktree/host-workspace-host-context.ts diff --git a/mobile/app/h/[hostId]/accounts.tsx b/mobile/app/h/[hostId]/accounts.tsx index cb14566df8be..7294a5391035 100644 --- a/mobile/app/h/[hostId]/accounts.tsx +++ b/mobile/app/h/[hostId]/accounts.tsx @@ -43,7 +43,7 @@ export default function AccountsScreen() { // Why: shared client per host. See docs/mobile-shared-client-per-host.md. const { client, state: connState } = useHostClient(hostId) const operations = useMemo( - () => (client && hostId ? defaultHostAccountOperations(client, hostId) : null), + () => (client && hostId ? defaultHostAccountOperations(client) : null), [client, hostId] ) const [hostName, setHostName] = useState('') diff --git a/mobile/src/accounts/default-host-account-operations.ts b/mobile/src/accounts/default-host-account-operations.ts index 88e6e7684fa3..1448a56ba70b 100644 --- a/mobile/src/accounts/default-host-account-operations.ts +++ b/mobile/src/accounts/default-host-account-operations.ts @@ -2,9 +2,6 @@ import type { RpcClient } from '../transport/rpc-client' import type { HostAccountOperations } from './host-account-operations' import { nativeHostAccountOperations } from './native-host-account-operations' -export function defaultHostAccountOperations( - client: RpcClient, - hostId: string -): HostAccountOperations { - return nativeHostAccountOperations(client, hostId) +export function defaultHostAccountOperations(client: RpcClient): HostAccountOperations { + return nativeHostAccountOperations(client) } diff --git a/mobile/src/accounts/host-account-operations.ts b/mobile/src/accounts/host-account-operations.ts index 626b54814693..8d9922b08737 100644 --- a/mobile/src/accounts/host-account-operations.ts +++ b/mobile/src/accounts/host-account-operations.ts @@ -3,20 +3,13 @@ import type { ProviderKey, RateLimitRuntimeTarget } from '../components/account-usage-state' -import type { CodexResetCreditRequestResult } from '../components/codex-reset-credit' -import type { CodexResetCreditExpectedScope } from '../../../src/shared/codex-reset-credit-scope' export type HostAccountOperations = { - loadHostName(hostId: string): Promise snapshot(): Promise select( provider: ProviderKey, accountId: string | null, codexTarget?: RateLimitRuntimeTarget | null ): Promise - readCodexResetCreditCapability(): Promise - consumeCodexResetCredit( - expectedScope: CodexResetCreditExpectedScope - ): Promise subscribe(listener: (snapshot: AccountsSnapshot) => void, onInvalid?: () => void): () => void } diff --git a/mobile/src/accounts/native-host-account-operations.ts b/mobile/src/accounts/native-host-account-operations.ts index 5f5dd27a54a7..7acd9d8b2238 100644 --- a/mobile/src/accounts/native-host-account-operations.ts +++ b/mobile/src/accounts/native-host-account-operations.ts @@ -3,22 +3,12 @@ import { type ProviderKey, type RateLimitRuntimeTarget } from '../components/account-usage-state' -import { requestCodexResetCredit } from '../components/codex-reset-credit' -import { readCodexResetCreditCapability } from '../components/codex-reset-credit-capability' -import { nativeDeviceOperations } from '../device/native-device-operations' -import { loadHosts } from '../transport/host-store' import type { RpcClient } from '../transport/rpc-client' import type { RpcSuccess } from '../transport/types' import type { HostAccountOperations } from './host-account-operations' -export function nativeHostAccountOperations( - client: RpcClient, - hostId: string -): HostAccountOperations { +export function nativeHostAccountOperations(client: RpcClient): HostAccountOperations { return { - async loadHostName(hostId) { - return (await loadHosts()).find((host) => host.id === hostId)?.name ?? null - }, async snapshot() { const response = await client.sendRequest('accounts.list') requireSuccess(response) @@ -34,16 +24,6 @@ export function nativeHostAccountOperations( : { accountId } requireSuccess(await client.sendRequest(method, params)) }, - readCodexResetCreditCapability() { - return readCodexResetCreditCapability(client) - }, - consumeCodexResetCredit(expectedScope) { - return requestCodexResetCredit(client, { - hostId, - expectedScope, - createIdempotencyKey: () => nativeDeviceOperations.randomNonce() - }) - }, subscribe(listener, onInvalid) { return client.subscribe('accounts.subscribe', null, (payload) => { if (!payload || typeof payload !== 'object') { diff --git a/mobile/src/device/default-device-operations.ts b/mobile/src/device/default-device-operations.ts deleted file mode 100644 index 6940fb09285c..000000000000 --- a/mobile/src/device/default-device-operations.ts +++ /dev/null @@ -1,6 +0,0 @@ -import type { DeviceOperations } from './device-operations' -import { nativeDeviceOperations } from './native-device-operations' - -export function defaultDeviceOperations(): DeviceOperations { - return nativeDeviceOperations -} diff --git a/mobile/src/device/device-operations.ts b/mobile/src/device/device-operations.ts deleted file mode 100644 index e179863d5ae7..000000000000 --- a/mobile/src/device/device-operations.ts +++ /dev/null @@ -1,8 +0,0 @@ -/** Device capabilities a screen reaches through its host binding instead of importing a native - * module directly, so the same screen runs against a non-native provider later. - * - * Deliberately narrow: only what a caller on this branch reads. Haptics, clipboard and external - * links join it when the screens that use them are routed. */ -export type DeviceOperations = { - randomNonce(): string -} diff --git a/mobile/src/device/native-device-operations.ts b/mobile/src/device/native-device-operations.ts deleted file mode 100644 index d791ea18e184..000000000000 --- a/mobile/src/device/native-device-operations.ts +++ /dev/null @@ -1,8 +0,0 @@ -import * as ExpoCrypto from 'expo-crypto' -import type { DeviceOperations } from './device-operations' - -export const nativeDeviceOperations: DeviceOperations = { - randomNonce() { - return ExpoCrypto.randomUUID() - } -} diff --git a/mobile/src/session/github-pr-mutations.ts b/mobile/src/session/github-pr-mutations.ts index e7327fc76b55..fad0d0ea22b6 100644 --- a/mobile/src/session/github-pr-mutations.ts +++ b/mobile/src/session/github-pr-mutations.ts @@ -19,10 +19,14 @@ type RawResult = { ok: true; result: unknown } | { ok: false; error: string } async function sendRaw( client: RpcRequestSender, method: string, - params: Record + params: Record, + options?: { timeoutMs?: number } ): Promise { try { - const response = await client.sendRequest(method, params) + // Keep the two-argument call shape when no timeout is requested. + const response = options + ? await client.sendRequest(method, params, options) + : await client.sendRequest(method, params) if (!response.ok) { return { ok: false, error: response.error?.message || `Request failed: ${method}` } } @@ -166,7 +170,8 @@ export async function fetchUpdatePRState( export async function fetchRequestPRReviewers( client: RpcRequestSender, worktreeId: string, - args: { prNumber: number; reviewers: string[]; prRepo?: GitHubPrRepoSlug | null } + args: { prNumber: number; reviewers: string[]; prRepo?: GitHubPrRepoSlug | null }, + options?: { timeoutMs?: number } ): Promise { return sendGithubPrMutation( client, @@ -176,7 +181,8 @@ export async function fetchRequestPRReviewers( worktreeId, { prNumber: args.prNumber, reviewers: args.reviewers }, { prRepo: args.prRepo } - ) + ), + options ) } @@ -211,7 +217,8 @@ export async function fetchAddPRReviewCommentReply( path?: string line?: number prRepo?: GitHubPrRepoSlug | null - } + }, + options?: { timeoutMs?: number } ): Promise { const params: Record = { prNumber: args.prNumber, @@ -232,7 +239,8 @@ export async function fetchAddPRReviewCommentReply( 'github.addPRReviewCommentReply', buildGithubPrParams('github.addPRReviewCommentReply', worktreeId, params, { prRepo: args.prRepo - }) + }), + options ) } @@ -247,7 +255,8 @@ export async function fetchAddIssueComment( // Why: the host addresses the comment by this; an issue row sent as 'pr' targets the // wrong conversation. PR call sites omit it. type?: 'issue' | 'pr' - } + }, + options?: { timeoutMs?: number } ): Promise { const params: Record = { number: args.prNumber, @@ -257,7 +266,8 @@ export async function fetchAddIssueComment( return sendGithubPrMutation( client, 'github.addIssueComment', - buildGithubPrParams('github.addIssueComment', worktreeId, params, { prRepo: args.prRepo }) + buildGithubPrParams('github.addIssueComment', worktreeId, params, { prRepo: args.prRepo }), + options ) } @@ -267,7 +277,8 @@ export async function fetchAddIssueComment( export async function fetchResolveReviewThread( client: RpcRequestSender, worktreeId: string, - args: { threadId: string; resolve: boolean; prRepo?: GitHubPrRepoSlug | null } + args: { threadId: string; resolve: boolean; prRepo?: GitHubPrRepoSlug | null }, + options?: { timeoutMs?: number } ): Promise { const response = await sendRaw( client, @@ -277,7 +288,8 @@ export async function fetchResolveReviewThread( worktreeId, { threadId: args.threadId, resolve: args.resolve }, { prRepo: args.prRepo } - ) + ), + options ) if (!response.ok) { return { diff --git a/mobile/src/session/host-session-native-chat-operations.ts b/mobile/src/session/host-session-native-chat-operations.ts index fa37cb77a389..419ee0307b34 100644 --- a/mobile/src/session/host-session-native-chat-operations.ts +++ b/mobile/src/session/host-session-native-chat-operations.ts @@ -56,7 +56,6 @@ export type HostSessionNativeChatOperations = { resolvedLaunchDraft?: { text: string; createdAt: number }, typeCommand?: boolean ): Promise - prepareCommit(target: HostSessionNativeChatTarget, deadline?: number): Promise respond( target: HostSessionNativeChatTarget, text: string, @@ -75,8 +74,11 @@ export type HostSessionNativeChatOperations = { followedByText?: boolean ): Promise releaseImages?(target: HostSessionNativeChatTarget, references: readonly string[]): Promise + /** Drops the legacy full-inventory fallback's cached listing for a workspace. Without it a + * second visit inside one connection serves the first read's inventory, so a file created in + * between is missing from `@` autocomplete. */ + resetFileSearchCache(workspaceId: string): void /** Null when the host refused the search. An empty array is a real answer the caller may * cache; a refusal must not be cached, or the next keystroke would never retry. */ searchFiles(target: HostSessionNativeChatTarget, query: string): Promise - openFile(target: HostSessionNativeChatTarget, pathText: string): Promise } diff --git a/mobile/src/session/host-session-tab-operations.ts b/mobile/src/session/host-session-tab-operations.ts index bd46d8075935..b55c24c89a11 100644 --- a/mobile/src/session/host-session-tab-operations.ts +++ b/mobile/src/session/host-session-tab-operations.ts @@ -1,32 +1,12 @@ import type { SessionTabsResult } from './mobile-session-route-types' -import type { HostSessionRuntimeCapabilities } from './host-session-runtime-capabilities' -import type { MobileNewTabAgentOption } from './mobile-new-tab-agent-options' export type HostSessionTabCloseResult = | { outcome: 'closed' } | { outcome: 'refused'; reason: string | null } -export type HostSessionQuickCommandLaunchResult = { - snapshot: SessionTabsResult - tabId: string - initialInput: { text: string; enter: false; successToast: string } | null -} - export type HostSessionTabOperations = { - streamFirstStartup?: boolean - runtimeCapabilities(): Promise - snapshot(workspaceId: string): Promise - subscribe( - workspaceId: string, - onSnapshot: (snapshot: SessionTabsResult) => void, - onError: () => void - ): () => void - agentOptions(workspaceId: string): Promise - createQuickCommand?( - workspaceId: string, - commandId: string - ): Promise createBrowser(workspaceId: string, url: string): Promise<{ browserPageId?: string }> - activate(workspaceId: string, tabId: string, leafId?: string): Promise close(workspaceId: string, tabId: string): Promise } + +export type { SessionTabsResult } diff --git a/mobile/src/session/mobile-native-chat-open-file.ts b/mobile/src/session/mobile-native-chat-open-file.ts index 685be5689db6..3de6755b4b33 100644 --- a/mobile/src/session/mobile-native-chat-open-file.ts +++ b/mobile/src/session/mobile-native-chat-open-file.ts @@ -1,6 +1,4 @@ import { splitFilePathLineSuffix } from '../components/markdown-file-path-detection' -import type { RuntimeTerminalPathResolution } from '../../../src/shared/runtime-types' -import type { RpcClient } from '../transport/rpc-client' import { openMobileFileTap, type FileTapSessionTab, @@ -30,50 +28,3 @@ export function openMobileNativeChatFileTap( column }) } - -export async function resolveMobileNativeChatWorktreePath(args: { - client: RpcClient - worktreeId: string - pathText: string - terminal: string | null -}): Promise { - try { - const response = await args.client.sendRequest('files.resolveTerminalPath', { - worktree: `id:${args.worktreeId}`, - pathText: args.pathText, - ...(args.terminal ? { terminal: args.terminal } : {}) - }) - if (!response.ok) { - return null - } - const resolved = response.result as RuntimeTerminalPathResolution - if (!resolved.exists || resolved.isDirectory) { - return null - } - return resolved.openTarget?.kind === 'worktree-file' - ? resolved.openTarget.relativePath - : (resolved.relativePath ?? null) - } catch { - return null - } -} - -export async function openMobileNativeChatFile(args: { - client: RpcClient - worktreeId: string - pathText: string - terminal: string | null -}): Promise { - const relativePath = await resolveMobileNativeChatWorktreePath(args) - if (!relativePath) { - return - } - try { - await args.client.sendRequest('files.open', { - worktree: `id:${args.worktreeId}`, - relativePath - }) - } catch { - // Best-effort open from transcript content. - } -} diff --git a/mobile/src/session/mobile-session-route-parity.test.ts b/mobile/src/session/mobile-session-route-parity.test.ts index d18b374fdd0e..dbf204dcd96c 100644 --- a/mobile/src/session/mobile-session-route-parity.test.ts +++ b/mobile/src/session/mobile-session-route-parity.test.ts @@ -70,7 +70,7 @@ const HEAD_CALLBACK_BODY_SHA256 = 'e66e6436cdb9a66e870c06fdfc140106502fbeddd8db4 const HEAD_EFFECT_SHA256 = 'd9ebfaabc1e79773cdada7ab370b20459ed972f1f8edce1652199f4d0391cd13' const HEAD_CONTENT_HOOK_SHA256 = '9c3b612fef3f370d66873aefdbe1d701f20cb64ded31fef5cc45fde6f8189581' const HEAD_NESTED_FUNCTION_SHA256 = - '1dc163bbb2c1b4c9f8ff46514d6d5dcfc987c01a98d92a5c90058a868f55e089' + 'd0aada4091de4551fcb5edabad4aa84249799d2fd3244c0f7493eadb4fe3ba58' const HEAD_NATIVE_REGISTRATION_SHA256 = 'cab85e4e4a3f43289ba93ddea9ccce57aea83e0bf14fd1620a965aad0c1cb49e' const HEAD_NATIVE_REMOVAL_SHA256 = diff --git a/mobile/src/session/native-host-session-native-chat-operations.ts b/mobile/src/session/native-host-session-native-chat-operations.ts index 27b5e8d9af90..9828df79fb1a 100644 --- a/mobile/src/session/native-host-session-native-chat-operations.ts +++ b/mobile/src/session/native-host-session-native-chat-operations.ts @@ -2,8 +2,6 @@ import type { RpcClient } from '../transport/rpc-client' import { buildNativeChatSubscriptionId } from '../../../src/shared/native-chat-stream-unsubscribe' import { isFloatingWorkspaceWorktreeId } from './floating-workspace' import { isMobileNativeChatTranscriptReadable } from './mobile-native-chat-eligibility' -import { openMobileNativeChatFile } from './mobile-native-chat-open-file' -import { healMobileNativeChatStaleInput } from './mobile-native-chat-stale-input' import { sendMobileNativeChatMessageWithOutcome, typeMobileNativeChatCommandWithOutcome, @@ -80,17 +78,6 @@ export function nativeHostSessionNativeChatOperations( } return sendNative(target, text, true, client, deadline, clearInputFirst, resolvedLaunchDraft) }, - prepareCommit(target, deadline) { - if (!target.terminalId) { - return Promise.resolve(false) - } - return healMobileNativeChatStaleInput({ - client, - terminal: target.terminalId, - deviceToken: target.clientId, - deadline - }) - }, respond(target, text, enter, deadline) { return sendNative(target, text, enter, client, deadline) }, @@ -99,6 +86,11 @@ export function nativeHostSessionNativeChatOperations( // had parked on its input line. return sendNative(target, escape(), false, client, deadline) }, + resetFileSearchCache(workspaceId) { + searchSupported = null + legacyPathsByWorkspace.delete(workspaceId) + legacyLoadByWorkspace.delete(workspaceId) + }, async searchFiles(target, query) { if (searchSupported !== false) { const response = await client.sendRequest('files.searchPaths', { @@ -141,14 +133,6 @@ export function nativeHostSessionNativeChatOperations( legacyPathsByWorkspace.set(target.workspaceId, paths) } return rankSuggestions(legacyPaths, query, FILE_RESULT_LIMIT) - }, - openFile(target, pathText) { - return openMobileNativeChatFile({ - client, - worktreeId: target.workspaceId, - pathText, - terminal: target.terminalId - }) } } } diff --git a/mobile/src/session/native-host-session-tab-operations.test.ts b/mobile/src/session/native-host-session-tab-operations.test.ts index ef10918eec25..5161e000d852 100644 --- a/mobile/src/session/native-host-session-tab-operations.test.ts +++ b/mobile/src/session/native-host-session-tab-operations.test.ts @@ -1,59 +1,25 @@ import { describe, expect, it, vi } from 'vitest' import type { RpcClient } from '../transport/rpc-client' -import { LogicalClientCutoverError } from '../transport/stable-logical-rpc-client' import { nativeHostSessionTabOperations } from './native-host-session-tab-operations' describe('native host session tab operations', () => { - it('projects status into the reviewed Session feature gates', async () => { - const sendRequest = vi.fn().mockResolvedValue({ - ok: true, - result: { - capabilities: [ - 'browser.screencast.v1', - 'aiVault.v1', - 'terminal.quick-commands.v1', - 'terminal.query-reply-input.v1', - 'secret.unreviewed.v1' - ] - } - }) - const operations = nativeHostSessionTabOperations({ - sendRequest - } as unknown as RpcClient) - - await expect(operations.runtimeCapabilities()).resolves.toEqual({ - browserScreencastSupported: true, - agentHistorySupported: true, - quickCommandsSupported: true, - terminalQueryReplyInputSupported: true - }) - expect(sendRequest).toHaveBeenCalledWith('status.get') - }) - - it('maps named lifecycle operations to the existing caller-local RPCs', async () => { + it('maps the two named lifecycle operations to the caller-local RPCs', async () => { const sendRequest = vi .fn() - .mockResolvedValueOnce({ ok: true, result: sessionSnapshot(1) }) .mockResolvedValueOnce({ ok: true, result: { browserPageId: 'browser-1' } }) - .mockResolvedValueOnce({ ok: true, result: sessionSnapshot(3) }) .mockResolvedValueOnce({ ok: true, result: { closed: true } }) const operations = nativeHostSessionTabOperations({ sendRequest } as unknown as RpcClient) - await expect(operations.snapshot('workspace-1')).resolves.toEqual(sessionSnapshot(1)) await expect(operations.createBrowser('workspace-1', 'https://example.com')).resolves.toEqual({ browserPageId: 'browser-1' }) - await expect(operations.activate('workspace-1', 'tab-1', 'leaf-1')).resolves.toEqual( - sessionSnapshot(3) - ) await expect(operations.close('workspace-1', 'tab-1')).resolves.toEqual({ outcome: 'closed' }) expect(sendRequest.mock.calls).toEqual([ - ['session.tabs.list', { worktree: 'id:workspace-1' }], [ 'browser.tabCreate', { @@ -65,104 +31,30 @@ describe('native host session tab operations', () => { // reconnect leaves the composer spinning with no error. { timeoutMs: 30_000 } ], - [ - 'session.tabs.activate', - { - worktree: 'id:workspace-1', - tabId: 'tab-1', - leafId: 'leaf-1', - notifyClients: false, - navigation: 'caller', - intent: 'user' - } - ], ['session.tabs.close', { worktree: 'id:workspace-1', tabId: 'tab-1', reason: 'user' }] ]) }) - it('forwards only snapshot events and preserves subscription cleanup', () => { - const unsubscribe = vi.fn() - let listener: ((event: unknown) => void) | null = null - const subscribe = vi.fn((_method, _params, onData) => { - listener = onData - return unsubscribe - }) - const onSnapshot = vi.fn() + it('treats a create that answers without a page id as a create, not a failure', async () => { const operations = nativeHostSessionTabOperations({ - subscribe + sendRequest: vi.fn().mockResolvedValue({ ok: true, result: {} }) } as unknown as RpcClient) - const cleanup = operations.subscribe('workspace-1', onSnapshot, vi.fn()) - listener?.({ type: 'ready' }) - listener?.({ type: 'updated', ...sessionSnapshot(3) }) - cleanup() - - expect(subscribe).toHaveBeenCalledWith( - 'session.tabs.subscribe', - { worktree: 'id:workspace-1' }, - expect.any(Function) + await expect(operations.createBrowser('workspace-1', 'https://example.com')).resolves.toEqual( + {} ) - expect(onSnapshot).toHaveBeenCalledWith({ - type: 'updated', - ...sessionSnapshot(3) - }) - expect(unsubscribe).toHaveBeenCalledOnce() }) - // Why: a host-side subscription cleanup ends the stream; without degrading, the tab - // list freezes on its last snapshot and never refetches. - it('degrades the stream on end and error rather than dropping them silently', () => { - let listener: ((event: unknown) => void) | null = null - const subscribe = vi.fn((_method, _params, onData) => { - listener = onData - return vi.fn() - }) - const onSnapshot = vi.fn() - const onError = vi.fn() - const operations = nativeHostSessionTabOperations({ subscribe } as unknown as RpcClient) - - operations.subscribe('workspace-1', onSnapshot, onError) - listener?.({ type: 'end' }) - listener?.({ type: 'error' }) - - expect(onSnapshot).not.toHaveBeenCalled() - expect(onError).toHaveBeenCalledTimes(2) - }) - - // Why: a relay-to-direct cutover rejects the in-flight request; activation is idempotent, - // so one retry keeps the host's active tab in step with the tab the user just tapped. - it('retries activation once after a logical client cutover', async () => { - const sendRequest = vi - .fn() - .mockRejectedValueOnce(new LogicalClientCutoverError('cutover')) - .mockResolvedValueOnce({ ok: true, result: sessionSnapshot(4) }) - const operations = nativeHostSessionTabOperations({ sendRequest } as unknown as RpcClient) - - await expect(operations.activate('workspace-1', 'tab-1')).resolves.toEqual(sessionSnapshot(4)) - expect(sendRequest).toHaveBeenCalledTimes(2) - }) - - it('loads enabled agent choices', async () => { - const sendRequest = vi.fn(async (method) => { - if (method === 'settings.get') { - return { - ok: true, - result: { settings: { defaultTuiAgent: 'codex', disabledTuiAgents: [] } } - } - } - if (method === 'preflight.detectAgents') { - return { ok: true, result: ['claude', 'codex'] } - } - return { ok: true, result: sessionSnapshot(4) } - }) + it('reports the host message when a browser create is refused', async () => { const operations = nativeHostSessionTabOperations({ - sendRequest + sendRequest: vi + .fn() + .mockResolvedValue({ ok: false, error: { code: 'busy', message: 'Browser busy' } }) } as unknown as RpcClient) - await expect(operations.agentOptions('global-floating-terminal')).resolves.toEqual([ - { agent: 'codex', label: 'Codex' }, - { agent: 'claude', label: 'Claude' } - ]) + await expect(operations.createBrowser('workspace-1', 'https://example.com')).rejects.toThrow( + 'Browser busy' + ) }) it('keeps refused closes visible to the shared screen', async () => { @@ -179,14 +71,3 @@ describe('native host session tab operations', () => { }) }) }) - -function sessionSnapshot(snapshotVersion: number) { - return { - worktree: 'workspace-1', - publicationEpoch: 'epoch-1', - snapshotVersion, - tabs: [], - activeTabId: null, - activeTabType: null - } -} diff --git a/mobile/src/session/native-host-session-tab-operations.ts b/mobile/src/session/native-host-session-tab-operations.ts index 0b7337bfc767..7aa079aed600 100644 --- a/mobile/src/session/native-host-session-tab-operations.ts +++ b/mobile/src/session/native-host-session-tab-operations.ts @@ -1,52 +1,9 @@ import type { RpcClient } from '../transport/rpc-client' import type { RpcSuccess } from '../transport/types' import type { HostSessionTabOperations } from './host-session-tab-operations' -import { projectHostSessionRuntimeCapabilities } from './host-session-runtime-capabilities' -import type { SessionTabsResult } from './mobile-session-route-types' -import { loadMobileNewTabAgentOptions } from './mobile-new-tab-agent-loader' -import { activateMobileSessionTab } from './mobile-session-tab-activation' export function nativeHostSessionTabOperations(client: RpcClient): HostSessionTabOperations { return { - async runtimeCapabilities() { - const response = await client.sendRequest('status.get') - if (!response.ok) { - throw new Error('session_capabilities_failed') - } - const result = (response as RpcSuccess).result as { capabilities?: unknown } - const capabilities = Array.isArray(result.capabilities) - ? result.capabilities.filter((value): value is string => typeof value === 'string') - : [] - return projectHostSessionRuntimeCapabilities(capabilities) - }, - async snapshot(workspaceId) { - return successfulSnapshot( - await client.sendRequest('session.tabs.list', { - worktree: `id:${workspaceId}` - }) - ) - }, - subscribe(workspaceId, onSnapshot, onError) { - return client.subscribe( - 'session.tabs.subscribe', - { worktree: `id:${workspaceId}` }, - (payload) => { - const event = payload as { type?: string } & SessionTabsResult - if (event.type === 'snapshot' || event.type === 'updated') { - onSnapshot(event) - return - } - // Why: a host-side subscription cleanup ends the stream; without degrading here the - // tab list freezes on its last snapshot and never refetches. - if (event.type === 'end' || event.type === 'error') { - onError() - } - } - ) - }, - agentOptions(workspaceId) { - return loadMobileNewTabAgentOptions({ client, worktreeId: workspaceId }) - }, async createBrowser(workspaceId, url) { const response = await client.sendRequest( 'browser.tabCreate', @@ -61,20 +18,6 @@ export function nativeHostSessionTabOperations(client: RpcClient): HostSessionTa const result = (response as RpcSuccess).result as { browserPageId?: unknown } return typeof result.browserPageId === 'string' ? { browserPageId: result.browserPageId } : {} }, - async activate(workspaceId, tabId, leafId) { - // Why: a relay-to-direct cutover rejects the in-flight request; activation is idempotent, - // so retrying once keeps the host's active tab in step with the UI the user just switched. - return successfulSnapshot( - await activateMobileSessionTab(client, { - worktree: `id:${workspaceId}`, - tabId, - ...(leafId ? { leafId } : {}), - notifyClients: false, - navigation: 'caller', - intent: 'user' - }) - ) - }, async close(workspaceId, tabId) { const response = await client.sendRequest('session.tabs.close', { worktree: `id:${workspaceId}`, @@ -98,10 +41,3 @@ export function nativeHostSessionTabOperations(client: RpcClient): HostSessionTa } } } - -function successfulSnapshot(response: Awaited>) { - if (!response.ok) { - throw new Error('session_snapshot_failed') - } - return (response as RpcSuccess).result as SessionTabsResult -} diff --git a/mobile/src/session/native-host-session-terminal-operations.ts b/mobile/src/session/native-host-session-terminal-operations.ts index 835f8156b8c9..677a3861eafa 100644 --- a/mobile/src/session/native-host-session-terminal-operations.ts +++ b/mobile/src/session/native-host-session-terminal-operations.ts @@ -49,11 +49,11 @@ export function nativeHostSessionTerminalOperations( () => false ) }, - clear(terminalId) { - return client.sendRequest('terminal.clearBuffer', { terminal: terminalId }).then( - (response) => response.ok, - () => false - ) + async clear(terminalId) { + // Rejection is deliberately not caught: the caller distinguishes a clear that never + // reached the host from one the host refused, and only the former is a failure. + const response = await client.sendRequest('terminal.clearBuffer', { terminal: terminalId }) + return response.ok }, rename(terminalId, title) { return client.sendRequest('terminal.rename', { terminal: terminalId, title }).then( diff --git a/mobile/src/session/use-mobile-native-chat-file-search.ts b/mobile/src/session/use-mobile-native-chat-file-search.ts index e3d55feb95c3..5ff1ad325bf1 100644 --- a/mobile/src/session/use-mobile-native-chat-file-search.ts +++ b/mobile/src/session/use-mobile-native-chat-file-search.ts @@ -26,6 +26,7 @@ export function useMobileNativeChatFileSearch(args: { useEffect(() => { sequenceRef.current++ queryCacheRef.current.clear() + operations?.resetFileSearchCache(worktreeId) setNativeChatFilePaths([]) return () => { if (timerRef.current) { diff --git a/mobile/src/session/use-mobile-session-terminal-input.ts b/mobile/src/session/use-mobile-session-terminal-input.ts index 4a5a50dd9fc2..10473104bc85 100644 --- a/mobile/src/session/use-mobile-session-terminal-input.ts +++ b/mobile/src/session/use-mobile-session-terminal-input.ts @@ -223,9 +223,12 @@ export function useMobileSessionTerminalInput(scope: MobileSessionFileActionsMod return } getTerminalRef(target.handle)?.clear() - if (await sessionOperations.terminal.clear(target.handle)) { + try { + // The refusal envelope is not a failure here: the local buffer above is already cleared, + // and only a clear that never reached the host is reported. + await sessionOperations.terminal.clear(target.handle) showToast('Terminal cleared') - } else { + } catch { showToast("Couldn't clear terminal", 1500) } } diff --git a/mobile/src/tasks/host-task-read-operations.ts b/mobile/src/tasks/host-task-read-operations.ts index fcc2affa2cf1..55d10e062905 100644 --- a/mobile/src/tasks/host-task-read-operations.ts +++ b/mobile/src/tasks/host-task-read-operations.ts @@ -9,6 +9,10 @@ import type { export type { HostTaskBootstrap, HostTaskLinearStatus, HostTaskLinearTeams, HostTaskRepository } export type HostTaskReadOperations = { + /** Split from `bootstrap` so the caller can commit its supported state before the settings + * fan-out runs. Folding the two together moves that commit behind four more requests, and a + * transport failure in any of them then leaves the screen with nothing rendered at all. */ + tasksSupported(): Promise bootstrap(): Promise listRepositories(): Promise /** Split from the team read so a caller can commit the workspace list before asking for diff --git a/mobile/src/tasks/host-task-runtime-payloads.ts b/mobile/src/tasks/host-task-runtime-payloads.ts index d832b200aca0..aa23ff1580dd 100644 --- a/mobile/src/tasks/host-task-runtime-payloads.ts +++ b/mobile/src/tasks/host-task-runtime-payloads.ts @@ -14,7 +14,6 @@ export type HostTaskLinearStatus = { } export type HostTaskBootstrap = { - supported: boolean settings: RuntimeTaskSettings taskResumeState: TaskResumeState trustedOrcaHooks: PersistedTrustedOrcaHooks diff --git a/mobile/src/tasks/mobile-tasks-refactor-parity.test.ts b/mobile/src/tasks/mobile-tasks-refactor-parity.test.ts index 20acdb373c09..22a3fcdc3581 100644 --- a/mobile/src/tasks/mobile-tasks-refactor-parity.test.ts +++ b/mobile/src/tasks/mobile-tasks-refactor-parity.test.ts @@ -25,9 +25,9 @@ const hash = (parts: string[] | string): string => * plus the row-target locals the adapters take in place of inline slug/number checks. Diff hooks, * declarations and styles are untouched. */ -const SCREEN_HOOKS = '9b2ac231e63169d3896ce30a3053262d30bc8f085456d75cbade522420205b02' +const SCREEN_HOOKS = '28f62d2fbd86d171bf162d26c6bd0763e4fb8c3f58895d7cd1a00633c1465f32' const DIFF_HOOKS = '93c7189b32bed8456cc51814fffa8ce80cf62011ef968a9d53ddec2b9686f58f' -const STATEMENTS = 'dd86f1ff89bf0bdbc3fbf159349d972a50d2dfa2607484848a34c4312b36ae60' +const STATEMENTS = 'd3f99f5ccf5decedadeef99e7633b8ce832b39e9a49675c43fbc0954b2a2e483' const DECLARATIONS = 'cff54172af17a877789be1479c2eb6ca97d83c3e31dd831cd59395962f2b4c4a' const SEMANTICS = 'f767906884b93537f2c6369d6d0bd2d4cb39b4314c31cca9d8f9e5e9b78a75ee' const STYLES = '1db6af69c791d9963928541ad5310942fcbda6d984b422c90b6eb92b6816579a' diff --git a/mobile/src/tasks/native-host-task-detail-operations.ts b/mobile/src/tasks/native-host-task-detail-operations.ts index 2a4481e5c6c0..181dab489418 100644 --- a/mobile/src/tasks/native-host-task-detail-operations.ts +++ b/mobile/src/tasks/native-host-task-detail-operations.ts @@ -93,12 +93,11 @@ export function nativeHostTaskDetailOperations(client: RpcRequestSender): HostTa } } +/** Tolerates a refusal envelope only. A transport rejection still fails the detail load, so a + * timed-out comment read cannot render as an issue that simply has no comments. */ async function optionalComments(request: Promise): Promise { - try { - return await successfulResult(request) - } catch { - return [] - } + const response = (await request) as { ok: boolean; result?: unknown } + return response.ok ? ((response.result as DetailComment[]) ?? []) : [] } async function successfulResult(request: Promise): Promise { diff --git a/mobile/src/tasks/native-host-task-item-review-operations.ts b/mobile/src/tasks/native-host-task-item-review-operations.ts index 6e8a028b032b..232be325b1c7 100644 --- a/mobile/src/tasks/native-host-task-item-review-operations.ts +++ b/mobile/src/tasks/native-host-task-item-review-operations.ts @@ -87,7 +87,7 @@ export function nativeHostTaskItemReviewOperations( }, { timeoutMs: 60_000 } ) - assertMutation(response, 'Failed to merge review') + assertMutation(response, 'Failed to merge') } } } diff --git a/mobile/src/tasks/native-host-task-list-operations.ts b/mobile/src/tasks/native-host-task-list-operations.ts index 532f4efdb848..eeb27edf44e8 100644 --- a/mobile/src/tasks/native-host-task-list-operations.ts +++ b/mobile/src/tasks/native-host-task-list-operations.ts @@ -6,16 +6,12 @@ export function nativeHostTaskListOperations(client: RpcRequestSender): HostTask return { async listGitHub(payload) { return successfulResult( - client.sendRequest( - 'github.listWorkItems', - { - repo: `id:${payload.repoId}`, - limit: payload.limit, - query: payload.query, - before: payload.before - }, - { timeoutMs: 30_000 } - ) + client.sendRequest('github.listWorkItems', { + repo: `id:${payload.repoId}`, + limit: payload.limit, + query: payload.query, + before: payload.before + }) ) }, async countGitHub(payload) { diff --git a/mobile/src/tasks/native-host-task-project-mutation-operations.ts b/mobile/src/tasks/native-host-task-project-mutation-operations.ts index 6cebae93c2a6..9a0155090244 100644 --- a/mobile/src/tasks/native-host-task-project-mutation-operations.ts +++ b/mobile/src/tasks/native-host-task-project-mutation-operations.ts @@ -15,6 +15,10 @@ import { } from '../session/github-pr-mutations' const PROJECT_PR_MUTATION_TIMEOUT_MS = 60_000 +/** Every project mutation carried a connect deadline before this seam existed. Without one the + * transport parks the request through the whole reconnect backoff, roughly six minutes, with + * the row's mutation UI disabled and no error. */ +const PROJECT_MUTATION_TIMEOUT_MS = 30_000 export function nativeHostTaskProjectMutationOperations( client: RpcRequestSender @@ -83,44 +87,64 @@ export function nativeHostTaskProjectMutationOperations( }, async resolveReviewThread(target, repoId, threadId, resolve) { requirePrMutation( - await fetchResolveReviewThread(client, repoId, { - threadId, - resolve, - // Why: a draft row - // has no slug — send it only when one resolved rather than an empty pair. - prRepo: prRepoPayload(target) - }), + await fetchResolveReviewThread( + client, + repoId, + { + threadId, + resolve, + // Why: a draft row + // has no slug — send it only when one resolved rather than an empty pair. + prRepo: prRepoPayload(target) + }, + { timeoutMs: PROJECT_MUTATION_TIMEOUT_MS } + ), resolve ? 'Failed to resolve thread' : 'Failed to reopen thread' ) }, async replyReviewComment(target, repoId, payload) { return prMutationComment( - await fetchAddPRReviewCommentReply(client, repoId, { - prNumber: target.number, - ...payload, - prRepo: prRepoPayload(target) - }), + await fetchAddPRReviewCommentReply( + client, + repoId, + { + prNumber: target.number, + ...payload, + prRepo: prRepoPayload(target) + }, + { timeoutMs: PROJECT_MUTATION_TIMEOUT_MS } + ), 'Failed to reply' ) }, async addConversationComment(target, repoId, body) { return prMutationComment( - await fetchAddIssueComment(client, repoId, { - prNumber: target.number, - body, - prRepo: prRepoPayload(target), - type: target.type - }), + await fetchAddIssueComment( + client, + repoId, + { + prNumber: target.number, + body, + prRepo: prRepoPayload(target), + type: target.type + }, + { timeoutMs: PROJECT_MUTATION_TIMEOUT_MS } + ), 'Failed to reply' ) }, async requestReviewers(target, repoId, reviewers) { requirePrMutation( - await fetchRequestPRReviewers(client, repoId, { - prNumber: target.number, - reviewers, - prRepo: prRepoPayload(target) - }), + await fetchRequestPRReviewers( + client, + repoId, + { + prNumber: target.number, + reviewers, + prRepo: prRepoPayload(target) + }, + { timeoutMs: PROJECT_MUTATION_TIMEOUT_MS } + ), 'Failed to request reviewers' ) }, diff --git a/mobile/src/tasks/native-host-task-project-read-operations.ts b/mobile/src/tasks/native-host-task-project-read-operations.ts index 502102802c07..cc7842612da4 100644 --- a/mobile/src/tasks/native-host-task-project-read-operations.ts +++ b/mobile/src/tasks/native-host-task-project-read-operations.ts @@ -70,7 +70,8 @@ export function nativeHostTaskProjectReadOperations( }, async listItemLabels(payload) { const result = await projectResult<{ labels?: string[] }>( - client.sendRequest('github.project.listLabelsBySlug', payload, { timeoutMs: 30_000 }) + client.sendRequest('github.project.listLabelsBySlug', payload, { timeoutMs: 30_000 }), + 'Failed to load labels' ) return result.labels ?? [] }, @@ -80,7 +81,8 @@ export function nativeHostTaskProjectReadOperations( }>( client.sendRequest('github.project.listAssignableUsersBySlug', payload, { timeoutMs: 30_000 - }) + }), + 'Failed to load assignees' ) return result.users ?? [] }, @@ -90,24 +92,30 @@ export function nativeHostTaskProjectReadOperations( }>( client.sendRequest('github.project.listIssueTypesBySlug', payload, { timeoutMs: 30_000 - }) + }), + 'Failed to load issue types' ) return result.types ?? [] } } } -export async function projectResult(request: Promise): Promise { +/** `fallback` is the wording the calling screen reported before these reads moved behind the + * seam; a host that refuses without a message must still name what failed to load. */ +export async function projectResult( + request: Promise, + fallback = 'GitHub Project request failed' +): Promise { const response = (await request) as { ok: boolean result?: { ok?: boolean; error?: { message?: string } } error?: { message?: string } } if (!response.ok) { - throw new Error(response.error?.message ?? 'GitHub Project request failed') + throw new Error(response.error?.message ?? fallback) } if (response.result?.ok === false) { - throw new Error(response.result.error?.message ?? 'GitHub Project request failed') + throw new Error(response.result.error?.message ?? fallback) } return response.result as T } diff --git a/mobile/src/tasks/native-host-task-provider-write-operations.ts b/mobile/src/tasks/native-host-task-provider-write-operations.ts index be5741b80c6d..eaac26ae5b30 100644 --- a/mobile/src/tasks/native-host-task-provider-write-operations.ts +++ b/mobile/src/tasks/native-host-task-provider-write-operations.ts @@ -24,7 +24,10 @@ export function nativeHostTaskProviderWriteOperations( error?: string } if (result.ok === false) { - throw new Error(result.error ?? `Failed to create ${payload.provider} issue`) + throw new Error( + result.error ?? + `Failed to create ${payload.provider === 'github' ? 'GitHub' : 'GitLab'} issue` + ) } return { ...(typeof result.number === 'number' ? { number: result.number } : {}), diff --git a/mobile/src/tasks/native-host-task-read-operations.ts b/mobile/src/tasks/native-host-task-read-operations.ts index 756c364fdb2e..c13791b1b79f 100644 --- a/mobile/src/tasks/native-host-task-read-operations.ts +++ b/mobile/src/tasks/native-host-task-read-operations.ts @@ -13,6 +13,7 @@ import type { RpcResponse, RpcSuccess } from '../transport/types' export function nativeHostTaskReadOperations(client: RpcRequestSender): HostTaskReadOperations { return { + tasksSupported: () => tasksSupported(client), bootstrap: () => bootstrap(client), listRepositories: () => listRepositories(client), linearStatus: () => linearStatus(client), @@ -21,13 +22,14 @@ export function nativeHostTaskReadOperations(client: RpcRequestSender): HostTask } } +async function tasksSupported(client: RpcRequestSender): Promise { + const response = await client.sendRequest('status.get') + requireSuccess(response) + const status = response.result as { capabilities?: string[] } + return status.capabilities?.includes(MOBILE_TASKS_CAPABILITY) === true +} + async function bootstrap(client: RpcRequestSender): Promise { - const statusResponse = await client.sendRequest('status.get') - requireSuccess(statusResponse) - const status = statusResponse.result as { capabilities?: string[] } - if (!status.capabilities?.includes(MOBILE_TASKS_CAPABILITY)) { - return emptyBootstrap(false) - } const [settingsResponse, uiResponse, preflightResponse, linearStatusResponse] = await Promise.all( [ client.sendRequest('settings.get'), @@ -47,7 +49,6 @@ async function bootstrap(client: RpcRequestSender): Promise { }>(uiResponse) const preflight = successResult<{ glab?: { installed?: boolean } }>(preflightResponse) return { - supported: true, settings: settingsEnvelope?.settings ?? {}, taskResumeState: uiEnvelope?.ui?.taskResumeState ?? {}, trustedOrcaHooks: uiEnvelope?.ui?.trustedOrcaHooks ?? {}, @@ -93,17 +94,6 @@ async function resolveGitHubRepoSlug( return response.result as GitHubOwnerRepo | null } -function emptyBootstrap(supported: boolean): HostTaskBootstrap { - return { - supported, - settings: {}, - taskResumeState: {}, - trustedOrcaHooks: {}, - gitLabInstalled: false, - linearStatus: normalizeLinearStatus(null) - } -} - function successResult(response: RpcResponse): T | null { return response.ok ? (response.result as T) : null } diff --git a/mobile/src/tasks/use-mobile-tasks-hydration-phases.test.tsx b/mobile/src/tasks/use-mobile-tasks-hydration-phases.test.tsx new file mode 100644 index 000000000000..ada6472906e0 --- /dev/null +++ b/mobile/src/tasks/use-mobile-tasks-hydration-phases.test.tsx @@ -0,0 +1,93 @@ +import { createElement, useEffect } from 'react' +import { act, create, type ReactTestRenderer } from 'react-test-renderer' +import { afterEach, describe, expect, it, vi } from 'vitest' + +// The hook reaches the Tasks barrels, which pull React Native in. Only the helpers this path +// runs before the settings fan-out matter, and the fan-out fails first in every case here. +vi.mock('./mobile-tasks-dependencies', () => ({ + filterAvailableTaskProviders: (providers: unknown) => providers, + isHostedTaskRepo: () => true, + normalizeVisibleTaskProviders: () => ['github'], + reconcileRepoSelection: () => new Set(), + resolveVisibleTaskProvider: () => 'github', + useEffect +})) +vi.mock('./mobile-tasks-legacy-foundation', () => ({ + EMPTY_GITHUB_PROJECT_SETTINGS: {}, + getTaskPresetQuery: () => '', + githubKindFromQuery: () => 'issues', + isTaskProvider: () => true, + normalizeGitHubPreset: () => 'issues', + normalizeLinearFilter: () => 'assigned', + scopeGitHubTaskSearch: (query: string) => query +})) + +const { useMobileTasksRuntimeHydration } = await import('./use-mobile-tasks-runtime-hydration') + +const client = { id: 'client-1' } + +/** 74 model fields reach this hook and only a handful steer this path, so anything unnamed + * answers with a spy. */ +function taskModel(taskOperations: unknown, recorded: Record>) { + const fixed: Record = { + client, + connState: 'connected', + taskOperations, + provider: 'github', + repoList: { state: { status: 'idle' }, repos: [], loading: false }, + repos: [], + requestedTaskSource: undefined, + visibleProviders: ['github'], + defaultLinearTeamSelectionRef: { current: null }, + defaultRepoSelectionRef: { current: null }, + repoSelectionHydratedRef: { current: false }, + taskResumeRef: { current: {} } + } + return new Proxy(fixed, { + get(target, property: string) { + if (property in target) { + return target[property] + } + recorded[property] ??= vi.fn() + return recorded[property] + }, + has: () => true + }) +} + +describe('tasks runtime hydration phases', () => { + let renderer: ReactTestRenderer | null = null + + afterEach(() => { + act(() => renderer?.unmount()) + renderer = null + }) + + it('renders a supported screen behind the error when the settings fan-out fails', async () => { + const recorded: Record> = {} + const taskOperations = { + read: { + tasksSupported: vi.fn().mockResolvedValue(true), + // The second phase is what a post-connect timeout on `preflight.check` rejects. + bootstrap: vi.fn().mockRejectedValue(new Error('Request timed out: preflight.check')) + } + } + + function Probe(): null { + useMobileTasksRuntimeHydration(taskModel(taskOperations, recorded) as never) + return null + } + await act(async () => { + renderer = create(createElement(Probe)) + }) + await act(async () => { + await Promise.resolve() + }) + + // Committed between the two phases. Folding them behind one await leaves this at 'unknown', + // which the list surface renders as a bare spinner with no path back. + expect(recorded.setTasksSupportState).toHaveBeenCalledWith({ kind: 'supported', client }) + expect(recorded.setError).toHaveBeenCalledWith('Request timed out: preflight.check') + expect(taskOperations.read.bootstrap).toHaveBeenCalledTimes(1) + }) +}) diff --git a/mobile/src/tasks/use-mobile-tasks-runtime-hydration.tsx b/mobile/src/tasks/use-mobile-tasks-runtime-hydration.tsx index 0be77b7a36f8..69f7c96f3451 100644 --- a/mobile/src/tasks/use-mobile-tasks-runtime-hydration.tsx +++ b/mobile/src/tasks/use-mobile-tasks-runtime-hydration.tsx @@ -185,11 +185,11 @@ export function useMobileTasksRuntimeHydration(model: ClientSettingsActionsModel resetWorkspaceCreateState() const hydrateTaskState = async (): Promise => { - const bootstrap = await taskOperations.read.bootstrap() + const supported = await taskOperations.read.tasksSupported() if (stale) { return } - if (!bootstrap.supported) { + if (!supported) { // Why: Tasks is additive RPC surface, so old desktop builds can still // pair but must not receive the newer task-specific method calls. setTasksSupportState({ kind: 'unsupported', client }) @@ -236,8 +236,15 @@ export function useMobileTasksRuntimeHydration(model: ClientSettingsActionsModel setTaskStateHydrated(false) return } + // Committed before the settings fan-out: a transport failure there must still leave the + // Tasks chrome rendered behind an error banner. The effect deps do not change on a + // post-connect timeout, so an uncommitted screen would never retry. setTasksSupportState({ kind: 'supported', client }) setError('') + const bootstrap = await taskOperations.read.bootstrap() + if (stale) { + return + } const settings = bootstrap.settings setRuntimeTaskSettings(settings) setTrustedOrcaHooks(bootstrap.trustedOrcaHooks) diff --git a/mobile/src/tasks/use-mobile-tasks-workspace-ssh-state.tsx b/mobile/src/tasks/use-mobile-tasks-workspace-ssh-state.tsx index 1de2e6b63e1a..e01e14985aa0 100644 --- a/mobile/src/tasks/use-mobile-tasks-workspace-ssh-state.tsx +++ b/mobile/src/tasks/use-mobile-tasks-workspace-ssh-state.tsx @@ -72,8 +72,11 @@ export function useMobileTasksWorkspaceSshState(model: WorkspaceSparseActionsMod return } const state = await taskWorkspaceCreationOperations.readSshState(repo.connectionId) - setWorkspaceSshState(state) - if (state.status !== 'connected') { + // An unregistered target answers with no state at all; leave whatever the badge shows. + if (state) { + setWorkspaceSshState(state) + } + if (state?.status !== 'connected') { throw new Error(`Connect ${repo.displayName} before creating a workspace.`) } }, diff --git a/mobile/src/transport/screen-rpc-ratchet.test.ts b/mobile/src/transport/screen-rpc-ratchet.test.ts index 51c684d12e3f..af5cbab11f46 100644 --- a/mobile/src/transport/screen-rpc-ratchet.test.ts +++ b/mobile/src/transport/screen-rpc-ratchet.test.ts @@ -19,8 +19,6 @@ const MOBILE_ROOT = join(__dirname, '../..') const ADAPTER_FILES = new Set([ 'src/accounts/default-host-account-operations.ts', 'src/accounts/native-host-account-operations.ts', - 'src/device/default-device-operations.ts', - 'src/device/native-device-operations.ts', 'src/files/default-host-file-explorer-operations.ts', 'src/files/native-host-file-explorer-operations.ts', 'src/session/default-host-session-browser-operations.ts', @@ -106,14 +104,13 @@ const INLINE_RPC_BY_FILE: Record = { 'src/notifications/mobile-notifications.ts': 4, 'src/session/ai-vault-resume-launch.ts': 3, 'src/session/ai-vault-resume-preparation.ts': 2, - 'src/session/github-pr-mutations.ts': 3, + 'src/session/github-pr-mutations.ts': 4, 'src/session/github-pr-rpc.ts': 9, 'src/session/mobile-clipboard-image.ts': 7, 'src/session/mobile-diff-review-loaders.ts': 5, 'src/session/mobile-image-attachment.ts': 2, 'src/session/mobile-native-chat-image-attachment.ts': 1, 'src/session/mobile-native-chat-image-send.ts': 2, - 'src/session/mobile-native-chat-open-file.ts': 2, 'src/session/mobile-native-chat-send.ts': 3, 'src/session/mobile-native-chat-session-option-persistence.ts': 1, 'src/session/mobile-native-chat-stale-input.ts': 1, diff --git a/mobile/src/worktree/host-workspace-creation-operations.ts b/mobile/src/worktree/host-workspace-creation-operations.ts index 4ca39de323e5..1780c009d70b 100644 --- a/mobile/src/worktree/host-workspace-creation-operations.ts +++ b/mobile/src/worktree/host-workspace-creation-operations.ts @@ -85,7 +85,8 @@ export type HostWorkspaceCreationOperations = { readTrustedHooks(): Promise isGitLabCliInstalled(): Promise isLinearConnected(): Promise - readSshState(targetId: string): Promise + /** Null when the host knows nothing about the target, which is not the same as disconnected. */ + readSshState(targetId: string): Promise connectSsh(targetId: string): Promise detectAgents(connectionId: string | null): Promise readRepoHooks(repoId: string): Promise diff --git a/mobile/src/worktree/host-workspace-host-context.ts b/mobile/src/worktree/host-workspace-host-context.ts deleted file mode 100644 index f17f7ae843d8..000000000000 --- a/mobile/src/worktree/host-workspace-host-context.ts +++ /dev/null @@ -1,32 +0,0 @@ -export type HostWorkspaceSshTarget = { id: string; label: string } - -/** Inputs the workspace list needs to name and badge rows from non-local execution hosts. */ -export type HostWorkspaceHostContext = { - sshTargets: readonly HostWorkspaceSshTarget[] - hostSettingOverrides: unknown - platform: NodeJS.Platform | null -} - -export function readHostWorkspaceSshTargets(result: unknown): HostWorkspaceSshTarget[] { - const targets = (result as { targets?: unknown } | null)?.targets - if (!Array.isArray(targets)) { - return [] - } - return targets.filter( - (target): target is HostWorkspaceSshTarget => - typeof target === 'object' && - target !== null && - typeof (target as HostWorkspaceSshTarget).id === 'string' && - typeof (target as HostWorkspaceSshTarget).label === 'string' - ) -} - -export function readHostWorkspacePlatform(result: unknown): NodeJS.Platform | null { - const platform = (result as { platform?: unknown } | null)?.platform - return typeof platform === 'string' && platform ? (platform as NodeJS.Platform) : null -} - -export function readHostWorkspaceSettingOverrides(result: unknown): unknown { - return (result as { settings?: { hostSettingOverrides?: unknown } } | null)?.settings - ?.hostSettingOverrides -} diff --git a/mobile/src/worktree/native-host-workspace-creation-read-operations.ts b/mobile/src/worktree/native-host-workspace-creation-read-operations.ts index b8f94743d820..2a47386dbd29 100644 --- a/mobile/src/worktree/native-host-workspace-creation-read-operations.ts +++ b/mobile/src/worktree/native-host-workspace-creation-read-operations.ts @@ -75,7 +75,7 @@ export function nativeHostWorkspaceCreationReadOperations( const result = await successfulResult<{ state?: SshConnectionState | null }>( client.sendRequest('ssh.getState', { targetId }) ) - return result.state ?? disconnectedSshState(targetId) + return result.state ?? null }, async connectSsh(targetId) { const result = await successfulResult<{ state?: SshConnectionState | null }>( From 0aaa70e5e930be04dfa11c4c7cdc7d8d5ea953ef Mon Sep 17 00:00:00 2001 From: Jinwoo-H Date: Wed, 9 Sep 2026 02:45:37 -0400 Subject: [PATCH 13/40] test(mobile): restore the four assertions the extraction weakened - The Project host oracle no longer accepts a bare `payload` identifier, which every call site satisfies by construction. Inline payloads must show a host or a slug builder; the four typed-payload reads are named explicitly and their payload types are pinned to carry the host. - `prRepo` is pinned per mutation and bounded to that adapter method, so dropping it from one of six fails instead of needing all six. `github.addPRReviewComment` is pinned again, with the row repository. - The smart-source fan-out fake now delegates to the shipped search functions over a scripted transport, so the repoId stamping under test is the real one rather than the fake's copy. - The retired-name read's method and `id:` prefix are asserted again, in the adapter test, since the hook now takes a callback. - The session adapters join the route parity family, bringing the runtime strings and identity fields that moved out of the hooks back into scope. Each restored assertion was verified to fail under the mutation it guards. Claude-Session: https://claude.ai/code/session_01JNnE9qzUZMMnqpZWCqM3nb --- .../mobile-session-route-parity.test.ts | 4 +- ...ession-route-source-family.test-support.ts | 12 +++- ...github-project-host-routing-source.test.ts | 64 +++++++++++++++++-- mobile/src/tasks/smart-source-fan-out.test.ts | 53 +++++++-------- ...host-workspace-creation-operations.test.ts | 15 +++++ 5 files changed, 109 insertions(+), 39 deletions(-) diff --git a/mobile/src/session/mobile-session-route-parity.test.ts b/mobile/src/session/mobile-session-route-parity.test.ts index dbf204dcd96c..83cd257b6719 100644 --- a/mobile/src/session/mobile-session-route-parity.test.ts +++ b/mobile/src/session/mobile-session-route-parity.test.ts @@ -79,7 +79,7 @@ const HEAD_TIMER_CREATION_SHA256 = '1a31b625e2174c3db77272249843196d2b6b06ab1e654a96d8f7858e3082e66b' const HEAD_TIMER_CLEANUP_SHA256 = 'c73f1d1c2cc89642f3d727d6f3b6b81860a9d6f34234541a2065ec3d1a8cd116' const HEAD_RUNTIME_STRING_SHA256 = - 'f7e7d7a99d506589d1b620b86f39bbce97223ab7ad4143b1f06a6a8d8ab81f5b' + '390b26467725abc0514fdbbee2cba3ded2586d471438cea0b113182465484d5b' const HEAD_HOST_JSX_SHA256 = '390405926b1695fa3a33686f0bc192b432f5468d8576499d7cafbb4922defbb5' const HEAD_LEAF_JSX_SHA256 = 'd5f1ef0db57c63eb3e4ee7c98e8483bc21882a151ce0ca24e42c7d1234e1dace' const HEAD_STYLE_REFERENCE_SHA256 = @@ -517,7 +517,7 @@ describe('mobile session route extraction parity', () => { it('preserves runtime strings, styles, and the expanded JSX tree', () => { const strings = readRuntimeStrings() - expect(strings).toHaveLength(522) + expect(strings).toHaveLength(593) expect(hash(strings)).toBe(HEAD_RUNTIME_STRING_SHA256) const jsx = readJsxFacts(readDefinitions()) expect(jsx.host).toHaveLength(124) diff --git a/mobile/src/session/mobile-session-route-source-family.test-support.ts b/mobile/src/session/mobile-session-route-source-family.test-support.ts index 41f2d8b9c2f3..5db4a95cfcb9 100644 --- a/mobile/src/session/mobile-session-route-source-family.test-support.ts +++ b/mobile/src/session/mobile-session-route-source-family.test-support.ts @@ -43,7 +43,17 @@ export const MOBILE_SESSION_ROUTE_SOURCE_FILES = [ './MobileSessionContentRow.tsx', './MobileSessionActiveContent.tsx', './MobileSessionCommandDock.tsx', - './MobileSessionSheets.tsx' + './MobileSessionSheets.tsx', + // The adapters the route's RPCs moved into. Without them the runtime strings and identity + // fields that left the hooks would leave this family's scope entirely. + './native-host-session-browser-operations.ts', + './native-host-session-file-operations.ts', + './native-host-session-markdown-operations.ts', + './native-host-session-native-chat-operations.ts', + './native-host-session-quick-command-operations.ts', + './native-host-session-tab-operations.ts', + './native-host-session-terminal-file-operations.ts', + './native-host-session-terminal-operations.ts' ] as const export function readMobileSessionRouteSource(relativePath: string): string { diff --git a/mobile/src/tasks/github-project-host-routing-source.test.ts b/mobile/src/tasks/github-project-host-routing-source.test.ts index 92e80628b6a6..550964e47a1c 100644 --- a/mobile/src/tasks/github-project-host-routing-source.test.ts +++ b/mobile/src/tasks/github-project-host-routing-source.test.ts @@ -19,7 +19,22 @@ const compositionSource = [ const projectReadAdapter = readSource('./native-host-task-project-read-operations.ts') const projectMutationAdapter = readSource('./native-host-task-project-mutation-operations.ts') const projectFileAdapter = readSource('./native-host-task-project-file-operations.ts') -const adapterSource = [projectReadAdapter, projectMutationAdapter, projectFileAdapter].join('\n') +const projectPayloadTypes = readSource('./host-task-project-payloads.ts') +/** The fallback map lists every method name as a key; those are not call sites. */ +const mutationCallSites = projectMutationAdapter.replace( + /const PROJECT_MUTATION_FALLBACKS[\s\S]*?\n\}\n/, + '' +) +const adapterSource = [projectReadAdapter, mutationCallSites, projectFileAdapter].join('\n') + +/** These four pass a typed payload rather than an inline object, so their host is guaranteed by + * the payload type asserted below. Pinned by name so a new call cannot silently join them. */ +const TYPED_PAYLOAD_CALLS = new Set([ + 'github.project.workItemDetailsBySlug', + 'github.project.listLabelsBySlug', + 'github.project.listAssignableUsersBySlug', + 'github.project.listIssueTypesBySlug' +]) describe('mobile GitHub Project host routing boundary', () => { it('keeps every Project RPC behind the adapter layer', () => { @@ -31,12 +46,31 @@ describe('mobile GitHub Project host routing boundary', () => { it('host-qualifies every Project RPC request', () => { const calls = [...adapterSource.matchAll(/['"](github\.project\.[^'"]+)['"]/g)] + expect(calls.length).toBeGreaterThan(10) for (const call of calls) { + if (TYPED_PAYLOAD_CALLS.has(call[1])) { + continue + } const request = adapterSource.slice(call.index, call.index + 700) expect(request, `${call[1]} must carry a host`).toMatch( - /\bhost:|slugPayload\(target\)|\bpayload\b/ + /\bhost:|slugPayload\(target\)|repoPayload\(/ + ) + } + // The typed-payload calls get their host from the type, so pin the type instead. + expect(projectPayloadTypes).toMatch( + /export type HostTaskProjectSlugPayload = \{\s*owner: string\s*repo: string\s*host: string/ + ) + for (const derived of [ + 'HostTaskProjectItemDetailPayload', + 'HostTaskProjectAssignableUsersPayload' + ]) { + expect(projectPayloadTypes, `${derived} must inherit the host`).toMatch( + new RegExp(`export type ${derived} = HostTaskProjectSlugPayload &`) ) } + expect(projectPayloadTypes).toMatch( + /export type HostTaskProjectTablePayload = GitHubProjectRef &/ + ) // slugPayload is the single place a row identity becomes a wire payload. expect(projectMutationAdapter).toMatch( /function slugPayload\(target: HostTaskProjectItemTarget\) \{\s*return \{\s*owner: target\.owner,\s*repo: target\.repo,\s*host: target\.host,/ @@ -54,10 +88,10 @@ describe('mobile GitHub Project host routing boundary', () => { } // The target type carries the host that the PR mutations forward as prRepo, and a row with // no slug forwards null rather than being refused. - expect(projectMutationAdapter).toContain('prRepo: prRepoPayload(target)') expect(projectMutationAdapter).toMatch( /function prRepoPayload\(target: HostTaskProjectItemTarget\) \{\s*return target\.owner && target\.repo/ ) + // Per method, not once per file: dropping prRepo from a single mutation must fail here. for (const method of [ 'fetchResolveReviewThread', 'fetchAddPRReviewCommentReply', @@ -66,10 +100,28 @@ describe('mobile GitHub Project host routing boundary', () => { 'fetchRerunPRChecks', 'fetchMergePR' ]) { - expect(projectMutationAdapter, `${method} must remain wired`).toContain(method) + const offset = projectMutationAdapter.indexOf(`${method}(`) + expect(offset, `${method} must remain wired`).toBeGreaterThan(-1) + // Bounded to this adapter method, so a neighbour's prRepo cannot satisfy it. + const end = projectMutationAdapter.indexOf('\n },', offset) + expect( + projectMutationAdapter.slice(offset, end === -1 ? undefined : end), + `${method} must carry prRepo` + ).toContain('prRepo: prRepoPayload(target)') } - for (const method of ['github.prChecks', 'github.setPRFileViewed', 'github.prFileContents']) { - expect(projectFileAdapter, `${method} must remain wired`).toContain(method) + for (const method of [ + 'github.prChecks', + 'github.setPRFileViewed', + 'github.prFileContents', + 'github.addPRReviewComment' + ]) { + const offset = projectFileAdapter.indexOf(`'${method}'`) + expect(offset, `${method} must remain wired`).toBeGreaterThan(-1) + const end = projectFileAdapter.indexOf('\n },', offset) + expect( + projectFileAdapter.slice(offset, end === -1 ? undefined : end), + `${method} must carry the row repository` + ).toContain('repoPayload(target, repoId)') } }) diff --git a/mobile/src/tasks/smart-source-fan-out.test.ts b/mobile/src/tasks/smart-source-fan-out.test.ts index 241b3bb1428d..94918d7707fc 100644 --- a/mobile/src/tasks/smart-source-fan-out.test.ts +++ b/mobile/src/tasks/smart-source-fan-out.test.ts @@ -1,45 +1,38 @@ import { describe, expect, it } from 'vitest' import type { HostWorkspaceCreationOperations } from '../worktree/host-workspace-creation-operations' import { fanOutSmartSearch } from './smart-source-fan-out' +import type { RpcRequestSender } from '../transport/rpc-client' +import { + searchBranches, + searchGitHubItems, + searchGitLabItems, + searchLinearIssues +} from './smart-source-search-requests' type Call = { method: string; params: Record } +/** Delegates to the shipped search functions over a scripted transport, so the `repoId` + * stamping and the envelope handling under test are the real ones rather than the fake's. */ function fakeOperations( byMethod: Record, calls: Call[] ): HostWorkspaceCreationOperations { - const invoke = async (method: string, params: Record): Promise => { - calls.push({ method, params }) - const result = byMethod[method] - if (result instanceof Error) { - throw result + const client = { + async sendRequest(method: string, params: unknown) { + calls.push({ method, params: params as Record }) + const scripted = byMethod[method] + if (scripted instanceof Error) { + return { ok: false as const, error: { code: 'failed', message: scripted.message } } + } + return { ok: true as const, result: scripted ?? {} } } - return result as T - } + } as unknown as RpcRequestSender return { - searchGitHubItems: async (repoId, query) => { - const result = await invoke<{ items?: never[] }>('github.listWorkItems', { repoId, query }) - return (result?.items ?? []).map((item) => ({ ...item, repoId })) - }, - searchGitLabItems: async (repoId, query, state) => { - const result = await invoke<{ items?: never[] }>('gitlab.listWorkItems', { - repoId, - query, - state - }) - return (result?.items ?? []).map((item) => ({ ...item, repoId })) - }, - searchLinearIssues: async (query, linearWorkspaceId) => { - const result = await invoke<{ items?: never[] }>('linear.searchIssues', { - query, - linearWorkspaceId - }) - return result?.items ?? [] - }, - searchBranches: async (repoId, query) => { - const result = await invoke<{ refDetails?: never[] }>('repo.searchRefs', { repoId, query }) - return result?.refDetails ?? [] - } + searchGitHubItems: (repoId, query) => searchGitHubItems(client, repoId, query), + searchGitLabItems: (repoId, query, state) => searchGitLabItems(client, repoId, query, state), + searchLinearIssues: (query, linearWorkspaceId) => + searchLinearIssues(client, query, linearWorkspaceId), + searchBranches: (repoId, query) => searchBranches(client, repoId, query) } as unknown as HostWorkspaceCreationOperations } diff --git a/mobile/src/worktree/native-host-workspace-creation-operations.test.ts b/mobile/src/worktree/native-host-workspace-creation-operations.test.ts index 03f726f61d99..899bccec1718 100644 --- a/mobile/src/worktree/native-host-workspace-creation-operations.test.ts +++ b/mobile/src/worktree/native-host-workspace-creation-operations.test.ts @@ -3,6 +3,21 @@ import type { RpcClient } from '../transport/rpc-client' import { nativeHostWorkspaceCreationOperations } from './native-host-workspace-creation-operations' describe('native host workspace creation operations', () => { + it('addresses the retired-name read by method and id-prefixed repo', async () => { + const sendRequest = vi + .fn() + .mockResolvedValue({ ok: true, result: { retiredNamesByRepo: { 'repo-1': ['spent'] } } }) + const operations = nativeHostWorkspaceCreationOperations({ + sendRequest + } as unknown as RpcClient) + + // The hook takes a callback now, so this is the only place the wire shape is pinned. + await expect(operations.readRetiredWorktreeNames('repo-1')).resolves.toMatchObject({ + names: ['spent'] + }) + expect(sendRequest.mock.calls).toEqual([['worktree.listRetiredNames', { repo: 'id:repo-1' }]]) + }) + it('maps named repository and environment reads to existing RPC authority', async () => { const sendRequest = vi .fn() From b1f1ff78d138c35c9a483df2aa385fb2254cbd5f Mon Sep 17 00:00:00 2001 From: Jinwoo-H Date: Wed, 9 Sep 2026 03:09:21 -0400 Subject: [PATCH 14/40] test(mobile): bound the Project host oracle to its own adapter method The per-call slice was still a fixed 700 characters, so deleting host from updateComment passed on deleteComment's host sitting inside the window. It now ends at the enclosing method, matching the prRepo loop, and accepts the shorthand property form that github.project.listAccessible uses. Verified: dropping `host: target.host` from updateComment fails the oracle. Claude-Session: https://claude.ai/code/session_01JNnE9qzUZMMnqpZWCqM3nb --- .../src/tasks/github-project-host-routing-source.test.ts | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/mobile/src/tasks/github-project-host-routing-source.test.ts b/mobile/src/tasks/github-project-host-routing-source.test.ts index 550964e47a1c..5cd2545160eb 100644 --- a/mobile/src/tasks/github-project-host-routing-source.test.ts +++ b/mobile/src/tasks/github-project-host-routing-source.test.ts @@ -51,9 +51,12 @@ describe('mobile GitHub Project host routing boundary', () => { if (TYPED_PAYLOAD_CALLS.has(call[1])) { continue } - const request = adapterSource.slice(call.index, call.index + 700) + // Bounded to the enclosing adapter method, so a neighbour's host cannot satisfy it. + const end = adapterSource.indexOf('\n },', call.index) + const request = adapterSource.slice(call.index, end === -1 ? undefined : end) + // `host` may be a shorthand property, so accept it followed by a colon, comma or brace. expect(request, `${call[1]} must carry a host`).toMatch( - /\bhost:|slugPayload\(target\)|repoPayload\(/ + /\bhost\s*[:,}]|slugPayload\(target\)|repoPayload\(/ ) } // The typed-payload calls get their host from the type, so pin the type instead. From 5cbbadfb2b84a5478762cd50afa55b6c3d8da294 Mon Sep 17 00:00:00 2001 From: Jinwoo-H Date: Wed, 9 Sep 2026 03:12:13 -0400 Subject: [PATCH 15/40] refactor(mobile): drop the five adapter methods with no live caller - HostSessionNativeChatOperations sendMessage, respond and attachImage. Every shipped send path calls sendMobileNativeChatMessageWithOutcome or typeMobileNativeChatCommandWithOutcome directly, as on main. - HostWorkspaceCreationOperations createBlankWorkspace and createWorkspaceFromSource. use-new-workspace-create-submit imports createBlankWorkspace from the source module instead. With those two gone the native creation factory only spread the RPC operations and RpcWorkspaceCreationOperations only excluded them, so both collapse. The arg and result types that existed solely for the five methods go with them, as does the dead SessionTabsResult re-export. Each name was grepped against non-test, non-adapter callers before and after. Claude-Session: https://claude.ai/code/session_01JNnE9qzUZMMnqpZWCqM3nb --- .../host-session-native-chat-operations.ts | 23 ------------ .../session/host-session-tab-operations.ts | 4 --- .../mobile-session-route-parity.test.ts | 4 +-- ...ive-host-session-native-chat-operations.ts | 19 ---------- .../host-workspace-creation-operations.ts | 35 +------------------ ...tive-host-workspace-creation-operations.ts | 20 +---------- .../rpc-workspace-creation-operations.ts | 12 ++----- 7 files changed, 7 insertions(+), 110 deletions(-) diff --git a/mobile/src/session/host-session-native-chat-operations.ts b/mobile/src/session/host-session-native-chat-operations.ts index 419ee0307b34..cad0d769f85d 100644 --- a/mobile/src/session/host-session-native-chat-operations.ts +++ b/mobile/src/session/host-session-native-chat-operations.ts @@ -4,7 +4,6 @@ import type { } from '../../../src/shared/native-chat-types' import type { MobileNativeChatSendOutcome } from './mobile-native-chat-send' import type { MobileNativeChatStreamFrame } from './mobile-native-chat-stream-frame' -import type { MobileImageSource } from './mobile-image-source-picker' export type HostSessionNativeChatTarget = { workspaceId: string @@ -29,10 +28,6 @@ export type HostSessionNativeChatImageAttachment = { previewUri: string } -export type HostSessionNativeChatImageAttachResult = - | { status: 'accepted'; attachment: HostSessionNativeChatImageAttachment } - | { status: 'cancelled' | 'permission-denied' | 'too-large' } - export type HostSessionNativeChatOperations = { /** Whether the serving host can read this workspace's agent transcripts. */ readability(workspaceId: string): Promise @@ -48,25 +43,7 @@ export type HostSessionNativeChatOperations = { limit: number, beforeOffset?: number ): Promise - sendMessage( - target: HostSessionNativeChatTarget, - text: string, - deadline?: number, - clearInputFirst?: boolean, - resolvedLaunchDraft?: { text: string; createdAt: number }, - typeCommand?: boolean - ): Promise - respond( - target: HostSessionNativeChatTarget, - text: string, - enter: boolean, - deadline?: number - ): Promise stop(target: HostSessionNativeChatTarget, deadline?: number): Promise - attachImage?( - target: HostSessionNativeChatTarget, - source: MobileImageSource - ): Promise pasteImages?( target: HostSessionNativeChatTarget, references: readonly string[], diff --git a/mobile/src/session/host-session-tab-operations.ts b/mobile/src/session/host-session-tab-operations.ts index b55c24c89a11..f755758af53d 100644 --- a/mobile/src/session/host-session-tab-operations.ts +++ b/mobile/src/session/host-session-tab-operations.ts @@ -1,5 +1,3 @@ -import type { SessionTabsResult } from './mobile-session-route-types' - export type HostSessionTabCloseResult = | { outcome: 'closed' } | { outcome: 'refused'; reason: string | null } @@ -8,5 +6,3 @@ export type HostSessionTabOperations = { createBrowser(workspaceId: string, url: string): Promise<{ browserPageId?: string }> close(workspaceId: string, tabId: string): Promise } - -export type { SessionTabsResult } diff --git a/mobile/src/session/mobile-session-route-parity.test.ts b/mobile/src/session/mobile-session-route-parity.test.ts index 83cd257b6719..3487cdc96276 100644 --- a/mobile/src/session/mobile-session-route-parity.test.ts +++ b/mobile/src/session/mobile-session-route-parity.test.ts @@ -79,7 +79,7 @@ const HEAD_TIMER_CREATION_SHA256 = '1a31b625e2174c3db77272249843196d2b6b06ab1e654a96d8f7858e3082e66b' const HEAD_TIMER_CLEANUP_SHA256 = 'c73f1d1c2cc89642f3d727d6f3b6b81860a9d6f34234541a2065ec3d1a8cd116' const HEAD_RUNTIME_STRING_SHA256 = - '390b26467725abc0514fdbbee2cba3ded2586d471438cea0b113182465484d5b' + 'f7ab0549d15dfa0b830bf916844816fa317581a129ace4e99917ddf9cfb3771e' const HEAD_HOST_JSX_SHA256 = '390405926b1695fa3a33686f0bc192b432f5468d8576499d7cafbb4922defbb5' const HEAD_LEAF_JSX_SHA256 = 'd5f1ef0db57c63eb3e4ee7c98e8483bc21882a151ce0ca24e42c7d1234e1dace' const HEAD_STYLE_REFERENCE_SHA256 = @@ -517,7 +517,7 @@ describe('mobile session route extraction parity', () => { it('preserves runtime strings, styles, and the expanded JSX tree', () => { const strings = readRuntimeStrings() - expect(strings).toHaveLength(593) + expect(strings).toHaveLength(592) expect(hash(strings)).toBe(HEAD_RUNTIME_STRING_SHA256) const jsx = readJsxFacts(readDefinitions()) expect(jsx.host).toHaveLength(124) diff --git a/mobile/src/session/native-host-session-native-chat-operations.ts b/mobile/src/session/native-host-session-native-chat-operations.ts index 9828df79fb1a..0c02bef274b8 100644 --- a/mobile/src/session/native-host-session-native-chat-operations.ts +++ b/mobile/src/session/native-host-session-native-chat-operations.ts @@ -4,7 +4,6 @@ import { isFloatingWorkspaceWorktreeId } from './floating-workspace' import { isMobileNativeChatTranscriptReadable } from './mobile-native-chat-eligibility' import { sendMobileNativeChatMessageWithOutcome, - typeMobileNativeChatCommandWithOutcome, type MobileNativeChatSendOutcome } from './mobile-native-chat-send' import { rankSuggestions } from './mobile-native-chat-autocomplete' @@ -63,24 +62,6 @@ export function nativeHostSessionNativeChatOperations( return { error: 'Transcript read failed' } } }, - sendMessage(target, text, deadline, clearInputFirst, resolvedLaunchDraft, typeCommand) { - if (typeCommand && target.terminalId) { - return typeMobileNativeChatCommandWithOutcome({ - client, - terminal: target.terminalId, - command: text, - resolvedLaunchDraft, - deadline, - ...(target.clientId - ? { mobileClient: { id: target.clientId, type: 'mobile' as const } } - : {}) - }) - } - return sendNative(target, text, true, client, deadline, clearInputFirst, resolvedLaunchDraft) - }, - respond(target, text, enter, deadline) { - return sendNative(target, text, enter, client, deadline) - }, stop(target, deadline) { // Escape must not carry Return: the extra newline submits whatever the agent // had parked on its input line. diff --git a/mobile/src/worktree/host-workspace-creation-operations.ts b/mobile/src/worktree/host-workspace-creation-operations.ts index 1780c009d70b..c2a4434b561d 100644 --- a/mobile/src/worktree/host-workspace-creation-operations.ts +++ b/mobile/src/worktree/host-workspace-creation-operations.ts @@ -8,20 +8,13 @@ import type { SparsePreset } from '../../../src/shared/worktree/create-types' import type { GitHubPrStartPoint } from '../../../src/shared/worktree/types' import type { RepoSlug } from '../../../src/shared/new-workspace/github-links' import type { SshConnectionState } from '../../../src/shared/ssh-types' -import type { WorktreeCreateResult } from '../tasks/worktree-create-retry' -import type { WorktreeCreateIdempotencyProbe } from '../tasks/worktree-create-idempotency-policy' import type { NewWorktreeRuntimeCapabilities } from '../tasks/worktree-create-capability' -import type { - MrStateFilter, - MobileComposerCreateSelection -} from '../tasks/mobile-composer-source-types' +import type { MrStateFilter } from '../tasks/mobile-composer-source-types' import type { ComposerHostedBase, ResolveComposerMrBaseArgs, ResolveComposerPrBaseArgs } from '../tasks/composer-source-base-resolve' -import type { WorkspaceAgentChoice } from '../tasks/workspace-agent-selection' -import type { WorkspaceCreateSetupDecision } from '../tasks/workspace-create-params' import type { SetupHookTrust } from '../tasks/setup-hook-trust' import type { ExecutionHostId } from '../../../src/shared/execution-host' import type { GitRemoteIdentity } from '../../../src/shared/git-remote-identity' @@ -56,28 +49,6 @@ export type NewWorkspaceRepoHooks = { setupTrust?: SetupHookTrust } -export type CreateBlankWorkspaceOperationArgs = { - repoId: string - baseName: string - agentChoice: WorkspaceAgentChoice - nameWasGenerated: boolean - comment: string | undefined - setupDecision: WorkspaceCreateSetupDecision - worktreeCreateIdempotency: WorktreeCreateIdempotencyProbe -} - -export type CreateWorkspaceFromSourceOperationArgs = { - selection: MobileComposerCreateSelection - targetRepoId: string - setupDecision: WorkspaceCreateSetupDecision - agentChoice: WorkspaceAgentChoice - workspaceName: string | undefined - note: string | undefined - sparseCheckout?: { directories: string[]; presetId?: string } - nameIsAutoManaged?: boolean - worktreeCreateIdempotency: WorktreeCreateIdempotencyProbe -} - export type HostWorkspaceCreationOperations = { listRepositories(): Promise readRetiredWorktreeNames(repoId: string): Promise @@ -129,8 +100,4 @@ export type HostWorkspaceCreationOperations = { }): Promise resolvePrBase(args: Omit): Promise resolveMrBase(args: Omit): Promise - createBlankWorkspace(args: CreateBlankWorkspaceOperationArgs): Promise - createWorkspaceFromSource( - args: CreateWorkspaceFromSourceOperationArgs - ): Promise } diff --git a/mobile/src/worktree/native-host-workspace-creation-operations.ts b/mobile/src/worktree/native-host-workspace-creation-operations.ts index 3f76cb4e8d1c..97155e36f540 100644 --- a/mobile/src/worktree/native-host-workspace-creation-operations.ts +++ b/mobile/src/worktree/native-host-workspace-creation-operations.ts @@ -1,27 +1,9 @@ import type { RpcClient } from '../transport/rpc-client' -import { createBlankWorkspace } from '../tasks/blank-workspace-create' -import { createWorkspaceFromComposerSource } from '../tasks/source-workspace-create' import type { HostWorkspaceCreationOperations } from './host-workspace-creation-operations' import { rpcWorkspaceCreationOperations } from './rpc-workspace-creation-operations' export function nativeHostWorkspaceCreationOperations( client: RpcClient ): HostWorkspaceCreationOperations { - return { - ...rpcWorkspaceCreationOperations(client), - async createBlankWorkspace(args) { - return createBlankWorkspace({ - client, - ...args, - createdWithAgentId: args.agentChoice === 'blank' ? undefined : args.agentChoice - }) - }, - async createWorkspaceFromSource(args) { - return createWorkspaceFromComposerSource({ - client, - ...args, - agent: { choice: args.agentChoice } - }) - } - } + return rpcWorkspaceCreationOperations(client) } diff --git a/mobile/src/worktree/rpc-workspace-creation-operations.ts b/mobile/src/worktree/rpc-workspace-creation-operations.ts index 051deca5ba1a..1b8e5f4e2600 100644 --- a/mobile/src/worktree/rpc-workspace-creation-operations.ts +++ b/mobile/src/worktree/rpc-workspace-creation-operations.ts @@ -4,17 +4,11 @@ import type { HostWorkspaceCreationOperations } from './host-workspace-creation- import { nativeHostWorkspaceCreationReadOperations } from './native-host-workspace-creation-read-operations' import { nativeHostWorkspaceCreationSourceOperations } from './native-host-workspace-creation-source-operations' -export type RpcWorkspaceCreationOperations = Omit< - HostWorkspaceCreationOperations, - 'createBlankWorkspace' | 'createWorkspaceFromSource' -> - -/** Every workspace-creation call that is a plain desktop request, written against a bare request - * sender so any non-socket provider can supply one without a second copy. Creation itself is - * excluded: it needs connection state for its retry, which a sender cannot report. */ +/** Every workspace-creation call the screens make, written against a bare request sender so any + * non-socket provider can supply one without a second copy. */ export function rpcWorkspaceCreationOperations( client: RpcRequestSender -): RpcWorkspaceCreationOperations { +): HostWorkspaceCreationOperations { return { ...nativeHostWorkspaceCreationReadOperations(client), ...nativeHostWorkspaceCreationSourceOperations(client), From 66e698aca22d66be7e5f9a712efb83c4316d375e Mon Sep 17 00:00:00 2001 From: Jinwoo-H Date: Wed, 9 Sep 2026 03:52:58 -0400 Subject: [PATCH 16/40] refactor(mobile): drop the capability projection its last caller left behind The tab adapter's capabilities() method was removed as uncalled; this module existed only to serve it. Claude-Session: https://claude.ai/code/session_01JNnE9qzUZMMnqpZWCqM3nb --- .../host-session-runtime-capabilities.ts | 17 ----------------- 1 file changed, 17 deletions(-) delete mode 100644 mobile/src/session/host-session-runtime-capabilities.ts diff --git a/mobile/src/session/host-session-runtime-capabilities.ts b/mobile/src/session/host-session-runtime-capabilities.ts deleted file mode 100644 index 201512cde6d1..000000000000 --- a/mobile/src/session/host-session-runtime-capabilities.ts +++ /dev/null @@ -1,17 +0,0 @@ -export type HostSessionRuntimeCapabilities = { - browserScreencastSupported: boolean - agentHistorySupported: boolean - quickCommandsSupported: boolean - terminalQueryReplyInputSupported: boolean -} - -export function projectHostSessionRuntimeCapabilities( - capabilities: readonly string[] -): HostSessionRuntimeCapabilities { - return { - browserScreencastSupported: capabilities.includes('browser.screencast.v1'), - agentHistorySupported: capabilities.includes('aiVault.v1'), - quickCommandsSupported: capabilities.includes('terminal.quick-commands.v1'), - terminalQueryReplyInputSupported: capabilities.includes('terminal.query-reply-input.v1') - } -} From 892c6fc1a97b092f2acb6ceafde8377b2056088f Mon Sep 17 00:00:00 2001 From: Jinwoo-H Date: Wed, 9 Sep 2026 03:54:47 -0400 Subject: [PATCH 17/40] refactor(mobile): drop the per-namespace default factories nothing imports Each was a one-line pass-through to its native factory. The five domain-level defaults are the only ones the screens construct. Claude-Session: https://claude.ai/code/session_01JNnE9qzUZMMnqpZWCqM3nb --- ...default-host-session-browser-operations.ts | 9 --------- .../default-host-session-file-operations.ts | 7 ------- ...efault-host-session-markdown-operations.ts | 9 --------- ...ult-host-session-native-chat-operations.ts | 9 --------- ...t-host-session-quick-command-operations.ts | 9 --------- .../default-host-session-tab-operations.ts | 7 ------- ...t-host-session-terminal-file-operations.ts | 9 --------- ...efault-host-session-terminal-operations.ts | 9 --------- .../default-host-task-detail-operations.ts | 7 ------- .../default-host-task-item-file-operations.ts | 7 ------- ...ault-host-task-item-mutation-operations.ts | 9 --------- ...efault-host-task-item-review-operations.ts | 9 --------- .../default-host-task-linear-operations.ts | 7 ------- .../default-host-task-list-operations.ts | 7 ------- ...default-host-task-preference-operations.ts | 9 --------- ...fault-host-task-project-file-operations.ts | 9 --------- ...t-host-task-project-mutation-operations.ts | 9 --------- ...fault-host-task-project-read-operations.ts | 9 --------- ...ult-host-task-provider-write-operations.ts | 9 --------- .../default-host-task-read-operations.ts | 7 ------- .../src/transport/screen-rpc-ratchet.test.ts | 20 ------------------- 21 files changed, 186 deletions(-) delete mode 100644 mobile/src/session/default-host-session-browser-operations.ts delete mode 100644 mobile/src/session/default-host-session-file-operations.ts delete mode 100644 mobile/src/session/default-host-session-markdown-operations.ts delete mode 100644 mobile/src/session/default-host-session-native-chat-operations.ts delete mode 100644 mobile/src/session/default-host-session-quick-command-operations.ts delete mode 100644 mobile/src/session/default-host-session-tab-operations.ts delete mode 100644 mobile/src/session/default-host-session-terminal-file-operations.ts delete mode 100644 mobile/src/session/default-host-session-terminal-operations.ts delete mode 100644 mobile/src/tasks/default-host-task-detail-operations.ts delete mode 100644 mobile/src/tasks/default-host-task-item-file-operations.ts delete mode 100644 mobile/src/tasks/default-host-task-item-mutation-operations.ts delete mode 100644 mobile/src/tasks/default-host-task-item-review-operations.ts delete mode 100644 mobile/src/tasks/default-host-task-linear-operations.ts delete mode 100644 mobile/src/tasks/default-host-task-list-operations.ts delete mode 100644 mobile/src/tasks/default-host-task-preference-operations.ts delete mode 100644 mobile/src/tasks/default-host-task-project-file-operations.ts delete mode 100644 mobile/src/tasks/default-host-task-project-mutation-operations.ts delete mode 100644 mobile/src/tasks/default-host-task-project-read-operations.ts delete mode 100644 mobile/src/tasks/default-host-task-provider-write-operations.ts delete mode 100644 mobile/src/tasks/default-host-task-read-operations.ts diff --git a/mobile/src/session/default-host-session-browser-operations.ts b/mobile/src/session/default-host-session-browser-operations.ts deleted file mode 100644 index e311e205ae10..000000000000 --- a/mobile/src/session/default-host-session-browser-operations.ts +++ /dev/null @@ -1,9 +0,0 @@ -import type { RpcClient } from '../transport/rpc-client' -import type { HostSessionBrowserOperations } from './host-session-browser-operations' -import { nativeHostSessionBrowserOperations } from './native-host-session-browser-operations' - -export function defaultHostSessionBrowserOperations( - client: RpcClient -): HostSessionBrowserOperations { - return nativeHostSessionBrowserOperations(client) -} diff --git a/mobile/src/session/default-host-session-file-operations.ts b/mobile/src/session/default-host-session-file-operations.ts deleted file mode 100644 index 2cfee5a1b910..000000000000 --- a/mobile/src/session/default-host-session-file-operations.ts +++ /dev/null @@ -1,7 +0,0 @@ -import type { RpcClient } from '../transport/rpc-client' -import type { HostSessionFileOperations } from './host-session-file-operations' -import { nativeHostSessionFileOperations } from './native-host-session-file-operations' - -export function defaultHostSessionFileOperations(client: RpcClient): HostSessionFileOperations { - return nativeHostSessionFileOperations(client) -} diff --git a/mobile/src/session/default-host-session-markdown-operations.ts b/mobile/src/session/default-host-session-markdown-operations.ts deleted file mode 100644 index 4c464b8b2043..000000000000 --- a/mobile/src/session/default-host-session-markdown-operations.ts +++ /dev/null @@ -1,9 +0,0 @@ -import type { RpcClient } from '../transport/rpc-client' -import type { HostSessionMarkdownOperations } from './host-session-markdown-operations' -import { nativeHostSessionMarkdownOperations } from './native-host-session-markdown-operations' - -export function defaultHostSessionMarkdownOperations( - client: RpcClient -): HostSessionMarkdownOperations { - return nativeHostSessionMarkdownOperations(client) -} diff --git a/mobile/src/session/default-host-session-native-chat-operations.ts b/mobile/src/session/default-host-session-native-chat-operations.ts deleted file mode 100644 index e05c089913e7..000000000000 --- a/mobile/src/session/default-host-session-native-chat-operations.ts +++ /dev/null @@ -1,9 +0,0 @@ -import type { RpcClient } from '../transport/rpc-client' -import type { HostSessionNativeChatOperations } from './host-session-native-chat-operations' -import { nativeHostSessionNativeChatOperations } from './native-host-session-native-chat-operations' - -export function defaultHostSessionNativeChatOperations( - client: RpcClient -): HostSessionNativeChatOperations { - return nativeHostSessionNativeChatOperations(client) -} diff --git a/mobile/src/session/default-host-session-quick-command-operations.ts b/mobile/src/session/default-host-session-quick-command-operations.ts deleted file mode 100644 index a67930a756da..000000000000 --- a/mobile/src/session/default-host-session-quick-command-operations.ts +++ /dev/null @@ -1,9 +0,0 @@ -import type { RpcClient } from '../transport/rpc-client' -import type { HostSessionQuickCommandOperations } from './host-session-quick-command-operations' -import { nativeHostSessionQuickCommandOperations } from './native-host-session-quick-command-operations' - -export function defaultHostSessionQuickCommandOperations( - client: RpcClient -): HostSessionQuickCommandOperations { - return nativeHostSessionQuickCommandOperations(client) -} diff --git a/mobile/src/session/default-host-session-tab-operations.ts b/mobile/src/session/default-host-session-tab-operations.ts deleted file mode 100644 index c29447a29dbf..000000000000 --- a/mobile/src/session/default-host-session-tab-operations.ts +++ /dev/null @@ -1,7 +0,0 @@ -import type { RpcClient } from '../transport/rpc-client' -import type { HostSessionTabOperations } from './host-session-tab-operations' -import { nativeHostSessionTabOperations } from './native-host-session-tab-operations' - -export function defaultHostSessionTabOperations(client: RpcClient): HostSessionTabOperations { - return nativeHostSessionTabOperations(client) -} diff --git a/mobile/src/session/default-host-session-terminal-file-operations.ts b/mobile/src/session/default-host-session-terminal-file-operations.ts deleted file mode 100644 index 796f3f583e36..000000000000 --- a/mobile/src/session/default-host-session-terminal-file-operations.ts +++ /dev/null @@ -1,9 +0,0 @@ -import type { RpcClient } from '../transport/rpc-client' -import type { HostSessionTerminalFileOperations } from './host-session-terminal-file-operations' -import { nativeHostSessionTerminalFileOperations } from './native-host-session-terminal-file-operations' - -export function defaultHostSessionTerminalFileOperations( - client: RpcClient -): HostSessionTerminalFileOperations { - return nativeHostSessionTerminalFileOperations(client) -} diff --git a/mobile/src/session/default-host-session-terminal-operations.ts b/mobile/src/session/default-host-session-terminal-operations.ts deleted file mode 100644 index a4827e450060..000000000000 --- a/mobile/src/session/default-host-session-terminal-operations.ts +++ /dev/null @@ -1,9 +0,0 @@ -import type { RpcClient } from '../transport/rpc-client' -import type { HostSessionTerminalOperations } from './host-session-terminal-operations' -import { nativeHostSessionTerminalOperations } from './native-host-session-terminal-operations' - -export function defaultHostSessionTerminalOperations( - client: RpcClient -): HostSessionTerminalOperations { - return nativeHostSessionTerminalOperations(client) -} diff --git a/mobile/src/tasks/default-host-task-detail-operations.ts b/mobile/src/tasks/default-host-task-detail-operations.ts deleted file mode 100644 index 54ed3161ff84..000000000000 --- a/mobile/src/tasks/default-host-task-detail-operations.ts +++ /dev/null @@ -1,7 +0,0 @@ -import type { HostTaskDetailOperations } from './host-task-detail-operations' -import { nativeHostTaskDetailOperations } from './native-host-task-detail-operations' -import type { RpcClient } from '../transport/rpc-client' - -export function defaultHostTaskDetailOperations(client: RpcClient): HostTaskDetailOperations { - return nativeHostTaskDetailOperations(client) -} diff --git a/mobile/src/tasks/default-host-task-item-file-operations.ts b/mobile/src/tasks/default-host-task-item-file-operations.ts deleted file mode 100644 index 899a236c5888..000000000000 --- a/mobile/src/tasks/default-host-task-item-file-operations.ts +++ /dev/null @@ -1,7 +0,0 @@ -import type { HostTaskItemFileOperations } from './host-task-item-file-operations' -import { nativeHostTaskItemFileOperations } from './native-host-task-item-file-operations' -import type { RpcClient } from '../transport/rpc-client' - -export function defaultHostTaskItemFileOperations(client: RpcClient): HostTaskItemFileOperations { - return nativeHostTaskItemFileOperations(client) -} diff --git a/mobile/src/tasks/default-host-task-item-mutation-operations.ts b/mobile/src/tasks/default-host-task-item-mutation-operations.ts deleted file mode 100644 index 17f920626861..000000000000 --- a/mobile/src/tasks/default-host-task-item-mutation-operations.ts +++ /dev/null @@ -1,9 +0,0 @@ -import type { HostTaskItemMutationOperations } from './host-task-item-mutation-operations' -import { nativeHostTaskItemMutationOperations } from './native-host-task-item-mutation-operations' -import type { RpcClient } from '../transport/rpc-client' - -export function defaultHostTaskItemMutationOperations( - client: RpcClient -): HostTaskItemMutationOperations { - return nativeHostTaskItemMutationOperations(client) -} diff --git a/mobile/src/tasks/default-host-task-item-review-operations.ts b/mobile/src/tasks/default-host-task-item-review-operations.ts deleted file mode 100644 index a080dc3b5ece..000000000000 --- a/mobile/src/tasks/default-host-task-item-review-operations.ts +++ /dev/null @@ -1,9 +0,0 @@ -import type { HostTaskItemReviewOperations } from './host-task-item-review-operations' -import { nativeHostTaskItemReviewOperations } from './native-host-task-item-review-operations' -import type { RpcClient } from '../transport/rpc-client' - -export function defaultHostTaskItemReviewOperations( - client: RpcClient -): HostTaskItemReviewOperations { - return nativeHostTaskItemReviewOperations(client) -} diff --git a/mobile/src/tasks/default-host-task-linear-operations.ts b/mobile/src/tasks/default-host-task-linear-operations.ts deleted file mode 100644 index 1408163e7171..000000000000 --- a/mobile/src/tasks/default-host-task-linear-operations.ts +++ /dev/null @@ -1,7 +0,0 @@ -import type { HostTaskLinearOperations } from './host-task-linear-operations' -import { nativeHostTaskLinearOperations } from './native-host-task-linear-operations' -import type { RpcClient } from '../transport/rpc-client' - -export function defaultHostTaskLinearOperations(client: RpcClient): HostTaskLinearOperations { - return nativeHostTaskLinearOperations(client) -} diff --git a/mobile/src/tasks/default-host-task-list-operations.ts b/mobile/src/tasks/default-host-task-list-operations.ts deleted file mode 100644 index 81472b9d7709..000000000000 --- a/mobile/src/tasks/default-host-task-list-operations.ts +++ /dev/null @@ -1,7 +0,0 @@ -import type { HostTaskListOperations } from './host-task-list-operations' -import { nativeHostTaskListOperations } from './native-host-task-list-operations' -import type { RpcClient } from '../transport/rpc-client' - -export function defaultHostTaskListOperations(client: RpcClient): HostTaskListOperations { - return nativeHostTaskListOperations(client) -} diff --git a/mobile/src/tasks/default-host-task-preference-operations.ts b/mobile/src/tasks/default-host-task-preference-operations.ts deleted file mode 100644 index 5328d37a5caa..000000000000 --- a/mobile/src/tasks/default-host-task-preference-operations.ts +++ /dev/null @@ -1,9 +0,0 @@ -import type { HostTaskPreferenceOperations } from './host-task-preference-operations' -import { nativeHostTaskPreferenceOperations } from './native-host-task-preference-operations' -import type { RpcClient } from '../transport/rpc-client' - -export function defaultHostTaskPreferenceOperations( - client: RpcClient -): HostTaskPreferenceOperations { - return nativeHostTaskPreferenceOperations(client) -} diff --git a/mobile/src/tasks/default-host-task-project-file-operations.ts b/mobile/src/tasks/default-host-task-project-file-operations.ts deleted file mode 100644 index 523b4c73b9f9..000000000000 --- a/mobile/src/tasks/default-host-task-project-file-operations.ts +++ /dev/null @@ -1,9 +0,0 @@ -import type { HostTaskProjectFileOperations } from './host-task-project-file-operations' -import { nativeHostTaskProjectFileOperations } from './native-host-task-project-file-operations' -import type { RpcClient } from '../transport/rpc-client' - -export function defaultHostTaskProjectFileOperations( - client: RpcClient -): HostTaskProjectFileOperations { - return nativeHostTaskProjectFileOperations(client) -} diff --git a/mobile/src/tasks/default-host-task-project-mutation-operations.ts b/mobile/src/tasks/default-host-task-project-mutation-operations.ts deleted file mode 100644 index d47eb21d5383..000000000000 --- a/mobile/src/tasks/default-host-task-project-mutation-operations.ts +++ /dev/null @@ -1,9 +0,0 @@ -import type { HostTaskProjectMutationOperations } from './host-task-project-mutation-operations' -import { nativeHostTaskProjectMutationOperations } from './native-host-task-project-mutation-operations' -import type { RpcClient } from '../transport/rpc-client' - -export function defaultHostTaskProjectMutationOperations( - client: RpcClient -): HostTaskProjectMutationOperations { - return nativeHostTaskProjectMutationOperations(client) -} diff --git a/mobile/src/tasks/default-host-task-project-read-operations.ts b/mobile/src/tasks/default-host-task-project-read-operations.ts deleted file mode 100644 index b4346f6f0f43..000000000000 --- a/mobile/src/tasks/default-host-task-project-read-operations.ts +++ /dev/null @@ -1,9 +0,0 @@ -import type { HostTaskProjectReadOperations } from './host-task-project-read-operations' -import { nativeHostTaskProjectReadOperations } from './native-host-task-project-read-operations' -import type { RpcClient } from '../transport/rpc-client' - -export function defaultHostTaskProjectReadOperations( - client: RpcClient -): HostTaskProjectReadOperations { - return nativeHostTaskProjectReadOperations(client) -} diff --git a/mobile/src/tasks/default-host-task-provider-write-operations.ts b/mobile/src/tasks/default-host-task-provider-write-operations.ts deleted file mode 100644 index 0521e8bb77fb..000000000000 --- a/mobile/src/tasks/default-host-task-provider-write-operations.ts +++ /dev/null @@ -1,9 +0,0 @@ -import type { HostTaskProviderWriteOperations } from './host-task-provider-write-operations' -import { nativeHostTaskProviderWriteOperations } from './native-host-task-provider-write-operations' -import type { RpcClient } from '../transport/rpc-client' - -export function defaultHostTaskProviderWriteOperations( - client: RpcClient -): HostTaskProviderWriteOperations { - return nativeHostTaskProviderWriteOperations(client) -} diff --git a/mobile/src/tasks/default-host-task-read-operations.ts b/mobile/src/tasks/default-host-task-read-operations.ts deleted file mode 100644 index abf2a2c8e435..000000000000 --- a/mobile/src/tasks/default-host-task-read-operations.ts +++ /dev/null @@ -1,7 +0,0 @@ -import type { HostTaskReadOperations } from './host-task-read-operations' -import { nativeHostTaskReadOperations } from './native-host-task-read-operations' -import type { RpcClient } from '../transport/rpc-client' - -export function defaultHostTaskReadOperations(client: RpcClient): HostTaskReadOperations { - return nativeHostTaskReadOperations(client) -} diff --git a/mobile/src/transport/screen-rpc-ratchet.test.ts b/mobile/src/transport/screen-rpc-ratchet.test.ts index af5cbab11f46..5d28f5e7c010 100644 --- a/mobile/src/transport/screen-rpc-ratchet.test.ts +++ b/mobile/src/transport/screen-rpc-ratchet.test.ts @@ -21,15 +21,7 @@ const ADAPTER_FILES = new Set([ 'src/accounts/native-host-account-operations.ts', 'src/files/default-host-file-explorer-operations.ts', 'src/files/native-host-file-explorer-operations.ts', - 'src/session/default-host-session-browser-operations.ts', - 'src/session/default-host-session-file-operations.ts', - 'src/session/default-host-session-markdown-operations.ts', - 'src/session/default-host-session-native-chat-operations.ts', 'src/session/default-host-session-operations.ts', - 'src/session/default-host-session-quick-command-operations.ts', - 'src/session/default-host-session-tab-operations.ts', - 'src/session/default-host-session-terminal-file-operations.ts', - 'src/session/default-host-session-terminal-operations.ts', 'src/session/native-host-session-browser-operations.ts', 'src/session/native-host-session-file-operations.ts', 'src/session/native-host-session-markdown-operations.ts', @@ -39,19 +31,7 @@ const ADAPTER_FILES = new Set([ 'src/session/native-host-session-tab-operations.ts', 'src/session/native-host-session-terminal-file-operations.ts', 'src/session/native-host-session-terminal-operations.ts', - 'src/tasks/default-host-task-detail-operations.ts', - 'src/tasks/default-host-task-item-file-operations.ts', - 'src/tasks/default-host-task-item-mutation-operations.ts', - 'src/tasks/default-host-task-item-review-operations.ts', - 'src/tasks/default-host-task-linear-operations.ts', - 'src/tasks/default-host-task-list-operations.ts', 'src/tasks/default-host-task-operations.ts', - 'src/tasks/default-host-task-preference-operations.ts', - 'src/tasks/default-host-task-project-file-operations.ts', - 'src/tasks/default-host-task-project-mutation-operations.ts', - 'src/tasks/default-host-task-project-read-operations.ts', - 'src/tasks/default-host-task-provider-write-operations.ts', - 'src/tasks/default-host-task-read-operations.ts', 'src/tasks/native-host-task-detail-operations.ts', 'src/tasks/native-host-task-item-file-operations.ts', 'src/tasks/native-host-task-item-mutation-operations.ts', From 753ec1354f783488065e40a8f1a76050e3f70054 Mon Sep 17 00:00:00 2001 From: Jinwoo-H Date: Wed, 9 Sep 2026 11:43:14 -0400 Subject: [PATCH 18/40] test(mobile): bound the Project host oracle to a real method boundary The adapter sources are concatenated, and the last method in each file closes with a bare brace, so the previous delimiter search could run into the next file. The slice now ends at the enclosing method's closing brace and fails outright when none exists. Claude-Session: https://claude.ai/code/session_01JNnE9qzUZMMnqpZWCqM3nb --- ...github-project-host-routing-source.test.ts | 20 +++++++++++++------ 1 file changed, 14 insertions(+), 6 deletions(-) diff --git a/mobile/src/tasks/github-project-host-routing-source.test.ts b/mobile/src/tasks/github-project-host-routing-source.test.ts index 5cd2545160eb..4ab16b0f81ce 100644 --- a/mobile/src/tasks/github-project-host-routing-source.test.ts +++ b/mobile/src/tasks/github-project-host-routing-source.test.ts @@ -36,6 +36,17 @@ const TYPED_PAYLOAD_CALLS = new Set([ 'github.project.listIssueTypesBySlug' ]) +/** The adapter method that contains `offset`, ending at its closing brace at 4-space indent + * (`},` or the last method's `}`); a method that never closes fails rather than leaking into + * the next method or file. */ +function enclosingAdapterMethod(source: string, offset: number): string { + const end = source.slice(offset).search(/\n {4}\},?\n/) + if (end === -1) { + throw new Error(`no method boundary after offset ${offset}`) + } + return source.slice(offset, offset + end) +} + describe('mobile GitHub Project host routing boundary', () => { it('keeps every Project RPC behind the adapter layer', () => { expect(compositionSource).not.toContain('sendRequest(') @@ -52,8 +63,7 @@ describe('mobile GitHub Project host routing boundary', () => { continue } // Bounded to the enclosing adapter method, so a neighbour's host cannot satisfy it. - const end = adapterSource.indexOf('\n },', call.index) - const request = adapterSource.slice(call.index, end === -1 ? undefined : end) + const request = enclosingAdapterMethod(adapterSource, call.index) // `host` may be a shorthand property, so accept it followed by a colon, comma or brace. expect(request, `${call[1]} must carry a host`).toMatch( /\bhost\s*[:,}]|slugPayload\(target\)|repoPayload\(/ @@ -106,9 +116,8 @@ describe('mobile GitHub Project host routing boundary', () => { const offset = projectMutationAdapter.indexOf(`${method}(`) expect(offset, `${method} must remain wired`).toBeGreaterThan(-1) // Bounded to this adapter method, so a neighbour's prRepo cannot satisfy it. - const end = projectMutationAdapter.indexOf('\n },', offset) expect( - projectMutationAdapter.slice(offset, end === -1 ? undefined : end), + enclosingAdapterMethod(projectMutationAdapter, offset), `${method} must carry prRepo` ).toContain('prRepo: prRepoPayload(target)') } @@ -120,9 +129,8 @@ describe('mobile GitHub Project host routing boundary', () => { ]) { const offset = projectFileAdapter.indexOf(`'${method}'`) expect(offset, `${method} must remain wired`).toBeGreaterThan(-1) - const end = projectFileAdapter.indexOf('\n },', offset) expect( - projectFileAdapter.slice(offset, end === -1 ? undefined : end), + enclosingAdapterMethod(projectFileAdapter, offset), `${method} must carry the row repository` ).toContain('repoPayload(target, repoId)') } From 3220919c876e73d209c2b7209b2e900e66f9ab21 Mon Sep 17 00:00:00 2001 From: Jinwoo-H Date: Wed, 9 Sep 2026 12:33:12 -0400 Subject: [PATCH 19/40] fix(mobile): delete the Ctrl+U prefix send path this PR added main had no clearInputFirst. The flag prefixed a clear byte onto the body of a terminal.send, which is the shape the same file documents as observed broken in the field: the burst reached the agent as literal control characters with the draft still parked. No production caller set it. mobile-native-chat-send.ts now has no diff against main. The assertions that existed only to prove nobody set the flag are gone; the case that pins verbatim text stays and fails if a prefix comes back. Claude-Session: https://claude.ai/code/session_01JNnE9qzUZMMnqpZWCqM3nb --- mobile/src/session/mobile-native-chat-send.test.ts | 2 +- mobile/src/session/mobile-native-chat-send.ts | 6 +----- .../session/native-host-session-native-chat-operations.ts | 2 -- .../src/session/use-mobile-native-chat-controller.test.ts | 4 ---- .../src/session/use-mobile-native-chat-message-send.test.ts | 3 --- 5 files changed, 2 insertions(+), 15 deletions(-) diff --git a/mobile/src/session/mobile-native-chat-send.test.ts b/mobile/src/session/mobile-native-chat-send.test.ts index c13841f7f773..e4e3d4836fc7 100644 --- a/mobile/src/session/mobile-native-chat-send.test.ts +++ b/mobile/src/session/mobile-native-chat-send.test.ts @@ -200,7 +200,7 @@ describe('sendMobileNativeChatMessage', () => { ) }) - it('sends the text verbatim when clearInputFirst is not set', async () => { + it('sends the text verbatim, never prefixed with a clear byte', async () => { // An image send pastes the image (behind its own leading Ctrl+U) before this // text write; a clear byte here would kill the pasted image off the input line. const client = clientWithResponse({ diff --git a/mobile/src/session/mobile-native-chat-send.ts b/mobile/src/session/mobile-native-chat-send.ts index a61aee3c205a..22c44f3eb84e 100644 --- a/mobile/src/session/mobile-native-chat-send.ts +++ b/mobile/src/session/mobile-native-chat-send.ts @@ -10,15 +10,11 @@ type MobileTerminalClient = { type: 'mobile' } -// Clear a parked TUI launch draft before writing a mobile chat message. -const CLEAR_UNSUBMITTED_INPUT = '\x15' - type MobileNativeChatSendArgs = { client: RpcClient terminal: string text: string enter?: boolean - clearInputFirst?: boolean /** Exact host launch draft this submitting write resolves when accepted. */ resolvedLaunchDraft?: { text: string; createdAt: number } mobileClient?: MobileTerminalClient @@ -59,7 +55,7 @@ export async function sendMobileNativeChatMessageWithOutcome( 'terminal.send', { terminal: args.terminal, - text: args.clearInputFirst ? `${CLEAR_UNSUBMITTED_INPUT}${args.text}` : args.text, + text: args.text, enter: args.enter ?? true, ...(args.resolvedLaunchDraft ? { resolvedLaunchDraft: args.resolvedLaunchDraft } : {}), ...(args.mobileClient ? { client: args.mobileClient } : {}) diff --git a/mobile/src/session/native-host-session-native-chat-operations.ts b/mobile/src/session/native-host-session-native-chat-operations.ts index 0c02bef274b8..2b091ea8ea8c 100644 --- a/mobile/src/session/native-host-session-native-chat-operations.ts +++ b/mobile/src/session/native-host-session-native-chat-operations.ts @@ -134,7 +134,6 @@ function sendNative( enter: boolean, client: RpcClient, deadline?: number, - clearInputFirst?: boolean, resolvedLaunchDraft?: { text: string; createdAt: number } ): Promise { if (!target.terminalId) { @@ -145,7 +144,6 @@ function sendNative( terminal: target.terminalId, text, enter, - clearInputFirst, resolvedLaunchDraft, deadline, ...(target.clientId ? { mobileClient: { id: target.clientId, type: 'mobile' as const } } : {}) diff --git a/mobile/src/session/use-mobile-native-chat-controller.test.ts b/mobile/src/session/use-mobile-native-chat-controller.test.ts index 83f8075d9141..896dfa93bb96 100644 --- a/mobile/src/session/use-mobile-native-chat-controller.test.ts +++ b/mobile/src/session/use-mobile-native-chat-controller.test.ts @@ -400,9 +400,6 @@ describe('useMobileNativeChatController handleNativeChatSend', () => { expect.objectContaining({ text: '\x15', enter: false }), expect.any(Object) ) - expect(sendWithOutcome).toHaveBeenLastCalledWith( - expect.not.objectContaining({ clearInputFirst: expect.anything() }) - ) clientStub.sendRequest.mockClear() @@ -411,7 +408,6 @@ describe('useMobileNativeChatController handleNativeChatSend', () => { }) expect(clientStub.sendRequest).not.toHaveBeenCalled() expect(sendWithOutcome).toHaveBeenLastCalledWith(expect.objectContaining({ text: 'look' })) - expect(sendWithOutcome.mock.calls.at(-1)?.[0]).not.toHaveProperty('clearInputFirst') }) it('holds an unknown-outcome send without posting the optimistic echo', async () => { diff --git a/mobile/src/session/use-mobile-native-chat-message-send.test.ts b/mobile/src/session/use-mobile-native-chat-message-send.test.ts index bd40aec2158e..d5b3ff5671c6 100644 --- a/mobile/src/session/use-mobile-native-chat-message-send.test.ts +++ b/mobile/src/session/use-mobile-native-chat-message-send.test.ts @@ -151,7 +151,6 @@ describe('useMobileNativeChatMessageSend', () => { await act(async () => { await api!.send('hello') }) - expect(sentArgs()).not.toHaveProperty('clearInputFirst') expect(sentArgs().resolvedLaunchDraft).toEqual({ text: DRAFT, createdAt: 1 }) }) @@ -161,7 +160,6 @@ describe('useMobileNativeChatMessageSend', () => { await api!.send('hello') }) expect(clearArgs().clearInput).toBe('\x15') - expect(sentArgs()).not.toHaveProperty('clearInputFirst') expect(sentArgs().resolvedLaunchDraft).toBeUndefined() }) @@ -200,7 +198,6 @@ describe('useMobileNativeChatMessageSend', () => { await api!.send('caption', ['file:///a.png']) }) expect(clearInputWrite).not.toHaveBeenCalled() - expect(sentArgs()).not.toHaveProperty('clearInputFirst') expect(sentArgs().resolvedLaunchDraft).toEqual({ text: DRAFT, createdAt: 1 }) }) From 73125e3f3b594a2c090840dfe0aec702d07b3ac5 Mon Sep 17 00:00:00 2001 From: Jinwoo-H Date: Wed, 9 Sep 2026 12:34:19 -0400 Subject: [PATCH 20/40] fix(mobile): prune a closed session tab on ok alone, as main did main checked only response.ok, pruned the tab, wrote a tombstone and let the host's republished snapshot restore it if the close was refused. The adapter had mapped a refusal to an outcome the caller skipped every state commit for, leaving the tab on screen, and had added a `closed !== true` precondition main never had, so a host answering ok without that field would strand the tab. close() returns a boolean again and the caller prunes on it. The test that pinned the refusal projection is replaced by two that pin main's contract: ok with an empty result still reports acceptance, a transport refusal does not. Claude-Session: https://claude.ai/code/session_01JNnE9qzUZMMnqpZWCqM3nb --- .../session/host-session-tab-operations.ts | 8 ++--- ...native-host-session-tab-operations.test.ts | 35 ++++++++++--------- .../native-host-session-tab-operations.ts | 15 +------- .../use-mobile-session-close-actions.ts | 3 +- 4 files changed, 23 insertions(+), 38 deletions(-) diff --git a/mobile/src/session/host-session-tab-operations.ts b/mobile/src/session/host-session-tab-operations.ts index f755758af53d..3ca73cc80d79 100644 --- a/mobile/src/session/host-session-tab-operations.ts +++ b/mobile/src/session/host-session-tab-operations.ts @@ -1,8 +1,6 @@ -export type HostSessionTabCloseResult = - | { outcome: 'closed' } - | { outcome: 'refused'; reason: string | null } - export type HostSessionTabOperations = { createBrowser(workspaceId: string, url: string): Promise<{ browserPageId?: string }> - close(workspaceId: string, tabId: string): Promise + /** True when the host accepted the request. The caller prunes on that alone, as it did + * before this seam existed; a refusal is undone by the host's republished snapshot. */ + close(workspaceId: string, tabId: string): Promise } diff --git a/mobile/src/session/native-host-session-tab-operations.test.ts b/mobile/src/session/native-host-session-tab-operations.test.ts index 5161e000d852..24175343a701 100644 --- a/mobile/src/session/native-host-session-tab-operations.test.ts +++ b/mobile/src/session/native-host-session-tab-operations.test.ts @@ -15,9 +15,7 @@ describe('native host session tab operations', () => { await expect(operations.createBrowser('workspace-1', 'https://example.com')).resolves.toEqual({ browserPageId: 'browser-1' }) - await expect(operations.close('workspace-1', 'tab-1')).resolves.toEqual({ - outcome: 'closed' - }) + await expect(operations.close('workspace-1', 'tab-1')).resolves.toBe(true) expect(sendRequest.mock.calls).toEqual([ [ @@ -35,6 +33,23 @@ describe('native host session tab operations', () => { ]) }) + it('reports a close the host accepted, whatever the result body says', async () => { + const operations = nativeHostSessionTabOperations({ + // main never inspected the result; a host that omits `closed` still had the tab closed. + sendRequest: vi.fn().mockResolvedValue({ ok: true, result: {} }) + } as unknown as RpcClient) + + await expect(operations.close('workspace-1', 'tab-1')).resolves.toBe(true) + }) + + it('reports a close the host refused at the transport', async () => { + const operations = nativeHostSessionTabOperations({ + sendRequest: vi.fn().mockResolvedValue({ ok: false, error: { code: 'x', message: 'no' } }) + } as unknown as RpcClient) + + await expect(operations.close('workspace-1', 'tab-1')).resolves.toBe(false) + }) + it('treats a create that answers without a page id as a create, not a failure', async () => { const operations = nativeHostSessionTabOperations({ sendRequest: vi.fn().mockResolvedValue({ ok: true, result: {} }) @@ -56,18 +71,4 @@ describe('native host session tab operations', () => { 'Browser busy' ) }) - - it('keeps refused closes visible to the shared screen', async () => { - const operations = nativeHostSessionTabOperations({ - sendRequest: vi.fn().mockResolvedValue({ - ok: true, - result: { closed: true, refused: true, refusalReason: 'live-host-pty' } - }) - } as unknown as RpcClient) - - await expect(operations.close('workspace-1', 'tab-1')).resolves.toEqual({ - outcome: 'refused', - reason: 'live-host-pty' - }) - }) }) diff --git a/mobile/src/session/native-host-session-tab-operations.ts b/mobile/src/session/native-host-session-tab-operations.ts index 7aa079aed600..1437d9c7e325 100644 --- a/mobile/src/session/native-host-session-tab-operations.ts +++ b/mobile/src/session/native-host-session-tab-operations.ts @@ -24,20 +24,7 @@ export function nativeHostSessionTabOperations(client: RpcClient): HostSessionTa tabId, reason: 'user' }) - if (!response.ok) { - throw new Error('session_close_failed') - } - const result = (response as RpcSuccess).result as { - closed?: boolean - refused?: boolean - refusalReason?: string - } - if (result.closed !== true) { - throw new Error('session_close_failed') - } - return result.refused - ? { outcome: 'refused', reason: result.refusalReason ?? null } - : { outcome: 'closed' } + return response.ok } } } diff --git a/mobile/src/session/use-mobile-session-close-actions.ts b/mobile/src/session/use-mobile-session-close-actions.ts index 94662539d1e7..0af994b05ea5 100644 --- a/mobile/src/session/use-mobile-session-close-actions.ts +++ b/mobile/src/session/use-mobile-session-close-actions.ts @@ -96,8 +96,7 @@ export function useMobileSessionCloseActions(scope: MobileSessionContentCreateAc try { // Why: a tapped tab close is explicit user intent; older hosts strip // the unknown reason and keep their legacy behavior. - const result = await sessionOperations.tab.close(worktreeId, tab.id) - if (result.outcome === 'closed') { + if (await sessionOperations.tab.close(worktreeId, tab.id)) { const remainingTabs = sessionTabsRef.current.filter((candidate) => candidate.id !== tab.id) reconcileBufferedDraftsRef.current(sessionTabsRef.current, remainingTabs) if (tab.type === 'browser' && tab.browserPageId === pendingBrowserFocusPageIdRef.current) { From 14e0c474b625ebc9eb482d713edcadbcb5308fe6 Mon Sep 17 00:00:00 2001 From: Jinwoo-H Date: Wed, 9 Sep 2026 12:39:18 -0400 Subject: [PATCH 21/40] fix(mobile): send Stop on whatever budget is left, and pin the device identity again Stop routed through the shared chat write, which refuses to start under a 2s residual budget. The call it replaced tried on anything above zero and could be accepted, so Stop now has its own send: main's params, main's { timeoutMs, budgetSpansConnect: true }, no enter field, the same worker takeover report on accept and the same unknown/rejected classification. The parity oracle also follows the two adapters the route's identity fields moved into, since the visitor only expands bare-identifier calls and could never reach operations.terminal.sendInput. Identity fields are 15 rather than main's 14: the seam turned two hook-side deviceToken fields into three adapter-side client:{id} builders. Dropping the binding in the adapter now fails the oracle. Claude-Session: https://claude.ai/code/session_01JNnE9qzUZMMnqpZWCqM3nb --- .../mobile-session-route-parity.test.ts | 70 +++++++++++++------ ...ost-session-native-chat-operations.test.ts | 36 ++++++++-- ...ive-host-session-native-chat-operations.ts | 64 +++++++++++------ 3 files changed, 118 insertions(+), 52 deletions(-) diff --git a/mobile/src/session/mobile-session-route-parity.test.ts b/mobile/src/session/mobile-session-route-parity.test.ts index 3487cdc96276..4acb598f7eb5 100644 --- a/mobile/src/session/mobile-session-route-parity.test.ts +++ b/mobile/src/session/mobile-session-route-parity.test.ts @@ -70,7 +70,7 @@ const HEAD_CALLBACK_BODY_SHA256 = 'e66e6436cdb9a66e870c06fdfc140106502fbeddd8db4 const HEAD_EFFECT_SHA256 = 'd9ebfaabc1e79773cdada7ab370b20459ed972f1f8edce1652199f4d0391cd13' const HEAD_CONTENT_HOOK_SHA256 = '9c3b612fef3f370d66873aefdbe1d701f20cb64ded31fef5cc45fde6f8189581' const HEAD_NESTED_FUNCTION_SHA256 = - 'd0aada4091de4551fcb5edabad4aa84249799d2fd3244c0f7493eadb4fe3ba58' + '3b75d854a92b086907571f4c877961bd429f76e3826979cee5b0e94ed2007c8e' const HEAD_NATIVE_REGISTRATION_SHA256 = 'cab85e4e4a3f43289ba93ddea9ccce57aea83e0bf14fd1620a965aad0c1cb49e' const HEAD_NATIVE_REMOVAL_SHA256 = @@ -79,13 +79,13 @@ const HEAD_TIMER_CREATION_SHA256 = '1a31b625e2174c3db77272249843196d2b6b06ab1e654a96d8f7858e3082e66b' const HEAD_TIMER_CLEANUP_SHA256 = 'c73f1d1c2cc89642f3d727d6f3b6b81860a9d6f34234541a2065ec3d1a8cd116' const HEAD_RUNTIME_STRING_SHA256 = - 'f7ab0549d15dfa0b830bf916844816fa317581a129ace4e99917ddf9cfb3771e' + '2f78f3e8f835b3a786c8940dabc127d0d131e909c0e736a4a341c5d50ce35059' const HEAD_HOST_JSX_SHA256 = '390405926b1695fa3a33686f0bc192b432f5468d8576499d7cafbb4922defbb5' const HEAD_LEAF_JSX_SHA256 = 'd5f1ef0db57c63eb3e4ee7c98e8483bc21882a151ce0ca24e42c7d1234e1dace' const HEAD_STYLE_REFERENCE_SHA256 = '295a3501c2c6d7bea7c8bbf38b3f3534f01344cd7e1b91bb8e07c040821d596a' const HEAD_IDENTITY_FIELD_SHA256 = - 'c5c6eaa5c161e842e66077dc2e934bb5871c6267f38d2f3046f902c92ae55f7b' + '2084e23285fc128e02ffbf751092ffc834b2d257c5c4bd782769f0bf97d2f161' const HEAD_NAVIGATION_SHA256 = '9d96f5dad7de555d6553eac39c0fab00efad507470fd562cb9beaa32db16f512' const HEAD_CAPABILITY_SHA256 = 'ca219f7909a091717110b823d5b94a20770ad3ae51894e0fa765e8628309392d' @@ -409,6 +409,37 @@ function readJsxFacts(definitions: ReadonlyMap): { return { host, leaf, styleReferences } } +/** The route's device identity now reaches the wire from inside these adapters, and the visitor + * follows bare-identifier calls only, so `operations.terminal.sendInput(...)` never leads it + * there. They are walked directly instead: the `deviceToken` to `client.id` binding is exactly + * what a presence-lock bug breaks, so it has to stay pinned wherever it now lives. */ +const ADAPTER_IDENTITY_SOURCES = [ + './native-host-session-terminal-operations.ts', + './native-host-session-native-chat-operations.ts' +] as const + +function collectIdentityFields( + node: ts.Node, + sourceFile: ts.SourceFile, + identityFields: string[] +): void { + if (!ts.isPropertyAssignment(node)) { + return + } + const name = node.name.getText(sourceFile) + if (['notifyClients', 'deviceToken', 'clientId'].includes(name)) { + identityFields.push(`${name}|${canonical(node.initializer, sourceFile)}`) + } + if ( + name === 'client' && + ts.isObjectLiteralExpression(node.initializer) && + node.initializer.properties.some((property) => property.name?.getText(sourceFile) === 'id') && + node.initializer.properties.some((property) => property.name?.getText(sourceFile) === 'type') + ) { + identityFields.push(`client|${canonical(node.initializer, sourceFile)}`) + } +} + function readCompatibilityFacts(definitions: ReadonlyMap): { capabilities: string[] identityFields: string[] @@ -421,24 +452,7 @@ function readCompatibilityFacts(definitions: ReadonlyMap): { if (!isRuntimeNode(node)) { return } - if (ts.isPropertyAssignment(node)) { - const name = node.name.getText(sourceFile) - if (['notifyClients', 'deviceToken', 'clientId'].includes(name)) { - identityFields.push(`${name}|${canonical(node.initializer, sourceFile)}`) - } - if ( - name === 'client' && - ts.isObjectLiteralExpression(node.initializer) && - node.initializer.properties.some( - (property) => property.name?.getText(sourceFile) === 'id' - ) && - node.initializer.properties.some( - (property) => property.name?.getText(sourceFile) === 'type' - ) - ) { - identityFields.push(`client|${canonical(node.initializer, sourceFile)}`) - } - } + collectIdentityFields(node, sourceFile, identityFields) if (!ts.isCallExpression(node)) { return } @@ -462,6 +476,14 @@ function readCompatibilityFacts(definitions: ReadonlyMap): { capabilities.push(callText) } }) + for (const relativePath of ADAPTER_IDENTITY_SOURCES) { + const sourceFile = parse(relativePath) + const visit = (node: ts.Node): void => { + collectIdentityFields(node, sourceFile, identityFields) + ts.forEachChild(node, visit) + } + visit(sourceFile) + } return { capabilities, identityFields, navigation } } @@ -507,7 +529,9 @@ describe('mobile session route extraction parity', () => { ) expect(hash(native.cleanups)).toBe(HEAD_TIMER_CLEANUP_SHA256) const compatibility = readCompatibilityFacts(definitions) - expect(compatibility.identityFields).toHaveLength(11) + // 15, not main's 14: the seam moved two hook-side `deviceToken` fields into three + // adapter-side `client: { id }` builders. Every binding main pinned is still pinned. + expect(compatibility.identityFields).toHaveLength(15) expect(hash(compatibility.identityFields)).toBe(HEAD_IDENTITY_FIELD_SHA256) expect(compatibility.navigation).toHaveLength(6) expect(hash(compatibility.navigation)).toBe(HEAD_NAVIGATION_SHA256) @@ -517,7 +541,7 @@ describe('mobile session route extraction parity', () => { it('preserves runtime strings, styles, and the expanded JSX tree', () => { const strings = readRuntimeStrings() - expect(strings).toHaveLength(592) + expect(strings).toHaveLength(593) expect(hash(strings)).toBe(HEAD_RUNTIME_STRING_SHA256) const jsx = readJsxFacts(readDefinitions()) expect(jsx.host).toHaveLength(124) diff --git a/mobile/src/session/native-host-session-native-chat-operations.test.ts b/mobile/src/session/native-host-session-native-chat-operations.test.ts index d9ee2dd0d4e5..dd83768ba8d9 100644 --- a/mobile/src/session/native-host-session-native-chat-operations.test.ts +++ b/mobile/src/session/native-host-session-native-chat-operations.test.ts @@ -20,7 +20,7 @@ function client(sendRequest: RpcClient['sendRequest']): RpcClient { } describe('native host session native chat operations', () => { - it('stops the agent with a bare Escape that cannot submit the input line', async () => { + it('stops the agent with a bare Escape that carries no enter at all', async () => { const sendRequest = vi.fn().mockResolvedValue({ ok: true, result: { delivered: true } @@ -29,11 +29,35 @@ describe('native host session native chat operations', () => { await operations.stop(target(), Date.now() + 15_000) - expect(sendRequest).toHaveBeenCalledWith( - 'terminal.send', - expect.objectContaining({ text: String.fromCharCode(27), enter: false }), - expect.anything() - ) + const params = sendRequest.mock.calls[0]?.[1] as Record + expect(sendRequest.mock.calls[0]?.[0]).toBe('terminal.send') + expect(params.text).toBe(String.fromCharCode(27)) + // The host tests `enter === true`, and the call it replaced omitted the field entirely. + expect(params).not.toHaveProperty('enter') + }) + + it('still attempts the Escape inside the shared write floor', async () => { + // The shared chat write refuses to start under a 2s residual budget. Stop does not: the + // call it replaced tried on whatever was left and could be accepted. + const sendRequest = vi.fn().mockResolvedValue({ + ok: true, + result: { send: { accepted: true } } + }) + const operations = nativeHostSessionNativeChatOperations(client(sendRequest)) + + await expect(operations.stop(target(), Date.now() + 1_500)).resolves.toBe('accepted') + // The second call is the worker-takeover report an accepted Stop always makes. + const sends = sendRequest.mock.calls.filter(([method]) => method === 'terminal.send') + expect(sends).toHaveLength(1) + expect(sends[0]?.[2]).toMatchObject({ budgetSpansConnect: true }) + }) + + it('does not attempt an Escape whose budget is already spent', async () => { + const sendRequest = vi.fn() + const operations = nativeHostSessionNativeChatOperations(client(sendRequest)) + + await expect(operations.stop(target(), Date.now() - 1)).resolves.toBe('rejected') + expect(sendRequest).not.toHaveBeenCalled() }) it('keeps the legacy file inventory scoped to the workspace that produced it', async () => { diff --git a/mobile/src/session/native-host-session-native-chat-operations.ts b/mobile/src/session/native-host-session-native-chat-operations.ts index 2b091ea8ea8c..baef6fec921f 100644 --- a/mobile/src/session/native-host-session-native-chat-operations.ts +++ b/mobile/src/session/native-host-session-native-chat-operations.ts @@ -3,9 +3,13 @@ import { buildNativeChatSubscriptionId } from '../../../src/shared/native-chat-s import { isFloatingWorkspaceWorktreeId } from './floating-workspace' import { isMobileNativeChatTranscriptReadable } from './mobile-native-chat-eligibility' import { - sendMobileNativeChatMessageWithOutcome, + MOBILE_NATIVE_CHAT_SEND_TIMEOUT_MS, type MobileNativeChatSendOutcome } from './mobile-native-chat-send' +import { isRpcDeliveryUnknown } from '../transport/rpc-delivery-ambiguity' +import { isLogicalClientCutoverError } from '../transport/stable-logical-rpc-client' +import { isTerminalSendRpcAccepted } from '../terminal/terminal-send-rpc-response' +import { reportWorkerTerminalUserInput } from '../terminal/worker-terminal-takeover-report' import { rankSuggestions } from './mobile-native-chat-autocomplete' import { getRepoIdFromMobileWorktreeId } from './mobile-session-route-helpers' import type { @@ -63,9 +67,7 @@ export function nativeHostSessionNativeChatOperations( } }, stop(target, deadline) { - // Escape must not carry Return: the extra newline submits whatever the agent - // had parked on its input line. - return sendNative(target, escape(), false, client, deadline) + return sendStopEscape(target, client, deadline) }, resetFileSearchCache(workspaceId) { searchSupported = null @@ -128,30 +130,46 @@ function nativeChatReadParams(target: HostSessionNativeChatTarget, limit: number } } -function sendNative( +/** Stop keeps its own send rather than the shared chat write: the shared one refuses to start + * under a 2s residual budget, and Stop is worth attempting on whatever is left. It carries no + * `enter`, so the Escape cannot submit whatever the agent had parked on its input line. */ +async function sendStopEscape( target: HostSessionNativeChatTarget, - text: string, - enter: boolean, client: RpcClient, - deadline?: number, - resolvedLaunchDraft?: { text: string; createdAt: number } + deadline?: number ): Promise { if (!target.terminalId) { - return Promise.resolve('rejected') + return 'rejected' + } + const handle = target.terminalId + const timeoutMs = + deadline === undefined ? MOBILE_NATIVE_CHAT_SEND_TIMEOUT_MS : deadline - Date.now() + if (timeoutMs <= 0) { + return 'rejected' + } + try { + const response = await client.sendRequest( + 'terminal.send', + { + terminal: handle, + text: String.fromCharCode(27), + ...(target.clientId ? { client: { id: target.clientId, type: 'mobile' as const } } : {}) + }, + // Why: without this the call parks indefinitely on reconnect, so "Stop not sent" never + // appears and a stale Escape can land minutes later, into a composer holding fresh text. + { timeoutMs, budgetSpansConnect: true } + ) + if (!isTerminalSendRpcAccepted(response)) { + return 'rejected' + } + // A deliberate Stop is human input; it takes the worker over like any other key. + reportWorkerTerminalUserInput(client, handle) + return 'accepted' + } catch (error) { + return isRpcDeliveryUnknown(error) || isLogicalClientCutoverError(error) + ? 'unknown' + : 'rejected' } - return sendMobileNativeChatMessageWithOutcome({ - client, - terminal: target.terminalId, - text, - enter, - resolvedLaunchDraft, - deadline, - ...(target.clientId ? { mobileClient: { id: target.clientId, type: 'mobile' as const } } : {}) - }) -} - -function escape(): string { - return String.fromCharCode(27) } function extractPaths(result: unknown): string[] { From df248c4368473b75e033a6a74276412df2b5239e Mon Sep 17 00:00:00 2001 From: Jinwoo-H Date: Wed, 9 Sep 2026 12:40:45 -0400 Subject: [PATCH 22/40] refactor(mobile): drop the two create fields with no producer or consumer sparseCheckout was added to the composer create args and forwarded into the worktree.create params; its only caller never passes it. warning was added to WorktreeCreateResult and read off the response; nothing reads it, and the one screen that shows a create warning is on the unchanged inline path with its own copy. worktree-create-retry.ts and source-workspace-create.ts are now byte-identical to main. Claude-Session: https://claude.ai/code/session_01JNnE9qzUZMMnqpZWCqM3nb --- mobile/src/tasks/source-workspace-create.ts | 7 ++----- mobile/src/tasks/worktree-create-retry.ts | 8 ++------ 2 files changed, 4 insertions(+), 11 deletions(-) diff --git a/mobile/src/tasks/source-workspace-create.ts b/mobile/src/tasks/source-workspace-create.ts index b96c28610ccf..6e666005ac3b 100644 --- a/mobile/src/tasks/source-workspace-create.ts +++ b/mobile/src/tasks/source-workspace-create.ts @@ -28,9 +28,8 @@ export type CreateWorkspaceFromComposerArgs = { setupDecision: WorkspaceCreateSetupDecision agent: WorkspaceCreateAgentBundle workspaceName: string | undefined - note: string | undefined - sparseCheckout?: { directories: string[]; presetId?: string } nameIsAutoManaged?: boolean + note: string | undefined worktreeCreateIdempotency: WorktreeCreateIdempotencyProbe } @@ -92,9 +91,8 @@ async function createWorkItemWorkspace(args: { setupDecision: WorkspaceCreateSetupDecision agent: WorkspaceCreateAgentBundle workspaceName: string | undefined - note: string | undefined - sparseCheckout?: { directories: string[]; presetId?: string } nameIsAutoManaged?: boolean + note: string | undefined worktreeCreateIdempotency: WorktreeCreateIdempotencyProbe }): Promise { const { client, selection, targetRepoId, setupDecision, agent, workspaceName, note } = args @@ -132,7 +130,6 @@ async function createWorkItemWorkspace(args: { compareBaseRef, branchNameOverride, pushTarget, - sparseCheckout: args.sparseCheckout, nameIsAutoManaged: args.nameIsAutoManaged }) // buildTaskWorkspaceCreateParams computes the name; reuse it as the retry base diff --git a/mobile/src/tasks/worktree-create-retry.ts b/mobile/src/tasks/worktree-create-retry.ts index a395e59baf42..a3fa8ae2e1b7 100644 --- a/mobile/src/tasks/worktree-create-retry.ts +++ b/mobile/src/tasks/worktree-create-retry.ts @@ -21,9 +21,7 @@ import { // branches outlive worktrees in git, and remote branches/PRs aren't visible from // worktree.ps. Retry by appending -2, -3, ... mirroring the desktop createWorktree // loop in src/renderer/src/store/slices/worktrees.ts. -export type WorktreeCreateResult = - | { worktreeId: string; name: string; warning?: string } - | { error: string } +export type WorktreeCreateResult = { worktreeId: string; name: string } | { error: string } // Why: a create in flight when the mobile transport migrates (relay/direct // hand-off on shoddy cellular, relay lease rotation) rejects with a cutover error @@ -86,7 +84,6 @@ export async function createWorktreeWithNameRetry( if (response.ok) { const result = (response as RpcSuccess).result as { worktree: { id: string; displayName?: string } - warning?: string } const authoritativeName = result.worktree.displayName return { @@ -94,8 +91,7 @@ export async function createWorktreeWithNameRetry( name: typeof authoritativeName === 'string' && authoritativeName.trim() ? authoritativeName - : candidateName, - ...(result.warning ? { warning: result.warning } : {}) + : candidateName } } lastError = response.error.message From 3924105b72c7102d8e5746060dfeb9a752b52991 Mon Sep 17 00:00:00 2001 From: Jinwoo-H Date: Wed, 9 Sep 2026 12:42:12 -0400 Subject: [PATCH 23/40] fix(mobile): check the quick-command load envelope outside the cutover retry main handled `!response.ok` after the retry helper returned. Throwing inside the try made a refusal replayable, because the cutover predicate matches any Error whose message is exactly the migration string, so a host refusal carrying that text was retried five times. The helper returns the response again and the caller checks it. The new test fails under the old shape with six attempts instead of one. Claude-Session: https://claude.ai/code/session_01JNnE9qzUZMMnqpZWCqM3nb --- ...t-session-quick-command-operations.test.ts | 39 +++++++++++++++++++ ...e-host-session-quick-command-operations.ts | 18 ++++----- 2 files changed, 47 insertions(+), 10 deletions(-) create mode 100644 mobile/src/session/native-host-session-quick-command-operations.test.ts diff --git a/mobile/src/session/native-host-session-quick-command-operations.test.ts b/mobile/src/session/native-host-session-quick-command-operations.test.ts new file mode 100644 index 000000000000..11bfb2df5bf8 --- /dev/null +++ b/mobile/src/session/native-host-session-quick-command-operations.test.ts @@ -0,0 +1,39 @@ +import { describe, expect, it, vi } from 'vitest' +import type { RpcClient } from '../transport/rpc-client' +import { LogicalClientCutoverError } from '../transport/stable-logical-rpc-client' +import { nativeHostSessionQuickCommandOperations } from './native-host-session-quick-command-operations' + +const client = (sendRequest: RpcClient['sendRequest']): RpcClient => + ({ sendRequest }) as unknown as RpcClient + +describe('native host session quick command operations', () => { + it('replays the load only when the transport rejected with a cutover', async () => { + let attempts = 0 + const sendRequest = vi.fn(async () => { + attempts += 1 + if (attempts === 1) { + throw new LogicalClientCutoverError() + } + return { ok: true, result: { terminalQuickCommands: [] } } + }) + + await expect( + nativeHostSessionQuickCommandOperations(client(sendRequest)).snapshot('wt-1') + ).resolves.toMatchObject({ commands: [] }) + expect(sendRequest).toHaveBeenCalledTimes(2) + }) + + it('does not replay a refusal envelope, whatever message it carries', async () => { + // A host refusal is an answer. Checking `ok` inside the retry would replay it up to five + // times whenever the host's own error text happened to match the cutover string. + const sendRequest = vi.fn().mockResolvedValue({ + ok: false, + error: { code: 'failed', message: 'RPC interrupted by connection migration' } + }) + + await expect( + nativeHostSessionQuickCommandOperations(client(sendRequest)).snapshot('wt-1') + ).rejects.toThrow('RPC interrupted by connection migration') + expect(sendRequest).toHaveBeenCalledTimes(1) + }) +}) diff --git a/mobile/src/session/native-host-session-quick-command-operations.ts b/mobile/src/session/native-host-session-quick-command-operations.ts index 36a7ce9906da..0d9e51dc06de 100644 --- a/mobile/src/session/native-host-session-quick-command-operations.ts +++ b/mobile/src/session/native-host-session-quick-command-operations.ts @@ -15,11 +15,13 @@ export function nativeHostSessionQuickCommandOperations( ): HostSessionQuickCommandOperations { return { async snapshot(workspaceId, signal) { - return quickCommandSnapshot( - await loadWithCutoverRetry(client, signal), - workspaceId, - 'Failed to load quick commands' - ) + // The ok check sits outside the retry, as it did before this seam existed: a refusal + // envelope is an answer, and replaying it would depend on the host's error text. + const response = await loadWithCutoverRetry(client, signal) + if (!response.ok) { + throw new Error(response.error.message || 'Failed to load quick commands') + } + return quickCommandSnapshot(response.result, workspaceId, 'Failed to load quick commands') }, async mutate(workspaceId, mutation) { // Why no cutover retry here: a quick-command mutation is not idempotent, so a replay @@ -38,11 +40,7 @@ export function nativeHostSessionQuickCommandOperations( async function loadWithCutoverRetry(client: RpcClient, signal?: AbortSignal) { for (let retry = 0; ; retry += 1) { try { - const response = await client.sendRequest('settings.getTerminalQuickCommands') - if (!response.ok) { - throw new Error(response.error.message || 'Failed to load quick commands') - } - return response.result + return await client.sendRequest('settings.getTerminalQuickCommands') } catch (error) { if ( signal?.aborted || From d0994be78ecbba259507fbe6e1808ca2fb89ce18 Mon Sep 17 00:00:00 2001 From: Jinwoo-H Date: Wed, 9 Sep 2026 12:46:42 -0400 Subject: [PATCH 24/40] refactor(mobile): delete the seam surface with no production reader Each was confirmed to have zero non-test readers before and after: - HostSessionTerminalOperations.subscribe, its adapter body and its test. The live stream still calls subscribeMobileTerminalSafely directly, as on main, so the method existed only to be tested. - pasteImages and releaseImages, declared on the native-chat interface and never implemented or called. - explicitQuickCommandScope, exported with no callers. - The quick-command snapshot's totalCount and repoId, which nothing read, and with them the workspaceId argument that existed only to compute repoId. The hook takes { operations, enabled } again, as main took { client, enabled }. - The web-artifact result variant, line and column on the resolve request, rename's third parameter and the directory variant's truncated. The legacy-list variant's truncated stays: the panel reads it. Deleting the terminal subscribe also brings the parity oracle's identity fields to 14, matching main exactly. Claude-Session: https://claude.ai/code/session_01JNnE9qzUZMMnqpZWCqM3nb --- .../files/host-file-explorer-operations.ts | 1 - mobile/src/session/MobileSessionSheets.tsx | 1 - mobile/src/session/QuickCommandsSheet.tsx | 3 -- .../host-session-native-chat-operations.ts | 7 ---- .../host-session-quick-command-operations.ts | 20 ++------- .../host-session-terminal-file-operations.ts | 10 ----- .../host-session-terminal-operations.ts | 7 +--- mobile/src/session/mobile-file-tap-open.ts | 4 +- .../mobile-session-route-parity.test.ts | 14 +++---- ...e-host-session-quick-command-operations.ts | 20 +++------ ...e-host-session-terminal-operations.test.ts | 42 +------------------ ...native-host-session-terminal-operations.ts | 15 ------- .../use-mobile-session-close-actions.ts | 2 +- mobile/src/session/use-quick-commands.ts | 23 ++++------ 14 files changed, 26 insertions(+), 143 deletions(-) diff --git a/mobile/src/files/host-file-explorer-operations.ts b/mobile/src/files/host-file-explorer-operations.ts index 8144d4ca4697..bad5cec19b05 100644 --- a/mobile/src/files/host-file-explorer-operations.ts +++ b/mobile/src/files/host-file-explorer-operations.ts @@ -5,7 +5,6 @@ export type HostFileExplorerDirectoryResult = | { kind: 'directory' entries: MobileDirEntry[] - truncated: boolean } | { kind: 'legacy-list' diff --git a/mobile/src/session/MobileSessionSheets.tsx b/mobile/src/session/MobileSessionSheets.tsx index e24c7e5bd4e4..5e02d9b9d8a5 100644 --- a/mobile/src/session/MobileSessionSheets.tsx +++ b/mobile/src/session/MobileSessionSheets.tsx @@ -105,7 +105,6 @@ export function MobileSessionSheets({ controller }: { controller: MobileSessionC visible={showQuickCommands && quickCommandsSupported === true} onClose={() => setShowQuickCommands(false)} operations={sessionOperations?.quickCommand ?? null} - workspaceId={worktreeId} repoId={ isFolderWorkspaceRoute || isFloatingWorkspaceRoute ? null diff --git a/mobile/src/session/QuickCommandsSheet.tsx b/mobile/src/session/QuickCommandsSheet.tsx index fac2b212f40a..1b68d1cb3aae 100644 --- a/mobile/src/session/QuickCommandsSheet.tsx +++ b/mobile/src/session/QuickCommandsSheet.tsx @@ -24,7 +24,6 @@ type Props = { visible: boolean onClose: () => void operations: HostSessionQuickCommandOperations | null - workspaceId: string repoId: string | null repoName: string | null onLaunch: (command: TerminalQuickCommand) => boolean @@ -36,14 +35,12 @@ export function QuickCommandsSheet({ visible, onClose, operations, - workspaceId, repoId, repoName, onLaunch }: Props) { const { commands, loading, ready, error, persist } = useQuickCommands({ operations, - workspaceId, enabled: visible }) const [view, setView] = useState('list') diff --git a/mobile/src/session/host-session-native-chat-operations.ts b/mobile/src/session/host-session-native-chat-operations.ts index cad0d769f85d..4a06f861bb05 100644 --- a/mobile/src/session/host-session-native-chat-operations.ts +++ b/mobile/src/session/host-session-native-chat-operations.ts @@ -44,13 +44,6 @@ export type HostSessionNativeChatOperations = { beforeOffset?: number ): Promise stop(target: HostSessionNativeChatTarget, deadline?: number): Promise - pasteImages?( - target: HostSessionNativeChatTarget, - references: readonly string[], - deadline?: number, - followedByText?: boolean - ): Promise - releaseImages?(target: HostSessionNativeChatTarget, references: readonly string[]): Promise /** Drops the legacy full-inventory fallback's cached listing for a workspace. Without it a * second visit inside one connection serves the first read's inventory, so a file created in * between is missing from `@` autocomplete. */ diff --git a/mobile/src/session/host-session-quick-command-operations.ts b/mobile/src/session/host-session-quick-command-operations.ts index 9e0022f934d2..99672a5cb721 100644 --- a/mobile/src/session/host-session-quick-command-operations.ts +++ b/mobile/src/session/host-session-quick-command-operations.ts @@ -1,25 +1,11 @@ -import type { - TerminalQuickCommand, - TerminalQuickCommandScope -} from '../../../src/shared/terminal-quick-command-types' +import type { TerminalQuickCommand } from '../../../src/shared/terminal-quick-command-types' import type { TerminalQuickCommandMutation } from '../terminal/quick-commands' export type HostSessionQuickCommandSnapshot = { commands: TerminalQuickCommand[] - totalCount: number - repoId: string | null } export type HostSessionQuickCommandOperations = { - snapshot(workspaceId: string, signal?: AbortSignal): Promise - mutate( - workspaceId: string, - mutation: TerminalQuickCommandMutation - ): Promise -} - -export function explicitQuickCommandScope( - scope: TerminalQuickCommandScope | undefined -): TerminalQuickCommandScope { - return scope?.type === 'repo' ? { type: 'repo', repoId: scope.repoId } : { type: 'global' } + snapshot(signal?: AbortSignal): Promise + mutate(mutation: TerminalQuickCommandMutation): Promise } diff --git a/mobile/src/session/host-session-terminal-file-operations.ts b/mobile/src/session/host-session-terminal-file-operations.ts index 9aa71937fc60..192546d36f1b 100644 --- a/mobile/src/session/host-session-terminal-file-operations.ts +++ b/mobile/src/session/host-session-terminal-file-operations.ts @@ -13,14 +13,6 @@ export type HostSessionTerminalFileTarget = grantId: string workspaceId?: string } - | { - kind: 'web-artifact' - /** The terminal text the desktop re-resolves for every chunk read. */ - pathText: string - displayName: string - previewKind: 'text' | 'raster' - workspaceId?: string - } export type HostSessionTerminalFileResolveRequest = { workspaceId: string @@ -28,8 +20,6 @@ export type HostSessionTerminalFileResolveRequest = { pathText: string cwd: string | null nativeChatContext: RuntimeNativeChatFileContext | null - line: number | null - column: number | null } export type HostSessionTerminalFileOperations = { diff --git a/mobile/src/session/host-session-terminal-operations.ts b/mobile/src/session/host-session-terminal-operations.ts index 5bffe947238c..594a84b52938 100644 --- a/mobile/src/session/host-session-terminal-operations.ts +++ b/mobile/src/session/host-session-terminal-operations.ts @@ -52,11 +52,6 @@ export type HostSessionTerminalSubscribeArgs = { } export type HostSessionTerminalOperations = { - subscribe( - args: HostSessionTerminalSubscribeArgs, - onEvent: (event: HostSessionTerminalStreamEvent) => void, - onError: () => void - ): () => void sendInput( terminalId: string, text: string, @@ -70,5 +65,5 @@ export type HostSessionTerminalOperations = { clientId: string | null ): Promise clear(terminalId: string): Promise - rename(terminalId: string, title: string, workspaceId: string): Promise + rename(terminalId: string, title: string): Promise } diff --git a/mobile/src/session/mobile-file-tap-open.ts b/mobile/src/session/mobile-file-tap-open.ts index 7a9315cfa52d..4bdec99f980c 100644 --- a/mobile/src/session/mobile-file-tap-open.ts +++ b/mobile/src/session/mobile-file-tap-open.ts @@ -77,9 +77,7 @@ async function openMobileFileTapAsync( terminalHandle, pathText: options.pathText, cwd, - nativeChatContext: options.nativeChatContext ?? null, - line: options.line, - column: options.column + nativeChatContext: options.nativeChatContext ?? null }) if (!resolved) { reportOpenFailure(options) diff --git a/mobile/src/session/mobile-session-route-parity.test.ts b/mobile/src/session/mobile-session-route-parity.test.ts index 4acb598f7eb5..eb583426d633 100644 --- a/mobile/src/session/mobile-session-route-parity.test.ts +++ b/mobile/src/session/mobile-session-route-parity.test.ts @@ -70,7 +70,7 @@ const HEAD_CALLBACK_BODY_SHA256 = 'e66e6436cdb9a66e870c06fdfc140106502fbeddd8db4 const HEAD_EFFECT_SHA256 = 'd9ebfaabc1e79773cdada7ab370b20459ed972f1f8edce1652199f4d0391cd13' const HEAD_CONTENT_HOOK_SHA256 = '9c3b612fef3f370d66873aefdbe1d701f20cb64ded31fef5cc45fde6f8189581' const HEAD_NESTED_FUNCTION_SHA256 = - '3b75d854a92b086907571f4c877961bd429f76e3826979cee5b0e94ed2007c8e' + 'ad78ecb8bd61cd0cc3a7037bbd7dcc06b0fbe0de62b23090b8350c2947d65c3d' const HEAD_NATIVE_REGISTRATION_SHA256 = 'cab85e4e4a3f43289ba93ddea9ccce57aea83e0bf14fd1620a965aad0c1cb49e' const HEAD_NATIVE_REMOVAL_SHA256 = @@ -79,13 +79,13 @@ const HEAD_TIMER_CREATION_SHA256 = '1a31b625e2174c3db77272249843196d2b6b06ab1e654a96d8f7858e3082e66b' const HEAD_TIMER_CLEANUP_SHA256 = 'c73f1d1c2cc89642f3d727d6f3b6b81860a9d6f34234541a2065ec3d1a8cd116' const HEAD_RUNTIME_STRING_SHA256 = - '2f78f3e8f835b3a786c8940dabc127d0d131e909c0e736a4a341c5d50ce35059' + '58ee753e4fc849c693aa6ebb71b2ff7c38dbbba50977cacc737b03c4bb2a7224' const HEAD_HOST_JSX_SHA256 = '390405926b1695fa3a33686f0bc192b432f5468d8576499d7cafbb4922defbb5' -const HEAD_LEAF_JSX_SHA256 = 'd5f1ef0db57c63eb3e4ee7c98e8483bc21882a151ce0ca24e42c7d1234e1dace' +const HEAD_LEAF_JSX_SHA256 = '15ea1af8ae1a28a4a5f2ea31c2aac908fc24a0fe68923733889f1d40d0c8e3a3' const HEAD_STYLE_REFERENCE_SHA256 = '295a3501c2c6d7bea7c8bbf38b3f3534f01344cd7e1b91bb8e07c040821d596a' const HEAD_IDENTITY_FIELD_SHA256 = - '2084e23285fc128e02ffbf751092ffc834b2d257c5c4bd782769f0bf97d2f161' + '89bdd544369e41829581e80d320112019f3127fd3529c810d9651e5ece37338b' const HEAD_NAVIGATION_SHA256 = '9d96f5dad7de555d6553eac39c0fab00efad507470fd562cb9beaa32db16f512' const HEAD_CAPABILITY_SHA256 = 'ca219f7909a091717110b823d5b94a20770ad3ae51894e0fa765e8628309392d' @@ -529,9 +529,7 @@ describe('mobile session route extraction parity', () => { ) expect(hash(native.cleanups)).toBe(HEAD_TIMER_CLEANUP_SHA256) const compatibility = readCompatibilityFacts(definitions) - // 15, not main's 14: the seam moved two hook-side `deviceToken` fields into three - // adapter-side `client: { id }` builders. Every binding main pinned is still pinned. - expect(compatibility.identityFields).toHaveLength(15) + expect(compatibility.identityFields).toHaveLength(14) expect(hash(compatibility.identityFields)).toBe(HEAD_IDENTITY_FIELD_SHA256) expect(compatibility.navigation).toHaveLength(6) expect(hash(compatibility.navigation)).toBe(HEAD_NAVIGATION_SHA256) @@ -541,7 +539,7 @@ describe('mobile session route extraction parity', () => { it('preserves runtime strings, styles, and the expanded JSX tree', () => { const strings = readRuntimeStrings() - expect(strings).toHaveLength(593) + expect(strings).toHaveLength(591) expect(hash(strings)).toBe(HEAD_RUNTIME_STRING_SHA256) const jsx = readJsxFacts(readDefinitions()) expect(jsx.host).toHaveLength(124) diff --git a/mobile/src/session/native-host-session-quick-command-operations.ts b/mobile/src/session/native-host-session-quick-command-operations.ts index 0d9e51dc06de..3ea3bba970d7 100644 --- a/mobile/src/session/native-host-session-quick-command-operations.ts +++ b/mobile/src/session/native-host-session-quick-command-operations.ts @@ -5,8 +5,6 @@ import type { HostSessionQuickCommandOperations, HostSessionQuickCommandSnapshot } from './host-session-quick-command-operations' -import { isFloatingWorkspaceWorktreeId } from './floating-workspace' -import { getRepoIdFromMobileWorktreeId } from './mobile-session-route-helpers' const LOAD_CUTOVER_MAX_RETRIES = 5 @@ -14,16 +12,16 @@ export function nativeHostSessionQuickCommandOperations( client: RpcClient ): HostSessionQuickCommandOperations { return { - async snapshot(workspaceId, signal) { + async snapshot(signal) { // The ok check sits outside the retry, as it did before this seam existed: a refusal // envelope is an answer, and replaying it would depend on the host's error text. const response = await loadWithCutoverRetry(client, signal) if (!response.ok) { throw new Error(response.error.message || 'Failed to load quick commands') } - return quickCommandSnapshot(response.result, workspaceId, 'Failed to load quick commands') + return quickCommandSnapshot(response.result, 'Failed to load quick commands') }, - async mutate(workspaceId, mutation) { + async mutate(mutation) { // Why no cutover retry here: a quick-command mutation is not idempotent, so a replay // after a logical cutover could apply the same edit twice. const response = await client.sendRequest('settings.updateTerminalQuickCommands', { @@ -32,7 +30,7 @@ export function nativeHostSessionQuickCommandOperations( if (!response.ok) { throw new Error(response.error.message || 'Failed to save quick command') } - return quickCommandSnapshot(response.result, workspaceId, 'Failed to save quick command') + return quickCommandSnapshot(response.result, 'Failed to save quick command') } } } @@ -55,7 +53,6 @@ async function loadWithCutoverRetry(client: RpcClient, signal?: AbortSignal) { function quickCommandSnapshot( result: unknown, - workspaceId: string, invalidResultMessage: string ): HostSessionQuickCommandSnapshot { const commands = parseNormalizedTerminalQuickCommands( @@ -64,12 +61,5 @@ function quickCommandSnapshot( if (!commands) { throw new Error(invalidResultMessage) } - return { - commands, - totalCount: commands.length, - repoId: - workspaceId.startsWith('folder:') || isFloatingWorkspaceWorktreeId(workspaceId) - ? null - : getRepoIdFromMobileWorktreeId(workspaceId) - } + return { commands } } diff --git a/mobile/src/session/native-host-session-terminal-operations.test.ts b/mobile/src/session/native-host-session-terminal-operations.test.ts index fd12d35cf77c..f7e2dddeddb7 100644 --- a/mobile/src/session/native-host-session-terminal-operations.test.ts +++ b/mobile/src/session/native-host-session-terminal-operations.test.ts @@ -3,47 +3,14 @@ import type { RpcClient } from '../transport/rpc-client' import { nativeHostSessionTerminalOperations } from './native-host-session-terminal-operations' describe('native host session terminal operations', () => { - it('preserves the existing mobile subscription and input RPC semantics', async () => { - const unsubscribe = vi.fn() - let onData: ((event: unknown) => void) | null = null - const subscribe = vi.fn((_method, _params, listener) => { - onData = listener - return unsubscribe - }) + it('preserves the existing mobile terminal input RPC semantics', async () => { const sendRequest = vi .fn() .mockResolvedValue({ ok: true, result: { send: { accepted: true } } }) const operations = nativeHostSessionTerminalOperations({ - subscribe, sendRequest } as unknown as RpcClient) - const onEvent = vi.fn() - - const cleanup = operations.subscribe( - { - workspaceId: 'workspace-1', - terminalId: 'terminal-native-1', - clientId: 'device-1', - viewport: { cols: 90, rows: 30 }, - visible: true, - capabilities: { terminalBinaryStream: 1 } - }, - onEvent, - vi.fn() - ) - onData?.({ type: 'data', chunk: 'hello' }) - expect(subscribe).toHaveBeenCalledWith( - 'terminal.subscribe', - { - terminal: 'terminal-native-1', - client: { id: 'device-1', type: 'mobile' }, - viewport: { cols: 90, rows: 30 }, - capabilities: { terminalBinaryStream: 1 } - }, - expect.any(Function) - ) - expect(onEvent).toHaveBeenCalledWith({ type: 'data', chunk: 'hello' }) await expect(operations.sendInput('terminal-native-1', 'ls', true, 'device-1')).resolves.toBe( true ) @@ -60,9 +27,7 @@ describe('native host session terminal operations', () => { await expect( operations.setDisplayMode('terminal-native-1', 'auto', { cols: 90, rows: 30 }, 'device-1') ).resolves.toBe(true) - await expect( - operations.rename('terminal-native-1', 'Build', 'workspace-native-1') - ).resolves.toBe(true) + await expect(operations.rename('terminal-native-1', 'Build')).resolves.toBe(true) await expect(operations.clear('terminal-native-1')).resolves.toBe(true) expect(sendRequest).toHaveBeenCalledWith('terminal.setDisplayMode', { terminal: 'terminal-native-1', @@ -77,8 +42,5 @@ describe('native host session terminal operations', () => { expect(sendRequest).toHaveBeenCalledWith('terminal.clearBuffer', { terminal: 'terminal-native-1' }) - - cleanup() - expect(unsubscribe).toHaveBeenCalledOnce() }) }) diff --git a/mobile/src/session/native-host-session-terminal-operations.ts b/mobile/src/session/native-host-session-terminal-operations.ts index 677a3861eafa..310c9a9141b2 100644 --- a/mobile/src/session/native-host-session-terminal-operations.ts +++ b/mobile/src/session/native-host-session-terminal-operations.ts @@ -2,26 +2,11 @@ import { isTerminalSendRpcAccepted } from '../terminal/terminal-send-rpc-respons import { TERMINAL_INPUT_SEND_OPTIONS } from '../terminal/terminal-send-request' import type { RpcClient } from '../transport/rpc-client' import type { HostSessionTerminalOperations } from './host-session-terminal-operations' -import { subscribeMobileTerminalSafely } from './mobile-terminal-stream-subscribe' export function nativeHostSessionTerminalOperations( client: RpcClient ): HostSessionTerminalOperations { return { - subscribe(args, onEvent, onError) { - const unsubscribe = subscribeMobileTerminalSafely( - client, - { - terminal: args.terminalId, - ...(args.clientId ? { client: { id: args.clientId, type: 'mobile' as const } } : {}), - viewport: args.viewport, - capabilities: args.capabilities - }, - (event) => onEvent(event as Parameters[0]), - onError - ) - return unsubscribe - }, async sendInput(terminalId, text, enter, clientId) { return client .sendRequest( diff --git a/mobile/src/session/use-mobile-session-close-actions.ts b/mobile/src/session/use-mobile-session-close-actions.ts index 0af994b05ea5..e3f50be3f5e2 100644 --- a/mobile/src/session/use-mobile-session-close-actions.ts +++ b/mobile/src/session/use-mobile-session-close-actions.ts @@ -40,7 +40,7 @@ export function useMobileSessionCloseActions(scope: MobileSessionContentCreateAc try { const title = value.trim() - if (await sessionOperations.terminal.rename(target.handle, title, worktreeId)) { + if (await sessionOperations.terminal.rename(target.handle, title)) { setTerminals((prev) => { const next = prev.map((terminal) => terminal.handle === target.handle diff --git a/mobile/src/session/use-quick-commands.ts b/mobile/src/session/use-quick-commands.ts index fe422ab9da21..17f68a08c42c 100644 --- a/mobile/src/session/use-quick-commands.ts +++ b/mobile/src/session/use-quick-commands.ts @@ -8,7 +8,6 @@ import type { HostSessionQuickCommandOperations } from './host-session-quick-com type Args = { operations: HostSessionQuickCommandOperations | null - workspaceId: string // Fetch only while the sheet is open — quick commands are settings data we // don't need to keep hydrated for every session screen. enabled: boolean @@ -31,14 +30,13 @@ type PendingMutation = { type MutationContext = { operations: HostSessionQuickCommandOperations - workspaceId: string confirmed: TerminalQuickCommand[] pending: PendingMutation[] queue: Promise nextMutationId: number } -export function useQuickCommands({ operations, workspaceId, enabled }: Args): QuickCommandsState { +export function useQuickCommands({ operations, enabled }: Args): QuickCommandsState { const [commands, setCommands] = useState([]) const [loading, setLoading] = useState(false) const [ready, setReady] = useState(false) @@ -53,11 +51,10 @@ export function useQuickCommands({ operations, workspaceId, enabled }: Args): Qu return } let mutationContext = mutationContextRef.current - if (mutationContext?.operations !== operations || mutationContext.workspaceId !== workspaceId) { + if (mutationContext?.operations !== operations) { // A request for an old host must not delay or update mutations on a new one. mutationContext = { operations, - workspaceId, confirmed: [], pending: [], queue: Promise.resolve(), @@ -89,7 +86,7 @@ export function useQuickCommands({ operations, workspaceId, enabled }: Args): Qu ) { return } - const snapshot = await operations.snapshot(workspaceId, abortController.signal) + const snapshot = await operations.snapshot(abortController.signal) if ( stale || operationId !== operationIdRef.current || @@ -124,20 +121,14 @@ export function useQuickCommands({ operations, workspaceId, enabled }: Args): Qu stale = true abortController.abort() } - }, [enabled, operations, workspaceId]) + }, [enabled, operations]) const persist = useCallback( async (commandMutation: TerminalQuickCommandMutation) => { // Why: the loaded list is the optimistic/rollback baseline; mutating // before it arrives would make failure recovery show invented state. const mutationContext = mutationContextRef.current - if ( - !operations || - loading || - !ready || - mutationContext?.operations !== operations || - mutationContext.workspaceId !== workspaceId - ) { + if (!operations || loading || !ready || mutationContext?.operations !== operations) { return false } const mutation: PendingMutation = { @@ -157,7 +148,7 @@ export function useQuickCommands({ operations, workspaceId, enabled }: Args): Qu try { // Why: an invalid success payload throws inside the adapter rather than // confirming [] — a later full-list mutation would erase live commands. - const snapshot = await operations.mutate(workspaceId, commandMutation) + const snapshot = await operations.mutate(commandMutation) mutationContext.confirmed = snapshot.commands succeeded = true return true @@ -191,7 +182,7 @@ export function useQuickCommands({ operations, workspaceId, enabled }: Args): Qu ) return await request }, - [loading, operations, ready, workspaceId] + [loading, operations, ready] ) return { commands, loading, ready, error, persist } From d96f68457cfb6605caec7b17bb7634d7f15ddcf3 Mon Sep 17 00:00:00 2001 From: Jinwoo-H Date: Wed, 9 Sep 2026 12:49:30 -0400 Subject: [PATCH 25/40] fix(mobile): restore main's guard conditions on the four Project-row actions Each had gained a non-null target requirement that demanded a number and a recognised item type where main's guard did not, so a row main would have sent for now returns silently or reports an error. File-viewed and the comment reply gate on main's conditions and build the never-null identity target after them. Metadata update, issue type and comment add gate on the slug and the number, as main did, through the slug target, which does not read the item type. Claude-Session: https://claude.ai/code/session_01JNnE9qzUZMMnqpZWCqM3nb --- .../github-project-host-routing-source.test.ts | 4 +++- .../tasks/mobile-tasks-refactor-parity.test.ts | 4 ++-- .../use-mobile-tasks-project-metadata-actions.tsx | 11 ++++++----- ...-mobile-tasks-project-review-check-actions.tsx | 15 ++++++--------- ...-mobile-tasks-project-thread-reply-actions.tsx | 10 +++------- ...le-tasks-project-workspace-comment-actions.tsx | 5 +++-- 6 files changed, 23 insertions(+), 26 deletions(-) diff --git a/mobile/src/tasks/github-project-host-routing-source.test.ts b/mobile/src/tasks/github-project-host-routing-source.test.ts index 4ab16b0f81ce..3c567a819ad0 100644 --- a/mobile/src/tasks/github-project-host-routing-source.test.ts +++ b/mobile/src/tasks/github-project-host-routing-source.test.ts @@ -93,7 +93,9 @@ describe('mobile GitHub Project host routing boundary', () => { it('pins Project-row PR actions to the row repository identity', () => { // Every Project-row action resolves its target from the row plus the active Project host. const targets = [ - ...compositionSource.matchAll(/projectRow(?:Mutation|PullRequest)Target\(([^)]*)\)/g) + ...compositionSource.matchAll( + /projectRow(?:Mutation|PullRequest|Slug|Identity)Target\(([^)]*)\)/g + ) ] expect(targets.length).toBeGreaterThan(10) for (const target of targets) { diff --git a/mobile/src/tasks/mobile-tasks-refactor-parity.test.ts b/mobile/src/tasks/mobile-tasks-refactor-parity.test.ts index 22a3fcdc3581..9ec7300ef4e6 100644 --- a/mobile/src/tasks/mobile-tasks-refactor-parity.test.ts +++ b/mobile/src/tasks/mobile-tasks-refactor-parity.test.ts @@ -25,9 +25,9 @@ const hash = (parts: string[] | string): string => * plus the row-target locals the adapters take in place of inline slug/number checks. Diff hooks, * declarations and styles are untouched. */ -const SCREEN_HOOKS = '28f62d2fbd86d171bf162d26c6bd0763e4fb8c3f58895d7cd1a00633c1465f32' +const SCREEN_HOOKS = '5f298d284b82e70b267c499d192c827c39c0e802e7e3cf2b17715480991376a8' const DIFF_HOOKS = '93c7189b32bed8456cc51814fffa8ce80cf62011ef968a9d53ddec2b9686f58f' -const STATEMENTS = 'd3f99f5ccf5decedadeef99e7633b8ce832b39e9a49675c43fbc0954b2a2e483' +const STATEMENTS = 'd5a642c641b1e830b71a437d53b809ba40e4e8a5fd36adbbbeb8173048569295' const DECLARATIONS = 'cff54172af17a877789be1479c2eb6ca97d83c3e31dd831cd59395962f2b4c4a' const SEMANTICS = 'f767906884b93537f2c6369d6d0bd2d4cb39b4314c31cca9d8f9e5e9b78a75ee' const STYLES = '1db6af69c791d9963928541ad5310942fcbda6d984b422c90b6eb92b6816579a' diff --git a/mobile/src/tasks/use-mobile-tasks-project-metadata-actions.tsx b/mobile/src/tasks/use-mobile-tasks-project-metadata-actions.tsx index 1a29bf6ff022..30550ae1afa4 100644 --- a/mobile/src/tasks/use-mobile-tasks-project-metadata-actions.tsx +++ b/mobile/src/tasks/use-mobile-tasks-project-metadata-actions.tsx @@ -7,7 +7,7 @@ import { type GitHubProjectRow, optimisticProjectFieldValue } from './mobile-tasks-legacy-foundation' -import { projectRowIdentityTarget, projectRowMutationTarget } from './mobile-tasks-mutation-targets' +import { projectRowIdentityTarget, projectRowSlugTarget } from './mobile-tasks-mutation-targets' export function useMobileTasksProjectMetadataActions(model: ProjectThreadReplyActionsModel) { const { @@ -35,8 +35,9 @@ export function useMobileTasksProjectMetadataActions(model: ProjectThreadReplyAc if (!taskOperations || projectMutating) { return } - const target = projectRowMutationTarget(row, activeGitHubProjectHost) - if (!target) { + // main gated on the slug and the number only; an unrecognised item type was not a refusal. + const target = projectRowSlugTarget(row, activeGitHubProjectHost) + if (!target || !row.content.number) { setProjectRowDetailError('This project item cannot be edited from mobile.') return } @@ -178,8 +179,8 @@ export function useMobileTasksProjectMetadataActions(model: ProjectThreadReplyAc if (!taskOperations || projectMutating) { return } - const target = projectRowMutationTarget(row, activeGitHubProjectHost) - if (row.itemType !== 'ISSUE' || !target) { + const target = projectRowSlugTarget(row, activeGitHubProjectHost) + if (row.itemType !== 'ISSUE' || !target || !row.content.number) { setProjectRowDetailError('This project issue type cannot be edited from mobile.') return } diff --git a/mobile/src/tasks/use-mobile-tasks-project-review-check-actions.tsx b/mobile/src/tasks/use-mobile-tasks-project-review-check-actions.tsx index e5b739dc0f66..e8c982aa937b 100644 --- a/mobile/src/tasks/use-mobile-tasks-project-review-check-actions.tsx +++ b/mobile/src/tasks/use-mobile-tasks-project-review-check-actions.tsx @@ -6,7 +6,10 @@ import { type GitHubProjectRow, splitReviewerList } from './mobile-tasks-legacy-foundation' -import { projectRowPullRequestTarget } from './mobile-tasks-mutation-targets' +import { + projectRowIdentityTarget, + projectRowPullRequestTarget +} from './mobile-tasks-mutation-targets' export function useMobileTasksProjectReviewCheckActions(model: ProjectMetadataActionsModel) { const { @@ -157,16 +160,10 @@ export function useMobileTasksProjectReviewCheckActions(model: ProjectMetadataAc const toggleProjectGitHubFileViewed = useCallback( async (row: GitHubProjectRow, file: GitHubDetailFile): Promise => { const repo = findProjectRowRepo(row) - const target = projectRowPullRequestTarget(row, activeGitHubProjectHost) - if ( - !taskOperations || - projectMutating || - row.itemType !== 'PULL_REQUEST' || - !repo || - !target - ) { + if (!taskOperations || projectMutating || row.itemType !== 'PULL_REQUEST' || !repo) { return } + const target = projectRowIdentityTarget(row, activeGitHubProjectHost) if (projectRowDetail?.provider !== 'github' || !projectRowDetail.pullRequestId) { setProjectRowDetailError('Unable to sync viewed state for this pull request.') return diff --git a/mobile/src/tasks/use-mobile-tasks-project-thread-reply-actions.tsx b/mobile/src/tasks/use-mobile-tasks-project-thread-reply-actions.tsx index 7e5135b4698c..1773300fa5f6 100644 --- a/mobile/src/tasks/use-mobile-tasks-project-thread-reply-actions.tsx +++ b/mobile/src/tasks/use-mobile-tasks-project-thread-reply-actions.tsx @@ -5,11 +5,7 @@ import { type GitHubProjectRow, commentAuthor } from './mobile-tasks-legacy-foundation' -import { - projectRowIdentityTarget, - projectRowMutationTarget, - projectRowSlugTarget -} from './mobile-tasks-mutation-targets' +import { projectRowIdentityTarget, projectRowSlugTarget } from './mobile-tasks-mutation-targets' export function useMobileTasksProjectThreadReplyActions( model: ProjectWorkspaceCommentActionsModel @@ -116,10 +112,10 @@ export function useMobileTasksProjectThreadReplyActions( const replyToProjectGitHubComment = useCallback( async (row: GitHubProjectRow, comment: DetailComment): Promise => { const repo = findProjectRowRepo(row) - const target = projectRowMutationTarget(row, activeGitHubProjectHost) - if (!taskOperations || projectMutating || !repo || !target) { + if (!taskOperations || projectMutating || !repo || !row.content.number) { return } + const target = projectRowIdentityTarget(row, activeGitHubProjectHost) const key = String(comment.id) const body = (itemReplyDrafts[key] ?? '').trim() if (!body) { diff --git a/mobile/src/tasks/use-mobile-tasks-project-workspace-comment-actions.tsx b/mobile/src/tasks/use-mobile-tasks-project-workspace-comment-actions.tsx index 86f4536e784f..53d62a7b84aa 100644 --- a/mobile/src/tasks/use-mobile-tasks-project-workspace-comment-actions.tsx +++ b/mobile/src/tasks/use-mobile-tasks-project-workspace-comment-actions.tsx @@ -158,9 +158,10 @@ export function useMobileTasksProjectWorkspaceCommentActions(model: WorkspaceCre if (!taskOperations || projectMutating) { return } - const target = projectRowMutationTarget(row, activeGitHubProjectHost) + // main gated on the slug, the number and a non-empty body; the item type was not read. + const target = projectRowSlugTarget(row, activeGitHubProjectHost) const body = projectCommentDraft.trim() - if (!target || !body) { + if (!target || !row.content.number || !body) { return } setProjectMutating(true) From 888d999b1b8533c883e0b481c5c9b6318f3d1ff2 Mon Sep 17 00:00:00 2001 From: Jinwoo-H Date: Wed, 9 Sep 2026 12:51:48 -0400 Subject: [PATCH 26/40] fix(mobile): drop the defensive normalizers main did not have - listRepositories dereferences result.repos, so a repo.list answer without it throws into the caller's catch as it did before. - projectResult requires an explicit ok:true again; a result that omits the flag is not a confirmed success. - readRuntimeSettings returns null for a settings-less answer, so the create sheet keeps what it already had instead of committing {}. The task-create path keeps its own {} default, which is what it had. Claude-Session: https://claude.ai/code/session_01JNnE9qzUZMMnqpZWCqM3nb --- mobile/src/tasks/mobile-tasks-refactor-parity.test.ts | 4 ++-- mobile/src/tasks/native-host-task-project-read-operations.ts | 5 +++-- mobile/src/tasks/native-host-task-read-operations.ts | 3 +-- .../src/tasks/use-mobile-tasks-workspace-create-actions.tsx | 5 ++++- mobile/src/worktree/host-workspace-creation-operations.ts | 3 ++- .../native-host-workspace-creation-read-operations.ts | 2 +- 6 files changed, 13 insertions(+), 9 deletions(-) diff --git a/mobile/src/tasks/mobile-tasks-refactor-parity.test.ts b/mobile/src/tasks/mobile-tasks-refactor-parity.test.ts index 9ec7300ef4e6..1ec6abd3b4fe 100644 --- a/mobile/src/tasks/mobile-tasks-refactor-parity.test.ts +++ b/mobile/src/tasks/mobile-tasks-refactor-parity.test.ts @@ -25,9 +25,9 @@ const hash = (parts: string[] | string): string => * plus the row-target locals the adapters take in place of inline slug/number checks. Diff hooks, * declarations and styles are untouched. */ -const SCREEN_HOOKS = '5f298d284b82e70b267c499d192c827c39c0e802e7e3cf2b17715480991376a8' +const SCREEN_HOOKS = 'ef31f40ab364d2c1958f0b130382e9f244aa824d491d329b639c3f2cba2b044a' const DIFF_HOOKS = '93c7189b32bed8456cc51814fffa8ce80cf62011ef968a9d53ddec2b9686f58f' -const STATEMENTS = 'd5a642c641b1e830b71a437d53b809ba40e4e8a5fd36adbbbeb8173048569295' +const STATEMENTS = '9df42716307eb166b1a862e2cea3d4bf2a9f3fa9bc8acd74ccc1e4302bbee9e4' const DECLARATIONS = 'cff54172af17a877789be1479c2eb6ca97d83c3e31dd831cd59395962f2b4c4a' const SEMANTICS = 'f767906884b93537f2c6369d6d0bd2d4cb39b4314c31cca9d8f9e5e9b78a75ee' const STYLES = '1db6af69c791d9963928541ad5310942fcbda6d984b422c90b6eb92b6816579a' diff --git a/mobile/src/tasks/native-host-task-project-read-operations.ts b/mobile/src/tasks/native-host-task-project-read-operations.ts index cc7842612da4..fce514a67cff 100644 --- a/mobile/src/tasks/native-host-task-project-read-operations.ts +++ b/mobile/src/tasks/native-host-task-project-read-operations.ts @@ -114,8 +114,9 @@ export async function projectResult( if (!response.ok) { throw new Error(response.error?.message ?? fallback) } - if (response.result?.ok === false) { - throw new Error(response.result.error?.message ?? fallback) + // main required an explicit ok:true; a result that omits the flag is not a confirmed success. + if (!response.result?.ok) { + throw new Error(response.result?.error?.message ?? fallback) } return response.result as T } diff --git a/mobile/src/tasks/native-host-task-read-operations.ts b/mobile/src/tasks/native-host-task-read-operations.ts index c13791b1b79f..e1b1fa347cb7 100644 --- a/mobile/src/tasks/native-host-task-read-operations.ts +++ b/mobile/src/tasks/native-host-task-read-operations.ts @@ -60,8 +60,7 @@ async function bootstrap(client: RpcRequestSender): Promise { async function listRepositories(client: RpcRequestSender): Promise { const response = await client.sendRequest('repo.list') requireSuccess(response) - const result = response.result as { repos?: HostTaskRepository[] } - return result.repos ?? [] + return (response.result as { repos: HostTaskRepository[] }).repos } async function linearStatus(client: RpcRequestSender): Promise { diff --git a/mobile/src/tasks/use-mobile-tasks-workspace-create-actions.tsx b/mobile/src/tasks/use-mobile-tasks-workspace-create-actions.tsx index 91dff2a2b658..c746a0112f19 100644 --- a/mobile/src/tasks/use-mobile-tasks-workspace-create-actions.tsx +++ b/mobile/src/tasks/use-mobile-tasks-workspace-create-actions.tsx @@ -73,8 +73,11 @@ export function useMobileTasksWorkspaceCreateActions(model: WorkspaceSshStateMod await ensureWorkspaceSshReady(targetRepo) let latestRuntimeTaskSettings = runtimeTaskSettings try { + // This caller committed `{}` for a settings-less answer; the create sheet keeps its + // previous value instead, so the empty default stays local to this path. latestRuntimeTaskSettings = - (await taskWorkspaceCreationOperations.readRuntimeSettings()) as RuntimeTaskSettings + ((await taskWorkspaceCreationOperations.readRuntimeSettings()) ?? + {}) as RuntimeTaskSettings setRuntimeTaskSettings(latestRuntimeTaskSettings) } catch { // Best-effort refresh; the runtime still validates agent availability before spawning. diff --git a/mobile/src/worktree/host-workspace-creation-operations.ts b/mobile/src/worktree/host-workspace-creation-operations.ts index c2a4434b561d..b89c6bfd8cdb 100644 --- a/mobile/src/worktree/host-workspace-creation-operations.ts +++ b/mobile/src/worktree/host-workspace-creation-operations.ts @@ -52,7 +52,8 @@ export type NewWorkspaceRepoHooks = { export type HostWorkspaceCreationOperations = { listRepositories(): Promise readRetiredWorktreeNames(repoId: string): Promise - readRuntimeSettings(): Promise + /** Null when the host answers without a settings key: the caller keeps what it has. */ + readRuntimeSettings(): Promise readTrustedHooks(): Promise isGitLabCliInstalled(): Promise isLinearConnected(): Promise diff --git a/mobile/src/worktree/native-host-workspace-creation-read-operations.ts b/mobile/src/worktree/native-host-workspace-creation-read-operations.ts index 2a47386dbd29..3ba17510513e 100644 --- a/mobile/src/worktree/native-host-workspace-creation-read-operations.ts +++ b/mobile/src/worktree/native-host-workspace-creation-read-operations.ts @@ -50,7 +50,7 @@ export function nativeHostWorkspaceCreationReadOperations( const result = await successfulResult<{ settings?: NewWorkspaceRuntimeSettings }>( client.sendRequest('settings.get') ) - return result.settings ?? {} + return result.settings ?? null }, async readTrustedHooks() { const result = await successfulResult<{ From 01215438f2e9d62ee89512706a8aaa3b3c84575d Mon Sep 17 00:00:00 2001 From: Jinwoo-H Date: Wed, 9 Sep 2026 12:53:16 -0400 Subject: [PATCH 27/40] test(mobile): fix the contracts target shape and pin the send option to its call The project target carried a `slug` field the type does not declare and omitted owner/repo/host, so repoPayload read them as undefined and the oracle only ever exercised the prRepo:null path. It now uses the real shape and asserts the row repository reaches the wire; blanking prRepo fails it. The connection gate asserts TERMINAL_INPUT_SEND_OPTIONS inside sendInput rather than anywhere in the counted set; removing it from that call fails the gate. Claude-Session: https://claude.ai/code/session_01JNnE9qzUZMMnqpZWCqM3nb --- ...tive-host-task-operation-contracts.test.ts | 26 ++++++++++++++++++- .../terminal-input-connection-gate.test.ts | 7 +++++ 2 files changed, 32 insertions(+), 1 deletion(-) diff --git a/mobile/src/tasks/native-host-task-operation-contracts.test.ts b/mobile/src/tasks/native-host-task-operation-contracts.test.ts index 0c7225d4322c..28d9063424a4 100644 --- a/mobile/src/tasks/native-host-task-operation-contracts.test.ts +++ b/mobile/src/tasks/native-host-task-operation-contracts.test.ts @@ -11,7 +11,13 @@ function client(sendRequest: RpcClient['sendRequest']): RpcClient { } const itemTarget = { repoId: 'repo-1', number: 7 } -const projectTarget = { number: 7, slug: { owner: 'orca', repo: 'orca' }, type: 'pr' as const } +const projectTarget = { + owner: 'orca', + repo: 'orca', + host: 'github.com', + number: 7, + type: 'pr' as const +} describe('native host task operation contracts', () => { it('rejects a non-array checks payload instead of crashing the checks list', async () => { @@ -78,4 +84,22 @@ describe('native host task operation contracts', () => { expect(call[2]).toEqual({ timeoutMs: 60_000 }) } }) + + it('carries the row repository on a project file request when the row has a slug', async () => { + // The target's owner/repo/host are what become prRepo; a target missing them only ever + // exercises the null path, which is why this pins the populated one. + const sendRequest = vi + .fn() + .mockResolvedValue({ ok: true, result: [] }) + + await nativeHostTaskProjectFileOperations(client(sendRequest)).refreshChecks( + projectTarget, + 'repo-1', + 'sha' + ) + + expect(sendRequest.mock.calls[0]?.[1]).toMatchObject({ + prRepo: { owner: 'orca', repo: 'orca', host: 'github.com' } + }) + }) }) diff --git a/mobile/src/terminal/terminal-input-connection-gate.test.ts b/mobile/src/terminal/terminal-input-connection-gate.test.ts index f48eeae7c338..60f6177d83d3 100644 --- a/mobile/src/terminal/terminal-input-connection-gate.test.ts +++ b/mobile/src/terminal/terminal-input-connection-gate.test.ts @@ -157,6 +157,13 @@ describe('session route offline-compose wiring', () => { for (const source of [sendActionsSource, terminalInputSource]) { expect(source).toContain('.terminal.sendInput(') } + // And the option is on that send, not merely somewhere in the adapter file. + const sendInput = terminalOperationsSource.slice( + terminalOperationsSource.indexOf('async sendInput(') + ) + expect(sendInput.slice(0, sendInput.indexOf('\n },'))).toContain( + 'TERMINAL_INPUT_SEND_OPTIONS' + ) expect(TERMINAL_INPUT_SEND_OPTIONS).toEqual({ failWhenDisconnected: true }) }) From 59e5e6e0d41a43f65a6fbf991a85cdc8c2bd7b0f Mon Sep 17 00:00:00 2001 From: Jinwoo-H Date: Wed, 9 Sep 2026 12:54:38 -0400 Subject: [PATCH 28/40] refactor(mobile): call the transport directly for Retry, and fix three comments The file explorer's reconnect ternary called the same function on both sides, and its comment claimed the null branch mattered. Retry now calls forceReconnect directly, as main did, and `reconnect` leaves the explorer operations interface, where a UI action did not belong. Comments corrected: the ratchet's regex doc no longer claims aliasing cannot hide a subscribe, and names the two shapes it misses; the deliberate-inline comment says those four are in the routed screens, not the whole remaining surface; and the chat stop's layout effect names the gate that requires it. Claude-Session: https://claude.ai/code/session_01JNnE9qzUZMMnqpZWCqM3nb --- mobile/src/files/MobileFileExplorerPanel.tsx | 13 +++++-------- .../default-host-file-explorer-operations.ts | 7 ++----- .../src/files/host-file-explorer-operations.ts | 1 - .../native-host-file-explorer-operations.ts | 8 ++------ .../src/session/use-mobile-native-chat-stop.ts | 6 ++++-- mobile/src/transport/screen-rpc-ratchet.test.ts | 17 ++++++++++------- 6 files changed, 23 insertions(+), 29 deletions(-) diff --git a/mobile/src/files/MobileFileExplorerPanel.tsx b/mobile/src/files/MobileFileExplorerPanel.tsx index 503030b0eddd..82d8e47422cc 100644 --- a/mobile/src/files/MobileFileExplorerPanel.tsx +++ b/mobile/src/files/MobileFileExplorerPanel.tsx @@ -44,15 +44,12 @@ export function MobileFileExplorerPanel(props: { const { client, state: connState } = useHostClient(hostId) const forceReconnect = useForceReconnect() const operations = useMemo( - () => (client ? defaultHostFileExplorerOperations(client, () => forceReconnect(hostId)) : null), - [client, forceReconnect, hostId] - ) - // Why: `operations` is null in exactly the disconnected state Retry exists for - // (no client), so the revive path cannot hang off it (#5049). - const reconnect = useCallback( - () => (operations ? operations.reconnect() : forceReconnect(hostId)), - [forceReconnect, hostId, operations] + () => (client ? defaultHostFileExplorerOperations(client) : null), + [client] ) + // Why: Retry exists for the disconnected state, where there is no client and so no operations + // provider; the revive path calls the transport directly rather than hanging off one (#5049). + const reconnect = useCallback(() => forceReconnect(hostId), [forceReconnect, hostId]) const scopeRef = useRef('') const scope = `${hostId}:${worktreeId}` scopeRef.current = scope diff --git a/mobile/src/files/default-host-file-explorer-operations.ts b/mobile/src/files/default-host-file-explorer-operations.ts index ca9a1cb0005a..249167f81891 100644 --- a/mobile/src/files/default-host-file-explorer-operations.ts +++ b/mobile/src/files/default-host-file-explorer-operations.ts @@ -2,9 +2,6 @@ import type { RpcClient } from '../transport/rpc-client' import type { HostFileExplorerOperations } from './host-file-explorer-operations' import { nativeHostFileExplorerOperations } from './native-host-file-explorer-operations' -export function defaultHostFileExplorerOperations( - client: RpcClient, - reconnect: () => Promise -): HostFileExplorerOperations { - return nativeHostFileExplorerOperations(client, reconnect) +export function defaultHostFileExplorerOperations(client: RpcClient): HostFileExplorerOperations { + return nativeHostFileExplorerOperations(client) } diff --git a/mobile/src/files/host-file-explorer-operations.ts b/mobile/src/files/host-file-explorer-operations.ts index bad5cec19b05..edecf7faba4b 100644 --- a/mobile/src/files/host-file-explorer-operations.ts +++ b/mobile/src/files/host-file-explorer-operations.ts @@ -14,5 +14,4 @@ export type HostFileExplorerDirectoryResult = export type HostFileExplorerOperations = { readDirectory(workspaceId: string, relativePath: string): Promise - reconnect(): Promise } diff --git a/mobile/src/files/native-host-file-explorer-operations.ts b/mobile/src/files/native-host-file-explorer-operations.ts index bd6113bf8ab9..157daeb30adc 100644 --- a/mobile/src/files/native-host-file-explorer-operations.ts +++ b/mobile/src/files/native-host-file-explorer-operations.ts @@ -6,10 +6,7 @@ import type { } from './host-file-explorer-operations' import type { MobileDirEntry } from './file-tree' -export function nativeHostFileExplorerOperations( - client: RpcClient, - reconnect: () => Promise -): HostFileExplorerOperations { +export function nativeHostFileExplorerOperations(client: RpcClient): HostFileExplorerOperations { return { async readDirectory(workspaceId, relativePath) { const response = await client.sendRequest('files.readDir', { @@ -32,8 +29,7 @@ export function nativeHostFileExplorerOperations( return readLegacyFileList(client, workspaceId, response.error?.message) } throw new Error(response.error?.message || 'Unable to load files') - }, - reconnect + } } } diff --git a/mobile/src/session/use-mobile-native-chat-stop.ts b/mobile/src/session/use-mobile-native-chat-stop.ts index 8dd8aa4f6545..df6b98032154 100644 --- a/mobile/src/session/use-mobile-native-chat-stop.ts +++ b/mobile/src/session/use-mobile-native-chat-stop.ts @@ -30,8 +30,10 @@ export function useMobileNativeChatStop(args: { * never happen. */ const dropSecondEscapeRef = useRef<(() => void) | null>(null) const activeRouteRef = useRef({ operations, enabled, streamIdentity }) - // Layout, not render or a passive Effect: the paced Escape fires from a timer, and only a - // synchronous post-commit write guarantees it never reads a route the render discarded. + // Layout, not render: the changed-code React Doctor gate rejects a ref write during render, + // and this file's rename put that pre-existing write in scope. Not a passive Effect either, + // because the paced Escape fires from a timer and needs a synchronous post-commit write. The + // guard now reads the last committed route rather than the last rendered one. useLayoutEffect(() => { activeRouteRef.current = { operations, enabled, streamIdentity } }, [operations, enabled, streamIdentity]) diff --git a/mobile/src/transport/screen-rpc-ratchet.test.ts b/mobile/src/transport/screen-rpc-ratchet.test.ts index 5d28f5e7c010..d49a896139df 100644 --- a/mobile/src/transport/screen-rpc-ratchet.test.ts +++ b/mobile/src/transport/screen-rpc-ratchet.test.ts @@ -5,10 +5,12 @@ import { describe, expect, it } from 'vitest' /** Every RPC entry point a screen could reach for. `subscribe` counts as much as `sendRequest`: * a streaming read reintroduces the same coupling the operations seam exists to remove. It is * recognised either by a client receiver or by the streaming-RPC call shape (a method-name - * string as the first argument), so aliasing the client into a local cannot hide it, while an - * adapter's or a store's listener-only `subscribe` is not counted. `sendRequest` is matched on - * the identifier rather than on `name(`, so `bind`, bracket access and a space before the paren - * all still count. */ + * string as the first argument), while an adapter's or a store's listener-only `subscribe` is + * not counted. `sendRequest` is matched on the identifier rather than on `name(`, so `bind`, + * bracket access, destructuring and a space before the paren all still count. + * + * Known gaps, both contrived: `const go = c.subscribe.bind(c)` on a non-client-named local, and + * a non-client receiver whose method name is held in a variable. Neither is caught. */ const RPC_ENTRY_POINT = /\bsendRequest\b|\b\w*[Cc]lient(?:Ref)?(?:\.current)?\s*\??\.\s*subscribe\s*\(|\b\w*[Cc]lient\w*\s*\[\s*['"]subscribe['"]\s*\]|\.\s*subscribe\s*\(\s*['"`]/g @@ -170,9 +172,10 @@ const INLINE_RPC_BY_FILE: Record = { 'src/worktree/worktree-catalog-snapshot-client.ts': 1 } -/** Four calls stay inline on purpose. Each has no adapter method that means the same thing, so - * routing it would change what reaches the host. Counted separately from the map above so a - * swap for a different RPC in the same file is still visible in review. */ +/** Four calls in the routed screens stay inline on purpose. Each has no adapter method that + * means the same thing, so routing it would change what reaches the host. This is not the whole + * remaining surface: the map above pins ~110 files, most of them screens this PR simply did not + * extract. Counted by RPC name rather than by count, so a swap in the same file is visible. */ const DELIBERATE_INLINE_CALLS: Record = { // `terminal.close` — closing the terminal, not the tab; the tab adapter's close is a tab close. 'src/session/use-mobile-session-close-actions.ts': ['terminal.close'], From bcba08b3e4675fe0c687fe6346655f8ce66cd138 Mon Sep 17 00:00:00 2001 From: Jinwoo-H Date: Wed, 9 Sep 2026 13:19:31 -0400 Subject: [PATCH 29/40] test(mobile): pin that a refused tab close still prunes, and drop two leftovers The refused-body case had no test after the round-5 revert; reintroducing the defect passed the suite. Also removes the stream types stranded when the terminal subscribe adapter was deleted, and a truncated field the directory result type no longer declares. Claude-Session: https://claude.ai/code/session_01JNnE9qzUZMMnqpZWCqM3nb --- .../native-host-file-explorer-operations.ts | 3 +- .../host-session-terminal-operations.ts | 53 ------------------- ...native-host-session-tab-operations.test.ts | 11 ++++ 3 files changed, 12 insertions(+), 55 deletions(-) diff --git a/mobile/src/files/native-host-file-explorer-operations.ts b/mobile/src/files/native-host-file-explorer-operations.ts index 157daeb30adc..a75bbc2d708a 100644 --- a/mobile/src/files/native-host-file-explorer-operations.ts +++ b/mobile/src/files/native-host-file-explorer-operations.ts @@ -16,8 +16,7 @@ export function nativeHostFileExplorerOperations(client: RpcClient): HostFileExp if (response.ok) { return { kind: 'directory', - entries: response.result as MobileDirEntry[], - truncated: false + entries: response.result as MobileDirEntry[] } } // Why: desktops that predate the files.readDir mobile allowlist entry still serve the diff --git a/mobile/src/session/host-session-terminal-operations.ts b/mobile/src/session/host-session-terminal-operations.ts index 594a84b52938..e9b2e8b788c1 100644 --- a/mobile/src/session/host-session-terminal-operations.ts +++ b/mobile/src/session/host-session-terminal-operations.ts @@ -1,56 +1,3 @@ -import type { TerminalOscLinkRange } from '../../../src/shared/terminal-osc-link-ranges' - -export type HostSessionTerminalData = string | Uint8Array - -export type HostSessionTerminalStreamEvent = - | { - type: 'subscribed' - cols?: number - rows?: number - } - | { - type: 'scrollback' - cols: number - rows: number - serialized: HostSessionTerminalData - preserveScroll?: boolean - throughSequence?: number - displayMode?: 'auto' | 'desktop' | 'phone' - oscLinks?: TerminalOscLinkRange[] - seq?: number - } - | { - type: 'data' - chunk: HostSessionTerminalData - throughSequence?: number - seq?: number - } - | { - type: 'resized' - cols: number - rows: number - serialized?: HostSessionTerminalData - throughSequence?: number - displayMode?: 'auto' | 'desktop' | 'phone' - oscLinks?: TerminalOscLinkRange[] - seq?: number - } - | { - type: 'metadata' - displayMode?: 'auto' | 'desktop' | 'phone' - cwd?: string - } - | { type: 'end' | 'error' } - -export type HostSessionTerminalSubscribeArgs = { - workspaceId: string - terminalId: string - clientId: string | null - viewport: { cols: number; rows: number } | null | undefined - visible: boolean - capabilities: { terminalBinaryStream: 1; mobileInputLeaseOnly?: 1 } -} - export type HostSessionTerminalOperations = { sendInput( terminalId: string, diff --git a/mobile/src/session/native-host-session-tab-operations.test.ts b/mobile/src/session/native-host-session-tab-operations.test.ts index 24175343a701..91594f3502ba 100644 --- a/mobile/src/session/native-host-session-tab-operations.test.ts +++ b/mobile/src/session/native-host-session-tab-operations.test.ts @@ -42,6 +42,17 @@ describe('native host session tab operations', () => { await expect(operations.close('workspace-1', 'tab-1')).resolves.toBe(true) }) + it('prunes a close the host refused, as main did', async () => { + const operations = nativeHostSessionTabOperations({ + sendRequest: vi.fn().mockResolvedValue({ + ok: true, + result: { closed: true, refused: true, refusalReason: 'live-host-pty' } + }) + } as unknown as RpcClient) + + await expect(operations.close('workspace-1', 'tab-1')).resolves.toBe(true) + }) + it('reports a close the host refused at the transport', async () => { const operations = nativeHostSessionTabOperations({ sendRequest: vi.fn().mockResolvedValue({ ok: false, error: { code: 'x', message: 'no' } }) From 1ec6db4a4e1193bbbd2fe6c50a7e3486606df346 Mon Sep 17 00:00:00 2001 From: Jinwoo-H Date: Wed, 9 Sep 2026 15:34:50 -0400 Subject: [PATCH 30/40] fix mobile project payload and account fixtures Claude-Session: https://claude.ai/code/session_01JNnE9qzUZMMnqpZWCqM3nb --- .../src/accounts-route-reset-credit.test.ts | 13 -------- ...ive-host-session-native-chat-operations.ts | 33 +++++++++++++------ .../src/tasks/host-task-project-payloads.ts | 1 - .../host-task-project-read-operations.ts | 2 +- .../host-workspace-creation-operations.ts | 15 +-------- 5 files changed, 25 insertions(+), 39 deletions(-) diff --git a/mobile/src/accounts-route-reset-credit.test.ts b/mobile/src/accounts-route-reset-credit.test.ts index 09019809bcc1..2de1e96881d4 100644 --- a/mobile/src/accounts-route-reset-credit.test.ts +++ b/mobile/src/accounts-route-reset-credit.test.ts @@ -54,19 +54,6 @@ vi.mock('expo-router', async () => { vi.mock('expo-crypto', () => ({ randomUUID: dependencies.randomUUID })) -// The account adapter reaches device operations for its idempotency nonce, which pulls the -// native expo modules into this module graph. -vi.mock('expo-clipboard', () => ({ setStringAsync: vi.fn() })) -vi.mock('expo-haptics', () => ({ - AndroidHaptics: {}, - ImpactFeedbackStyle: {}, - NotificationFeedbackType: {}, - impactAsync: vi.fn(), - notificationAsync: vi.fn(), - performAndroidHapticsAsync: vi.fn(), - selectionAsync: vi.fn() -})) - vi.mock('lucide-react-native', () => ({ Check: 'Check', ChevronLeft: 'ChevronLeft', diff --git a/mobile/src/session/native-host-session-native-chat-operations.ts b/mobile/src/session/native-host-session-native-chat-operations.ts index baef6fec921f..3086d4306499 100644 --- a/mobile/src/session/native-host-session-native-chat-operations.ts +++ b/mobile/src/session/native-host-session-native-chat-operations.ts @@ -27,6 +27,7 @@ export function nativeHostSessionNativeChatOperations( // `@` autocomplete in a second workspace suggest the first workspace's files. const legacyPathsByWorkspace = new Map() const legacyLoadByWorkspace = new Map>() + const legacyGenerationByWorkspace = new Map() return { async readability(workspaceId) { if (isFloatingWorkspaceWorktreeId(workspaceId)) { @@ -72,7 +73,10 @@ export function nativeHostSessionNativeChatOperations( resetFileSearchCache(workspaceId) { searchSupported = null legacyPathsByWorkspace.delete(workspaceId) - legacyLoadByWorkspace.delete(workspaceId) + legacyGenerationByWorkspace.set( + workspaceId, + (legacyGenerationByWorkspace.get(workspaceId) ?? 0) + 1 + ) }, async searchFiles(target, query) { if (searchSupported !== false) { @@ -98,22 +102,31 @@ export function nativeHostSessionNativeChatOperations( if (!legacyLoad) { // Older hosts expose only the full inventory RPC; overlapping queries must // share one slow local/SSH read. - legacyLoad = client + const generation = legacyGenerationByWorkspace.get(target.workspaceId) ?? 0 + const request = client .sendRequest('files.list', { worktree: `id:${target.workspaceId}` }) .then((response) => (response.ok ? extractPaths(response.result) : null)) - .finally(() => { + legacyLoad = request.finally(() => { + if (legacyLoadByWorkspace.get(target.workspaceId) === legacyLoad) { legacyLoadByWorkspace.delete(target.workspaceId) - }) + } + }) legacyLoadByWorkspace.set(target.workspaceId, legacyLoad) + const paths = await legacyLoad + if ((legacyGenerationByWorkspace.get(target.workspaceId) ?? 0) !== generation) { + return null + } + if (!paths) return null + legacyPaths = paths + legacyPathsByWorkspace.set(target.workspaceId, paths) + } else { + const paths = await legacyLoad + if (!paths) return null + legacyPaths = paths + legacyPathsByWorkspace.set(target.workspaceId, paths) } - const paths = await legacyLoad - if (!paths) { - return null - } - legacyPaths = paths - legacyPathsByWorkspace.set(target.workspaceId, paths) } return rankSuggestions(legacyPaths, query, FILE_RESULT_LIMIT) } diff --git a/mobile/src/tasks/host-task-project-payloads.ts b/mobile/src/tasks/host-task-project-payloads.ts index c17cc7c80136..984eb2d913be 100644 --- a/mobile/src/tasks/host-task-project-payloads.ts +++ b/mobile/src/tasks/host-task-project-payloads.ts @@ -27,7 +27,6 @@ export type HostTaskProjectResolveResult = { export type HostTaskProjectTablePayload = GitHubProjectRef & { viewId: string queryOverride?: string - cursor?: string } export type HostTaskProjectSlugPayload = { diff --git a/mobile/src/tasks/host-task-project-read-operations.ts b/mobile/src/tasks/host-task-project-read-operations.ts index a973bd4cb411..98fe2076d358 100644 --- a/mobile/src/tasks/host-task-project-read-operations.ts +++ b/mobile/src/tasks/host-task-project-read-operations.ts @@ -17,7 +17,7 @@ export type HostTaskProjectReadOperations = { listAccessible(host: string): Promise listViews(project: GitHubProjectRef): Promise resolveRef(payload: HostTaskProjectResolvePayload): Promise - loadTable(payload: Omit): Promise + loadTable(payload: HostTaskProjectTablePayload): Promise loadItemDetail(payload: HostTaskProjectItemDetailPayload): Promise listItemLabels(payload: HostTaskProjectSlugPayload): Promise listItemAssignableUsers( diff --git a/mobile/src/worktree/host-workspace-creation-operations.ts b/mobile/src/worktree/host-workspace-creation-operations.ts index b89c6bfd8cdb..eec2753aa0e5 100644 --- a/mobile/src/worktree/host-workspace-creation-operations.ts +++ b/mobile/src/worktree/host-workspace-creation-operations.ts @@ -21,20 +21,7 @@ import type { GitRemoteIdentity } from '../../../src/shared/git-remote-identity' import type { RepoIcon } from '../../../src/shared/repo-icon' import type { RetiredNameRegistry } from '../../../src/shared/worktree/retired-name-registry' -export type NewWorkspaceRepository = { - id: string - displayName: string - path: string - badgeColor?: string - connectionId?: string | null - executionHostId?: ExecutionHostId | null - executionHostLabel?: string - projectId?: string - kind?: 'git' | 'folder' - upstream?: { owner: string; repo: string; host?: string } | null - repoIcon?: RepoIcon | null - gitRemoteIdentity?: GitRemoteIdentity | null -} +export type { MobileWorkspaceRepo as NewWorkspaceRepository } from '../components/new-worktree-modal-types' export type NewWorkspaceRuntimeSettings = { defaultTuiAgent?: TuiAgent | 'blank' | null From 55865697a29ebc85ac239c59a08a10b962cb9b73 Mon Sep 17 00:00:00 2001 From: Jinwoo-H Date: Wed, 9 Sep 2026 15:35:05 -0400 Subject: [PATCH 31/40] Fix stale legacy file inventory generation guard Claude-Session: https://claude.ai/code/session_01JNnE9qzUZMMnqpZWCqM3nb --- ...ost-session-native-chat-operations.test.ts | 21 +++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/mobile/src/session/native-host-session-native-chat-operations.test.ts b/mobile/src/session/native-host-session-native-chat-operations.test.ts index dd83768ba8d9..7b4522b74cf0 100644 --- a/mobile/src/session/native-host-session-native-chat-operations.test.ts +++ b/mobile/src/session/native-host-session-native-chat-operations.test.ts @@ -60,6 +60,27 @@ describe('native host session native chat operations', () => { expect(sendRequest).not.toHaveBeenCalled() }) + it('ignores an older inventory completion after cache reset', async () => { + const deferred: Array<(value: any) => void> = [] + const sendRequest = vi.fn((method) => { + if (method === 'files.searchPaths') + return Promise.resolve({ + ok: false, + error: { code: 'method_not_found', message: 'unsupported' } + }) + return new Promise((resolve) => deferred.push(resolve)) + }) + const operations = nativeHostSessionNativeChatOperations(client(sendRequest)) + const old = operations.searchFiles(target(), 'fresh') + operations.resetFileSearchCache('wt-1') + const fresh = operations.searchFiles(target(), 'fresh') + deferred[1]?.({ ok: true, result: { files: [{ relativePath: 'fresh.ts' }] } }) + await expect(fresh).resolves.toEqual(['fresh.ts']) + deferred[0]?.({ ok: true, result: { files: [{ relativePath: 'old.ts' }] } }) + await old + await expect(operations.searchFiles(target(), 'fresh')).resolves.toEqual(['fresh.ts']) + }) + it('keeps the legacy file inventory scoped to the workspace that produced it', async () => { const sendRequest = vi.fn(async (method, params) => { if (method === 'files.searchPaths') { From 18d8062005767dd33e1b632e2d5b753b3991c7b5 Mon Sep 17 00:00:00 2001 From: Jinwoo-H Date: Wed, 9 Sep 2026 15:35:54 -0400 Subject: [PATCH 32/40] fix mobile test fixtures Claude-Session: https://claude.ai/code/session_01JNnE9qzUZMMnqpZWCqM3nb --- .../native-host-session-quick-command-operations.test.ts | 4 ++-- mobile/src/session/use-quick-commands.test.ts | 4 ---- mobile/src/tasks/native-host-task-operation-contracts.test.ts | 2 +- 3 files changed, 3 insertions(+), 7 deletions(-) diff --git a/mobile/src/session/native-host-session-quick-command-operations.test.ts b/mobile/src/session/native-host-session-quick-command-operations.test.ts index 11bfb2df5bf8..9c79663c387e 100644 --- a/mobile/src/session/native-host-session-quick-command-operations.test.ts +++ b/mobile/src/session/native-host-session-quick-command-operations.test.ts @@ -18,7 +18,7 @@ describe('native host session quick command operations', () => { }) await expect( - nativeHostSessionQuickCommandOperations(client(sendRequest)).snapshot('wt-1') + nativeHostSessionQuickCommandOperations(client(sendRequest)).snapshot() ).resolves.toMatchObject({ commands: [] }) expect(sendRequest).toHaveBeenCalledTimes(2) }) @@ -32,7 +32,7 @@ describe('native host session quick command operations', () => { }) await expect( - nativeHostSessionQuickCommandOperations(client(sendRequest)).snapshot('wt-1') + nativeHostSessionQuickCommandOperations(client(sendRequest)).snapshot() ).rejects.toThrow('RPC interrupted by connection migration') expect(sendRequest).toHaveBeenCalledTimes(1) }) diff --git a/mobile/src/session/use-quick-commands.test.ts b/mobile/src/session/use-quick-commands.test.ts index 10acd13029a3..b66ee1063e6c 100644 --- a/mobile/src/session/use-quick-commands.test.ts +++ b/mobile/src/session/use-quick-commands.test.ts @@ -77,7 +77,6 @@ describe('useQuickCommands', () => { function Harness(): null { state = useQuickCommands({ operations: quickCommandOperations(client), - workspaceId: WORKSPACE_ID, enabled }) return null @@ -152,7 +151,6 @@ describe('useQuickCommands', () => { function Harness({ enabled }: { enabled: boolean }): null { state = useQuickCommands({ operations: quickCommandOperations(client), - workspaceId: WORKSPACE_ID, enabled }) return null @@ -335,7 +333,6 @@ describe('useQuickCommands', () => { function Harness({ client }: { client: RpcClient }): null { state = useQuickCommands({ operations: quickCommandOperations(client), - workspaceId: WORKSPACE_ID, enabled: true }) return null @@ -414,7 +411,6 @@ describe('useQuickCommands', () => { function Harness({ enabled }: { enabled: boolean }): null { state = useQuickCommands({ operations: quickCommandOperations(client), - workspaceId: WORKSPACE_ID, enabled }) return null diff --git a/mobile/src/tasks/native-host-task-operation-contracts.test.ts b/mobile/src/tasks/native-host-task-operation-contracts.test.ts index 28d9063424a4..550d411ae693 100644 --- a/mobile/src/tasks/native-host-task-operation-contracts.test.ts +++ b/mobile/src/tasks/native-host-task-operation-contracts.test.ts @@ -10,7 +10,7 @@ function client(sendRequest: RpcClient['sendRequest']): RpcClient { return { sendRequest } as unknown as RpcClient } -const itemTarget = { repoId: 'repo-1', number: 7 } +const itemTarget = { repoId: 'repo-1', number: 7, provider: 'github' as const, type: 'pr' as const } const projectTarget = { owner: 'orca', repo: 'orca', From 053d6d4cc291e41aee0936ac4a3643384e74aea0 Mon Sep 17 00:00:00 2001 From: Jinwoo-H Date: Wed, 9 Sep 2026 15:36:02 -0400 Subject: [PATCH 33/40] Fix Project mutation acceptance and Linear detail ordering Claude-Session: https://claude.ai/code/session_01JNnE9qzUZMMnqpZWCqM3nb --- .../native-host-task-detail-operations.ts | 24 +++++++++---------- ...e-host-task-project-mutation-operations.ts | 11 ++++++--- 2 files changed, 19 insertions(+), 16 deletions(-) diff --git a/mobile/src/tasks/native-host-task-detail-operations.ts b/mobile/src/tasks/native-host-task-detail-operations.ts index 181dab489418..40132a85c13f 100644 --- a/mobile/src/tasks/native-host-task-detail-operations.ts +++ b/mobile/src/tasks/native-host-task-detail-operations.ts @@ -69,22 +69,20 @@ export function nativeHostTaskDetailOperations(client: RpcRequestSender): HostTa } }, async loadLinear(payload) { - const [issue, comments] = await Promise.all([ - successfulResult( - client.sendRequest( - 'linear.getIssue', - { id: payload.issueId, workspaceId: payload.workspaceId }, - { timeoutMs: 30_000 } - ) + const [issueResponse, commentsResponse] = await Promise.all([ + client.sendRequest( + 'linear.getIssue', + { id: payload.issueId, workspaceId: payload.workspaceId }, + { timeoutMs: 30_000 } ), - optionalComments( - client.sendRequest( - 'linear.issueComments', - { issueId: payload.issueId, workspaceId: payload.workspaceId }, - { timeoutMs: 30_000 } - ) + client.sendRequest( + 'linear.issueComments', + { issueId: payload.issueId, workspaceId: payload.workspaceId }, + { timeoutMs: 30_000 } ) ]) + const issue = await successfulResult(issueResponse) + const comments = await optionalComments(commentsResponse) if (!issue) { throw new Error('Details not found') } diff --git a/mobile/src/tasks/native-host-task-project-mutation-operations.ts b/mobile/src/tasks/native-host-task-project-mutation-operations.ts index 9a0155090244..875bb30a6f81 100644 --- a/mobile/src/tasks/native-host-task-project-mutation-operations.ts +++ b/mobile/src/tasks/native-host-task-project-mutation-operations.ts @@ -34,10 +34,11 @@ export function nativeHostTaskProjectMutationOperations( ) }, async addComment(target, body) { - const result = await projectMutation<{ comment?: DetailComment }>( + const result = await projectMutation<{ ok?: boolean; comment?: DetailComment }>( client, 'github.project.addIssueCommentBySlug', - { ...slugPayload(target), body } + { ...slugPayload(target), body }, + true ) return result.comment }, @@ -207,7 +208,8 @@ const PROJECT_MUTATION_FALLBACKS: Record = { async function projectMutation( client: RpcRequestSender, method: string, - payload: object + payload: object, + requireOk = false ): Promise { const fallback = PROJECT_MUTATION_FALLBACKS[method] ?? 'GitHub Project request failed' const response = (await client.sendRequest(method, payload, { timeoutMs: 30_000 })) as { @@ -218,6 +220,9 @@ async function projectMutation( if (!response.ok) { throw new Error(response.error?.message ?? fallback) } + if (requireOk && !response.result?.ok) { + throw new Error(fallback) + } if (response.result?.ok === false) { const error = response.result.error throw new Error(typeof error === 'string' ? error : (error?.message ?? fallback)) From f25dd7db7e3aa386078fc150cd7251bea462f052 Mon Sep 17 00:00:00 2001 From: Jinwoo-H Date: Wed, 9 Sep 2026 15:36:55 -0400 Subject: [PATCH 34/40] Guard stale legacy inventory completions Claude-Session: https://claude.ai/code/session_01JNnE9qzUZMMnqpZWCqM3nb --- mobile/src/session/native-host-session-native-chat-operations.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/mobile/src/session/native-host-session-native-chat-operations.ts b/mobile/src/session/native-host-session-native-chat-operations.ts index 3086d4306499..15d9b257b275 100644 --- a/mobile/src/session/native-host-session-native-chat-operations.ts +++ b/mobile/src/session/native-host-session-native-chat-operations.ts @@ -28,6 +28,7 @@ export function nativeHostSessionNativeChatOperations( const legacyPathsByWorkspace = new Map() const legacyLoadByWorkspace = new Map>() const legacyGenerationByWorkspace = new Map() + const legacyGenerationByWorkspace = new Map() return { async readability(workspaceId) { if (isFloatingWorkspaceWorktreeId(workspaceId)) { From 76c8fc331b2d40f1130edfef162eeb2ed07e2f57 Mon Sep 17 00:00:00 2001 From: Jinwoo-H Date: Wed, 9 Sep 2026 15:37:57 -0400 Subject: [PATCH 35/40] fix mobile task detail projections and list types Claude-Session: https://claude.ai/code/session_01JNnE9qzUZMMnqpZWCqM3nb --- .../tasks/github-task-detail-projection.ts | 19 ++++++++++++++----- .../src/tasks/host-task-provider-payloads.ts | 4 ++-- ...use-mobile-tasks-provider-load-actions.tsx | 4 +--- .../use-mobile-tasks-task-list-loading.tsx | 4 +--- 4 files changed, 18 insertions(+), 13 deletions(-) diff --git a/mobile/src/tasks/github-task-detail-projection.ts b/mobile/src/tasks/github-task-detail-projection.ts index e7b97ce58628..f26c2c554dc9 100644 --- a/mobile/src/tasks/github-task-detail-projection.ts +++ b/mobile/src/tasks/github-task-detail-projection.ts @@ -1,7 +1,16 @@ import type { HostTaskGitHubDetail } from './host-task-provider-payloads' import type { GitHubAssignableUser } from './mobile-tasks-provider-detail-types' -type GitHubRawDetails = Partial & { +type GitHubRawDetails = { + body?: string + comments?: HostTaskGitHubDetail['comments'] + assignees?: string[] + headSha?: string + baseSha?: string + pullRequestId?: string + checks?: HostTaskGitHubDetail['checks'] + files?: HostTaskGitHubDetail['files'] + item?: { labels?: string[] reviewDecision?: string | null @@ -18,11 +27,11 @@ export function projectGitHubTaskDetail(value: unknown): HostTaskGitHubDetail { return { body: details.body ?? '', comments: details.comments ?? [], - labels: details.item?.labels ?? details.labels, + labels: details.item?.labels, assignees: details.assignees ?? [], - reviewDecision: details.item?.reviewDecision ?? details.reviewDecision, - reviewRequests: details.item?.reviewRequests ?? details.reviewRequests, - latestReviews: details.item?.latestReviews ?? details.latestReviews, + reviewDecision: details.item?.reviewDecision, + reviewRequests: details.item?.reviewRequests, + latestReviews: details.item?.latestReviews, headSha: details.headSha, baseSha: details.baseSha, pullRequestId: details.pullRequestId, diff --git a/mobile/src/tasks/host-task-provider-payloads.ts b/mobile/src/tasks/host-task-provider-payloads.ts index a22e3ee2b9f0..13e5e9614a9d 100644 --- a/mobile/src/tasks/host-task-provider-payloads.ts +++ b/mobile/src/tasks/host-task-provider-payloads.ts @@ -66,7 +66,7 @@ export type HostTaskGitHubListPayload = { } export type HostTaskGitHubListResult = { - items: GitHubWorkItem[] + items: Array> sources?: GitHubRepoSources errors?: { issues?: { message: string } } issueSourceFellBack?: true @@ -86,7 +86,7 @@ export type HostTaskGitLabListPayload = { } export type HostTaskGitLabListResult = { - items: GitLabWorkItem[] + items: Array> error?: { type?: string; message: string } } diff --git a/mobile/src/tasks/use-mobile-tasks-provider-load-actions.tsx b/mobile/src/tasks/use-mobile-tasks-provider-load-actions.tsx index 46c6b6ad95e8..0ba46d01ac16 100644 --- a/mobile/src/tasks/use-mobile-tasks-provider-load-actions.tsx +++ b/mobile/src/tasks/use-mobile-tasks-provider-load-actions.tsx @@ -103,9 +103,7 @@ export function useMobileTasksProviderLoadActions(model: RuntimeHydrationModel) before }) return { - items: envelope.items.map((item) => - createGitHubTask(repo, item as Omit) - ), + items: envelope.items.map((item) => createGitHubTask(repo, item)), sources: envelope.sources, sourceError: extractGitHubIssueSourceError(repo, envelope), sourceFallback: extractGitHubIssueSourceFallback(repo, envelope), diff --git a/mobile/src/tasks/use-mobile-tasks-task-list-loading.tsx b/mobile/src/tasks/use-mobile-tasks-task-list-loading.tsx index 5c54e2da32d4..449b50c799c1 100644 --- a/mobile/src/tasks/use-mobile-tasks-task-list-loading.tsx +++ b/mobile/src/tasks/use-mobile-tasks-task-list-loading.tsx @@ -170,9 +170,7 @@ export function useMobileTasksTaskListLoading(model: ProviderLoadActionsModel) { return { items: [], error: envelope.error.message } } return { - items: envelope.items.map((item) => - createGitLabTask(repo, item as Omit) - ) + items: envelope.items.map((item) => createGitLabTask(repo, item)) } } catch (err) { console.warn(`[mobile tasks] failed to fetch ${provider} work items`, repo.id, err) From be4a2da30f9d2723c0ea903747c509883a3effb3 Mon Sep 17 00:00:00 2001 From: Jinwoo-H Date: Wed, 9 Sep 2026 15:40:38 -0400 Subject: [PATCH 36/40] Fix mobile task detail projections and list result types Claude-Session: https://claude.ai/code/session_01JNnE9qzUZMMnqpZWCqM3nb --- mobile/src/tasks/use-mobile-tasks-provider-load-actions.tsx | 1 - mobile/src/tasks/use-mobile-tasks-task-list-loading.tsx | 1 - 2 files changed, 2 deletions(-) diff --git a/mobile/src/tasks/use-mobile-tasks-provider-load-actions.tsx b/mobile/src/tasks/use-mobile-tasks-provider-load-actions.tsx index 0ba46d01ac16..256b2c155c66 100644 --- a/mobile/src/tasks/use-mobile-tasks-provider-load-actions.tsx +++ b/mobile/src/tasks/use-mobile-tasks-provider-load-actions.tsx @@ -13,7 +13,6 @@ import { import { GITHUB_REPO_CONCURRENCY, type GitHubRepoSources, - type GitHubWorkItem, type LinearTeam, type RepoSummary, type TaskItem, diff --git a/mobile/src/tasks/use-mobile-tasks-task-list-loading.tsx b/mobile/src/tasks/use-mobile-tasks-task-list-loading.tsx index 449b50c799c1..6444a2113d24 100644 --- a/mobile/src/tasks/use-mobile-tasks-task-list-loading.tsx +++ b/mobile/src/tasks/use-mobile-tasks-task-list-loading.tsx @@ -4,7 +4,6 @@ import { GITHUB_REPO_CONCURRENCY, GITLAB_PER_PAGE, type GitLabTodo, - type GitLabWorkItem, LINEAR_LIMIT, type TaskItem, buildPartialRepositoryNotice, From 5e93f06343bd5efdcae8395d670e183c553f356e Mon Sep 17 00:00:00 2001 From: Jinwoo-H Date: Wed, 9 Sep 2026 15:49:21 -0400 Subject: [PATCH 37/40] Fix mobile legacy inventory reset and stale completion regression Claude-Session: https://claude.ai/code/session_01JNnE9qzUZMMnqpZWCqM3nb --- ...ost-session-native-chat-operations.test.ts | 40 +++++++++++++--- ...ive-host-session-native-chat-operations.ts | 47 +++++++++++-------- 2 files changed, 61 insertions(+), 26 deletions(-) diff --git a/mobile/src/session/native-host-session-native-chat-operations.test.ts b/mobile/src/session/native-host-session-native-chat-operations.test.ts index 7b4522b74cf0..974e9f18e626 100644 --- a/mobile/src/session/native-host-session-native-chat-operations.test.ts +++ b/mobile/src/session/native-host-session-native-chat-operations.test.ts @@ -22,6 +22,8 @@ function client(sendRequest: RpcClient['sendRequest']): RpcClient { describe('native host session native chat operations', () => { it('stops the agent with a bare Escape that carries no enter at all', async () => { const sendRequest = vi.fn().mockResolvedValue({ + id: 'test', + _meta: { runtimeId: 'host' }, ok: true, result: { delivered: true } }) @@ -40,6 +42,8 @@ describe('native host session native chat operations', () => { // The shared chat write refuses to start under a 2s residual budget. Stop does not: the // call it replaced tried on whatever was left and could be accepted. const sendRequest = vi.fn().mockResolvedValue({ + id: 'test', + _meta: { runtimeId: 'host' }, ok: true, result: { send: { accepted: true } } }) @@ -61,33 +65,57 @@ describe('native host session native chat operations', () => { }) it('ignores an older inventory completion after cache reset', async () => { - const deferred: Array<(value: any) => void> = [] + const deferred: Array<(value: Awaited>) => void> = [] const sendRequest = vi.fn((method) => { - if (method === 'files.searchPaths') + if (method === 'files.searchPaths') { return Promise.resolve({ + id: 'test', + _meta: { runtimeId: 'host' }, ok: false, error: { code: 'method_not_found', message: 'unsupported' } }) + } return new Promise((resolve) => deferred.push(resolve)) }) const operations = nativeHostSessionNativeChatOperations(client(sendRequest)) const old = operations.searchFiles(target(), 'fresh') + await vi.waitFor(() => expect(deferred).toHaveLength(1)) + const overlapping = operations.searchFiles(target(), 'old') operations.resetFileSearchCache('wt-1') const fresh = operations.searchFiles(target(), 'fresh') - deferred[1]?.({ ok: true, result: { files: [{ relativePath: 'fresh.ts' }] } }) + await vi.waitFor(() => expect(deferred).toHaveLength(2)) + deferred[1]!({ + id: 'test', + _meta: { runtimeId: 'host' }, + ok: true, + result: { files: [{ relativePath: 'fresh.ts' }] } + }) await expect(fresh).resolves.toEqual(['fresh.ts']) - deferred[0]?.({ ok: true, result: { files: [{ relativePath: 'old.ts' }] } }) - await old + deferred[0]!({ + id: 'test', + _meta: { runtimeId: 'host' }, + ok: true, + result: { files: [{ relativePath: 'old.ts' }] } + }) + await expect(old).resolves.toBeNull() + await expect(overlapping).resolves.toBeNull() await expect(operations.searchFiles(target(), 'fresh')).resolves.toEqual(['fresh.ts']) }) it('keeps the legacy file inventory scoped to the workspace that produced it', async () => { const sendRequest = vi.fn(async (method, params) => { if (method === 'files.searchPaths') { - return { ok: false, error: { code: 'method_not_found', message: 'unsupported' } } + return { + id: 'test', + _meta: { runtimeId: 'host' }, + ok: false, + error: { code: 'method_not_found', message: 'unsupported' } + } } const worktree = (params as { worktree: string }).worktree return { + id: 'test', + _meta: { runtimeId: 'host' }, ok: true, result: { files: diff --git a/mobile/src/session/native-host-session-native-chat-operations.ts b/mobile/src/session/native-host-session-native-chat-operations.ts index 15d9b257b275..b3ced59cbbd5 100644 --- a/mobile/src/session/native-host-session-native-chat-operations.ts +++ b/mobile/src/session/native-host-session-native-chat-operations.ts @@ -28,7 +28,6 @@ export function nativeHostSessionNativeChatOperations( const legacyPathsByWorkspace = new Map() const legacyLoadByWorkspace = new Map>() const legacyGenerationByWorkspace = new Map() - const legacyGenerationByWorkspace = new Map() return { async readability(workspaceId) { if (isFloatingWorkspaceWorktreeId(workspaceId)) { @@ -74,6 +73,7 @@ export function nativeHostSessionNativeChatOperations( resetFileSearchCache(workspaceId) { searchSupported = null legacyPathsByWorkspace.delete(workspaceId) + legacyLoadByWorkspace.delete(workspaceId) legacyGenerationByWorkspace.set( workspaceId, (legacyGenerationByWorkspace.get(workspaceId) ?? 0) + 1 @@ -108,26 +108,33 @@ export function nativeHostSessionNativeChatOperations( .sendRequest('files.list', { worktree: `id:${target.workspaceId}` }) - .then((response) => (response.ok ? extractPaths(response.result) : null)) - legacyLoad = request.finally(() => { - if (legacyLoadByWorkspace.get(target.workspaceId) === legacyLoad) { - legacyLoadByWorkspace.delete(target.workspaceId) - } - }) - legacyLoadByWorkspace.set(target.workspaceId, legacyLoad) - const paths = await legacyLoad - if ((legacyGenerationByWorkspace.get(target.workspaceId) ?? 0) !== generation) { - return null - } - if (!paths) return null - legacyPaths = paths - legacyPathsByWorkspace.set(target.workspaceId, paths) - } else { - const paths = await legacyLoad - if (!paths) return null - legacyPaths = paths - legacyPathsByWorkspace.set(target.workspaceId, paths) + .then((response) => { + if ( + !response.ok || + (legacyGenerationByWorkspace.get(target.workspaceId) ?? 0) !== generation + ) { + return null + } + const paths = extractPaths(response.result) + legacyPathsByWorkspace.set(target.workspaceId, paths) + return paths + }) + .finally(() => { + if ( + legacyLoadByWorkspace.get(target.workspaceId) === request && + !legacyPathsByWorkspace.has(target.workspaceId) + ) { + legacyLoadByWorkspace.delete(target.workspaceId) + } + }) + legacyLoad = request + legacyLoadByWorkspace.set(target.workspaceId, request) + } + const paths = await legacyLoad + if (!paths) { + return null } + legacyPaths = paths } return rankSuggestions(legacyPaths, query, FILE_RESULT_LIMIT) } From dace3bc65fa4a4b4a0cc0ba03608d453c8016fb5 Mon Sep 17 00:00:00 2001 From: Jinwoo-H Date: Wed, 9 Sep 2026 15:49:21 -0400 Subject: [PATCH 38/40] Fix Project mutation acceptance and Linear detail ordering tests Claude-Session: https://claude.ai/code/session_01JNnE9qzUZMMnqpZWCqM3nb --- ...github-project-host-routing-source.test.ts | 14 +- ...native-host-task-detail-operations.test.ts | 27 +++ .../native-host-task-detail-operations.ts | 16 +- ...t-task-project-mutation-operations.test.ts | 113 ++++++++++ ...e-host-task-project-mutation-operations.ts | 201 ++++++++---------- 5 files changed, 243 insertions(+), 128 deletions(-) create mode 100644 mobile/src/tasks/native-host-task-detail-operations.test.ts create mode 100644 mobile/src/tasks/native-host-task-project-mutation-operations.test.ts diff --git a/mobile/src/tasks/github-project-host-routing-source.test.ts b/mobile/src/tasks/github-project-host-routing-source.test.ts index 3c567a819ad0..693f741714ed 100644 --- a/mobile/src/tasks/github-project-host-routing-source.test.ts +++ b/mobile/src/tasks/github-project-host-routing-source.test.ts @@ -108,14 +108,14 @@ describe('mobile GitHub Project host routing boundary', () => { ) // Per method, not once per file: dropping prRepo from a single mutation must fail here. for (const method of [ - 'fetchResolveReviewThread', - 'fetchAddPRReviewCommentReply', - 'fetchAddIssueComment', - 'fetchRequestPRReviewers', - 'fetchRerunPRChecks', - 'fetchMergePR' + 'github.resolveReviewThread', + 'github.addPRReviewCommentReply', + 'github.addIssueComment', + 'github.requestPRReviewers', + 'github.rerunPRChecks', + 'github.mergePR' ]) { - const offset = projectMutationAdapter.indexOf(`${method}(`) + const offset = projectMutationAdapter.indexOf(`'${method}'`) expect(offset, `${method} must remain wired`).toBeGreaterThan(-1) // Bounded to this adapter method, so a neighbour's prRepo cannot satisfy it. expect( diff --git a/mobile/src/tasks/native-host-task-detail-operations.test.ts b/mobile/src/tasks/native-host-task-detail-operations.test.ts new file mode 100644 index 000000000000..5ac77ea2991a --- /dev/null +++ b/mobile/src/tasks/native-host-task-detail-operations.test.ts @@ -0,0 +1,27 @@ +import { expect, it, vi } from 'vitest' +import type { RpcRequestSender } from '../transport/rpc-client' +import { nativeHostTaskDetailOperations } from './native-host-task-detail-operations' + +it('waits for raw Linear requests so a comments transport rejection wins over an issue refusal', async () => { + let rejectComments!: (error: Error) => void + const comments = new Promise((_resolve, reject) => { + rejectComments = reject + }) + const sendRequest = vi.fn((method) => + method === 'linear.getIssue' + ? Promise.resolve({ + id: 'test', + _meta: { runtimeId: 'host' }, + ok: false, + error: { code: 'refused', message: 'issue refused' } + }) + : comments + ) + const outcome = nativeHostTaskDetailOperations({ sendRequest }) + .loadLinear({ issueId: 'issue-1', workspaceId: 'workspace-1' }) + .catch((error: unknown) => error) + await new Promise((resolve) => setTimeout(resolve, 0)) + const commentsError = new Error('comments transport failed') + rejectComments(commentsError) + await expect(outcome).resolves.toBe(commentsError) +}) diff --git a/mobile/src/tasks/native-host-task-detail-operations.ts b/mobile/src/tasks/native-host-task-detail-operations.ts index 40132a85c13f..01cce9f75273 100644 --- a/mobile/src/tasks/native-host-task-detail-operations.ts +++ b/mobile/src/tasks/native-host-task-detail-operations.ts @@ -81,8 +81,13 @@ export function nativeHostTaskDetailOperations(client: RpcRequestSender): HostTa { timeoutMs: 30_000 } ) ]) - const issue = await successfulResult(issueResponse) - const comments = await optionalComments(commentsResponse) + if (!issueResponse.ok) { + throw new Error(issueResponse.error.message) + } + const issue = issueResponse.result as LinearIssue | null + const comments = commentsResponse.ok + ? ((commentsResponse.result as DetailComment[]) ?? []) + : [] if (!issue) { throw new Error('Details not found') } @@ -91,13 +96,6 @@ export function nativeHostTaskDetailOperations(client: RpcRequestSender): HostTa } } -/** Tolerates a refusal envelope only. A transport rejection still fails the detail load, so a - * timed-out comment read cannot render as an issue that simply has no comments. */ -async function optionalComments(request: Promise): Promise { - const response = (await request) as { ok: boolean; result?: unknown } - return response.ok ? ((response.result as DetailComment[]) ?? []) : [] -} - async function successfulResult(request: Promise): Promise { const response = (await request) as { ok: boolean diff --git a/mobile/src/tasks/native-host-task-project-mutation-operations.test.ts b/mobile/src/tasks/native-host-task-project-mutation-operations.test.ts new file mode 100644 index 000000000000..e1898d7142aa --- /dev/null +++ b/mobile/src/tasks/native-host-task-project-mutation-operations.test.ts @@ -0,0 +1,113 @@ +import { describe, expect, it, vi } from 'vitest' +import type { RpcRequestSender } from '../transport/rpc-client' +import type { HostTaskProjectMutationOperations } from './host-task-project-mutation-operations' +import { nativeHostTaskProjectMutationOperations } from './native-host-task-project-mutation-operations' + +const target = { owner: 'orca', repo: 'orca', host: 'github.com', number: 7, type: 'pr' as const } +const mutations: Array< + [string, (ops: HostTaskProjectMutationOperations) => Promise, string] +> = [ + [ + 'updateItem', + (ops) => ops.updateItem(target, { title: 'title' }), + 'Failed to update GitHub item' + ], + [ + 'updateIssue', + (ops) => ops.updateItem({ ...target, type: 'issue' }, {}), + 'Failed to update GitHub item' + ], + ['updateComment', (ops) => ops.updateComment(target, 1, 'body'), 'Failed to edit comment'], + ['deleteComment', (ops) => ops.deleteComment(target, 1), 'Failed to delete comment'], + ['updateMetadata', (ops) => ops.updateMetadata(target, {}), 'Failed to update GitHub item'], + [ + 'updateField', + (ops) => + ops.updateField({ ...target, projectId: 'p', itemId: 'i' }, 'f', { + kind: 'text', + text: 'value' + }), + 'Failed to update project field' + ], + [ + 'clearField', + (ops) => ops.updateField({ ...target, projectId: 'p', itemId: 'i' }, 'f', null), + 'Failed to update project field' + ], + ['updateIssueType', (ops) => ops.updateIssueType(target, null), 'Failed to update issue type'], + [ + 'replyReviewComment', + (ops) => ops.replyReviewComment(target, 'repo-1', { commentId: 1, body: 'body' }), + 'Failed to reply' + ], + [ + 'addConversationComment', + (ops) => ops.addConversationComment(target, 'repo-1', 'body'), + 'Failed to reply' + ], + [ + 'requestReviewers', + (ops) => ops.requestReviewers(target, 'repo-1', ['reviewer']), + 'Failed to request reviewers' + ], + [ + 'rerunChecks', + (ops) => ops.rerunChecks(target, 'repo-1', { failedOnly: true }), + 'Failed to rerun checks' + ], + ['merge', (ops) => ops.merge(target, 'repo-1', 'squash'), 'Failed to merge pull request'] +] + +function operations(result: unknown) { + const sendRequest = vi + .fn() + .mockResolvedValue({ id: 'test', _meta: { runtimeId: 'host' }, ok: true, result }) + return nativeHostTaskProjectMutationOperations({ sendRequest }) +} + +describe('Project mutation result acceptance', () => { + it.each(mutations)( + '%s rejects absent results, accepts missing ok, and reports refusal', + async (_name, mutate, fallback) => { + for (const result of [null, undefined]) { + await expect(mutate(operations(result))).rejects.toBeInstanceOf(TypeError) + } + for (const result of [{}, { ok: undefined }, { ok: true }]) { + await expect(mutate(operations(result))).resolves.toBeUndefined() + } + await expect(mutate(operations({ ok: false }))).rejects.toThrow(fallback) + } + ) + + it('addComment requires truthy ok and preserves the host message', async () => { + for (const result of [null, undefined]) { + await expect(operations(result).addComment(target, 'body')).rejects.toBeInstanceOf(TypeError) + } + for (const result of [{}, { ok: undefined }, { ok: false }]) { + await expect(operations(result).addComment(target, 'body')).rejects.toThrow( + 'Failed to add comment' + ) + } + await expect( + operations({ ok: false, error: { message: 'host refusal' } }).addComment(target, 'body') + ).rejects.toThrow('host refusal') + await expect(operations({ ok: true }).addComment(target, 'body')).resolves.toBeUndefined() + }) + + it('merge preserves its string refusal', async () => { + await expect( + operations({ ok: false, error: 'merge refusal' }).merge(target, 'repo-1', 'merge') + ).rejects.toThrow('merge refusal') + }) + + it('resolveReviewThread requires the literal true result', async () => { + for (const result of [null, undefined, {}, { ok: true }, false]) { + await expect( + operations(result).resolveReviewThread(target, 'repo-1', 'thread', true) + ).rejects.toThrow('Failed to resolve thread') + } + await expect( + operations(true).resolveReviewThread(target, 'repo-1', 'thread', true) + ).resolves.toBeUndefined() + }) +}) diff --git a/mobile/src/tasks/native-host-task-project-mutation-operations.ts b/mobile/src/tasks/native-host-task-project-mutation-operations.ts index 875bb30a6f81..f983405291e4 100644 --- a/mobile/src/tasks/native-host-task-project-mutation-operations.ts +++ b/mobile/src/tasks/native-host-task-project-mutation-operations.ts @@ -4,15 +4,6 @@ import type { HostTaskProjectMutationOperations } from './host-task-project-mutation-operations' import type { RpcRequestSender } from '../transport/rpc-client' -import { - fetchAddIssueComment, - fetchAddPRReviewCommentReply, - fetchMergePR, - fetchRequestPRReviewers, - fetchRerunPRChecks, - fetchResolveReviewThread, - type GitHubPrMutationOutcome -} from '../session/github-pr-mutations' const PROJECT_PR_MUTATION_TIMEOUT_MS = 60_000 /** Every project mutation carried a connect deadline before this seam existed. Without one the @@ -87,89 +78,84 @@ export function nativeHostTaskProjectMutationOperations( }) }, async resolveReviewThread(target, repoId, threadId, resolve) { - requirePrMutation( - await fetchResolveReviewThread( - client, - repoId, - { - threadId, - resolve, - // Why: a draft row - // has no slug — send it only when one resolved rather than an empty pair. - prRepo: prRepoPayload(target) - }, - { timeoutMs: PROJECT_MUTATION_TIMEOUT_MS } - ), - resolve ? 'Failed to resolve thread' : 'Failed to reopen thread' + const response = await client.sendRequest( + 'github.resolveReviewThread', + { + repo: `id:${repoId}`, + prRepo: prRepoPayload(target), + threadId, + resolve + }, + { timeoutMs: PROJECT_MUTATION_TIMEOUT_MS } ) + if (!response.ok) { + throw new Error(response.error.message) + } + if (response.result !== true) { + throw new Error(resolve ? 'Failed to resolve thread' : 'Failed to reopen thread') + } }, async replyReviewComment(target, repoId, payload) { - return prMutationComment( - await fetchAddPRReviewCommentReply( - client, - repoId, - { - prNumber: target.number, - ...payload, - prRepo: prRepoPayload(target) - }, - { timeoutMs: PROJECT_MUTATION_TIMEOUT_MS } - ), - 'Failed to reply' + const result = await projectMutation<{ comment?: DetailComment }>( + client, + 'github.addPRReviewCommentReply', + { + repo: `id:${repoId}`, + prNumber: target.number, + prRepo: prRepoPayload(target), + ...payload + } ) + return result.comment }, async addConversationComment(target, repoId, body) { - return prMutationComment( - await fetchAddIssueComment( - client, - repoId, - { - prNumber: target.number, - body, - prRepo: prRepoPayload(target), - type: target.type - }, - { timeoutMs: PROJECT_MUTATION_TIMEOUT_MS } - ), - 'Failed to reply' + const result = await projectMutation<{ comment?: DetailComment }>( + client, + 'github.addIssueComment', + { + repo: `id:${repoId}`, + number: target.number, + prRepo: prRepoPayload(target), + body, + type: target.type + } ) + return result.comment }, async requestReviewers(target, repoId, reviewers) { - requirePrMutation( - await fetchRequestPRReviewers( - client, - repoId, - { - prNumber: target.number, - reviewers, - prRepo: prRepoPayload(target) - }, - { timeoutMs: PROJECT_MUTATION_TIMEOUT_MS } - ), - 'Failed to request reviewers' - ) + await projectMutation(client, 'github.requestPRReviewers', { + repo: `id:${repoId}`, + prNumber: target.number, + prRepo: prRepoPayload(target), + reviewers + }) }, async rerunChecks(target, repoId, payload) { - requirePrMutation( - await fetchRerunPRChecks( - client, - repoId, - { prNumber: target.number, ...payload, prRepo: prRepoPayload(target) }, - // A CI rerun and a merge both routinely outrun the 30s default. - { timeoutMs: PROJECT_PR_MUTATION_TIMEOUT_MS } - ), - 'Failed to rerun checks' + await projectMutation( + client, + 'github.rerunPRChecks', + { + repo: `id:${repoId}`, + prNumber: target.number, + prRepo: prRepoPayload(target), + ...payload + }, + false, + PROJECT_PR_MUTATION_TIMEOUT_MS ) }, async merge(target, repoId, method) { - requirePrMutation( - await fetchMergePR( - client, - repoId, - { prNumber: target.number, method, prRepo: prRepoPayload(target) }, - { timeoutMs: PROJECT_PR_MUTATION_TIMEOUT_MS } - ), - 'Failed to merge pull request' + await projectMutation( + client, + 'github.mergePR', + { + repo: `id:${repoId}`, + prNumber: target.number, + prRepo: prRepoPayload(target), + method + }, + false, + PROJECT_PR_MUTATION_TIMEOUT_MS ) } } @@ -202,49 +188,40 @@ const PROJECT_MUTATION_FALLBACKS: Record = { 'github.project.deleteIssueCommentBySlug': 'Failed to delete comment', 'github.project.updateItemField': 'Failed to update project field', 'github.project.clearItemField': 'Failed to update project field', - 'github.project.updateIssueTypeBySlug': 'Failed to update issue type' + 'github.project.updateIssueTypeBySlug': 'Failed to update issue type', + 'github.addPRReviewCommentReply': 'Failed to reply', + 'github.addIssueComment': 'Failed to reply', + 'github.requestPRReviewers': 'Failed to request reviewers', + 'github.rerunPRChecks': 'Failed to rerun checks', + 'github.mergePR': 'Failed to merge pull request' } async function projectMutation( client: RpcRequestSender, method: string, payload: object, - requireOk = false + requireOk = false, + timeoutMs = PROJECT_MUTATION_TIMEOUT_MS ): Promise { const fallback = PROJECT_MUTATION_FALLBACKS[method] ?? 'GitHub Project request failed' - const response = (await client.sendRequest(method, payload, { timeoutMs: 30_000 })) as { - ok: boolean - result?: { ok?: boolean; error?: string | { message?: string } } - error?: { message?: string } - } + const response = await client.sendRequest(method, payload, { timeoutMs }) if (!response.ok) { - throw new Error(response.error?.message ?? fallback) - } - if (requireOk && !response.result?.ok) { - throw new Error(fallback) - } - if (response.result?.ok === false) { - const error = response.result.error - throw new Error(typeof error === 'string' ? error : (error?.message ?? fallback)) + throw new Error(response.error.message) } - return (response.result ?? {}) as T -} - -/** The wrapper substitutes its own copy for two cases the caller used to word itself: a host - * that says nothing (`Request failed: `) and a review thread it could not update. */ -const WRAPPER_SUBSTITUTED_COPY = ['Request failed: ', 'Failed to update review thread.'] - -function requirePrMutation(result: GitHubPrMutationOutcome, fallback: string): void { - if (!result.ok) { - const substituted = WRAPPER_SUBSTITUTED_COPY.some((copy) => result.error.startsWith(copy)) - throw new Error(substituted ? fallback : result.error) + const result = response.result as { ok?: boolean; error?: string | { message?: string } } + if (requireOk ? !result.ok : result.ok === false) { + const error = result.error + if (!method.startsWith('github.project.')) { + throw new Error((error as string | undefined) ?? fallback) + } + const acceptsString = + method === 'github.project.updateIssueCommentBySlug' || + method === 'github.project.deleteIssueCommentBySlug' + throw new Error( + acceptsString && typeof error === 'string' + ? error + : ((typeof error === 'object' ? error?.message : undefined) ?? fallback) + ) } -} - -function prMutationComment( - result: GitHubPrMutationOutcome, - fallback: string -): DetailComment | undefined { - requirePrMutation(result, fallback) - return (result as { comment?: DetailComment }).comment + return result as T } From 3d2c11e238332d069b2ad54f367fd9c77fdb94db Mon Sep 17 00:00:00 2001 From: Jinwoo-H Date: Wed, 9 Sep 2026 15:49:22 -0400 Subject: [PATCH 39/40] Repair mobile fixture types, detail shape, workspace type and parity comments Claude-Session: https://claude.ai/code/session_01JNnE9qzUZMMnqpZWCqM3nb --- ...t-session-quick-command-operations.test.ts | 9 +++++++- .../session/use-mobile-native-chat-stop.ts | 5 +---- mobile/src/session/use-quick-commands.test.ts | 1 - .../tasks/github-task-detail-projection.ts | 21 +++++-------------- .../mobile-tasks-refactor-parity.test.ts | 18 +++++----------- ...tive-host-task-operation-contracts.test.ts | 17 ++++++++++++--- ...asks-project-workspace-comment-actions.tsx | 2 +- .../host-workspace-creation-operations.ts | 7 +++---- 8 files changed, 37 insertions(+), 43 deletions(-) diff --git a/mobile/src/session/native-host-session-quick-command-operations.test.ts b/mobile/src/session/native-host-session-quick-command-operations.test.ts index 9c79663c387e..a8e58ad051e0 100644 --- a/mobile/src/session/native-host-session-quick-command-operations.test.ts +++ b/mobile/src/session/native-host-session-quick-command-operations.test.ts @@ -14,7 +14,12 @@ describe('native host session quick command operations', () => { if (attempts === 1) { throw new LogicalClientCutoverError() } - return { ok: true, result: { terminalQuickCommands: [] } } + return { + id: 'test', + _meta: { runtimeId: 'host' }, + ok: true, + result: { terminalQuickCommands: [] } + } }) await expect( @@ -27,6 +32,8 @@ describe('native host session quick command operations', () => { // A host refusal is an answer. Checking `ok` inside the retry would replay it up to five // times whenever the host's own error text happened to match the cutover string. const sendRequest = vi.fn().mockResolvedValue({ + id: 'test', + _meta: { runtimeId: 'host' }, ok: false, error: { code: 'failed', message: 'RPC interrupted by connection migration' } }) diff --git a/mobile/src/session/use-mobile-native-chat-stop.ts b/mobile/src/session/use-mobile-native-chat-stop.ts index df6b98032154..6dfd6148e1db 100644 --- a/mobile/src/session/use-mobile-native-chat-stop.ts +++ b/mobile/src/session/use-mobile-native-chat-stop.ts @@ -30,10 +30,7 @@ export function useMobileNativeChatStop(args: { * never happen. */ const dropSecondEscapeRef = useRef<(() => void) | null>(null) const activeRouteRef = useRef({ operations, enabled, streamIdentity }) - // Layout, not render: the changed-code React Doctor gate rejects a ref write during render, - // and this file's rename put that pre-existing write in scope. Not a passive Effect either, - // because the paced Escape fires from a timer and needs a synchronous post-commit write. The - // guard now reads the last committed route rather than the last rendered one. + // The paced Escape timer must read the last committed route synchronously. useLayoutEffect(() => { activeRouteRef.current = { operations, enabled, streamIdentity } }, [operations, enabled, streamIdentity]) diff --git a/mobile/src/session/use-quick-commands.test.ts b/mobile/src/session/use-quick-commands.test.ts index b66ee1063e6c..d11c399626d0 100644 --- a/mobile/src/session/use-quick-commands.test.ts +++ b/mobile/src/session/use-quick-commands.test.ts @@ -8,7 +8,6 @@ import type { RpcResponse } from '../transport/types' import { defaultHostSessionOperations } from './default-host-session-operations' import { useQuickCommands } from './use-quick-commands' -const WORKSPACE_ID = 'repo::/worktree' /** One provider per client, exactly as the session model memoizes it, so the * effect keys stay stable across renders. */ const operationsByClient = new WeakMap< diff --git a/mobile/src/tasks/github-task-detail-projection.ts b/mobile/src/tasks/github-task-detail-projection.ts index f26c2c554dc9..184dbfd2b62a 100644 --- a/mobile/src/tasks/github-task-detail-projection.ts +++ b/mobile/src/tasks/github-task-detail-projection.ts @@ -1,22 +1,11 @@ import type { HostTaskGitHubDetail } from './host-task-provider-payloads' -import type { GitHubAssignableUser } from './mobile-tasks-provider-detail-types' +import type { GitHubWorkItemDetails } from '../../../src/shared/github/work-item-types' -type GitHubRawDetails = { - body?: string - comments?: HostTaskGitHubDetail['comments'] - assignees?: string[] - headSha?: string - baseSha?: string - pullRequestId?: string - checks?: HostTaskGitHubDetail['checks'] - files?: HostTaskGitHubDetail['files'] +import type { DetailComment } from './mobile-tasks-provider-detail-types' - item?: { - labels?: string[] - reviewDecision?: string | null - reviewRequests?: GitHubAssignableUser[] - latestReviews?: HostTaskGitHubDetail['latestReviews'] - } +type GitHubRawDetails = Partial> & { + comments?: DetailComment[] + item?: Partial } export function projectGitHubTaskDetail(value: unknown): HostTaskGitHubDetail { diff --git a/mobile/src/tasks/mobile-tasks-refactor-parity.test.ts b/mobile/src/tasks/mobile-tasks-refactor-parity.test.ts index 1ec6abd3b4fe..6556f762094b 100644 --- a/mobile/src/tasks/mobile-tasks-refactor-parity.test.ts +++ b/mobile/src/tasks/mobile-tasks-refactor-parity.test.ts @@ -16,20 +16,12 @@ const hash = (parts: string[] | string): string => .update(Array.isArray(parts) ? parts.join('\n') : parts) .digest('hex') -/** - * Re-frozen when the Tasks screens stopped calling `client.sendRequest` and started calling the - * host operation adapters. Every RPC envelope check, response cast and payload literal moved out - * of the composition into `native-host-task-*-operations.ts`, so the semantic source shrinks and - * the render tree loses the two casts that lived inside JSX callbacks. Screen hooks gain the three - * `useMemo` adapter bindings in `useMobileTasksRouteAndItemState`; statements gain the same three - * plus the row-target locals the adapters take in place of inline slug/number checks. Diff hooks, - * declarations and styles are untouched. - */ -const SCREEN_HOOKS = 'ef31f40ab364d2c1958f0b130382e9f244aa824d491d329b639c3f2cba2b044a' +// N1 removes list casts; D1 shortens a comment included in hook/statement fingerprints. +const SCREEN_HOOKS = '958721790452dd53263a84af0d882394d8abde9cde027a9c1b7726f020373ea4' const DIFF_HOOKS = '93c7189b32bed8456cc51814fffa8ce80cf62011ef968a9d53ddec2b9686f58f' -const STATEMENTS = '9df42716307eb166b1a862e2cea3d4bf2a9f3fa9bc8acd74ccc1e4302bbee9e4' +const STATEMENTS = '3f62cf6b6781006b7a24d0ae3aa8b6850df5d0f4ffc4e0667b013b1520637ff1' const DECLARATIONS = 'cff54172af17a877789be1479c2eb6ca97d83c3e31dd831cd59395962f2b4c4a' -const SEMANTICS = 'f767906884b93537f2c6369d6d0bd2d4cb39b4314c31cca9d8f9e5e9b78a75ee' +const SEMANTICS = 'f42b15496308dbed002740b3a9cf44c8dc630de67ec6dfde046dc15b659bfc65' const STYLES = '1db6af69c791d9963928541ad5310942fcbda6d984b422c90b6eb92b6816579a' const RENDER_TREE = '62b9f49e69e699887c9f1873d7d3c9c7e6f556d34a83ec1a1b79831b6f647ff3' @@ -58,7 +50,7 @@ describe('Mobile Tasks refactor parity', () => { it('preserves RPC calls, runtime strings, and JSX host signatures', () => { const semantics = readMobileTasksSemanticSource() - expect(semantics.split('\n')).toHaveLength(3_278) + expect(semantics.split('\n')).toHaveLength(3_274) expect(hash(semantics)).toBe(SEMANTICS) }) diff --git a/mobile/src/tasks/native-host-task-operation-contracts.test.ts b/mobile/src/tasks/native-host-task-operation-contracts.test.ts index 550d411ae693..20a31f660ea0 100644 --- a/mobile/src/tasks/native-host-task-operation-contracts.test.ts +++ b/mobile/src/tasks/native-host-task-operation-contracts.test.ts @@ -23,7 +23,12 @@ describe('native host task operation contracts', () => { it('rejects a non-array checks payload instead of crashing the checks list', async () => { const sendRequest = vi .fn() - .mockResolvedValue({ ok: true, result: { error: 'rate limited' } }) + .mockResolvedValue({ + id: 'test', + _meta: { runtimeId: 'host' }, + ok: true, + result: { error: 'rate limited' } + }) await expect( nativeHostTaskItemFileOperations(client(sendRequest)).refreshChecks(itemTarget, 'sha') @@ -39,6 +44,8 @@ describe('native host task operation contracts', () => { it('accepts a Linear workspace switch the host confirms by echoing the id', async () => { const sendRequest = vi.fn().mockResolvedValue({ + id: 'test', + _meta: { runtimeId: 'host' }, ok: true, result: { connected: true, workspaces: [], selectedWorkspaceId: 'ws-2' } }) @@ -51,6 +58,8 @@ describe('native host task operation contracts', () => { it('reports a refused Linear workspace switch, which the host answers with its old status', () => { // The host has no `ok` field here: a refusal is its unchanged status, so only the id proves it. const sendRequest = vi.fn().mockResolvedValue({ + id: 'test', + _meta: { runtimeId: 'host' }, ok: true, result: { connected: true, workspaces: [], selectedWorkspaceId: 'ws-1' } }) @@ -63,7 +72,7 @@ describe('native host task operation contracts', () => { it('reads an absent GitLab todo list as empty rather than an error banner', async () => { const sendRequest = vi .fn() - .mockResolvedValue({ ok: true, result: null }) + .mockResolvedValue({ id: 'test', _meta: { runtimeId: 'host' }, ok: true, result: null }) await expect( nativeHostTaskListOperations(client(sendRequest)).listGitLabTodos('repo-1') @@ -72,6 +81,8 @@ describe('native host task operation contracts', () => { it('gives project merge and rerun the long timeout their item-level twins use', async () => { const sendRequest = vi.fn().mockResolvedValue({ + id: 'test', + _meta: { runtimeId: 'host' }, ok: true, result: { ok: true } }) @@ -90,7 +101,7 @@ describe('native host task operation contracts', () => { // exercises the null path, which is why this pins the populated one. const sendRequest = vi .fn() - .mockResolvedValue({ ok: true, result: [] }) + .mockResolvedValue({ id: 'test', _meta: { runtimeId: 'host' }, ok: true, result: [] }) await nativeHostTaskProjectFileOperations(client(sendRequest)).refreshChecks( projectTarget, diff --git a/mobile/src/tasks/use-mobile-tasks-project-workspace-comment-actions.tsx b/mobile/src/tasks/use-mobile-tasks-project-workspace-comment-actions.tsx index 53d62a7b84aa..ec8b0829df20 100644 --- a/mobile/src/tasks/use-mobile-tasks-project-workspace-comment-actions.tsx +++ b/mobile/src/tasks/use-mobile-tasks-project-workspace-comment-actions.tsx @@ -158,7 +158,7 @@ export function useMobileTasksProjectWorkspaceCommentActions(model: WorkspaceCre if (!taskOperations || projectMutating) { return } - // main gated on the slug, the number and a non-empty body; the item type was not read. + // Adding a comment requires a repository slug, item number, and non-empty body. const target = projectRowSlugTarget(row, activeGitHubProjectHost) const body = projectCommentDraft.trim() if (!target || !row.content.number || !body) { diff --git a/mobile/src/worktree/host-workspace-creation-operations.ts b/mobile/src/worktree/host-workspace-creation-operations.ts index eec2753aa0e5..cfe87661f708 100644 --- a/mobile/src/worktree/host-workspace-creation-operations.ts +++ b/mobile/src/worktree/host-workspace-creation-operations.ts @@ -16,11 +16,10 @@ import type { ResolveComposerPrBaseArgs } from '../tasks/composer-source-base-resolve' import type { SetupHookTrust } from '../tasks/setup-hook-trust' -import type { ExecutionHostId } from '../../../src/shared/execution-host' -import type { GitRemoteIdentity } from '../../../src/shared/git-remote-identity' -import type { RepoIcon } from '../../../src/shared/repo-icon' import type { RetiredNameRegistry } from '../../../src/shared/worktree/retired-name-registry' +import type { MobileWorkspaceRepo } from '../components/new-worktree-modal-types' + export type { MobileWorkspaceRepo as NewWorkspaceRepository } from '../components/new-worktree-modal-types' export type NewWorkspaceRuntimeSettings = { @@ -37,7 +36,7 @@ export type NewWorkspaceRepoHooks = { } export type HostWorkspaceCreationOperations = { - listRepositories(): Promise + listRepositories(): Promise readRetiredWorktreeNames(repoId: string): Promise /** Null when the host answers without a settings key: the caller keeps what it has. */ readRuntimeSettings(): Promise From 1043e1ebd3a24a736d99d69d4dbdce8df8a791d8 Mon Sep 17 00:00:00 2001 From: Jinwoo-H Date: Wed, 9 Sep 2026 17:00:38 -0400 Subject: [PATCH 40/40] style(mobile): format native-host-task-operation-contracts test Claude-Session: https://claude.ai/code/session_01JNnE9qzUZMMnqpZWCqM3nb --- .../native-host-task-operation-contracts.test.ts | 14 ++++++-------- 1 file changed, 6 insertions(+), 8 deletions(-) diff --git a/mobile/src/tasks/native-host-task-operation-contracts.test.ts b/mobile/src/tasks/native-host-task-operation-contracts.test.ts index 20a31f660ea0..43a4d4d54ed2 100644 --- a/mobile/src/tasks/native-host-task-operation-contracts.test.ts +++ b/mobile/src/tasks/native-host-task-operation-contracts.test.ts @@ -21,14 +21,12 @@ const projectTarget = { describe('native host task operation contracts', () => { it('rejects a non-array checks payload instead of crashing the checks list', async () => { - const sendRequest = vi - .fn() - .mockResolvedValue({ - id: 'test', - _meta: { runtimeId: 'host' }, - ok: true, - result: { error: 'rate limited' } - }) + const sendRequest = vi.fn().mockResolvedValue({ + id: 'test', + _meta: { runtimeId: 'host' }, + ok: true, + result: { error: 'rate limited' } + }) await expect( nativeHostTaskItemFileOperations(client(sendRequest)).refreshChecks(itemTarget, 'sha')