fix(mobile): open the Resume workspace through a mounted host stack (#12001)

* fix(mobile): open the Resume workspace through a mounted host stack

Tapping Resume on Home landed on a blank host screen instead of the
session. A cold push straight into the nested /h/[hostId] navigator
resolves to the host index route without the dynamic id, so
HostProtocolGate mounts with hostId undefined and never connects.

Home already worked around this for the host editor (#11635) and Tasks
(#11853) by mounting /h/[hostId] first and replacing it once the stack
is committed. Extract that mechanism into host-stack-navigation so
Resume uses the same transition instead of a direct push.

The previous Resume fix (#11876) swapped the manual href for a typed
dynamic href, but expo-router's encodeParam already applies
encodeURIComponent to dynamic segments, so it resolved to the same URL
the manual string produced and left the cold-navigator path unchanged.

Claude-Session: https://claude.ai/code/session_01RMoaxp7MLg2ydP28KFLX7B

* fix(mobile): harden the host-stack transition after bot review

- match a host route committed as the encoded segment it was pushed as,
  so an id containing `/`, `#`, or `%` still triggers the REPLACE
- share one pending transition across the Home entry points; per-hook
  refs let a Tasks tap and a Resume tap arm two pushes that could not
  cancel each other
- assert the source markers before slicing in the Resume wiring test

Claude-Session: https://claude.ai/code/session_01RMoaxp7MLg2ydP28KFLX7B

* test(mobile): lock the host-stack transition state machine

Assert the replace waits for the host mount (zero dispatches before it,
exactly one after), and cover cancel/retarget — the paths the shared
pending transition relies on.

* test(mobile): model listener removal in the navigation harness

A no-op unsubscribe let setState keep calling a canceled listener, so the
teardown assertions only exercised the active guard. Dropping the
unsubscribe call from dispose now fails the suite.

---------

Co-authored-by: kaynan <kaynan.camargo@terceiro-sky.com.br>
This commit is contained in:
Kaynan Sampaio de Camargo
2026-08-04 16:06:37 -07:00
committed by GitHub
co-authored by kaynan
parent 535b5a594d
commit 7948e46db8
9 changed files with 512 additions and 179 deletions
+7 -8
View File
@@ -54,7 +54,7 @@ import {
} from '../src/tasks/mobile-task-providers'
import { useOpenMobileTasks } from '../src/tasks/use-open-mobile-tasks'
import { useResponsiveLayout } from '../src/layout/responsive-layout'
import { createMobileSessionHref } from '../src/session/mobile-session-route'
import { useOpenMobileSession } from '../src/session/use-open-mobile-session'
function endpointLabel(endpoint: string): string {
try {
@@ -208,6 +208,7 @@ export default function HomeScreen() {
const router = useRouter()
const openMobileHostEdit = useOpenMobileHostEdit()
const openMobileTasks = useOpenMobileTasks()
const openMobileSession = useOpenMobileSession()
const insets = useSafeAreaInsets()
// Why: cap/center content on wide/tablet canvases so cards don't stretch edge-to-edge on iPad.
const { isWideLayout, contentMaxWidth } = useResponsiveLayout()
@@ -737,13 +738,11 @@ export default function HomeScreen() {
<Pressable
style={({ pressed }) => [styles.resumeCard, pressed && styles.hostCardPressed]}
onPress={() =>
router.push(
createMobileSessionHref({
hostId: resumeWorktree.hostId,
worktreeId: resumeWorktree.worktree.worktreeId,
name: resumeWorktree.worktree.displayName || resumeWorktree.worktree.repo
})
)
openMobileSession({
hostId: resumeWorktree.hostId,
worktreeId: resumeWorktree.worktree.worktreeId,
name: resumeWorktree.worktree.displayName || resumeWorktree.worktree.repo
})
}
>
<View style={styles.resumeIcon}>
@@ -0,0 +1,141 @@
import { describe, expect, it, vi } from 'vitest'
import {
coordinateHostStackNavigation,
hostStackHostRoute,
navigateToHostStackRoute,
type HostStackNavigationState
} from './host-stack-navigation'
const TARGET = { name: '[hostId]/tasks', params: { hostId: 'host/one' } } as const
const OTHER_TARGET = {
name: '[hostId]/session/[worktreeId]',
params: { hostId: 'host/one', worktreeId: 'repo::/tmp/wt' }
} as const
// Removal is modeled for real: a no-op unsubscribe would let `setState` keep
// calling a canceled listener, testing the `active` guard instead of teardown.
function navigationHarness(initialState: HostStackNavigationState) {
const stateListeners = new Set<() => void>()
let state = initialState
const unsubscribe = vi.fn()
const navigation = {
addListener: vi.fn((_event: 'state', listener: () => void) => {
stateListeners.add(listener)
return () => {
unsubscribe()
stateListeners.delete(listener)
}
}),
dispatch: vi.fn(),
getState: () => state
}
return {
navigation,
unsubscribe,
listenerCount: () => stateListeners.size,
setState(nextState: HostStackNavigationState) {
state = nextState
for (const listener of stateListeners) {
listener()
}
}
}
}
function committedHostState(hostIdParam: string): HostStackNavigationState {
return {
index: 0,
routes: [
{
name: 'h',
state: {
key: '/h',
index: 0,
routes: [{ key: 'host-index', name: '[hostId]/index', params: { hostId: hostIdParam } }]
}
}
]
}
}
describe('host stack navigation', () => {
it('matches a host committed as the encoded segment it was pushed as', () => {
const harness = navigationHarness({ index: 0, routes: [{ name: 'index' }] })
const push = vi.fn()
navigateToHostStackRoute(harness.navigation, { push }, 'host/one', TARGET)
expect(push).toHaveBeenCalledWith(hostStackHostRoute('host/one'))
expect(harness.navigation.dispatch).not.toHaveBeenCalled()
harness.setState(committedHostState(encodeURIComponent('host/one')))
expect(harness.navigation.dispatch).toHaveBeenCalledTimes(1)
expect(harness.navigation.dispatch).toHaveBeenCalledWith({
type: 'REPLACE',
target: '/h',
source: 'host-index',
payload: TARGET
})
})
it('ignores a different host whose id merely decodes badly', () => {
const harness = navigationHarness({ index: 0, routes: [{ name: 'index' }] })
navigateToHostStackRoute(harness.navigation, { push: vi.fn() }, 'host/one', TARGET)
harness.setState(committedHostState('100%'))
expect(harness.navigation.dispatch).not.toHaveBeenCalled()
})
it('stops listening and never replaces once canceled', () => {
const harness = navigationHarness({ index: 0, routes: [{ name: 'index' }] })
const controller = navigateToHostStackRoute(
harness.navigation,
{ push: vi.fn() },
'host/one',
TARGET
)
expect(harness.listenerCount()).toBe(1)
controller.cancel()
expect(harness.unsubscribe).toHaveBeenCalledTimes(1)
expect(harness.listenerCount()).toBe(0)
expect(controller.isActive()).toBe(false)
harness.setState(committedHostState('host/one'))
expect(harness.navigation.dispatch).not.toHaveBeenCalled()
})
it('retargets a still-pending transition to the same host instead of pushing twice', () => {
const harness = navigationHarness({ index: 0, routes: [{ name: 'index' }] })
const push = vi.fn()
const router = { push }
const pending = coordinateHostStackNavigation(
null,
harness.navigation,
router,
'host/one',
TARGET
)
const retargeted = coordinateHostStackNavigation(
pending,
harness.navigation,
router,
'host/one',
OTHER_TARGET
)
expect(retargeted).toBe(pending)
expect(push).toHaveBeenCalledTimes(1)
expect(harness.listenerCount()).toBe(1)
harness.setState(committedHostState('host/one'))
expect(harness.navigation.dispatch).toHaveBeenCalledTimes(1)
expect(harness.navigation.dispatch).toHaveBeenCalledWith(
expect.objectContaining({ payload: OTHER_TARGET })
)
})
})
@@ -0,0 +1,171 @@
export type HostStackNavigationState = Readonly<{
key?: string
index: number
routes: readonly HostStackNavigationRoute[]
}>
export type HostStackNavigationRoute = Readonly<{
key?: string
name: string
params?: Readonly<{ hostId?: unknown }>
state?: HostStackNavigationState
}>
/** A screen inside app/h/_layout.tsx plus the params it needs, e.g.
* `{ name: '[hostId]/session/[worktreeId]', params: { hostId, worktreeId } }`. */
export type HostStackRouteTarget = Readonly<{
name: string
params: Readonly<Record<string, string>>
}>
export type HostStackReplaceAction = Readonly<{
type: 'REPLACE'
target: string
source: string
payload: HostStackRouteTarget
}>
export type HostStackRootNavigation = {
addListener: (event: 'state', listener: () => void) => () => void
dispatch: (action: HostStackReplaceAction) => void
getState: () => HostStackNavigationState
}
export type HostStackHostRoute = `/h/${string}`
export type HostStackRouter = {
push: (route: HostStackHostRoute) => void
}
export type HostStackNavigationController = Readonly<{
cancel: () => void
isActive: () => boolean
retarget: (target: HostStackRouteTarget) => void
}>
export type PendingHostStackNavigation = Readonly<{
hostId: string
controller: HostStackNavigationController
}>
export function hostStackHostRoute(hostId: string): HostStackHostRoute {
return `/h/${encodeURIComponent(hostId)}`
}
// Why: the host is pushed as an encoded segment, so the committed route may hold
// either form — an id with `/`, `#`, or `%` must still match its own push.
function hostParamMatches(param: unknown, expectedHostId: string): boolean {
if (typeof param !== 'string') {
return false
}
if (param === expectedHostId) {
return true
}
try {
return decodeURIComponent(param) === expectedHostId
} catch {
return false // Lone `%` — not our encoding.
}
}
function mountedHostStack(
state: HostStackNavigationState,
expectedHostId: string
): { key: string; routeKey: string } | null {
const hostContainer = state.routes[state.index]
const hostState = hostContainer?.state
const hostRoute = hostState?.routes[hostState.index]
if (
hostContainer?.name !== 'h' ||
!hostState?.key ||
hostRoute?.name !== '[hostId]/index' ||
!hostRoute.key ||
!hostParamMatches(hostRoute.params?.hostId, expectedHostId)
) {
return null
}
return { key: hostState.key, routeKey: hostRoute.key }
}
/** Opens a deep host route by mounting `/h/[hostId]` first and replacing it once
* its stack is committed. A cold push straight to a nested route resolves to the
* host index without the dynamic id, which lands on a blank host screen. */
export function navigateToHostStackRoute(
navigation: HostStackRootNavigation,
router: HostStackRouter,
hostId: string,
target: HostStackRouteTarget
): HostStackNavigationController {
let active = true
let hostRouteSeen = false
let selectedTarget = target
let unsubscribeState = () => {}
const dispose = () => {
if (!active) {
return
}
active = false
unsubscribeState()
}
// Why: cold Expo deep links resolve to index; target the route only after its HostStack exists.
const onState = () => {
if (!active) {
return
}
const state = navigation.getState()
const currentRoute = state.routes[state.index]
if (currentRoute?.name === 'h') {
hostRouteSeen = true
} else if (hostRouteSeen) {
dispose()
return
}
const hostStack = mountedHostStack(state, hostId)
if (!hostStack) {
return
}
dispose()
navigation.dispatch({
type: 'REPLACE',
target: hostStack.key,
source: hostStack.routeKey,
payload: selectedTarget
})
}
try {
unsubscribeState = navigation.addListener('state', onState)
router.push(hostStackHostRoute(hostId))
} catch (error) {
dispose()
throw error
}
return {
cancel: dispose,
isActive: () => active,
retarget: (nextTarget) => {
if (active) {
selectedTarget = nextTarget
}
}
}
}
export function coordinateHostStackNavigation(
current: PendingHostStackNavigation | null,
navigation: HostStackRootNavigation,
router: HostStackRouter,
hostId: string,
target: HostStackRouteTarget
): PendingHostStackNavigation {
if (current?.hostId === hostId && current.controller.isActive()) {
current.controller.retarget(target)
return current
}
current?.controller.cancel()
return {
hostId,
controller: navigateToHostStackRoute(navigation, router, hostId, target)
}
}
@@ -0,0 +1,38 @@
import { useCallback, useEffect } from 'react'
import { useNavigation, useRouter } from 'expo-router'
import {
coordinateHostStackNavigation,
type HostStackRootNavigation,
type HostStackRouteTarget,
type PendingHostStackNavigation
} from './host-stack-navigation'
// Why: one root navigator means one pending transition. A per-hook ref would let a
// Resume tap and a Tasks tap arm two independent pushes that cannot cancel each other.
let pendingNavigation: PendingHostStackNavigation | null = null
export function useOpenHostStackRoute(): (hostId: string, target: HostStackRouteTarget) => void {
const navigation = useNavigation<HostStackRootNavigation>()
const router = useRouter()
useEffect(
() => () => {
pendingNavigation?.controller.cancel()
pendingNavigation = null
},
[]
)
return useCallback(
(hostId, target) => {
pendingNavigation = coordinateHostStackNavigation(
pendingNavigation,
navigation,
router,
hostId,
target
)
},
[navigation, router]
)
}
@@ -1,19 +1,63 @@
import { readFileSync } from 'node:fs'
import { describe, expect, it } from 'vitest'
import { createMobileSessionHref } from './mobile-session-route'
import { describe, expect, it, vi } from 'vitest'
import { mobileSessionRouteTarget } from './mobile-session-route'
import {
hostStackHostRoute,
navigateToHostStackRoute,
type HostStackNavigationState
} from '../navigation/host-stack-navigation'
const homeSource = readFileSync(new URL('../../app/index.tsx', import.meta.url), 'utf8')
function navigationHarness(initialState: HostStackNavigationState) {
const stateListeners = new Set<() => void>()
let state = initialState
const navigation = {
addListener: vi.fn((_event: 'state', listener: () => void) => {
stateListeners.add(listener)
return () => stateListeners.delete(listener)
}),
dispatch: vi.fn(),
getState: () => state
}
return {
navigation,
setState(nextState: HostStackNavigationState) {
state = nextState
for (const listener of stateListeners) {
listener()
}
}
}
}
function mountedHostState(hostId: string): HostStackNavigationState {
return {
index: 1,
routes: [
{ name: 'index' },
{
name: 'h',
state: {
key: '/h',
index: 0,
routes: [{ key: 'host-index', name: '[hostId]/index', params: { hostId } }]
}
}
]
}
}
describe('mobile session route', () => {
it('keeps dynamic route identities raw for Expo Router to encode', () => {
it('keeps dynamic route identities raw for the navigator to encode', () => {
expect(
createMobileSessionHref({
mobileSessionRouteTarget({
hostId: 'host/one',
worktreeId: 'repo::/Users/ada/orca/workspaces/fix #1',
name: 'Fix #1'
})
).toEqual({
pathname: '/h/[hostId]/session/[worktreeId]',
name: '[hostId]/session/[worktreeId]',
params: {
hostId: 'host/one',
worktreeId: 'repo::/Users/ada/orca/workspaces/fix #1',
@@ -22,14 +66,47 @@ describe('mobile session route', () => {
})
})
it('routes the home Resume card through the typed dynamic href', () => {
it('omits an absent workspace name instead of sending an empty param', () => {
expect(
mobileSessionRouteTarget({ hostId: 'host-1', worktreeId: 'repo::/tmp/wt' }).params
).toEqual({ hostId: 'host-1', worktreeId: 'repo::/tmp/wt' })
})
it('mounts the host before replacing it with the session route', () => {
const harness = navigationHarness({ index: 0, routes: [{ name: 'index' }] })
const push = vi.fn()
const target = mobileSessionRouteTarget({
hostId: 'host/one',
worktreeId: 'repo::/Users/ada/orca/workspaces/fix #1',
name: 'Fix #1'
})
navigateToHostStackRoute(harness.navigation, { push }, 'host/one', target)
expect(push).toHaveBeenCalledWith(hostStackHostRoute('host/one'))
expect(harness.navigation.dispatch).not.toHaveBeenCalled()
harness.setState(mountedHostState('host/one'))
expect(harness.navigation.dispatch).toHaveBeenCalledWith({
type: 'REPLACE',
target: '/h',
source: 'host-index',
payload: target
})
})
it('routes the home Resume card through the cold-navigator-safe transition', () => {
const start = homeSource.indexOf('{/* ─── Resume card ─── */}')
const end = homeSource.indexOf('{/* ─── Quick actions ─── */}', start)
const resumeCard = homeSource.slice(start, end)
// Assert the markers first: a renamed banner would otherwise slice garbage and
// report a missing call instead of the real cause.
expect(start).toBeGreaterThanOrEqual(0)
expect(end).toBeGreaterThan(start)
expect(resumeCard).toContain('createMobileSessionHref({')
expect(resumeCard).not.toContain('encodeURIComponent(resumeWorktree.worktree.worktreeId)')
const resumeCard = homeSource.slice(start, end)
expect(resumeCard).toContain('openMobileSession({')
expect(resumeCard).not.toContain('router.push(')
})
})
+11 -8
View File
@@ -1,17 +1,20 @@
import type { HostStackRouteTarget } from '../navigation/host-stack-navigation'
export type MobileSessionRouteParams = {
hostId: string
worktreeId: string
name?: string
}
export type MobileSessionHref = {
pathname: '/h/[hostId]/session/[worktreeId]'
params: MobileSessionRouteParams
}
export function createMobileSessionHref(params: MobileSessionRouteParams): MobileSessionHref {
/** Identities stay raw — the navigator owns the params, so pre-encoding a
* workspace id would reach the session screen still escaped. */
export function mobileSessionRouteTarget({
hostId,
worktreeId,
name
}: MobileSessionRouteParams): HostStackRouteTarget {
return {
pathname: '/h/[hostId]/session/[worktreeId]',
params
name: '[hostId]/session/[worktreeId]',
params: name ? { hostId, worktreeId, name } : { hostId, worktreeId }
}
}
@@ -0,0 +1,14 @@
import { useCallback } from 'react'
import { useOpenHostStackRoute } from '../navigation/use-open-host-stack-route'
import { mobileSessionRouteTarget, type MobileSessionRouteParams } from './mobile-session-route'
export function useOpenMobileSession(): (params: MobileSessionRouteParams) => void {
const openHostStackRoute = useOpenHostStackRoute()
return useCallback(
(params) => {
openHostStackRoute(params.hostId, mobileSessionRouteTarget(params))
},
[openHostStackRoute]
)
}
+38 -128
View File
@@ -1,72 +1,36 @@
import {
coordinateHostStackNavigation,
hostStackHostRoute,
navigateToHostStackRoute,
type HostStackHostRoute,
type HostStackNavigationController,
type HostStackNavigationState,
type HostStackRootNavigation,
type HostStackRouteTarget,
type HostStackRouter,
type PendingHostStackNavigation
} from '../navigation/host-stack-navigation'
import type { TaskProvider } from './mobile-task-providers'
export type MobileTasksHostRoute = `/h/${string}`
export type MobileTasksNavigationState = Readonly<{
key?: string
index: number
routes: readonly MobileTasksNavigationRoute[]
}>
export type MobileTasksNavigationRoute = Readonly<{
key?: string
name: string
params?: Readonly<{ hostId?: unknown }>
state?: MobileTasksNavigationState
}>
export type MobileTasksRootNavigation = {
addListener: (event: 'state', listener: () => void) => () => void
dispatch: (action: MobileTasksHostReplaceAction) => void
getState: () => MobileTasksNavigationState
}
export type MobileTasksHostReplaceAction = Readonly<{
type: 'REPLACE'
target: string
source: string
payload: Readonly<{
name: '[hostId]/tasks'
params: Readonly<{ hostId: string; taskSource?: TaskProvider }>
}>
}>
export type MobileTasksRouter = {
push: (route: MobileTasksHostRoute) => void
}
export type MobileTasksNavigationController = Readonly<{
cancel: () => void
isActive: () => boolean
selectProvider: (provider?: TaskProvider) => void
}>
export type PendingMobileTasksNavigation = Readonly<{
hostId: string
controller: MobileTasksNavigationController
}>
export type MobileTasksHostRoute = HostStackHostRoute
export type MobileTasksNavigationState = HostStackNavigationState
export type MobileTasksRootNavigation = HostStackRootNavigation
export type MobileTasksRouter = HostStackRouter
export type MobileTasksNavigationController = HostStackNavigationController
export type PendingMobileTasksNavigation = PendingHostStackNavigation
export function mobileTasksHostRoute(hostId: string): MobileTasksHostRoute {
return `/h/${encodeURIComponent(hostId)}`
return hostStackHostRoute(hostId)
}
function mountedHostStack(
state: MobileTasksNavigationState,
expectedHostId: string
): { key: string; routeKey: string } | null {
const hostContainer = state.routes[state.index]
const hostState = hostContainer?.state
const hostRoute = hostState?.routes[hostState.index]
if (
hostContainer?.name !== 'h' ||
!hostState?.key ||
hostRoute?.name !== '[hostId]/index' ||
!hostRoute.key ||
hostRoute.params?.hostId !== expectedHostId
) {
return null
export function mobileTasksRouteTarget(
hostId: string,
provider?: TaskProvider
): HostStackRouteTarget {
return {
name: '[hostId]/tasks',
params: provider ? { hostId, taskSource: provider } : { hostId }
}
return { key: hostState.key, routeKey: hostRoute.key }
}
export function navigateToMobileTasks(
@@ -75,64 +39,12 @@ export function navigateToMobileTasks(
hostId: string,
provider?: TaskProvider
): MobileTasksNavigationController {
let active = true
let hostRouteSeen = false
let selectedProvider = provider
let unsubscribeState = () => {}
const dispose = () => {
if (!active) {
return
}
active = false
unsubscribeState()
}
// Why: cold Expo deep links resolve to index; target Tasks only after its HostStack exists.
const onState = () => {
if (!active) {
return
}
const state = navigation.getState()
const currentRoute = state.routes[state.index]
if (currentRoute?.name === 'h') {
hostRouteSeen = true
} else if (hostRouteSeen) {
dispose()
return
}
const hostStack = mountedHostStack(state, hostId)
if (!hostStack) {
return
}
dispose()
const action: MobileTasksHostReplaceAction = {
type: 'REPLACE',
target: hostStack.key,
source: hostStack.routeKey,
payload: {
name: '[hostId]/tasks',
params: selectedProvider ? { hostId, taskSource: selectedProvider } : { hostId }
}
}
navigation.dispatch(action)
}
try {
unsubscribeState = navigation.addListener('state', onState)
router.push(mobileTasksHostRoute(hostId))
} catch (error) {
dispose()
throw error
}
return {
cancel: dispose,
isActive: () => active,
selectProvider: (nextProvider) => {
if (active) {
selectedProvider = nextProvider
}
}
}
return navigateToHostStackRoute(
navigation,
router,
hostId,
mobileTasksRouteTarget(hostId, provider)
)
}
export function coordinateMobileTasksNavigation(
@@ -142,13 +54,11 @@ export function coordinateMobileTasksNavigation(
hostId: string,
provider?: TaskProvider
): PendingMobileTasksNavigation {
if (current?.hostId === hostId && current.controller.isActive()) {
current.controller.selectProvider(provider)
return current
}
current?.controller.cancel()
return {
return coordinateHostStackNavigation(
current,
navigation,
router,
hostId,
controller: navigateToMobileTasks(navigation, router, hostId, provider)
}
mobileTasksRouteTarget(hostId, provider)
)
}
+6 -26
View File
@@ -1,35 +1,15 @@
import { useCallback, useEffect, useRef } from 'react'
import { useNavigation, useRouter } from 'expo-router'
import {
coordinateMobileTasksNavigation,
type MobileTasksRootNavigation,
type PendingMobileTasksNavigation
} from './mobile-task-navigation'
import { useCallback } from 'react'
import { useOpenHostStackRoute } from '../navigation/use-open-host-stack-route'
import { mobileTasksRouteTarget } from './mobile-task-navigation'
import type { TaskProvider } from './mobile-task-providers'
export function useOpenMobileTasks(): (hostId: string, provider?: TaskProvider) => void {
const navigation = useNavigation<MobileTasksRootNavigation>()
const router = useRouter()
const pendingRef = useRef<PendingMobileTasksNavigation | null>(null)
useEffect(
() => () => {
pendingRef.current?.controller.cancel()
pendingRef.current = null
},
[]
)
const openHostStackRoute = useOpenHostStackRoute()
return useCallback(
(hostId, provider) => {
pendingRef.current = coordinateMobileTasksNavigation(
pendingRef.current,
navigation,
router,
hostId,
provider
)
openHostStackRoute(hostId, mobileTasksRouteTarget(hostId, provider))
},
[navigation, router]
[openHostStackRoute]
)
}