diff --git a/mobile/app/h/[hostId]/accounts.tsx b/mobile/app/h/[hostId]/accounts.tsx index b107f34da975..7294a5391035 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) : 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/default-host-account-operations.ts b/mobile/src/accounts/default-host-account-operations.ts new file mode 100644 index 000000000000..1448a56ba70b --- /dev/null +++ b/mobile/src/accounts/default-host-account-operations.ts @@ -0,0 +1,7 @@ +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): HostAccountOperations { + return nativeHostAccountOperations(client) +} diff --git a/mobile/src/accounts/host-account-operations.ts b/mobile/src/accounts/host-account-operations.ts new file mode 100644 index 000000000000..8d9922b08737 --- /dev/null +++ b/mobile/src/accounts/host-account-operations.ts @@ -0,0 +1,15 @@ +import type { + AccountsSnapshot, + ProviderKey, + RateLimitRuntimeTarget +} from '../components/account-usage-state' + +export type HostAccountOperations = { + snapshot(): Promise + select( + provider: ProviderKey, + accountId: string | null, + codexTarget?: RateLimitRuntimeTarget | null + ): 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..7acd9d8b2238 --- /dev/null +++ b/mobile/src/accounts/native-host-account-operations.ts @@ -0,0 +1,59 @@ +import { + decodeAccountsSnapshot, + type ProviderKey, + type RateLimitRuntimeTarget +} from '../components/account-usage-state' +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): HostAccountOperations { + return { + async snapshot() { + const response = await client.sendRequest('accounts.list') + requireSuccess(response) + 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' + ? { accountId, target: codexTarget } + : { accountId } + requireSuccess(await client.sendRequest(method, params)) + }, + 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/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..233ff9ec080e 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 + .readRepoHooksIfAvailable(selectedRepo.id) + .then((result) => { + if (stale || !result) { 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/files/MobileFileExplorerPanel.tsx b/mobile/src/files/MobileFileExplorerPanel.tsx index 7e67bf81b5f9..82d8e47422cc 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,13 @@ export function MobileFileExplorerPanel(props: { const router = useRouter() const { client, state: connState } = useHostClient(hostId) const forceReconnect = useForceReconnect() + const operations = useMemo( + () => (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 @@ -67,7 +69,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 +109,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 +158,7 @@ export function MobileFileExplorerPanel(props: { } } }, - [client, connState, worktreeId] + [connState, operations, worktreeId] ) useEffect(() => { @@ -249,12 +220,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 +303,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/default-host-file-explorer-operations.ts b/mobile/src/files/default-host-file-explorer-operations.ts new file mode 100644 index 000000000000..249167f81891 --- /dev/null +++ b/mobile/src/files/default-host-file-explorer-operations.ts @@ -0,0 +1,7 @@ +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): HostFileExplorerOperations { + return nativeHostFileExplorerOperations(client) +} 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..edecf7faba4b --- /dev/null +++ b/mobile/src/files/host-file-explorer-operations.ts @@ -0,0 +1,17 @@ +import type { LegacyMobileFileEntry } from './file-list-fallback' +import type { MobileDirEntry } from './file-tree' + +export type HostFileExplorerDirectoryResult = + | { + kind: 'directory' + entries: MobileDirEntry[] + } + | { + kind: 'legacy-list' + files: LegacyMobileFileEntry[] + truncated: boolean + } + +export type HostFileExplorerOperations = { + readDirectory(workspaceId: string, relativePath: 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..a75bbc2d708a --- /dev/null +++ b/mobile/src/files/native-host-file-explorer-operations.ts @@ -0,0 +1,52 @@ +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): 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[] + } + } + // 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) + ) { + return readLegacyFileList(client, workspaceId, response.error?.message) + } + throw new Error(response.error?.message || 'Unable to load files') + } + } +} + +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/session/MobileSessionSheets.tsx b/mobile/src/session/MobileSessionSheets.tsx index 0aac2bb9d42e..5e02d9b9d8a5 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,7 @@ export function MobileSessionSheets({ controller }: { controller: MobileSessionC setShowQuickCommands(false)} - client={client} + operations={sessionOperations?.quickCommand ?? null} repoId={ isFolderWorkspaceRoute || isFloatingWorkspaceRoute ? null diff --git a/mobile/src/session/QuickCommandsSheet.tsx b/mobile/src/session/QuickCommandsSheet.tsx index 3342f1226653..1b68d1cb3aae 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,7 @@ import { type Props = { visible: boolean onClose: () => void - client: RpcClient | null + operations: HostSessionQuickCommandOperations | null repoId: string | null repoName: string | null onLaunch: (command: TerminalQuickCommand) => boolean @@ -34,13 +34,13 @@ type SheetView = 'list' | 'editor' | 'agent' export function QuickCommandsSheet({ visible, onClose, - client, + operations, repoId, repoName, onLaunch }: Props) { const { commands, loading, ready, error, persist } = useQuickCommands({ - client, + operations, enabled: visible }) const [view, setView] = useState('list') 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/github-pr-mutations.ts b/mobile/src/session/github-pr-mutations.ts index bd1d9c423b90..fad0d0ea22b6 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,12 +17,16 @@ 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 + 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}` } } @@ -50,20 +56,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 +87,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 +99,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 +108,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 +130,7 @@ export async function fetchUpdatePRTitle( } export async function fetchSetPRAutoMerge( - client: Pick, + client: RpcRequestSender, worktreeId: string, args: { prNumber: number @@ -139,7 +151,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,9 +168,10 @@ export async function fetchUpdatePRState( } export async function fetchRequestPRReviewers( - client: Pick, + 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, @@ -168,12 +181,13 @@ export async function fetchRequestPRReviewers( worktreeId, { prNumber: args.prNumber, reviewers: args.reviewers }, { prRepo: args.prRepo } - ) + ), + options ) } export async function fetchRemovePRReviewers( - client: Pick, + client: RpcRequestSender, worktreeId: string, args: { prNumber: number; reviewers: string[]; prRepo?: GitHubPrRepoSlug | null } ): Promise { @@ -193,7 +207,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 @@ -203,7 +217,8 @@ export async function fetchAddPRReviewCommentReply( path?: string line?: number prRepo?: GitHubPrRepoSlug | null - } + }, + options?: { timeoutMs?: number } ): Promise { const params: Record = { prNumber: args.prNumber, @@ -224,25 +239,35 @@ export async function fetchAddPRReviewCommentReply( 'github.addPRReviewCommentReply', buildGithubPrParams('github.addPRReviewCommentReply', worktreeId, params, { prRepo: args.prRepo - }) + }), + options ) } -// 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' + }, + options?: { timeoutMs?: number } ): Promise { const params: Record = { number: args.prNumber, body: args.body, - type: 'pr' + type: args.type ?? 'pr' } return sendGithubPrMutation( client, 'github.addIssueComment', - buildGithubPrParams('github.addIssueComment', worktreeId, params, { prRepo: args.prRepo }) + buildGithubPrParams('github.addIssueComment', worktreeId, params, { prRepo: args.prRepo }), + options ) } @@ -250,9 +275,10 @@ 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 } + args: { threadId: string; resolve: boolean; prRepo?: GitHubPrRepoSlug | null }, + options?: { timeoutMs?: number } ): Promise { const response = await sendRaw( client, @@ -262,7 +288,8 @@ export async function fetchResolveReviewThread( worktreeId, { threadId: args.threadId, resolve: args.resolve }, { prRepo: args.prRepo } - ) + ), + options ) if (!response.ok) { return { @@ -283,7 +310,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 +322,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 +332,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 +352,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..3931007539a4 --- /dev/null +++ b/mobile/src/session/host-session-browser-operations.ts @@ -0,0 +1,10 @@ +export type HostSessionBrowserTarget = { + workspaceId: string + pageId: string +} + +export type HostSessionBrowserOperations = { + back(target: HostSessionBrowserTarget): Promise + forward(target: HostSessionBrowserTarget): Promise + reload(target: HostSessionBrowserTarget): Promise +} 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..4a06f861bb05 --- /dev/null +++ b/mobile/src/session/host-session-native-chat-operations.ts @@ -0,0 +1,54 @@ +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' + +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 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 + ): () => void + read( + target: HostSessionNativeChatTarget, + limit: number, + beforeOffset?: number + ): Promise + stop(target: HostSessionNativeChatTarget, deadline?: number): 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 +} 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..99672a5cb721 --- /dev/null +++ b/mobile/src/session/host-session-quick-command-operations.ts @@ -0,0 +1,11 @@ +import type { TerminalQuickCommand } from '../../../src/shared/terminal-quick-command-types' +import type { TerminalQuickCommandMutation } from '../terminal/quick-commands' + +export type HostSessionQuickCommandSnapshot = { + commands: TerminalQuickCommand[] +} + +export type HostSessionQuickCommandOperations = { + snapshot(signal?: AbortSignal): Promise + mutate(mutation: TerminalQuickCommandMutation): Promise +} 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..3ca73cc80d79 --- /dev/null +++ b/mobile/src/session/host-session-tab-operations.ts @@ -0,0 +1,6 @@ +export type HostSessionTabOperations = { + createBrowser(workspaceId: string, url: string): Promise<{ browserPageId?: string }> + /** 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/host-session-terminal-file-operations.ts b/mobile/src/session/host-session-terminal-file-operations.ts new file mode 100644 index 000000000000..192546d36f1b --- /dev/null +++ b/mobile/src/session/host-session-terminal-file-operations.ts @@ -0,0 +1,30 @@ +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 + } + +export type HostSessionTerminalFileResolveRequest = { + workspaceId: string + terminalHandle: string | null + pathText: string + cwd: string | null + nativeChatContext: RuntimeNativeChatFileContext | 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..e9b2e8b788c1 --- /dev/null +++ b/mobile/src/session/host-session-terminal-operations.ts @@ -0,0 +1,16 @@ +export type HostSessionTerminalOperations = { + sendInput( + terminalId: string, + text: string, + enter: boolean, + clientId: string | null + ): 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): Promise +} 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..4bdec99f980c 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,18 @@ 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 + // Why: resolution opts into sibling-workspace hits; this caller honors resolved.workspaceId. + const resolved = await options.operations.resolveTerminalPath({ + workspaceId: options.worktreeId, + terminalHandle, + pathText: options.pathText, + cwd, + nativeChatContext: options.nativeChatContext ?? null + }) + if (!resolved) { reportOpenFailure(options) return } @@ -102,32 +87,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 +117,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 +144,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-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-session-route-parity.test.ts b/mobile/src/session/mobile-session-route-parity.test.ts index 3a6b04661dec..eb583426d633 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' + '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 = - '31951b0b83be01ebfa659c4b94df9ad7eaff6404df5338fbade89eb7473a3cb4' + '58ee753e4fc849c693aa6ebb71b2ff7c38dbbba50977cacc737b03c4bb2a7224' const HEAD_HOST_JSX_SHA256 = '390405926b1695fa3a33686f0bc192b432f5468d8576499d7cafbb4922defbb5' -const HEAD_LEAF_JSX_SHA256 = '21dba981875e173f692590bf910d60964660c5f4cbb79f3a377c7e54f6a1f016' +const HEAD_LEAF_JSX_SHA256 = '15ea1af8ae1a28a4a5f2ea31c2aac908fc24a0fe68923733889f1d40d0c8e3a3' const HEAD_STYLE_REFERENCE_SHA256 = '295a3501c2c6d7bea7c8bbf38b3f3534f01344cd7e1b91bb8e07c040821d596a' const HEAD_IDENTITY_FIELD_SHA256 = - '91146853930a34dd1f3d80e5c97fbacd7cf19fb93dd26fe8fc6f29169622f9d6' + '89bdd544369e41829581e80d320112019f3127fd3529c810d9651e5ece37338b' 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 } } @@ -472,7 +494,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) @@ -517,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(546) + 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/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/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/native-host-session-browser-operations.ts b/mobile/src/session/native-host-session-browser-operations.ts new file mode 100644 index 000000000000..b3da99049e51 --- /dev/null +++ b/mobile/src/session/native-host-session-browser-operations.ts @@ -0,0 +1,32 @@ +import type { RpcClient } from '../transport/rpc-client' +import type { + HostSessionBrowserOperations, + HostSessionBrowserTarget +} from './host-session-browser-operations' + +export function nativeHostSessionBrowserOperations( + client: RpcClient +): HostSessionBrowserOperations { + return { + 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): Promise { + const response = await client.sendRequest(method, payload, { timeoutMs: 15_000 }) + if (!response.ok) { + throw new Error(response.error.message) + } +} 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..974e9f18e626 --- /dev/null +++ b/mobile/src/session/native-host-session-native-chat-operations.test.ts @@ -0,0 +1,139 @@ +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 carries no enter at all', async () => { + const sendRequest = vi.fn().mockResolvedValue({ + id: 'test', + _meta: { runtimeId: 'host' }, + ok: true, + result: { delivered: true } + }) + const operations = nativeHostSessionNativeChatOperations(client(sendRequest)) + + await operations.stop(target(), Date.now() + 15_000) + + 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({ + id: 'test', + _meta: { runtimeId: 'host' }, + 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('ignores an older inventory completion after cache reset', async () => { + const deferred: Array<(value: Awaited>) => void> = [] + const sendRequest = vi.fn((method) => { + 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') + 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]!({ + 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 { + 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: + 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..b3ced59cbbd5 --- /dev/null +++ b/mobile/src/session/native-host-session-native-chat-operations.ts @@ -0,0 +1,201 @@ +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 { + 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 { + 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>() + const legacyGenerationByWorkspace = 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' } + } + }, + stop(target, deadline) { + return sendStopEscape(target, client, deadline) + }, + 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) { + 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') { + // 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 + } + 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. + const generation = legacyGenerationByWorkspace.get(target.workspaceId) ?? 0 + const request = client + .sendRequest('files.list', { + worktree: `id:${target.workspaceId}` + }) + .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) + } + } +} + +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 } : {}) + } +} + +/** 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, + client: RpcClient, + deadline?: number +): Promise { + if (!target.terminalId) { + 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' + } +} + +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.test.ts b/mobile/src/session/native-host-session-quick-command-operations.test.ts new file mode 100644 index 000000000000..a8e58ad051e0 --- /dev/null +++ b/mobile/src/session/native-host-session-quick-command-operations.test.ts @@ -0,0 +1,46 @@ +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 { + id: 'test', + _meta: { runtimeId: 'host' }, + ok: true, + result: { terminalQuickCommands: [] } + } + }) + + await expect( + nativeHostSessionQuickCommandOperations(client(sendRequest)).snapshot() + ).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({ + id: 'test', + _meta: { runtimeId: 'host' }, + ok: false, + error: { code: 'failed', message: 'RPC interrupted by connection migration' } + }) + + await expect( + nativeHostSessionQuickCommandOperations(client(sendRequest)).snapshot() + ).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 new file mode 100644 index 000000000000..3ea3bba970d7 --- /dev/null +++ b/mobile/src/session/native-host-session-quick-command-operations.ts @@ -0,0 +1,65 @@ +import { parseNormalizedTerminalQuickCommands } 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' + +const LOAD_CUTOVER_MAX_RETRIES = 5 + +export function nativeHostSessionQuickCommandOperations( + client: RpcClient +): HostSessionQuickCommandOperations { + return { + 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, 'Failed to load quick commands') + }, + 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', { + mutation + }) + if (!response.ok) { + throw new Error(response.error.message || 'Failed to save quick command') + } + return quickCommandSnapshot(response.result, 'Failed to save quick command') + } + } +} + +async function loadWithCutoverRetry(client: RpcClient, signal?: AbortSignal) { + for (let retry = 0; ; retry += 1) { + try { + return await client.sendRequest('settings.getTerminalQuickCommands') + } catch (error) { + if ( + signal?.aborted || + !isLogicalClientCutoverError(error) || + retry >= LOAD_CUTOVER_MAX_RETRIES + ) { + throw error + } + } + } +} + +function quickCommandSnapshot( + result: unknown, + invalidResultMessage: string +): HostSessionQuickCommandSnapshot { + const commands = parseNormalizedTerminalQuickCommands( + (result as { terminalQuickCommands?: unknown } | null)?.terminalQuickCommands + ) + if (!commands) { + throw new Error(invalidResultMessage) + } + return { commands } +} 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..91594f3502ba --- /dev/null +++ b/mobile/src/session/native-host-session-tab-operations.test.ts @@ -0,0 +1,85 @@ +import { describe, expect, it, vi } from 'vitest' +import type { RpcClient } from '../transport/rpc-client' +import { nativeHostSessionTabOperations } from './native-host-session-tab-operations' + +describe('native host session tab operations', () => { + it('maps the two named lifecycle operations to the caller-local RPCs', async () => { + const sendRequest = vi + .fn() + .mockResolvedValueOnce({ ok: true, result: { browserPageId: 'browser-1' } }) + .mockResolvedValueOnce({ ok: true, result: { closed: true } }) + const operations = nativeHostSessionTabOperations({ + sendRequest + } as unknown as RpcClient) + + await expect(operations.createBrowser('workspace-1', 'https://example.com')).resolves.toEqual({ + browserPageId: 'browser-1' + }) + await expect(operations.close('workspace-1', 'tab-1')).resolves.toBe(true) + + expect(sendRequest.mock.calls).toEqual([ + [ + 'browser.tabCreate', + { + 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.close', { worktree: 'id:workspace-1', tabId: 'tab-1', reason: 'user' }] + ]) + }) + + 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('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' } }) + } 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: {} }) + } as unknown as RpcClient) + + await expect(operations.createBrowser('workspace-1', 'https://example.com')).resolves.toEqual( + {} + ) + }) + + it('reports the host message when a browser create is refused', async () => { + const operations = nativeHostSessionTabOperations({ + sendRequest: vi + .fn() + .mockResolvedValue({ ok: false, error: { code: 'busy', message: 'Browser busy' } }) + } as unknown as RpcClient) + + await expect(operations.createBrowser('workspace-1', 'https://example.com')).rejects.toThrow( + 'Browser busy' + ) + }) +}) 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..1437d9c7e325 --- /dev/null +++ b/mobile/src/session/native-host-session-tab-operations.ts @@ -0,0 +1,30 @@ +import type { RpcClient } from '../transport/rpc-client' +import type { RpcSuccess } from '../transport/types' +import type { HostSessionTabOperations } from './host-session-tab-operations' + +export function nativeHostSessionTabOperations(client: RpcClient): HostSessionTabOperations { + return { + async createBrowser(workspaceId, url) { + const response = await client.sendRequest( + 'browser.tabCreate', + { worktree: `id:${workspaceId}`, url, activate: true }, + { timeoutMs: 30_000 } + ) + if (!response.ok) { + 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 } + return typeof result.browserPageId === 'string' ? { browserPageId: result.browserPageId } : {} + }, + async close(workspaceId, tabId) { + const response = await client.sendRequest('session.tabs.close', { + worktree: `id:${workspaceId}`, + tabId, + reason: 'user' + }) + return response.ok + } + } +} 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..f7e2dddeddb7 --- /dev/null +++ b/mobile/src/session/native-host-session-terminal-operations.test.ts @@ -0,0 +1,46 @@ +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 terminal input RPC semantics', async () => { + const sendRequest = vi + .fn() + .mockResolvedValue({ ok: true, result: { send: { accepted: true } } }) + const operations = nativeHostSessionTerminalOperations({ + sendRequest + } as unknown as RpcClient) + + 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')).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' + }) + }) +}) 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..310c9a9141b2 --- /dev/null +++ b/mobile/src/session/native-host-session-terminal-operations.ts @@ -0,0 +1,50 @@ +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' + +export function nativeHostSessionTerminalOperations( + client: RpcClient +): HostSessionTerminalOperations { + return { + 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) + }, + 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 + ) + }, + 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( + (response) => response.ok, + () => false + ) + } + } +} 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.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-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..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 @@ -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 () => { @@ -88,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 53df98e3ee0c..5ff1ad325bf1 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,32 @@ -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 + operations?.resetFileSearchCache(worktreeId) setNativeChatFilePaths([]) return () => { if (timerRef.current) { @@ -43,11 +34,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,12 +58,11 @@ export function useMobileNativeChatFileSearch(args: { clearTimeout(timerRef.current) } const sequence = ++sequenceRef.current - const generation = generationRef.current 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) @@ -85,61 +75,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 ? paths.slice(0, FILE_SEARCH_RESULT_LIMIT) : null)) + .catch(() => {}) }, FILE_SEARCH_DEBOUNCE_MS) }, - [client, worktreeId] + [operations, target] ) return { nativeChatFilePaths, loadNativeChatFiles } 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 }) }) 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..e5de241cea80 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,88 +141,85 @@ 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, + // 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 + } + const frame = raw as MobileNativeChatStreamFrame + const applied = applyMobileNativeChatStreamFrame({ + merger: mergerRef.current, + frame, limit: limitRef.current, - subscriptionId: buildNativeChatSubscriptionId(agent, sessionId), - capabilities: { transcriptPending: 1 }, - ...(transcriptPath ? { transcriptPath } : {}) - }, - (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({ client, 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({ client, identity, status: applied.pending ? 'awaiting-transcript' : 'ready' }) + 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 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 +237,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 +275,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..6dfd6148e1db 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 { 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' export function useMobileNativeChatStop(args: { - client: RpcClient | null + operations: HostSessionNativeChatOperations | null + workspaceId: string enabled: boolean handleRef: MutableRefObject deviceTokenRef: MutableRefObject @@ -15,16 +13,27 @@ 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 }) + // The paced Escape timer must read the last committed route synchronously. + useLayoutEffect(() => { + activeRouteRef.current = { operations, enabled, streamIdentity } + }, [operations, enabled, streamIdentity]) const cancelSecondEscape = useCallback(() => { if (timerRef.current) { clearTimeout(timerRef.current) @@ -39,11 +48,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 +89,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 +143,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..e3f50be3f5e2 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)) { setTerminals((prev) => { const next = prev.map((terminal) => terminal.handle === target.handle @@ -93,18 +90,13 @@ 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. + 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) { 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..10473104bc85 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 - }) + // 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') } 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..d11c399626d0 100644 --- a/mobile/src/session/use-quick-commands.test.ts +++ b/mobile/src/session/use-quick-commands.test.ts @@ -5,8 +5,25 @@ 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' +/** 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 +74,10 @@ describe('useQuickCommands', () => { async function mount(client: RpcClient, enabled = true): Promise { function Harness(): null { - state = useQuickCommands({ client, enabled }) + state = useQuickCommands({ + operations: quickCommandOperations(client), + enabled + }) return null } await act(async () => { @@ -128,7 +148,10 @@ describe('useQuickCommands', () => { } as unknown as RpcClient function Harness({ enabled }: { enabled: boolean }): null { - state = useQuickCommands({ client, enabled }) + state = useQuickCommands({ + operations: quickCommandOperations(client), + enabled + }) return null } await act(async () => { @@ -307,7 +330,10 @@ describe('useQuickCommands', () => { } as unknown as RpcClient function Harness({ client }: { client: RpcClient }): null { - state = useQuickCommands({ client, enabled: true }) + state = useQuickCommands({ + operations: quickCommandOperations(client), + enabled: true + }) return null } await act(async () => { @@ -382,7 +408,10 @@ describe('useQuickCommands', () => { } as unknown as RpcClient function Harness({ enabled }: { enabled: boolean }): null { - state = useQuickCommands({ client, enabled }) + state = useQuickCommands({ + operations: quickCommandOperations(client), + 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..17f68a08c42c 100644 --- a/mobile/src/session/use-quick-commands.ts +++ b/mobile/src/session/use-quick-commands.ts @@ -1,16 +1,13 @@ 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 // 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 +29,14 @@ type PendingMutation = { } type MutationContext = { - client: RpcClient + operations: HostSessionQuickCommandOperations 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, enabled }: Args): QuickCommandsState { const [commands, setCommands] = useState([]) const [loading, setLoading] = useState(false) const [ready, setReady] = useState(false) @@ -78,15 +46,15 @@ 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) { // A request for an old host must not delay or update mutations on a new one. mutationContext = { - client, + operations, confirmed: [], pending: [], queue: Promise.resolve(), @@ -97,6 +65,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 +86,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(abortController.signal) if ( stale || operationId !== operationIdRef.current || @@ -129,18 +94,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 +119,16 @@ export function useQuickCommands({ client, enabled }: Args): QuickCommandsState return () => { stale = true + abortController.abort() } - }, [client, enabled]) + }, [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 (!client || loading || !ready || mutationContext?.client !== client) { + if (!operations || loading || !ready || mutationContext?.operations !== operations) { return false } const mutation: PendingMutation = { @@ -189,21 +146,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(commandMutation) + mutationContext.confirmed = snapshot.commands succeeded = true return true } catch (err) { @@ -236,7 +182,7 @@ export function useQuickCommands({ client, enabled }: Args): QuickCommandsState ) return await request }, - [client, loading, ready] + [loading, operations, ready] ) return { commands, loading, ready, error, persist } 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-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/github-project-host-routing-source.test.ts b/mobile/src/tasks/github-project-host-routing-source.test.ts index 7a13aab09a2a..693f741714ed 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,144 @@ 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 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' +]) + +/** 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(') + expect( + [...adapterSource.matchAll(/['"](github\.project\.[^'"]+)['"]/g)].length + ).toBeGreaterThan(10) + }) + it('host-qualifies every Project RPC request', () => { - const calls = [...source.matchAll(/['"](github\.project\.[^'"]+)['"]/g)] + const calls = [...adapterSource.matchAll(/['"](github\.project\.[^'"]+)['"]/g)] expect(calls.length).toBeGreaterThan(10) 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*:/) + if (TYPED_PAYLOAD_CALLS.has(call[1])) { + continue + } + // Bounded to the enclosing adapter method, so a neighbour's host cannot satisfy it. + 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\(/ + ) } + // 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,/ + ) }) 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( + /projectRow(?:Mutation|PullRequest|Slug|Identity)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, and a row with + // no slug forwards null rather than being refused. + 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 [ 'github.resolveReviewThread', 'github.addPRReviewCommentReply', 'github.addIssueComment', 'github.requestPRReviewers', - 'github.prChecks', 'github.rerunPRChecks', + 'github.mergePR' + ]) { + 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( + enclosingAdapterMethod(projectMutationAdapter, offset), + `${method} must carry prRepo` + ).toContain('prRepo: prRepoPayload(target)') + } + for (const method of [ + 'github.prChecks', 'github.setPRFileViewed', 'github.prFileContents', - 'github.addPRReviewComment', - 'github.mergePR' + 'github.addPRReviewComment' ]) { - 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)' - ) + const offset = projectFileAdapter.indexOf(`'${method}'`) + expect(offset, `${method} must remain wired`).toBeGreaterThan(-1) + expect( + enclosingAdapterMethod(projectFileAdapter, offset), + `${method} must carry the row repository` + ).toContain('repoPayload(target, repoId)') } }) 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/github-task-detail-projection.ts b/mobile/src/tasks/github-task-detail-projection.ts new file mode 100644 index 000000000000..184dbfd2b62a --- /dev/null +++ b/mobile/src/tasks/github-task-detail-projection.ts @@ -0,0 +1,30 @@ +import type { HostTaskGitHubDetail } from './host-task-provider-payloads' +import type { GitHubWorkItemDetails } from '../../../src/shared/github/work-item-types' + +import type { DetailComment } from './mobile-tasks-provider-detail-types' + +type GitHubRawDetails = Partial> & { + comments?: DetailComment[] + item?: Partial +} + +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, + assignees: details.assignees ?? [], + reviewDecision: details.item?.reviewDecision, + reviewRequests: details.item?.reviewRequests, + latestReviews: details.item?.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..984eb2d913be --- /dev/null +++ b/mobile/src/tasks/host-task-project-payloads.ts @@ -0,0 +1,47 @@ +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 +} + +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..98fe2076d358 --- /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: HostTaskProjectTablePayload): 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..13e5e9614a9d --- /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: Array> + 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: Array> + 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..55d10e062905 --- /dev/null +++ b/mobile/src/tasks/host-task-read-operations.ts @@ -0,0 +1,23 @@ +import type { GitHubOwnerRepo } from '../../../src/shared/github/pull-request-types' +import type { + HostTaskBootstrap, + HostTaskLinearStatus, + HostTaskLinearTeams, + HostTaskRepository +} from './host-task-runtime-payloads' + +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 + * 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 new file mode 100644 index 000000000000..aa23ff1580dd --- /dev/null +++ b/mobile/src/tasks/host-task-runtime-payloads.ts @@ -0,0 +1,35 @@ +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 = { + settings: RuntimeTaskSettings + taskResumeState: TaskResumeState + trustedOrcaHooks: PersistedTrustedOrcaHooks + gitLabInstalled: boolean + linearStatus: HostTaskLinearStatus +} + +export type HostTaskRepository = RepoSummary + +export type HostTaskLinearTeams = LinearTeam[] + +export type HostTaskSettingsUpdate = Pick< + RuntimeTaskSettings, + | 'defaultTaskSource' + | 'defaultTaskViewPreset' + | 'defaultRepoSelection' + | 'defaultLinearTeamSelection' + | 'githubProjects' +> 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 78d406db9ac1..14c84a03af9e 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,13 +168,17 @@ export function renderMobileTasksLinearWorkspacePicker(model: ConnectionPresenta onSelect={(workspaceId) => { setSelectedLinearWorkspaceId(workspaceId) setSelectedLinearTeamIds(new Set()) - if (client) { - void client - .sendRequest('linear.selectWorkspace', { workspaceId }) + 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-mutation-targets.ts b/mobile/src/tasks/mobile-tasks-mutation-targets.ts new file mode 100644 index 000000000000..851b0ec7e28f --- /dev/null +++ b/mobile/src/tasks/mobile-tasks-mutation-targets.ts @@ -0,0 +1,53 @@ +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, + projectRowPullRequestTarget, + 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..25b2442711e3 --- /dev/null +++ b/mobile/src/tasks/mobile-tasks-project-row-targets.ts @@ -0,0 +1,84 @@ +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 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 + * (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..6556f762094b 100644 --- a/mobile/src/tasks/mobile-tasks-refactor-parity.test.ts +++ b/mobile/src/tasks/mobile-tasks-refactor-parity.test.ts @@ -16,50 +16,51 @@ 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' +// N1 removes list casts; D1 shortens a comment included in hook/statement fingerprints. +const SCREEN_HOOKS = '958721790452dd53263a84af0d882394d8abde9cde027a9c1b7726f020373ea4' +const DIFF_HOOKS = '93c7189b32bed8456cc51814fffa8ce80cf62011ef968a9d53ddec2b9686f58f' +const STATEMENTS = '3f62cf6b6781006b7a24d0ae3aa8b6850df5d0f4ffc4e0667b013b1520637ff1' +const DECLARATIONS = 'cff54172af17a877789be1479c2eb6ca97d83c3e31dd831cd59395962f2b4c4a' +const SEMANTICS = 'f42b15496308dbed002740b3a9cf44c8dc630de67ec6dfde046dc15b659bfc65' +const STYLES = '1db6af69c791d9963928541ad5310942fcbda6d984b422c90b6eb92b6816579a' +const RENDER_TREE = '62b9f49e69e699887c9f1873d7d3c9c7e6f556d34a83ec1a1b79831b6f647ff3' 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(352) + 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(419) + 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_274) + 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_209) + 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/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 new file mode 100644 index 000000000000..01cce9f75273 --- /dev/null +++ b/mobile/src/tasks/native-host-task-detail-operations.ts @@ -0,0 +1,109 @@ +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 [issueResponse, commentsResponse] = await Promise.all([ + client.sendRequest( + 'linear.getIssue', + { id: payload.issueId, workspaceId: payload.workspaceId }, + { timeoutMs: 30_000 } + ), + client.sendRequest( + 'linear.issueComments', + { issueId: payload.issueId, workspaceId: payload.workspaceId }, + { timeoutMs: 30_000 } + ) + ]) + 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') + } + return { issue, comments } + } + } +} + +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..7f30a1efa8cb --- /dev/null +++ b/mobile/src/tasks/native-host-task-item-mutation-operations.ts @@ -0,0 +1,146 @@ +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) + // 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, + target.provider === 'github' + ? 'Failed to update GitHub issue' + : 'Failed to update GitLab item' + ) + } + } +} + +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..232be325b1c7 --- /dev/null +++ b/mobile/src/tasks/native-host-task-item-review-operations.ts @@ -0,0 +1,152 @@ +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) { + 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') + } + }, + 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') + } + } +} + +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..1d64ef99b0c1 --- /dev/null +++ b/mobile/src/tasks/native-host-task-linear-operations.ts @@ -0,0 +1,140 @@ +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' + +/** 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 { + 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) { + // 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. 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', { + 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 }, + INTERACTIVE + ) + 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 }, + INTERACTIVE + ) + if (!issue) { + 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 + }, + INTERACTIVE + ), + 'Failed to create sub-issue' + ) + }, + async createIssue(payload) { + return createdIssue( + await request(client, 'linear.createIssue', { + teamId: payload.team.id, + title: payload.title, + description: payload.description, + workspaceId: payload.team.workspaceId + }), + 'Failed to create Linear issue' + ) + } + } +} + +async function request( + client: RpcRequestSender, + method: string, + payload?: object, + options?: SendRequestOptions +): Promise { + 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') + } + 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, fallback: string) { + 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 ?? fallback) + } + 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..eeb27edf44e8 --- /dev/null +++ b/mobile/src/tasks/native-host-task-list-operations.ts @@ -0,0 +1,72 @@ +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 + }) + ) + }, + 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..43a4d4d54ed2 --- /dev/null +++ b/mobile/src/tasks/native-host-task-operation-contracts.test.ts @@ -0,0 +1,114 @@ +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' + +function client(sendRequest: RpcClient['sendRequest']): RpcClient { + return { sendRequest } as unknown as RpcClient +} + +const itemTarget = { repoId: 'repo-1', number: 7, provider: 'github' as const, 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 () => { + const sendRequest = vi.fn().mockResolvedValue({ + id: 'test', + _meta: { runtimeId: 'host' }, + 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('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' } + }) + + 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({ + id: 'test', + _meta: { runtimeId: 'host' }, + 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() + .mockResolvedValue({ id: 'test', _meta: { runtimeId: 'host' }, 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({ + id: 'test', + _meta: { runtimeId: 'host' }, + 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 }) + } + }) + + 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({ id: 'test', _meta: { runtimeId: 'host' }, 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/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..978fb9250275 --- /dev/null +++ b/mobile/src/tasks/native-host-task-project-file-operations.ts @@ -0,0 +1,76 @@ +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}`, + // 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 + } +} + +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.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 new file mode 100644 index 000000000000..f983405291e4 --- /dev/null +++ b/mobile/src/tasks/native-host-task-project-mutation-operations.ts @@ -0,0 +1,227 @@ +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' + +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 +): 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<{ ok?: boolean; comment?: DetailComment }>( + client, + 'github.project.addIssueCommentBySlug', + { ...slugPayload(target), body }, + true + ) + 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) { + 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) { + 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) { + 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) { + await projectMutation(client, 'github.requestPRReviewers', { + repo: `id:${repoId}`, + prNumber: target.number, + prRepo: prRepoPayload(target), + reviewers + }) + }, + async rerunChecks(target, repoId, payload) { + 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) { + await projectMutation( + client, + 'github.mergePR', + { + repo: `id:${repoId}`, + prNumber: target.number, + prRepo: prRepoPayload(target), + method + }, + false, + PROJECT_PR_MUTATION_TIMEOUT_MS + ) + } + } +} + +/** 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, + repo: target.repo, + host: target.host, + number: target.number + } +} + +/** 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', + '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, + timeoutMs = PROJECT_MUTATION_TIMEOUT_MS +): Promise { + const fallback = PROJECT_MUTATION_FALLBACKS[method] ?? 'GitHub Project request failed' + const response = await client.sendRequest(method, payload, { timeoutMs }) + if (!response.ok) { + throw new Error(response.error.message) + } + 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) + ) + } + return result as T +} 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..fce514a67cff --- /dev/null +++ b/mobile/src/tasks/native-host-task-project-read-operations.ts @@ -0,0 +1,122 @@ +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 }), + 'Failed to load labels' + ) + return result.labels ?? [] + }, + async listItemAssignableUsers(payload) { + const result = await projectResult<{ + users?: Awaited> + }>( + client.sendRequest('github.project.listAssignableUsersBySlug', payload, { + timeoutMs: 30_000 + }), + 'Failed to load assignees' + ) + return result.users ?? [] + }, + async listIssueTypes(payload) { + const result = await projectResult<{ + types?: Awaited> + }>( + client.sendRequest('github.project.listIssueTypesBySlug', payload, { + timeoutMs: 30_000 + }), + 'Failed to load issue types' + ) + return result.types ?? [] + } + } +} + +/** `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 ?? 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-provider-write-operations.ts b/mobile/src/tasks/native-host-task-provider-write-operations.ts new file mode 100644 index 000000000000..eaac26ae5b30 --- /dev/null +++ b/mobile/src/tasks/native-host-task-provider-write-operations.ts @@ -0,0 +1,51 @@ +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 === 'github' ? 'GitHub' : 'GitLab'} 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..e1b1fa347cb7 --- /dev/null +++ b/mobile/src/tasks/native-host-task-read-operations.ts @@ -0,0 +1,104 @@ +import type { GitHubOwnerRepo } from '../../../src/shared/github/pull-request-types' +import { MOBILE_TASKS_CAPABILITY } from './mobile-tasks-capability' +import type { + HostTaskBootstrap, + 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' + +export function nativeHostTaskReadOperations(client: RpcRequestSender): HostTaskReadOperations { + return { + tasksSupported: () => tasksSupported(client), + bootstrap: () => bootstrap(client), + listRepositories: () => listRepositories(client), + linearStatus: () => linearStatus(client), + linearTeams: (workspaceId) => linearTeams(client, workspaceId), + resolveGitHubRepoSlug: (repoId) => resolveGitHubRepoSlug(client, repoId) + } +} + +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 [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 { + 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) + return (response.result as { repos: HostTaskRepository[] }).repos +} + +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(response) + return response.result as HostTaskLinearTeams +} + +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 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-fan-out.test.ts b/mobile/src/tasks/smart-source-fan-out.test.ts index cffdc287e22f..94918d7707fc 100644 --- a/mobile/src/tasks/smart-source-fan-out.test.ts +++ b/mobile/src/tasks/smart-source-fan-out.test.ts @@ -1,25 +1,39 @@ 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' +import type { RpcRequestSender } from '../transport/rpc-client' +import { + searchBranches, + searchGitHubItems, + searchGitLabItems, + searchLinearIssues +} from './smart-source-search-requests' type Call = { method: string; params: Record } -function fakeClient(byMethod: Record, calls: Call[]): RpcClient { - 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' } - } +/** 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 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 { id: '1', ok: true, result: result ?? { items: [] }, _meta: { runtimeId: 'r' } } + return { ok: true as const, result: scripted ?? {} } } - } as unknown as RpcClient + } as unknown as RpcRequestSender + 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) + } as unknown as HostWorkspaceCreationOperations } const smartArgs = { @@ -36,7 +50,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 +59,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 +75,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 +84,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/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/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-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-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-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-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..fd38d089b57f 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,10 +125,10 @@ export function useMobileTasksProjectDetailLoading(model: ItemDetailLoadingModel } }, [ activeGitHubProjectHost, - client, githubProjectTable, projectRowDetailRefreshSeq, projectRowItem, + taskOperations, tasksSupported ]) return model 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..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 @@ -1,20 +1,20 @@ 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 { + projectRowPullRequestTarget, + taskItemMutationTarget +} from './mobile-tasks-mutation-targets' export function useMobileTasksProjectFileMergeActions(model: ProjectReviewCheckActionsModel) { const { activeGitHubProjectHost, - client, expandedPrFilePath, findProjectRowRepo, loadTasks, @@ -34,7 +34,8 @@ export function useMobileTasksProjectFileMergeActions(model: ProjectReviewCheckA setProjectMutating, setProjectRowDetail, setProjectRowDetailError, - setProjectRowItem + setProjectRowItem, + taskOperations } = model const toggleProjectGitHubFileExpansion = useCallback( async (row: GitHubProjectRow, file: GitHubDetailFile): Promise => { @@ -47,11 +48,12 @@ export function useMobileTasksProjectFileMergeActions(model: ProjectReviewCheckA return } const repo = findProjectRowRepo(row) + const target = projectRowPullRequestTarget(row, activeGitHubProjectHost) if ( - !client || + !taskOperations || row.itemType !== 'PULL_REQUEST' || !repo || - !row.content.number || + !target || projectRowDetail?.provider !== 'github' || !projectRowDetail.headSha || !projectRowDetail.baseSha @@ -62,27 +64,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 +82,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 = projectRowPullRequestTarget(row, activeGitHubProjectHost) if ( - !client || + !taskOperations || projectMutating || row.itemType !== 'PULL_REQUEST' || !repo || - !row.content.number + !target ) { return } @@ -125,31 +115,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 +149,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 = projectRowPullRequestTarget(row, activeGitHubProjectHost) if ( - !client || + !taskOperations || projectMutating || row.itemType !== 'PULL_REQUEST' || !repo || - !row.content.number + !target ) { return } @@ -203,23 +176,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 +202,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 +226,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..30550ae1afa4 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, projectRowSlugTarget } 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,18 @@ 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) { + // 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 } 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 +116,7 @@ export function useMobileTasksProjectMetadataActions(model: ProjectThreadReplyAc setProjectMutating(false) } }, - [activeGitHubProjectHost, client, projectMutating] + [activeGitHubProjectHost, projectMutating, taskOperations] ) const mutateProjectRowField = useCallback( @@ -142,36 +125,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 +171,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 = projectRowSlugTarget(row, activeGitHubProjectHost) + if (row.itemType !== 'ISSUE' || !target || !row.content.number) { 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 +210,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..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 @@ -2,18 +2,18 @@ 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 { + projectRowIdentityTarget, + projectRowPullRequestTarget +} from './mobile-tasks-mutation-targets' export function useMobileTasksProjectReviewCheckActions(model: ProjectMetadataActionsModel) { const { activeGitHubProjectHost, - client, findProjectRowRepo, projectMutating, projectReviewersDraft, @@ -22,12 +22,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 = projectRowPullRequestTarget(row, activeGitHubProjectHost) + if ( + !taskOperations || + projectMutating || + row.itemType !== 'PULL_REQUEST' || + !repo || + !target + ) { return } const reviewers = logins ?? splitReviewerList(projectReviewersDraft) @@ -37,23 +45,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 +84,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 = projectRowPullRequestTarget(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 +122,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 = projectRowPullRequestTarget(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,15 +154,16 @@ 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) { + 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 @@ -202,23 +172,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 +197,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..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 @@ -3,19 +3,15 @@ import { useCallback } from './mobile-tasks-dependencies' import { type DetailComment, type GitHubProjectRow, - commentAuthor, - isSuccess, - projectRowGitHubRepository, - projectRowType, - splitRepositorySlug + commentAuthor } from './mobile-tasks-legacy-foundation' +import { projectRowIdentityTarget, projectRowSlugTarget } from './mobile-tasks-mutation-targets' export function useMobileTasksProjectThreadReplyActions( model: ProjectWorkspaceCommentActionsModel ) { const { activeGitHubProjectHost, - client, findProjectRowRepo, itemReplyDrafts, projectEditingCommentId, @@ -25,46 +21,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 +58,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 +80,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,15 +106,16 @@ 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) { + 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) { @@ -160,44 +129,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 +167,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..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 @@ -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,28 @@ 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) + // Adding a comment requires a repository slug, item number, and non-empty body. + const target = projectRowSlugTarget(row, activeGitHubProjectHost) const body = projectCommentDraft.trim() - if (!slug || !row.content.number || !body) { + if (!target || !row.content.number || !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 +181,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 +219,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..256b2c155c66 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, @@ -13,13 +13,10 @@ import { import { GITHUB_REPO_CONCURRENCY, type GitHubRepoSources, - type GitHubWorkItem, - type LinearStatusResponse, type LinearTeam, type RepoSummary, type TaskItem, createGitHubTask, - isSuccess, mapWithConcurrency, reconcileTeamSelection, scopeGitHubTaskSearch, @@ -29,7 +26,6 @@ import { export function useMobileTasksProviderLoadActions(model: RuntimeHydrationModel) { const { appliedQuery, - client, connState, defaultLinearTeamSelectionRef, githubKind, @@ -38,62 +34,53 @@ 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 = await taskOperations.read.linearStatus() + 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) + 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(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[] + const teams = await taskOperations.read.linearTeams(workspaceId) 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,21 +95,12 @@ 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)), sources: envelope.sources, @@ -177,24 +155,22 @@ 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 + // 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) + }) } 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..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 @@ -10,6 +10,7 @@ import { useLastConnectedAt, useRelayRecoveryStatus, useLocalSearchParams, + useMemo, useReconnectAttempt, useRef, useRouter, @@ -40,9 +41,10 @@ import { type TaskResumeState, type TaskSort, type TasksSupportState, - getTaskPresetQuery, - isSuccess + getTaskPresetQuery } from './mobile-tasks-legacy-foundation' +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 +58,18 @@ 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 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 +178,8 @@ export function useMobileTasksRouteAndItemState() { router, insets, client, + taskOperations, + taskWorkspaceCreationOperations, 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..69f7c96f3451 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 supported = await taskOperations.read.tasksSupported() 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 (!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 }) @@ -246,49 +236,26 @@ 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 [settingsResponse, uiResponse, preflightResponse, linearStatusResponse] = - await Promise.all([ - client.sendRequest('settings.get'), - client.sendRequest('ui.get'), - client.sendRequest('preflight.check'), - client.sendRequest('linear.status') - ]) + const bootstrap = await taskOperations.read.bootstrap() 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 +320,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..6444a2113d24 100644 --- a/mobile/src/tasks/use-mobile-tasks-task-list-loading.tsx +++ b/mobile/src/tasks/use-mobile-tasks-task-list-loading.tsx @@ -1,14 +1,9 @@ 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, type GitLabTodo, - type GitLabWorkItem, LINEAR_LIMIT, type TaskItem, buildPartialRepositoryNotice, @@ -16,7 +11,6 @@ import { createGitLabTask, createGitLabTodoTask, createLinearTask, - isSuccess, mapWithConcurrency, taskTime } from './mobile-tasks-legacy-foundation' @@ -26,6 +20,7 @@ export function useMobileTasksTaskListLoading(model: ProviderLoadActionsModel) { appliedQuery, client, clientRef, + taskOperations, connState, countGitHubItems, fetchGitHubItemsPage, @@ -57,12 +52,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 +110,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 +124,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 +142,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 +158,19 @@ 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)) + } } catch (err) { console.warn(`[mobile tasks] failed to fetch ${provider} work items`, repo.id, err) return { @@ -209,21 +201,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 +249,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..c746a0112f19 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,12 @@ 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) - } + // 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 + setRuntimeTaskSettings(latestRuntimeTaskSettings) } catch { // Best-effort refresh; the runtime still validates agent availability before spawning. } @@ -156,35 +156,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 +182,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 +220,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 +259,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..e01e14985aa0 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,11 +71,8 @@ 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 + const state = await taskWorkspaceCreationOperations.readSshState(repo.connectionId) + // An unregistered target answers with no state at all; leave whatever the badge shows. if (state) { setWorkspaceSshState(state) } @@ -99,11 +80,16 @@ export function useMobileTasksWorkspaceSshState(model: WorkspaceSparseActionsMod 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 +101,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 +118,7 @@ export function useMobileTasksWorkspaceSshState(model: WorkspaceSparseActionsMod stale = true } }, [ - client, + taskWorkspaceCreationOperations, tasksSupported, workspaceCreateDraft, workspaceCreateSshStatus, @@ -187,14 +167,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 +189,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 c4ca8170312b..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 } 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, @@ -32,7 +33,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 { @@ -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/terminal/terminal-input-connection-gate.test.ts b/mobile/src/terminal/terminal-input-connection-gate.test.ts index f046a674a8b1..60f6177d83d3 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,22 @@ 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(') + } + // 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 }) }) 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/transport/screen-rpc-ratchet.test.ts b/mobile/src/transport/screen-rpc-ratchet.test.ts new file mode 100644 index 000000000000..d49a896139df --- /dev/null +++ b/mobile/src/transport/screen-rpc-ratchet.test.ts @@ -0,0 +1,291 @@ +import { readFileSync, readdirSync, statSync } from 'node:fs' +import { join, relative } from 'node:path' +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), 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 + +const MOBILE_ROOT = join(__dirname, '../..') + +/** 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/files/default-host-file-explorer-operations.ts', + 'src/files/native-host-file-explorer-operations.ts', + 'src/session/default-host-session-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-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': 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-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 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'], + // 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. + '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'] +} + +/** 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 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 + } + const path = relative(MOBILE_ROOT, absolute).split('\\').join('/') + if (/\.tsx?$/.test(entry) && !NOT_SOURCE.test(path) && !ADAPTER_FILES.has(path)) { + found.push(path) + } + } + } + walk(join(MOBILE_ROOT, 'src')) + walk(join(MOBILE_ROOT, 'app')) + return found.sort() +} + +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 RPC', () => { + const regrown = ROUTED_SCREENS.filter((path) => countEntryPoints(read(path)) > 0) + expect(regrown).toEqual([]) + }) + + 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, + [...read(path).matchAll(/sendRequest\(\s*'([\w.]+)'/g)].map((match) => match[1]).sort() + ]) + ) + const expected = Object.fromEntries( + Object.entries(DELIBERATE_INLINE_CALLS).map(([path, methods]) => [path, [...methods].sort()]) + ) + expect(actual).toEqual(expected) + }) + + 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-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/host-workspace-creation-operations.ts b/mobile/src/worktree/host-workspace-creation-operations.ts new file mode 100644 index 000000000000..cfe87661f708 --- /dev/null +++ b/mobile/src/worktree/host-workspace-creation-operations.ts @@ -0,0 +1,90 @@ +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 { NewWorktreeRuntimeCapabilities } from '../tasks/worktree-create-capability' +import type { MrStateFilter } from '../tasks/mobile-composer-source-types' +import type { + ComposerHostedBase, + ResolveComposerMrBaseArgs, + ResolveComposerPrBaseArgs +} from '../tasks/composer-source-base-resolve' +import type { SetupHookTrust } from '../tasks/setup-hook-trust' +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 = { + 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 HostWorkspaceCreationOperations = { + listRepositories(): Promise + readRetiredWorktreeNames(repoId: string): Promise + /** Null when the host answers without a settings key: the caller keeps what it has. */ + readRuntimeSettings(): Promise + readTrustedHooks(): Promise + isGitLabCliInstalled(): Promise + isLinearConnected(): 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 + /** 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( + 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 +} 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..899bccec1718 --- /dev/null +++ b/mobile/src/worktree/native-host-workspace-creation-operations.test.ts @@ -0,0 +1,157 @@ +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('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() + .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..97155e36f540 --- /dev/null +++ b/mobile/src/worktree/native-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 { rpcWorkspaceCreationOperations } from './rpc-workspace-creation-operations' + +export function nativeHostWorkspaceCreationOperations( + client: RpcClient +): HostWorkspaceCreationOperations { + return rpcWorkspaceCreationOperations(client) +} 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..3ba17510513e --- /dev/null +++ b/mobile/src/worktree/native-host-workspace-creation-read-operations.ts @@ -0,0 +1,124 @@ +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' + | 'readRepoHooksIfAvailable' + | '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) { + // 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 }>( + client.sendRequest('settings.get') + ) + return result.settings ?? null + }, + 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 ?? null + }, + 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}` }) + ) + }, + 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) + } + } +} + +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/rpc-workspace-creation-operations.ts b/mobile/src/worktree/rpc-workspace-creation-operations.ts new file mode 100644 index 000000000000..1b8e5f4e2600 --- /dev/null +++ b/mobile/src/worktree/rpc-workspace-creation-operations.ts @@ -0,0 +1,48 @@ +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' + +/** 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 +): HostWorkspaceCreationOperations { + 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 }) + } +} 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) }