Files
orca/mobile/src/session/use-live-worktree-name.test.ts
T
Jinwoo HongandOrcaWin 738f640428 fix(mobile): relay UX overhaul — steady status colors, visible relay dials, coordinated deep links (F1-F10)
* fix(mobile): keep healthy relays green through focus and network nudges (F1+F2)

Focus/app-resume nudges probe the active relay instead of suspending it;
network-change nudges replace it make-before-break, suspending only after a
failed dial. Mount, Retry, and host-swap windows read 'connecting' instead of
'disconnected'; the host list keeps last-known worktrees for every
not-connected state and spins instead of rendering nothing.

* feat(mobile): surface the pairing relay path in the pairing log (F3)

The relay candidate was silent during pairing: dialing, E2EE handshake,
director recovery, and the winning path now emit redacted phase lines through
the same connectOptions.onLog the direct path already used.

* docs(mobile): relay UX investigation findings and F0-F10 fix plan

* feat(mobile): name and narrate relay dials while they happen (F5)

migrateTo forwards the dialing session's connecting/handshaking/reconnecting
phases whenever the client is suspended or disconnected — never downgrading a
live session — and exposes getPendingPath so the host card can say
'· Orca Relay' during the dial instead of only after it.

* feat(mobile): race a relay dial when the direct dial stalls (F6)

A 2.5s grace timer starts relay recovery while an unauthenticated direct dial
is still inside its 12s connect window; the race gets one attempt through the
existing mutex/cooldown machinery, cancels when direct authenticates, and
never arms for hosts without a relay endpoint.

* fix(mobile): overlay the protocol gate instead of unmounting the host stack (F9)

A pending status.get used to swap the mounted HostStack for a spinner at the
moment the socket connected, destroying in-flight nested navigation. Once
children have rendered for a host they stay mounted under an opaque
touch-blocking overlay; first visits and blocked verdicts keep the old
behavior.

* fix(mobile): keep loaded data through transient connection blips (F10)

Git history no longer blanks on reconnect (and commit files refetch instead
of caching an offline empty answer), the repo picker keeps its last-good list
when an in-flight repo.list rejects, the diff review's ready-state
preservation actually runs, and proven host capabilities survive a drop
flagged unverified instead of being wiped.

* feat(mobile): coordinate every home deep push and bounce dead resume targets (F4+F7+F8)

Notification taps, the Accounts card, and host-edit now use the shared
mount-then-replace transition (with a focused-route walker so root-layout
scope works); the Resume card renders from the snapshot in a disabled state
so its late arrival can't shift Tasks under the thumb; resume targets are
validated against proven catalog data, and a session route whose worktree
the host proves missing bounces to the host index with a notice banner
instead of stranding on a dead screen.

* test(mobile): cover the resume-target and notice policies (F7)

Key notice dismissal by code so closing one banner cannot swallow a later,
different one, and move the visibility rule into host-route-notice.ts where it
is testable without a screen.

Adds the missing units for F7's decision points: isResumeTargetConfirmedMissing
(unproven catalog is silence, synthetic routes exempt), the validating
last-visited reader, and the notice visibility rule.

* fix(mobile): review-pass hardening for the gate overlay and diff preservation

Adversarial review findings: the reader's hunk position now survives a
connection blip (reset only on item change), the covered stack is hidden from
TalkBack while the gate overlay is up, and the overlay's hit-test comment is
scoped honestly to in-tree views (native-Modal drawers present above it —
follow-up).

* fix(mobile): CI + CodeRabbit review fixes for #12609

Move the findings doc under docs/ (root directory guard), drop two unused
eslint-disable directives, and address review findings: an unproven snapshot
seed can no longer downgrade a proven worktree catalog; a locally-aborted
relay dial skips the director fallback; post-migration bookkeeping failures
log instead of masquerading as dial failures (which could suspend the healthy
session); the auth wait arms its timeout before subscribing; forwarded dial
phases stop at close(); the legacy selector_not_found fallback requires
runtime_error; the diff-loading effect depends on the fields it reads; and
host-edit auto-cancellation is now pinned by a test.

* fix(mobile): second review round — queued replacements, race fence, confirmed bounces

A network-change replacement now survives the recovery mutex and cooldowns as
a queued intent instead of being dropped or suspending a healthy session —
only a failed dial or a dead probe tears one down. The happy-eyeballs
migration withdraws when direct authenticated during the relay dial
(first-authenticated-wins). A worktree bounce requires two consecutive
host-proven misses, since a transient desktop repo-scan rejection answers
selector_not_found for a live worktree. Background network flaps no longer
wake a billed relay splice, the lifecycle foreground flag stays in sync, a
screen unmount cancels only its own pending host-stack transition, and diff
review keeps the loaded review when its reconnect refresh rejects.

Extracted mobile-endpoint-nudge-router.ts and the establisher's dialEligible
pass, and split the supervisor nudge tests, to stay under max-lines.

