From d322fa083dee27822526819cf2c95eeb8b2cbaa7 Mon Sep 17 00:00:00 2001 From: Jinjing <6427696+AmethystLiang@users.noreply.github.com> Date: Thu, 12 Nov 2026 16:34:01 -0800 Subject: [PATCH] fix(mobile): open a linked workspace root from a chat link --- .../mobile-file-tap-open.test.ts | 54 +++++++ .../session-documents/mobile-file-tap-open.ts | 31 +++- .../use-mobile-file-tap-handlers.test.tsx | 144 ++++++++++++++++++ .../use-mobile-file-tap-handlers.ts | 21 ++- .../tabs/opened-mobile-session-tab.test.ts | 18 +++ .../session/tabs/opened-mobile-session-tab.ts | 3 + .../connection/client-authority-epoch.test.ts | 34 +++++ .../connection/client-authority-epoch.ts | 44 ++++++ ...ime-files-terminal-artifact-grants.test.ts | 38 +++++ .../terminal/terminal-path-resolver.ts | 17 +++ 10 files changed, 400 insertions(+), 4 deletions(-) create mode 100644 mobile/src/files/session-documents/use-mobile-file-tap-handlers.test.tsx create mode 100644 mobile/src/session/tabs/opened-mobile-session-tab.test.ts create mode 100644 mobile/src/transport/connection/client-authority-epoch.test.ts create mode 100644 mobile/src/transport/connection/client-authority-epoch.ts diff --git a/mobile/src/files/session-documents/mobile-file-tap-open.test.ts b/mobile/src/files/session-documents/mobile-file-tap-open.test.ts index 778676c0d8e..94ab9f2357d 100644 --- a/mobile/src/files/session-documents/mobile-file-tap-open.test.ts +++ b/mobile/src/files/session-documents/mobile-file-tap-open.test.ts @@ -85,4 +85,58 @@ describe('openMobileFileTap', () => { ) expect(opened).toEqual([{ worktree: 'id:wt-1', relativePath: 'src/file19.ts' }]) }) + + function openLinkedWorkspaceRoot(sourceAuthorityCurrent: boolean) { + const calls = { openWorkspace: vi.fn(), pushPreviewRoute: vi.fn(), onOpenFailed: vi.fn() } + openMobileFileTap({ + client: { + sendRequest: vi + .fn(async (method) => { + throw new Error(`no scripted response for ${method}`) + }) + .mockResolvedValueOnce( + ok({ + worktree: 'wt-2', + relativePath: '', + absolutePath: '/workspaces/wt-2', + exists: true, + isDirectory: true + }) + ) + }, + hostId: 'host-1', + worktreeId: 'wt-1', + candidates: [{ pathText: '/workspaces/wt-2', line: null, column: null }], + openBrowser: vi.fn(), + triggerOpenFeedback: vi.fn(), + fetchSessionTabs: vi.fn(), + getSessionTabs: () => [], + getActiveSessionTabId: () => null, + getActivationState: (activated) => ({ + ...activeTerminalState(activated), + sourceAuthorityCurrent + }), + switchSessionTab: vi.fn(), + scheduleDelayedAction: vi.fn(), + ...calls + }) + return calls + } + + it("opens the workspace when the link is another workspace's root", async () => { + const calls = openLinkedWorkspaceRoot(true) + await vi.advanceTimersByTimeAsync(0) + + expect(calls.openWorkspace.mock.calls).toEqual([['wt-2']]) + expect(calls.onOpenFailed).not.toHaveBeenCalled() + }) + + it('drops a workspace-root reply that outlived its host authority', async () => { + const calls = openLinkedWorkspaceRoot(false) + await vi.advanceTimersByTimeAsync(0) + + expect(calls.openWorkspace).not.toHaveBeenCalled() + expect(calls.pushPreviewRoute).not.toHaveBeenCalled() + expect(calls.onOpenFailed).not.toHaveBeenCalled() + }) }) diff --git a/mobile/src/files/session-documents/mobile-file-tap-open.ts b/mobile/src/files/session-documents/mobile-file-tap-open.ts index cabeebe5a3d..f08eed88cad 100644 --- a/mobile/src/files/session-documents/mobile-file-tap-open.ts +++ b/mobile/src/files/session-documents/mobile-file-tap-open.ts @@ -50,6 +50,8 @@ export type OpenMobileFileTapOptions = { scheduleDelayedAction: (callback: () => void, delayMs: number) => unknown // Callers choose whether unresolved guesses need feedback. onOpenFailed?: (failure: MobileFileTapFailure) => void + // Given by surfaces where a link to another workspace's root should open that workspace. + openWorkspace?: (worktreeId: string) => void } export function openMobileFileTap( @@ -83,7 +85,22 @@ function requestFileTapResolution( ) } -function existingFileTapResolution( +function linkedWorkspaceId( + options: OpenMobileFileTapOptions, + resolved: RuntimeTerminalPathResolution +): string | null { + const worktreeId = resolved.worktree?.trim() + return options.openWorkspace && + resolved.isDirectory && + resolved.relativePath === '' && + worktreeId && + worktreeId !== options.worktreeId + ? worktreeId + : null +} + +function existingFileTapResolution( + options: OpenMobileFileTapOptions, response: RpcResponse | null ): RuntimeTerminalPathResolution | null { const accepted = response ? fileTapPathResolve.interpret(response) : null @@ -92,7 +109,9 @@ function existingFileTapResolution( } // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: Preserve the established response shape at this boundary. const resolved = accepted.value as RuntimeTerminalPathResolution - return resolved.exists && !resolved.isDirectory ? resolved : null + return resolved.exists && (!resolved.isDirectory || linkedWorkspaceId(options, resolved)) + ? resolved + : null } function reportOpenFailure( @@ -119,7 +138,7 @@ async function openMobileFileTapAsync( async (target) => { // Why: a reading the host cannot answer must not hide a sibling. const response = await requestFileTapResolution(options, target.pathText).catch(() => null) - return { target, response, resolved: existingFileTapResolution(response) } + return { target, response, resolved: existingFileTapResolution(options, response) } } ) const found = readings.reduce<(typeof readings)[number] | undefined>( @@ -152,6 +171,12 @@ async function openResolvedMobileFileTap( if (!shouldActivateOpenedMobileSessionTab(options.getActivationState(false))) { return } + const linkedWorkspace = linkedWorkspaceId(options, resolved) + if (linkedWorkspace) { + options.triggerOpenFeedback() + options.openWorkspace?.(linkedWorkspace) + return + } const resolvedWorktreeId = resolved.worktree?.trim() || options.worktreeId const resolvedWorktree = `id:${resolvedWorktreeId}` const resolvedWorktreeName = diff --git a/mobile/src/files/session-documents/use-mobile-file-tap-handlers.test.tsx b/mobile/src/files/session-documents/use-mobile-file-tap-handlers.test.tsx new file mode 100644 index 00000000000..094289cb6e5 --- /dev/null +++ b/mobile/src/files/session-documents/use-mobile-file-tap-handlers.test.tsx @@ -0,0 +1,144 @@ +import { createElement } from 'react' +import { act, create, type ReactTestRenderer } from 'react-test-renderer' +import { beforeEach, describe, expect, it, vi } from 'vitest' +import type { RpcResponse } from '../../transport/rpc/rpc-wire-types' + +const push = vi.hoisted(() => vi.fn()) +vi.mock('../../navigation/workspace-execution-host', () => ({ + useWorkspaceExecutionHost: () => undefined +})) +vi.mock('../../navigation/workspace-route-handoff', () => ({ + useWorkspaceRouteHandoff: () => ({ push }) +})) +vi.mock('../../platform/haptics', () => ({ triggerSelection: () => {} })) + +import { useMobileFileTapHandlers } from './use-mobile-file-tap-handlers' + +type Client = { + getGeneration: () => number + sendRequest: () => Promise +} + +const SIBLING_ROOT: RpcResponse = { + id: 'rpc', + ok: true, + result: { + worktree: 'wt-2', + relativePath: '', + absolutePath: '/workspaces/wt-2', + exists: true, + isDirectory: true + }, + _meta: { runtimeId: 'runtime-1' } +} + +function mountChat() { + let generation = 1 + let reply: (response: RpcResponse) => void = () => {} + const createClient = (): Client => ({ + getGeneration: () => generation, + sendRequest: () => + new Promise((resolve) => { + reply = resolve + }) + }) + const reportChatTapFailure = vi.fn() + let tap: (pathText: string) => void = () => {} + const stable = { + nativeChatSessionId: 'session-1', + activeHandleRef: { current: null }, + terminalCwdRef: { current: new Map() }, + openBrowser: () => {}, + fetchSessionTabs: async () => {}, + getSessionTabs: () => [], + getActiveSessionTabId: () => 'chat-tab', + getActiveSessionTabType: () => 'agent-session', + switchSessionTab: () => {}, + scheduleDelayedAction: () => {}, + reportChatTapFailure, + // Held constant so only the authority fence can drop the reply. + getSendCompletionGeneration: () => 1 + } + function Probe(props: { client: Client; hostId: string }) { + tap = useMobileFileTapHandlers({ + ...stable, + ...props, + worktreeId: 'wt-1' + }).handleNativeChatFileTap + return null + } + const first = createClient() + let renderer!: ReactTestRenderer + act(() => { + renderer = create(createElement(Probe, { client: first, hostId: 'host-a' })) + }) + return { + first, + createClient, + reportChatTapFailure, + tap: () => tap('/workspaces/wt-2'), + render: (client: Client, hostId: string) => + act(() => renderer.update(createElement(Probe, { client, hostId }))), + moveGeneration: () => { + generation = 2 + }, + reply: async () => { + await act(async () => { + reply(SIBLING_ROOT) + await new Promise((resolve) => setTimeout(resolve, 0)) + }) + } + } +} + +describe('useMobileFileTapHandlers workspace-root reply', () => { + beforeEach(() => { + push.mockClear() + }) + + it('opens the linked workspace on the tapped host', async () => { + const chat = mountChat() + chat.tap() + await chat.reply() + + expect(push.mock.calls).toEqual([ + [ + { + pathname: '/h/[hostId]/session/[worktreeId]', + params: { hostId: 'host-a', worktreeId: 'wt-2' } + } + ] + ]) + }) + + it('drops the reply after the client is replaced on the same host', async () => { + const chat = mountChat() + chat.tap() + chat.render(chat.createClient(), 'host-a') + await chat.reply() + + expect(push).not.toHaveBeenCalled() + expect(chat.reportChatTapFailure).not.toHaveBeenCalled() + }) + + it('drops the reply after the host changes away and back', async () => { + const chat = mountChat() + chat.tap() + chat.render(chat.first, 'host-b') + chat.render(chat.first, 'host-a') + await chat.reply() + + expect(push).not.toHaveBeenCalled() + expect(chat.reportChatTapFailure).not.toHaveBeenCalled() + }) + + it('drops the reply after the client generation moves with no render', async () => { + const chat = mountChat() + chat.tap() + chat.moveGeneration() + await chat.reply() + + expect(push).not.toHaveBeenCalled() + expect(chat.reportChatTapFailure).not.toHaveBeenCalled() + }) +}) diff --git a/mobile/src/files/session-documents/use-mobile-file-tap-handlers.ts b/mobile/src/files/session-documents/use-mobile-file-tap-handlers.ts index 31752b15f51..6e455fdbb86 100644 --- a/mobile/src/files/session-documents/use-mobile-file-tap-handlers.ts +++ b/mobile/src/files/session-documents/use-mobile-file-tap-handlers.ts @@ -2,14 +2,18 @@ import { isCommittedChatAttachmentCandidate } from '../../../../src/shared/nativ import { createMobileFilePreviewHref } from '../mobile-file-preview-route' import { useCallback, useLayoutEffect, useRef, type MutableRefObject } from 'react' import type { ParsedFileLinkLocation } from '../../../../src/shared/file-links/file-link-location' +import { hostStackRouteHref } from '../../navigation/host-stack-navigation' +import { useWorkspaceExecutionHost } from '../../navigation/workspace-execution-host' import { useWorkspaceRouteHandoff } from '../../navigation/workspace-route-handoff' import { triggerSelection } from '../../platform/haptics' import { openMobileFileTap, type FileTapSessionTab } from './mobile-file-tap-open' +import { mobileSessionRouteTarget } from '../../session/mobile-session-route' import { openMobileNativeChatFileTap } from '../../session/native-chat/visual/mobile-native-chat-open-file' +import { createClientAuthorityEpoch } from '../../transport/connection/client-authority-epoch' import type { UnvalidatedRpcRequestPort } from '../../transport/rpc/unvalidated-rpc-request-port' type MobileFileTapHandlerOptions = { - client: UnvalidatedRpcRequestPort | null + client: (UnvalidatedRpcRequestPort & { getGeneration?: () => number }) | null hostId: string worktreeId: string worktreeName?: string @@ -56,11 +60,14 @@ export function useMobileFileTapHandlers( } = options const router = useWorkspaceRouteHandoff() const routerRef = useRef(router) + const executionHost = useWorkspaceExecutionHost() + const authorityRef = useRef(createClientAuthorityEpoch()) const optionsRef = useRef(options) const activationSeqRef = useRef(0) useLayoutEffect(() => { routerRef.current = router + authorityRef.current.update({ client, hostId, executionHost, worktreeId }) optionsRef.current = { activeHandleRef, client, @@ -83,6 +90,7 @@ export function useMobileFileTapHandlers( }, [ activeHandleRef, client, + executionHost, fetchSessionTabs, getActiveSessionTabId, getActiveSessionTabType, @@ -113,6 +121,7 @@ export function useMobileFileTapHandlers( } const activationSeq = ++activationSeqRef.current const sourceNavigationGeneration = current.getSendCompletionGeneration() + const sourceAuthority = authorityRef.current.token() openMobileFileTap({ client: current.client, hostId: current.hostId, @@ -133,6 +142,7 @@ export function useMobileFileTapHandlers( latestActivationSeq: activationSeqRef.current, sourceNavigationGeneration, activeNavigationGeneration: current.getSendCompletionGeneration(), + sourceAuthorityCurrent: authorityRef.current.isCurrent(sourceAuthority), sourceTerminalHandle: handle, activeTerminalHandle: current.activeHandleRef.current, activeTabType: current.getActiveSessionTabType() @@ -171,6 +181,7 @@ export function useMobileFileTapHandlers( } const activationSeq = ++activationSeqRef.current const sourceNavigationGeneration = current.getSendCompletionGeneration() + const sourceAuthority = authorityRef.current.token() openMobileNativeChatFileTap({ client: current.client, hostId: current.hostId, @@ -182,6 +193,13 @@ export function useMobileFileTapHandlers( ? { tabId: nativeChatTabId, sessionId: nativeChatSessionId } : null, pushPreviewRoute: (href) => routerRef.current.push(href), + // Chat only: terminal output is full of bare directory paths, so a mis-tap there would jump workspaces. + openWorkspace: (linkedWorktreeId) => + routerRef.current.push( + hostStackRouteHref( + mobileSessionRouteTarget({ hostId: current.hostId, worktreeId: linkedWorktreeId }) + ) + ), openBrowser: current.openBrowser, triggerOpenFeedback: triggerSelection, fetchSessionTabs: current.fetchSessionTabs, @@ -193,6 +211,7 @@ export function useMobileFileTapHandlers( latestActivationSeq: activationSeqRef.current, sourceNavigationGeneration, activeNavigationGeneration: current.getSendCompletionGeneration(), + sourceAuthorityCurrent: authorityRef.current.isCurrent(sourceAuthority), sourceTerminalHandle, activeTerminalHandle: current.activeHandleRef.current, sourceSessionTabId: nativeChatTabId, diff --git a/mobile/src/session/tabs/opened-mobile-session-tab.test.ts b/mobile/src/session/tabs/opened-mobile-session-tab.test.ts new file mode 100644 index 00000000000..82566666b2d --- /dev/null +++ b/mobile/src/session/tabs/opened-mobile-session-tab.test.ts @@ -0,0 +1,18 @@ +import { expect, it } from 'vitest' +import { shouldActivateOpenedMobileSessionTab } from './opened-mobile-session-tab' + +it('refuses a completion whose host authority is no longer current', () => { + const state = { + activated: false, + activationSeq: 1, + latestActivationSeq: 1, + sourceTerminalHandle: 'terminal-1', + activeTerminalHandle: 'terminal-1', + activeTabType: 'terminal' + } + + expect(shouldActivateOpenedMobileSessionTab(state)).toBe(true) + expect(shouldActivateOpenedMobileSessionTab({ ...state, sourceAuthorityCurrent: false })).toBe( + false + ) +}) diff --git a/mobile/src/session/tabs/opened-mobile-session-tab.ts b/mobile/src/session/tabs/opened-mobile-session-tab.ts index 2f320e43c7f..a8546c8e31e 100644 --- a/mobile/src/session/tabs/opened-mobile-session-tab.ts +++ b/mobile/src/session/tabs/opened-mobile-session-tab.ts @@ -9,6 +9,8 @@ export type OpenedMobileSessionTabActivationState = { activeTabType: string | null sourceNavigationGeneration?: number activeNavigationGeneration?: number + // False once the host, client or its authority generation changed after the tap; absent means unfenced. + sourceAuthorityCurrent?: boolean } export function shouldActivateOpenedMobileSessionTab( @@ -26,6 +28,7 @@ export function shouldActivateOpenedMobileSessionTab( !state.activated && state.activationSeq === state.latestActivationSeq && state.sourceNavigationGeneration === state.activeNavigationGeneration && + state.sourceAuthorityCurrent !== false && sourceStillActive ) } diff --git a/mobile/src/transport/connection/client-authority-epoch.test.ts b/mobile/src/transport/connection/client-authority-epoch.test.ts new file mode 100644 index 00000000000..4d68231d091 --- /dev/null +++ b/mobile/src/transport/connection/client-authority-epoch.test.ts @@ -0,0 +1,34 @@ +import { describe, expect, it } from 'vitest' +import { createClientAuthorityEpoch } from './client-authority-epoch' + +describe('createClientAuthorityEpoch', () => { + it('keeps a token stale after the host changes away and back with the same client', () => { + const epoch = createClientAuthorityEpoch() + const client = { getGeneration: () => 1 } + const hostA = { client, hostId: 'host-a', executionHost: undefined, worktreeId: 'wt-1' } + epoch.update(hostA) + const token = epoch.token() + expect(epoch.isCurrent(token)).toBe(true) + + epoch.update({ ...hostA, hostId: 'host-b' }) + epoch.update(hostA) + + expect(epoch.isCurrent(token)).toBe(false) + }) + + it('expires a token when the client generation moves without a new update', () => { + const epoch = createClientAuthorityEpoch() + let generation = 1 + epoch.update({ + client: { getGeneration: () => generation }, + hostId: 'host-a', + executionHost: undefined, + worktreeId: 'wt-1' + }) + const token = epoch.token() + + generation = 2 + + expect(epoch.isCurrent(token)).toBe(false) + }) +}) diff --git a/mobile/src/transport/connection/client-authority-epoch.ts b/mobile/src/transport/connection/client-authority-epoch.ts new file mode 100644 index 00000000000..d233ad2149d --- /dev/null +++ b/mobile/src/transport/connection/client-authority-epoch.ts @@ -0,0 +1,44 @@ +type AuthorityClient = { getGeneration?: () => number } + +export type ClientAuthority = { + client: AuthorityClient | null + hostId: string + executionHost: string | undefined + worktreeId: string +} + +export type ClientAuthorityToken = readonly [ + epoch: number, + client: AuthorityClient | null, + generation: number | undefined +] + +// A monotonic count of authority changes, so work started under A is stale after A→B→A. +export function createClientAuthorityEpoch(): { + update: (authority: ClientAuthority) => void + token: () => ClientAuthorityToken + isCurrent: (token: ClientAuthorityToken) => boolean +} { + let epoch = 0 + let last: ClientAuthority | null = null + return { + update(authority) { + if ( + last && + (last.client !== authority.client || + last.hostId !== authority.hostId || + last.executionHost !== authority.executionHost || + last.worktreeId !== authority.worktreeId) + ) { + epoch += 1 + } + last = authority + }, + token: () => [epoch, last?.client ?? null, last?.client?.getGeneration?.()], + // Reads the generation live: migrateTo moves it without a render. + isCurrent: ([tokenEpoch, client, generation]) => + tokenEpoch === epoch && + client === (last?.client ?? null) && + generation === client?.getGeneration?.() + } +} diff --git a/src/main/runtime/terminal/artifacts/orca-runtime-files-terminal-artifact-grants.test.ts b/src/main/runtime/terminal/artifacts/orca-runtime-files-terminal-artifact-grants.test.ts index df795e843f5..f48d09c1af9 100644 --- a/src/main/runtime/terminal/artifacts/orca-runtime-files-terminal-artifact-grants.test.ts +++ b/src/main/runtime/terminal/artifacts/orca-runtime-files-terminal-artifact-grants.test.ts @@ -7,6 +7,7 @@ import { describe, expect, it, vi } from 'vitest' import { realpath } from 'node:fs/promises' import { useRuntimeFileHostLifecycle } from '../../files/runtime-file-host.test-fixture' +import { resolveAuthorizedPathMock, statMock } from '../../files/runtime-file-command-mock-registry' vi.mock('fs', async () => (await import('../../files/runtime-file-command-mock-registry')).fsModuleMock() @@ -78,6 +79,43 @@ describe('RuntimeTerminalArtifacts', () => { ).resolves.toEqual({ ok: true }) }) + it('answers the root of a workspace nested inside the tapped one as that workspace', async () => { + resolveAuthorizedPathMock.mockImplementation(async (p: string) => p) + statMock.mockResolvedValue({ isDirectory: () => true, size: 0, dev: 1, ino: 2, mtimeMs: 3 }) + const resolveKnownWorkspaceFileTarget = vi.fn(async (absolutePath: string) => + absolutePath === '/repo/worktrees/wt-2' + ? { + worktree: { id: 'wt-2', repoId: 'repo-1', path: '/repo/worktrees/wt-2' }, + executionHostId: 'local', + relativePath: '' + } + : { + worktree: { id: 'wt-1', repoId: 'repo-1', path: '/repo' }, + executionHostId: 'local', + relativePath: 'src' + } + ) + const { paths } = createTerminalArtifactSubjects({ + path: '/repo', + resolveKnownWorkspaceFileTarget + }) + const resolve = (pathText: string) => + paths.resolveTerminalPath('id:wt-1', pathText, null, 'client-a', null, true) + + expect(await resolve('/repo/worktrees/wt-2')).toEqual({ + worktree: 'wt-2', + relativePath: '', + absolutePath: '/repo/worktrees/wt-2', + exists: true, + isDirectory: true + }) + expect(await resolve('/repo/src')).toMatchObject({ + worktree: 'wt-1', + relativePath: 'src', + isDirectory: true + }) + }) + // Why: procfs reports size 0 for files with content, so the grant digest cannot trust stat size. it.runIf(process.platform === 'linux')('reads a procfs file that reports size 0', async () => { const { paths, commands } = createTerminalArtifactSubjects({ path: '/repo' }) diff --git a/src/main/runtime/terminal/terminal-path-resolver.ts b/src/main/runtime/terminal/terminal-path-resolver.ts index b6bc4130ca1..901b6c972e4 100644 --- a/src/main/runtime/terminal/terminal-path-resolver.ts +++ b/src/main/runtime/terminal/terminal-path-resolver.ts @@ -116,6 +116,23 @@ export class RuntimeTerminalPathResolver { absolutePath ) ).type === 'directory' + // Why: a workspace nested inside this one is inside its root, so the outside-root lookup above never sees it. + const nestedWorkspace = + crossWorkspace && isDirectory && !knownWorkspaceTarget && ownedRelativePath !== '' + ? await this.host.resolveKnownWorkspaceFileTarget?.( + absolutePath, + target.executionHostId + ) + : null + if (nestedWorkspace?.relativePath === '') { + return { + worktree: nestedWorkspace.worktree.id, + relativePath: '', + absolutePath, + exists: true, + isDirectory: true + } + } return { worktree: ownedWorktree.id, relativePath: ownedRelativePath,