fix(mobile): open a linked workspace root from a chat link

This commit is contained in:
Jinjing
2026-11-12 16:34:01 -08:00
parent c702d7e20c
commit d322fa083d
10 changed files with 400 additions and 4 deletions
@@ -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<SendRequest>(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()
})
})
@@ -50,6 +50,8 @@ export type OpenMobileFileTapOptions<T extends FileTapSessionTab> = {
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<T extends FileTapSessionTab>(
@@ -83,7 +85,22 @@ function requestFileTapResolution<T extends FileTapSessionTab>(
)
}
function existingFileTapResolution(
function linkedWorkspaceId<T extends FileTapSessionTab>(
options: OpenMobileFileTapOptions<T>,
resolved: RuntimeTerminalPathResolution
): string | null {
const worktreeId = resolved.worktree?.trim()
return options.openWorkspace &&
resolved.isDirectory &&
resolved.relativePath === '' &&
worktreeId &&
worktreeId !== options.worktreeId
? worktreeId
: null
}
function existingFileTapResolution<T extends FileTapSessionTab>(
options: OpenMobileFileTapOptions<T>,
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<T extends FileTapSessionTab>(
@@ -119,7 +138,7 @@ async function openMobileFileTapAsync<T extends FileTapSessionTab>(
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<T extends FileTapSessionTab>(
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 =
@@ -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<RpcResponse>
}
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<string, string>() },
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()
})
})
@@ -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<T extends FileTapSessionTab> = {
client: UnvalidatedRpcRequestPort | null
client: (UnvalidatedRpcRequestPort & { getGeneration?: () => number }) | null
hostId: string
worktreeId: string
worktreeName?: string
@@ -56,11 +60,14 @@ export function useMobileFileTapHandlers<T extends FileTapSessionTab>(
} = 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<T extends FileTapSessionTab>(
}, [
activeHandleRef,
client,
executionHost,
fetchSessionTabs,
getActiveSessionTabId,
getActiveSessionTabType,
@@ -113,6 +121,7 @@ export function useMobileFileTapHandlers<T extends FileTapSessionTab>(
}
const activationSeq = ++activationSeqRef.current
const sourceNavigationGeneration = current.getSendCompletionGeneration()
const sourceAuthority = authorityRef.current.token()
openMobileFileTap<T>({
client: current.client,
hostId: current.hostId,
@@ -133,6 +142,7 @@ export function useMobileFileTapHandlers<T extends FileTapSessionTab>(
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<T extends FileTapSessionTab>(
}
const activationSeq = ++activationSeqRef.current
const sourceNavigationGeneration = current.getSendCompletionGeneration()
const sourceAuthority = authorityRef.current.token()
openMobileNativeChatFileTap<T>({
client: current.client,
hostId: current.hostId,
@@ -182,6 +193,13 @@ export function useMobileFileTapHandlers<T extends FileTapSessionTab>(
? { 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<T extends FileTapSessionTab>(
latestActivationSeq: activationSeqRef.current,
sourceNavigationGeneration,
activeNavigationGeneration: current.getSendCompletionGeneration(),
sourceAuthorityCurrent: authorityRef.current.isCurrent(sourceAuthority),
sourceTerminalHandle,
activeTerminalHandle: current.activeHandleRef.current,
sourceSessionTabId: nativeChatTabId,
@@ -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
)
})
@@ -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
)
}
@@ -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)
})
})
@@ -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?.()
}
}
@@ -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' })
@@ -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,