* fix(mobile): satisfy the React Doctor changed-code gate

Render-phase ref writes move into effects: the protocol gate's resolved/mounted
latches now record committed outcomes only (a discarded children render can no
longer count as mounted), and the bounce hook syncs its callback ref in an
effect. Array<T> annotations become T[] in the extracted modules.

* fix(mobile): keep the loaded diff when the reconnect refetch rejects (F10)

The diff-loading hook's catch was the one path still erasing a ready diff —
the same keepLoadedDiff guard its disconnect and loading branches already use,
now pinned by a reject-after-ready test.

* fix(mobile): process foreground revival nudges

---------

Co-authored-by: OrcaWin <293788423+OrcaWin@users.noreply.github.com>
2026-08-04 19:47:39 -07:00

310 lines
9.4 KiB
TypeScript

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 { useLiveWorktreeName } from './use-live-worktree-name'
vi.mock('expo-router', async () => {
const React = await import('react')
return {
useFocusEffect(effect: () => void | (() => void)): void {
React.useEffect(effect, [effect])
}
}
})
function suppressReactTestRendererDeprecationWarning(): () => void {
const originalConsoleError = console.error
const consoleErrorSpy = vi.spyOn(console, 'error').mockImplementation((...args) => {
const firstArg = args[0]
if (typeof firstArg === 'string' && firstArg.includes('react-test-renderer is deprecated')) {
return
}
originalConsoleError(...args)
})
return () => consoleErrorSpy.mockRestore()
}
describe('useLiveWorktreeName request volume', () => {
let renderer: ReactTestRenderer | null = null
let eventListener: ((payload: unknown) => void) | null = null
const unsubscribeStream = vi.fn()
const sendRequest = vi.fn().mockResolvedValue({
id: 'worktree-show',
ok: true,
result: { worktree: { id: 'repo-1::/worktree', displayName: 'Live name' } },
_meta: { runtimeId: 'runtime-1' }
})
const subscribe = vi.fn(
(_method: string, _params: unknown, listener: (payload: unknown) => void) => {
eventListener = listener
return unsubscribeStream
}
)
const client = { sendRequest, subscribe } as unknown as RpcClient
async function mountHarness(): Promise<void> {
function Harness(): null {
useLiveWorktreeName({
client,
connState: 'connected',
routeName: 'Route name',
worktreeId: 'repo-1::/worktree'
})
return null
}
const restoreConsoleError = suppressReactTestRendererDeprecationWarning()
try {
await act(async () => {
renderer = create(createElement(Harness))
await Promise.resolve()
})
} finally {
restoreConsoleError()
}
}
async function emitEvent(payload: unknown): Promise<void> {
await act(async () => {
eventListener?.(payload)
await Promise.resolve()
await Promise.resolve()
})
}
beforeEach(() => {
vi.useFakeTimers()
globalThis.IS_REACT_ACT_ENVIRONMENT = true
eventListener = null
sendRequest.mockClear().mockResolvedValue({
id: 'worktree-show',
ok: true,
result: { worktree: { id: 'repo-1::/worktree', displayName: 'Live name' } },
_meta: { runtimeId: 'runtime-1' }
})
subscribe.mockClear()
unsubscribeStream.mockClear()
})
afterEach(() => {
act(() => renderer?.unmount())
renderer = null
vi.useRealTimers()
})
it('cuts thirty-second idle request volume from eleven calls to one', async () => {
await mountHarness()
expect(subscribe).toHaveBeenCalledWith(
'runtime.clientEvents.subscribe',
null,
expect.any(Function)
)
expect(sendRequest).toHaveBeenCalledTimes(1)
await emitEvent({ type: 'ready', subscriptionId: 'runtime-events-1' })
await act(async () => {
await vi.advanceTimersByTimeAsync(30_000)
})
// The retired 3s interval made one initial request plus ten idle ticks here.
expect(sendRequest).toHaveBeenCalledTimes(1)
await emitEvent({ type: 'worktreesChanged', repoId: 'repo-2' })
expect(sendRequest).toHaveBeenCalledTimes(1)
await emitEvent({ type: 'worktreesChanged', repoId: 'repo-1' })
expect(sendRequest).toHaveBeenCalledTimes(2)
await act(async () => {
await vi.advanceTimersByTimeAsync(30_000)
})
expect(sendRequest).toHaveBeenCalledTimes(2)
})
it('keeps polling when an older runtime rejects the event stream', async () => {
await mountHarness()
await emitEvent({ type: 'error', message: 'Unknown method' })
await act(async () => {
await vi.advanceTimersByTimeAsync(9_000)
})
expect(sendRequest).toHaveBeenCalledTimes(4)
})
it('retries a failed initial read even after the event stream is ready', async () => {
sendRequest.mockRejectedValueOnce(new Error('transient')).mockResolvedValue({
id: 'worktree-show',
ok: true,
result: { worktree: { id: 'repo-1::/worktree', displayName: 'Live name' } },
_meta: { runtimeId: 'runtime-1' }
})
await mountHarness()
await emitEvent({ type: 'ready', subscriptionId: 'runtime-events-1' })
await act(async () => {
await vi.advanceTimersByTimeAsync(3_000)
await vi.advanceTimersByTimeAsync(30_000)
})
expect(sendRequest).toHaveBeenCalledTimes(2)
})
it('refreshes once when a reconnected stream becomes ready again', async () => {
await mountHarness()
await emitEvent({ type: 'ready', subscriptionId: 'runtime-events-1' })
await emitEvent({ type: 'ready', subscriptionId: 'runtime-events-2' })
expect(sendRequest).toHaveBeenCalledTimes(2)
})
it('unsubscribes when the screen loses focus', async () => {
await mountHarness()
act(() => renderer?.unmount())
renderer = null
expect(unsubscribeStream).toHaveBeenCalledTimes(1)
})
it('never calls worktree.show for the floating workspace sentinel', async () => {
let name = ''
function FloatingHarness(): null {
name = useLiveWorktreeName({
client,
connState: 'connected',
routeName: undefined,
worktreeId: 'global-floating-terminal'
}).name
return null
}
const restoreConsoleError = suppressReactTestRendererDeprecationWarning()
try {
await act(async () => {
renderer = create(createElement(FloatingHarness))
await Promise.resolve()
})
} finally {
restoreConsoleError()
}
await act(async () => {
await vi.advanceTimersByTimeAsync(30_000)
})
expect(sendRequest).not.toHaveBeenCalled()
expect(subscribe).not.toHaveBeenCalled()
expect(name).toBe('Floating Workspace')
})
it('does not render stale names while switching through the floating route', async () => {
const firstNameByWorktree = new Map<string, string>()
let renderer: ReactTestRenderer | null = null
function RouteHarness(props: { routeName?: string; worktreeId: string }): null {
const { name } = useLiveWorktreeName({
client,
connState: 'connected',
routeName: props.routeName,
worktreeId: props.worktreeId
})
if (!firstNameByWorktree.has(props.worktreeId)) {
firstNameByWorktree.set(props.worktreeId, name)
}
return null
}
const restoreConsoleError = suppressReactTestRendererDeprecationWarning()
try {
await act(async () => {
renderer = create(
createElement(RouteHarness, {
routeName: 'Previous workspace',
worktreeId: 'repo-1::/worktree'
})
)
await Promise.resolve()
})
await act(async () => {
renderer?.update(
createElement(RouteHarness, {
worktreeId: 'global-floating-terminal'
})
)
})
await act(async () => {
renderer?.update(
createElement(RouteHarness, {
routeName: 'Next workspace',
worktreeId: 'repo-2::/worktree'
})
)
})
} finally {
restoreConsoleError()
act(() => renderer?.unmount())
}
expect(firstNameByWorktree.get('global-floating-terminal')).toBe('Floating Workspace')
expect(firstNameByWorktree.get('repo-2::/worktree')).toBe('Next workspace')
})
// The bounce in use-missing-worktree-bounce.ts rides this poll rather than adding a second
// RPC, so the failure branch has to publish a verdict instead of returning early.
it('reports the host-proven verdict from the same poll', async () => {
let resolution = ''
function VerdictHarness(): null {
resolution = useLiveWorktreeName({
client,
connState: 'connected',
routeName: 'Route name',
worktreeId: 'repo-1::/worktree'
}).resolution
return null
}
const mount = async (): Promise<void> => {
const restoreConsoleError = suppressReactTestRendererDeprecationWarning()
try {
await act(async () => {
renderer = create(createElement(VerdictHarness))
await Promise.resolve()
})
} finally {
restoreConsoleError()
}
}
await mount()
expect(resolution).toBe('present')
act(() => renderer?.unmount())
renderer = null
sendRequest.mockResolvedValue({
id: 'worktree-show',
ok: false,
error: { code: 'selector_not_found', message: 'Selector not found' },
_meta: { runtimeId: 'runtime-1' }
})
await mount()
// Why: a transient desktop repo-scan rejection also answers selector_not_found,
// so one miss stays unproven; only the confirming poll may say 'missing'.
expect(resolution).toBe('unknown')
await act(async () => {
await vi.advanceTimersByTimeAsync(3_000)
})
expect(resolution).toBe('missing')
act(() => renderer?.unmount())
renderer = null
// A dropped socket is not a deletion, so it must leave the verdict unproven.
sendRequest.mockResolvedValue({
id: 'worktree-show',
ok: false,
error: { code: 'runtime_busy', message: 'Runtime busy' },
_meta: { runtimeId: 'runtime-1' }
})
await mount()
expect(resolution).toBe('unknown')
})
})