test: remove 61 low-value mobile tests (#39955)

* test: remove 61 low-value mobile tests

* test: use array shorthand in retry fixture

---------

Co-authored-by: OrcaWin <293788423+OrcaWin@users.noreply.github.com>
This commit is contained in:
OrcaWin
2026-11-08 12:31:33 -08:00
committed by GitHub
co-authored by OrcaWin
parent 8e55f80278
commit 2b89fa7c98
24 changed files with 27 additions and 1201 deletions
-1
View File
@@ -147,7 +147,6 @@
1 test-no-polling-loop:tests/e2e/terminal-tui-wheel-reports.spec.ts
1 test-no-polling-loop:tests/e2e/workspace-sleep-in-main.spec.ts
2 test-no-polling-loop:tests/e2e/worktree-card-downward-drag.spec.ts
1 test-no-real-time-wait:mobile/src/tasks/worktree-create-retry.test.ts
1 test-no-real-time-wait:mobile/src/terminal/terminal-webview-tap-routing.test.ts
1 test-no-real-time-wait:src/main/agent-hooks/posix-hook-json-stdin-reader.test.ts
3 test-no-real-time-wait:src/main/agent-hooks/server-copilot-normalization.test.ts
@@ -50,41 +50,6 @@ describe('useConnectedHostPicker', () => {
act(() => handle.current!.pickHost(action, hosts))
}
it('runs the action on the only offered host without a picker', () => {
render([desk, laptop])
const action = vi.fn()
pickHost(action, [laptop])
expect(action).toHaveBeenCalledWith('laptop')
expect(picker().visible).toBe(false)
})
it('offers only the hosts passed in', () => {
render([desk, laptop, server])
const action = vi.fn()
pickHost(action, [desk, server])
expect(picker().visible).toBe(true)
expect(picker().options.map((option) => option.value)).toEqual(['desk', 'server'])
act(() => picker().onSelect('server'))
act(() => picker().onAfterClose())
expect(action).toHaveBeenCalledWith('server')
})
it('runs nothing when the picker is dismissed', () => {
render([desk, laptop])
const action = vi.fn()
pickHost(action)
act(() => picker().onClose())
act(() => picker().onAfterClose())
expect(picker().visible).toBe(false)
expect(action).not.toHaveBeenCalled()
})
it('disambiguates path-routed hosts without exposing endpoint paths', () => {
render([
host('desk-a', 'Desk', 'wss://gateway.example.com/v1/connect/bearer-secret-a'),
@@ -1,86 +0,0 @@
import { describe, expect, it } from 'vitest'
import { getReportableConnectionIncidentId } from './connection-diagnostics-analysis'
import type { ConnectionLogEntry } from './connection/connection-log-types'
// Reproduce a 0.0.50 phone / 1.4.203 host export (2026-09-18): relay dials failed 4404, LAN timed out, and a resume before export erased the reported cause.
const ENDPOINT = 'ws://192.168.1.2:55927'
let sequence = 0
function entry(fields: Omit<ConnectionLogEntry, 'id' | 'ts'>): ConnectionLogEntry {
sequence += 1
return { id: `export-${sequence}`, ts: Date.parse('2026-09-18T22:44:00Z') + sequence, ...fields }
}
const appResumed = () =>
entry({
level: 'info',
code: 'app-resumed',
message: 'App returned to foreground',
detail: 'Connection recovery notified'
})
const lanOpening = () =>
entry({ level: 'info', path: 'lan', message: 'Opening WebSocket', detail: '192.168.1.2:55927' })
const relayDialFailed = (closeCode: number) =>
entry({
level: 'error',
code: 'relay-dial-failed',
path: 'relay',
message: 'Relay: relay dial failed',
detail: `Error: relay_outer_${closeCode}`,
relayCloseCode: closeCode
})
const lanConnectTimeout = () =>
entry({
level: 'error',
code: 'connect-timeout',
path: 'lan',
message: 'WebSocket connect timeout',
detail: 'No TCP/WS handshake within 12s — endpoint unreachable?'
})
const retryScheduled = () =>
entry({
level: 'info',
code: 'retry-scheduled',
path: 'lan',
message: 'Reconnect scheduled in 500ms',
detail: 'Attempt 1'
})
function resumeWindow(closeCode: number): ConnectionLogEntry[] {
return [
appResumed(),
lanOpening(),
relayDialFailed(closeCode),
lanConnectTimeout(),
retryScheduled()
]
}
describe('diagnoseConnection on the relay-4404 export', () => {
// The export ends before a new outcome, so the latest evidence predates resume.
const CUT_MID_WINDOW = [...resumeWindow(4404), ...resumeWindow(4404), appResumed(), lanOpening()]
// The later LAN timeout only means the phone is off LAN; it must not outrank the relay verdict.
it('is never a sendable relay incident', () => {
expect(
getReportableConnectionIncidentId({
endpoint: ENDPOINT,
state: 'connecting',
entries: CUT_MID_WINDOW
})
).toBeNull()
expect(
getReportableConnectionIncidentId({
endpoint: ENDPOINT,
state: 'connecting',
entries: resumeWindow(4404)
})
).toBeNull()
})
})
@@ -7,24 +7,6 @@ function entry(id: number): ConnectionLogEntry {
}
describe('connection log buffer', () => {
it('keeps entries per host without cross-talk', () => {
const store = createConnectionLogStore()
store.append('host-a', entry(1))
store.append('host-b', entry(2))
expect(store.get('host-a').map((e) => e.id)).toEqual(['log-1'])
expect(store.get('host-b').map((e) => e.id)).toEqual(['log-2'])
})
it('drops the oldest entries past the cap', () => {
const store = createConnectionLogStore(3)
for (let i = 1; i <= 5; i++) {
store.append('host-a', entry(i))
}
expect(store.get('host-a').map((e) => e.id)).toEqual(['log-3', 'log-4', 'log-5'])
})
it('redacts credentials before retaining or persisting an event', async () => {
const save = vi.fn(async () => {})
const store = createConnectionLogStore(3, {
@@ -1,55 +0,0 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { createConnectionLogStore } from './connection-log-buffer'
import type { ConnectionLogEntry } from './connection-log-types'
const entry = (id: number): ConnectionLogEntry => ({
id: `${id}`,
ts: id,
level: 'info',
message: `event ${id}`
})
const drain = () => vi.advanceTimersByTimeAsync(0)
beforeEach(() => {
vi.useFakeTimers()
})
afterEach(() => {
vi.clearAllTimers()
vi.useRealTimers()
})
describe('connection log persistence revisions', () => {
it('replaces obsolete queued revisions while a save is delayed', async () => {
const saved: string[][] = []
let release!: () => void
let delay = false
const store = createConnectionLogStore(2, {
load: async () => [],
save: async (_host, entries) => {
saved.push(entries.map((item) => item.id))
if (delay) {
delay = false
await new Promise<void>((resolve) => {
release = resolve
})
}
}
})
await store.hydrate('a')
await drain()
saved.length = 0
delay = true
store.append('a', entry(1))
await drain()
store.append('a', entry(2))
await drain()
store.append('a', entry(3))
await drain()
expect(saved).toEqual([['1']])
release()
await drain()
expect(saved).toEqual([['1'], ['2', '3']])
})
})
@@ -1,18 +0,0 @@
import { afterEach, describe, expect, it, vi } from 'vitest'
import { createRelayRecoveryLog } from './mobile-relay-recovery-log'
import type { ConnectionLogEntry } from './connection-log-types'
afterEach(() => vi.restoreAllMocks())
describe('createRelayRecoveryLog', () => {
it('uses distinct ids across logger instances', () => {
vi.spyOn(Date, 'now').mockReturnValue(1)
const entries: ConnectionLogEntry[] = []
const sink = vi.fn((entry: ConnectionLogEntry) => entries.push(entry))
createRelayRecoveryLog(() => 1, sink)('first')
createRelayRecoveryLog(() => 1, sink)('second')
expect(entries).toHaveLength(2)
expect(entries[0]?.id).not.toBe(entries[1]?.id)
})
})
@@ -79,13 +79,4 @@ describe('native connection diagnostic reports', () => {
expect(report).toContain('Host Orca version: unknown')
expect(report).not.toContain('1.4.197')
})
it('keeps disconnected reports explicit even with a captured version', async () => {
const context = createContext()
context.setConnection('disconnected', 1_000)
const device = createNativeDiagnosticsOperations(host, context, '1.4.197')
const { report } = await device.report()
expect(report).toContain('Host Orca version: unknown (not currently connected)')
expect(report).not.toContain('1.4.197')
})
})
@@ -1,12 +1,9 @@
import { describe, expect, it, vi } from 'vitest'
import {
buildMobileImagePastePayload,
buildMobileTerminalImagePastePayload,
normalizeMobileClipboardImageBase64,
saveMobileClipboardImageAsTempFile
} from './mobile-clipboard-image'
import { computeMobileClipboardImageDownscale } from './mobile-clipboard-image-downscale'
import type { RpcClient } from '../../transport/rpc/rpc-client-contract'
import '../../transport/connection/stable-logical-rpc-client'
@@ -39,16 +36,6 @@ function clientWithResponses(responses: RpcResponse[]): Pick<RpcClient, 'sendReq
}
describe('mobile clipboard image paste helpers', () => {
it('strips data URL image prefixes', () => {
expect(normalizeMobileClipboardImageBase64('data:image/png;base64,aGVsbG8=')).toBe('aGVsbG8=')
})
it('rejects non-base64 image data', () => {
expect(() => normalizeMobileClipboardImageBase64('not base64!')).toThrow(
'Clipboard image content must be base64'
)
})
it('falls back to the legacy single-frame image save method when needed', async () => {
const client = clientWithResponses([
fail('start', 'method_not_found', 'missing'),
@@ -87,32 +74,6 @@ describe('mobile clipboard image paste helpers', () => {
})
})
it('brackets generated image paths before sending to the terminal', () => {
expect(buildMobileImagePastePayload('/tmp/orca.png', 'claude')).toBe(
'\x1b[200~/tmp/orca.png\x1b[201~'
)
expect(buildMobileImagePastePayload('/tmp/\x1b.png', 'claude')).toBe(
'\x1b[200~/tmp/\u241b.png\x1b[201~'
)
})
it('escapes spaced paths for Codex and unidentified terminals', () => {
const escaped = '\x1b[200~/tmp/or\\ ca.png\x1b[201~'
expect(buildMobileTerminalImagePastePayload('/tmp/or ca.png', 'codex')).toBe(escaped)
expect(buildMobileTerminalImagePastePayload('/tmp/or ca.png', null)).toBe(escaped)
expect(buildMobileTerminalImagePastePayload('/tmp/or ca.png', undefined)).toBe(escaped)
expect(buildMobileTerminalImagePastePayload('/tmp/or ca.png', 'unknown')).toBe(escaped)
expect(buildMobileTerminalImagePastePayload('/tmp/\x1b.png', null)).toBe(
'\x1b[200~/tmp/\u241b.png\x1b[201~'
)
})
it('keeps file mentions for agents that need them', () => {
const mention = '\x1b[200~@"/tmp/or ca.png"\x1b[201~'
expect(buildMobileTerminalImagePastePayload('/tmp/or ca.png', 'opencode')).toBe(mention)
expect(buildMobileImagePastePayload('/tmp/or ca.png', null)).toBe(mention)
})
it.each([null, 'unknown', 'codex', 'omp'])(
'contains embedded paste markers inside the image paste for %s',
(agent) => {
@@ -126,25 +87,4 @@ describe('mobile clipboard image paste helpers', () => {
expect(payload).toContain('image\u241b[201~\ncommand\u241b[200~.png')
}
)
it('quotes Windows paths with spaces using the host path dialect', () => {
expect(
buildMobileTerminalImagePastePayload('C:\\Users\\Jane Doe\\Temp\\orca-paste.png', null)
).toBe('\x1b[200~"C:\\Users\\Jane Doe\\Temp\\orca-paste.png"\x1b[201~')
})
})
describe('mobile clipboard image downscaling', () => {
it('does not downscale images already within the byte budget', () => {
expect(computeMobileClipboardImageDownscale(50, 100, 100, 100)).toBeNull()
})
it('shrinks both edges by ~sqrt(budget/actual) when over the budget', () => {
expect(computeMobileClipboardImageDownscale(400, 40, 20, 100)).toEqual({ width: 17, height: 8 })
})
it('refuses to downscale when source dimensions are unusable', () => {
expect(computeMobileClipboardImageDownscale(400, 0, 20, 100)).toBeNull()
expect(computeMobileClipboardImageDownscale(400, 40, -1, 100)).toBeNull()
})
})
@@ -1,33 +0,0 @@
import { describe, expect, it, vi } from 'vitest'
vi.mock('expo-image-picker', () => ({}))
vi.mock('expo-document-picker', () => ({ getDocumentAsync: vi.fn() }))
vi.mock('expo-file-system', () => ({ File: vi.fn() }))
import '../../platform/media-picker-contract'
import type { PickedMobileFile } from '../../platform/media-picker-contract'
import { pickMobileFiles } from './mobile-file-source-picker'
type Asset = { uri: string; name: string; size?: number; mimeType?: string }
function launcher(assets: Asset[] | null) {
return vi.fn(async () =>
assets === null
? { canceled: true as const, assets: null }
: { canceled: false as const, assets: assets.map((asset) => ({ lastModified: 0, ...asset })) }
)
}
async function collect(files: AsyncIterable<PickedMobileFile>): Promise<PickedMobileFile[]> {
const taken: PickedMobileFile[] = []
for await (const file of files) {
taken.push(file)
}
return taken
}
describe('pickMobileFiles', () => {
it('yields nothing for a cancelled picker', async () => {
expect(await collect(pickMobileFiles({ launch: launcher(null) }))).toEqual([])
})
})
@@ -56,15 +56,6 @@ describe('useMobileAttachmentInputLeaseGate', () => {
}
}
it('passes immediately when the lease is ready and the target is active', async () => {
const refs = baseRefs()
const showToast = vi.fn()
const { gate } = renderGate({ ...refs, showToast })
await expect(gate()('terminal-1')).resolves.toBe(true)
expect(showToast).not.toHaveBeenCalled()
})
it('waits out a lease-not-ready window and then sends', async () => {
const refs = baseRefs()
refs.leaseReady.current = false
@@ -1,109 +0,0 @@
import { describe, expect, it } from 'vitest'
import type { RpcResponse } from '../transport/rpc/rpc-wire-types'
import { resolveMobileFileTabDoc } from './mobile-file-tab-doc'
function ok(result: unknown): RpcResponse {
return { id: 'x', ok: true, result, _meta: { runtimeId: 'r' } }
}
function fail(code: string, message: string): RpcResponse {
return { id: 'x', ok: false, error: { code, message }, _meta: { runtimeId: 'r' } }
}
function clientOf(byMethod: Record<string, RpcResponse>): {
sendRequest: (method: string, params?: unknown) => Promise<RpcResponse>
calls: string[]
requests: { method: string; params: unknown }[]
} {
const calls: string[] = []
const requests: { method: string; params: unknown }[] = []
return {
calls,
requests,
sendRequest: (method: string, params?: unknown) => {
calls.push(method)
requests.push({ method, params })
const response = byMethod[method]
if (!response) {
throw new Error(`unexpected method ${method}`)
}
return Promise.resolve(response)
}
}
}
const WT = { worktreeId: 'wt1' }
describe('resolveMobileFileTabDoc', () => {
it('renders a staged text diff', async () => {
const client = clientOf({
'git.diff': ok({ kind: 'text', originalContent: 'a\n', modifiedContent: 'a\nb\n' })
})
const doc = await resolveMobileFileTabDoc(client, {
...WT,
relativePath: 'a.ts',
diffSource: 'staged'
})
expect(doc).toEqual({
status: 'ready',
kind: 'diff',
lines: [
{ kind: 'context', text: 'a', oldLineNumber: 1, newLineNumber: 1 },
{ kind: 'add', text: 'b', newLineNumber: 2 }
],
truncated: false
})
expect(client.requests).toEqual([
{ method: 'git.diff', params: { worktree: 'id:wt1', filePath: 'a.ts', staged: true } }
])
})
it('throws binary_file for an image modify whose bytes are empty (no stale fallback)', async () => {
const client = clientOf({
'git.diff': ok({
kind: 'binary',
originalContent: 'b2xk',
modifiedContent: '',
modifiedIsBinary: true,
isImage: true,
mimeType: 'image/png'
})
})
await expect(
resolveMobileFileTabDoc(client, { ...WT, relativePath: 'm1.png', diffSource: 'unstaged' })
).rejects.toThrow('binary_file')
})
it('throws binary_file for a non-image binary diff', async () => {
const client = clientOf({ 'git.diff': ok({ kind: 'binary', modifiedContent: 'AAAA' }) })
await expect(
resolveMobileFileTabDoc(client, { ...WT, relativePath: 'a.bin', diffSource: 'unstaged' })
).rejects.toThrow('binary_file')
})
it('throws binary_file when readPreview returns no image bytes', async () => {
const client = clientOf({
'files.readPreview': ok({ content: '', isImage: true, mimeType: 'image/png' })
})
await expect(
resolveMobileFileTabDoc(client, { ...WT, relativePath: 'logo.png' })
).rejects.toThrow('binary_file')
})
// An older client must still surface the host’s oversized-diff error message rather than render an empty diff.
it('propagates a host diff_too_large failure instead of rendering an empty diff', async () => {
const client = clientOf({
'git.diff': fail('diff_too_large', 'This diff is too large to open over a remote connection.')
})
await expect(
resolveMobileFileTabDoc(client, { ...WT, relativePath: 'a.ts', diffSource: 'staged' })
).rejects.toThrow('This diff is too large to open over a remote connection.')
})
it('propagates the RPC error message when a read fails', async () => {
const client = clientOf({ 'files.read': fail('EIO', 'file_too_large') })
await expect(
resolveMobileFileTabDoc(client, { ...WT, relativePath: 'notes.txt' })
).rejects.toThrow('file_too_large')
})
})
@@ -1,56 +0,0 @@
import { describe, expect, it, vi } from 'vitest'
import {
navigateToMobileHostEdit,
type MobileHostEditNavigationState
} from './host-edit-navigation'
function navigationHarness(initialState: MobileHostEditNavigationState) {
let stateListener = () => {}
let state = initialState
const unsubscribeState = vi.fn()
const navigation = {
addListener: vi.fn((_event: 'state', listener: () => void) => {
stateListener = listener
return unsubscribeState
}),
dispatch: vi.fn(),
getState: () => state
}
return {
navigation,
setState(nextState: MobileHostEditNavigationState) {
state = nextState
stateListener()
},
unsubscribeState
}
}
// Replacement targets the nested host stack, so committed fixtures must include it.
function committedHostState(hostIdParam: string): MobileHostEditNavigationState {
return {
index: 1,
routes: [
{ name: 'index' },
{
name: 'h',
state: {
key: '/h',
index: 0,
routes: [{ key: 'host-index', name: '[hostId]/index', params: { hostId: hostIdParam } }]
}
}
]
}
}
describe('mobile host edit navigation', () => {
it('does not replace an unrelated host route', () => {
const harness = navigationHarness({ index: 0, routes: [{ name: 'index' }] })
navigateToMobileHostEdit(harness.navigation, { push: vi.fn(), replace: vi.fn() }, 'host-1')
harness.setState(committedHostState('host-2'))
expect(harness.navigation.dispatch).not.toHaveBeenCalled()
})
})
@@ -8,11 +8,9 @@ vi.mock('../../../src/shared/sidebar-inputs-switch', () => ({ ORCA_SIDEBAR_INPUT
import '../../../src/shared/rpc-contract/workspace-view-collapse-params'
import { FakeSession } from '../transport/connection/mobile-endpoint-supervisor-test-fakes'
import type { RpcResponse } from '../transport/rpc/rpc-wire-types'
import { INITIAL_MOBILE_VIEW } from '../worktree/workspace-view-settings'
import {
addPendingViewChange,
reconcilePendingViewChanges,
withPendingViewChanges,
type PendingViewChange
} from './host-view-pending-changes'
import {
@@ -150,16 +148,6 @@ describe('pending changes over the desktop’s values', () => {
collapsed
})
it('lay the desired values over the view, oldest first', () => {
const view = withPendingViewChanges(INITIAL_MOBILE_VIEW, [
{ opId: 1, sentAt: 0, kind: 'view', patch: { groupBy: 'none' }, payload: {} },
collapse(2, true),
{ opId: 3, sentAt: 0, kind: 'view', patch: { groupBy: 'pr-status' }, payload: {} }
])
expect(view.groupBy).toBe('pr-status')
expect(view.collapsedGroups).toEqual(['k'])
})
it('keep only the latest intent for a section toggled twice', () => {
const pending = addPendingViewChange([collapse(1, true)], collapse(2, false))
expect(pending.map((change) => change.opId)).toEqual([2])
@@ -135,30 +135,3 @@ describe('the cases the rulings name', () => {
expect(bridge.frames().some((frame) => frame.type === 'end')).toBe(false)
})
})
// Test the enforced half of the desktop snapshot budget: a serialized payload at budget crosses, and one over frame cap is refused.
describe('a snapshot payload at the budget the page asks for', () => {
function scrollbackPayload(payloadBytes: number): unknown {
const skeleton = JSON.stringify({ type: 'scrollback', streamId: 1, serialized: '' }).length
return { type: 'scrollback', streamId: 1, serialized: 'x'.repeat(payloadBytes - skeleton) }
}
function post(payloadBytes: number): ReturnType<typeof harness> {
const bridge = harness({ ready: true, terminalTimers: manualTimers() })
bridge.host.receive(
clientFrame({ type: 'subscribe', id: ID, method: 'terminal.subscribe', params: {} })
)
const payload = scrollbackPayload(payloadBytes)
expect(JSON.stringify(payload)).toHaveLength(payloadBytes)
bridge.client.streams[0].emit(payload)
return bridge
}
it('ends the stream on a payload the cap cannot hold, which is why the host trims', () => {
// A host-budgeted snapshot must never reach this refusal; the page cannot detect a silently omitted event (C0.3).
const bridge = post(BRIDGE_MAX_MESSAGE_BYTES)
expect(bridge.frames().filter((frame) => frame.type === 'end')).toEqual([
{ v: 1, type: 'end', id: ID, reason: 'overflow' }
])
})
})
@@ -27,20 +27,6 @@ afterEach(() => {
})
describe('bridge client refusals and send failures', () => {
it('reports a frame its own reader will not take, and changes nothing', () => {
const page = createPageClient()
page.start()
page.deliverRaw('{ not json')
page.deliverRaw(JSON.stringify({ v: 99, type: 'state' }))
page.deliverRaw(`"${'z'.repeat(BRIDGE_MAX_MESSAGE_BYTES)}"`)
expect(page.diagnostics).toEqual([
{ kind: 'refused', refusal: 'malformed-json' },
{ kind: 'refused', refusal: 'unrecognised-message' },
{ kind: 'refused', refusal: 'oversized' }
])
expect(page.client.getState()).toBe('connected')
})
it('settles the request a reply it could not read was answering, on the same turn', async () => {
const page = createPageClient()
page.start()
@@ -42,26 +42,6 @@ afterEach(() => {
// The typed member must reject desktop methods too; widened callers could otherwise bypass the raw-port inventory’s call shapes.
// Preserve one typed refusal with a stable code; callers must not distinguish recovery actions by message text.
describe('a verb the shell refuses', () => {
it('names the grant when this side refused before sending', async () => {
const page = createPageClient()
page.deliver({ ...INIT, grants: { ...GRANTS, native: ['navigate'] } })
act(() => {
create(
<RpcClientProvider client={page.client}>
<Screen />
</RpcClientProvider>
)
})
const verbs = held.verbs
if (verbs === null) {
throw new Error('nothing mounted')
}
await expect(verbs.readClipboardText()).rejects.toMatchObject({ reason: 'ungranted' })
})
})
describe('a code this page has never heard of', () => {
it('floors to unreported rather than crossing verbatim', async () => {
// Inject a newer-shell code directly; this host normalizes unknown codes before sending, so the pair cannot produce it itself.
@@ -1,98 +0,0 @@
import { createElement } from 'react'
import { act, create } from 'react-test-renderer'
import { beforeEach, describe, expect, it, vi } from 'vitest'
type RouteDependencies = {
routes: { pathname: string; params?: Record<string, string> }[]
refusals: string[]
lifecycle: string[]
params: Record<string, string | string[] | undefined>
}
const dependencies = vi.hoisted((): RouteDependencies => ({
routes: [],
refusals: [],
lifecycle: [],
params: {}
}))
vi.mock('@react-native-async-storage/async-storage', () => ({
default: { getItem: async () => null, setItem: async () => {} }
}))
vi.mock('react-native', () => ({
StyleSheet: { create: (styles: unknown) => styles },
View: 'View'
}))
vi.mock('../transport/connection/host-client-hooks', () => ({
useHostClient: () => ({ client: null, state: 'disconnected' })
}))
vi.mock('../worktree/workspace-server', () => ({
useWorkspaceServer: () => ({ routeHost: undefined, server: null })
}))
vi.mock('expo-router', () => ({ useLocalSearchParams: () => dependencies.params }))
vi.mock('./PageRouteUnavailableScreen', () => ({
PageRouteUnavailableScreen: (props: { hostId: string }) => {
dependencies.refusals.push(props.hostId)
return null
}
}))
vi.mock('./MobileWebShellScreen', async () => {
const React = await import('react')
return {
MobileWebShellScreen: (props: {
hostId: string
route: { pathname: string; params?: Record<string, string> }
}) => {
dependencies.routes.push(props.route)
// Keep deps empty: pathname-driven effects would also run on prop updates and falsely look like remounts.
const mountedAs = React.useRef(props.route.pathname)
React.useEffect(() => {
const pathname = mountedAs.current
dependencies.lifecycle.push(`mount:${pathname}`)
return () => {
dependencies.lifecycle.push(`unmount:${pathname}`)
}
}, [])
return null
}
}
})
import MobileAgentSessionHistoryScreen from '../../app/h/[hostId]/agent-history/[worktreeId]'
async function renderRoute(): Promise<void> {
await act(async () => {
create(createElement(MobileAgentSessionHistoryScreen))
})
}
describe('the agent-history route that hands off to the shell', () => {
beforeEach(() => {
dependencies.routes.length = 0
dependencies.refusals.length = 0
dependencies.lifecycle.length = 0
dependencies.params = { hostId: 'host-1', worktreeId: 'wt-1', name: 'my worktree' }
})
// encodeURIComponent leaves dot segments intact; refuse them before constructing a route the bridge rejects.
it('refuses a dot-segment worktree id too, which is the other segment', async () => {
dependencies.params = { hostId: 'host-1', worktreeId: '..', name: 'n' }
await renderRoute()
expect(dependencies.routes).toEqual([])
expect(dependencies.refusals.at(-1)).toBe('host-1')
})
it('refuses when the route names no worktree, which the shell could not open', async () => {
dependencies.params = { hostId: 'host-1' }
await renderRoute()
expect(dependencies.routes).toEqual([])
expect(dependencies.refusals.at(-1)).toBe('host-1')
})
// Remount on route change to dispose the bridge that captured the previous route’s grants.
})
@@ -1,74 +0,0 @@
import { createElement } from 'react'
import { act, create, type ReactTestRenderer } from 'react-test-renderer'
import { afterEach, beforeEach, describe, expect, it, vi, type Mock } from 'vitest'
import {
createPageBackConsumers,
type PageBackConsumers
} from '../mobile-web-shell/bridge/page-back-consumers'
type PageBackProbe = {
claims: boolean[]
unclaimed: Mock
consumers: PageBackConsumers | null
}
// Build the real stack after imports, not inside vi.hoisted, so no fake duplicates the behavior under test.
const page = vi.hoisted((): PageBackProbe => ({ claims: [], unclaimed: vi.fn(), consumers: null }))
vi.mock('../transport/connection/client-context.web', () => ({
usePageBridgeClientIfPresent: () =>
page.consumers === null ? null : { claimBack: (claim: () => boolean) => stack().claim(claim) }
}))
import { useBackClaim } from './use-back-claim.web'
function stack(): PageBackConsumers {
if (page.consumers === null) {
throw new Error('the page back stack was not built for this case')
}
return page.consumers
}
function Screen({ claim }: { claim: (() => boolean) | null }): null {
useBackClaim(claim)
return null
}
const trees: ReactTestRenderer[] = []
function render(claim: (() => boolean) | null): ReactTestRenderer {
let tree!: ReactTestRenderer
act(() => {
tree = create(createElement(Screen, { claim }))
})
trees.push(tree)
return tree
}
beforeEach(() => {
page.claims.length = 0
page.unclaimed.mockClear()
page.consumers = createPageBackConsumers({
publishClaim: (claimed) => page.claims.push(claimed),
onUnclaimed: page.unclaimed
})
})
afterEach(() => {
act(() => {
for (const tree of trees.splice(0)) {
tree.unmount()
}
})
page.consumers = null
})
// RN Web BackHandler is inert, so sheets must claim the shell’s key through the bridge.
describe('a page screen claiming the device Back key from the shell', () => {
// Shared drawers can mount without a page provider; no available shell means no claim, never a thrown render.
it('claims nothing, and does not throw, outside the page bridge', () => {
page.consumers = null
expect(() => render(() => true)).not.toThrow()
expect(page.claims).toEqual([])
})
})
@@ -1,50 +0,0 @@
import { createElement } from 'react'
import { act, create, type ReactTestRenderer } from 'react-test-renderer'
import { afterEach, describe, expect, it, vi } from 'vitest'
const handoff = vi.hoisted(() => ({ back: vi.fn(), replace: vi.fn() }))
vi.mock('expo-router', () => ({ useLocalSearchParams: () => ({ hostId: 'laptop' }) }))
vi.mock('../navigation/route-handoff', () => ({ useRouteHandoff: () => handoff }))
vi.mock('../transport/connection/host-client-hooks', () => ({
useHostClient: () => ({ client: null, state: 'connected' })
}))
vi.mock('../components/host-protocol-gates-context', () => ({
useHostProtocolGates: () => ({ hostCapabilities: ['cap'] })
}))
vi.mock('./use-host-worktree-rows', () => ({
useHostWorktreeRows: () => [{ path: '/repo/marlin', repoId: 'r1', branch: 'marlin' }]
}))
vi.mock('../platform/external-link', () => ({ openExternalLink: vi.fn() }))
vi.mock('../components/NewWorktreeModalController', () => ({
NewWorktreeModalController: 'NewWorktreeModalController'
}))
import { NewWorkspacePageScreen } from './NewWorkspacePageScreen'
describe('the Create Workspace page', () => {
let renderer: ReactTestRenderer | null = null
afterEach(() => {
act(() => renderer?.unmount())
renderer = null
vi.clearAllMocks()
})
async function render() {
await act(async () => {
renderer = create(createElement(NewWorkspacePageScreen))
})
return renderer!.root.find((node) => String(node.type) === 'NewWorktreeModalController')
}
it("opens the new workspace's session in the overlay's place", async () => {
const drawer = await render()
act(() => drawer.props.onCreated('wt-1', 'Hammerhead', 'No startup terminal', 'ssh:box'))
expect(handoff.replace).toHaveBeenCalledWith(
'/h/laptop/session/wt-1?name=Hammerhead&created=1&warning=No+startup+terminal&executionHost=ssh%3Abox'
)
})
})
@@ -1,64 +0,0 @@
import { createElement } from 'react'
import { act, create, type ReactTestRenderer } from 'react-test-renderer'
import { afterEach, describe, expect, it, vi } from 'vitest'
import type { HostCatalogEntry, HostProfile } from '../transport/hosts/host-profile'
const router = vi.hoisted(() => ({ back: vi.fn(), push: vi.fn(), replace: vi.fn() }))
const params = vi.hoisted((): { current: Record<string, string> } => ({ current: {} }))
const catalog = vi.hoisted((): { current: HostCatalogEntry[] } => ({ current: [] }))
vi.mock('expo-router', () => ({
useLocalSearchParams: () => params.current,
useRouter: () => router
}))
vi.mock('../transport/hosts/host-store', () => ({
loadHostCatalog: async () => catalog.current
}))
vi.mock('../components/PickerModal', () => ({ PickerModal: 'PickerModal' }))
vi.mock('./NewWorkspaceOverlay', () => ({ NewWorkspaceOverlay: 'NewWorkspaceOverlay' }))
import NewWorkspaceOverlayRoute from '../../app/new-workspace'
import { newWorkspaceOverlayHref } from './new-workspace-overlay-route'
function entry(id: string, name: string): HostCatalogEntry {
const profile: HostProfile = {
id,
name,
endpoint: `ws://${id}.local:6768`,
deviceToken: `token-${id}`,
publicKeyB64: `key-${id}`,
lastConnected: 1
}
const { deviceToken: _deviceToken, ...listed } = profile
return { ...listed, credentialStatus: 'ready', profile }
}
describe("Home's New Workspace overlay", () => {
let renderer: ReactTestRenderer | null = null
afterEach(() => {
act(() => renderer?.unmount())
renderer = null
vi.clearAllMocks()
})
async function open(hostIds: string[]) {
params.current = newWorkspaceOverlayHref(hostIds).params
await act(async () => {
renderer = create(createElement(NewWorkspaceOverlayRoute))
})
const root = renderer!.root
return {
overlayFor: () =>
root.findAll((node) => String(node.type) === 'NewWorkspaceOverlay')[0]?.props.hostId,
picker: () => root.find((node) => String(node.type) === 'PickerModal')
}
}
it("opens the only offered desktop's drawer without asking", async () => {
catalog.current = [entry('desk', 'Desk')]
const overlay = await open(['desk'])
expect(overlay.overlayFor()).toBe('desk')
})
})
@@ -1,44 +0,0 @@
import { describe, expect, it, vi } from 'vitest'
vi.mock('./mobile-tasks-dependencies', () => ({ colors: {} }))
import { githubKindFromQuery, normalizeGitHubPreset } from './mobile-tasks-item-mapping'
import { scopeGitHubTaskSearch } from '../../../src/shared/work-items/task-github-search'
import { getTaskPresetQuery } from '../../../src/shared/work-items/task-preset-query'
describe('mobile task search parity', () => {
it('lets an explicit issue query override a saved PR preset', () => {
for (const preset of ['prs', 'my-prs', 'review'] as const) {
expect(githubKindFromQuery('is:issue is:open', preset)).toBe('issues')
expect(githubKindFromQuery('is:"issue" is:open', preset)).toBe('issues')
expect(scopeGitHubTaskSearch('is:issue is:open', 'prs')).toBe('is:issue is:open')
}
})
it('preserves the pull-request alias while browsing issues', () => {
expect(scopeGitHubTaskSearch('is:pull-request is:open', 'issues')).toBe(
'is:pull-request is:open'
)
expect(githubKindFromQuery('is:pull-request is:open', 'issues')).toBe('prs')
})
it('opens the PR tab for draft and review searches', () => {
for (const query of ['is:draft', 'reviewed-by:@me', 'review-requested:@me', 'is:merged']) {
expect(githubKindFromQuery(query, 'issues')).toBe('prs')
expect(scopeGitHubTaskSearch(query, 'issues')).toBe(`is:pr ${query}`)
}
})
it('does not read scope qualifiers out of labels or quoted search text', () => {
expect(scopeGitHubTaskSearch('label:is:pr', 'issues')).toBe('is:issue label:is:pr')
expect(scopeGitHubTaskSearch('"is:pull-request"', 'issues')).toBe('is:issue "is:pull-request"')
expect(githubKindFromQuery('"is:pr"', 'issues')).toBe('issues')
expect(scopeGitHubTaskSearch('is:"pr"', 'issues')).toBe('is:"pr"')
})
it('uses the current split-tab fallback for a legacy all preset', () => {
const preset = normalizeGitHubPreset('all')
expect(preset).toBe('issues')
expect(getTaskPresetQuery(preset)).toBe('is:issue is:open')
})
})
@@ -1,36 +1,7 @@
import { describe, expect, it } from 'vitest'
import {
deriveRepoSlug,
findRepoMatchingSlugForPaste,
resolvePasteIntent,
type PasteRepoCandidate
} from './smart-source-paste-intent'
import type { RpcClient } from '../transport/rpc/rpc-client-contract'
import { deriveRepoSlug, resolvePasteIntent } from './smart-source-paste-intent'
describe('resolvePasteIntent', () => {
it('classifies a GitHub issue/PR URL as a github-link', () => {
expect(resolvePasteIntent('https://github.com/acme/widgets/pull/12')).toEqual({
kind: 'github-link',
link: { slug: { owner: 'acme', repo: 'widgets', host: 'github.com' }, number: 12, type: 'pr' }
})
})
it('classifies a bare #number as a github-number', () => {
expect(resolvePasteIntent('#42')).toEqual({ kind: 'github-number', number: 42 })
})
it('classifies a GitLab MR URL as a gitlab-link', () => {
const intent = resolvePasteIntent('https://gitlab.com/group/proj/-/merge_requests/8')
expect(intent?.kind).toBe('gitlab-link')
if (intent?.kind === 'gitlab-link') {
expect(intent.link).toMatchObject({ number: 8, type: 'mr' })
}
})
it('returns null for plain search text', () => {
expect(resolvePasteIntent('login bug')).toBeNull()
})
it('rejects oversized paste intents before any exact lookup', () => {
expect(
resolvePasteIntent(`https://github.com/acme/widgets/issues/12/${'x'.repeat(2048)}`)
@@ -39,13 +10,6 @@ describe('resolvePasteIntent', () => {
})
describe('deriveRepoSlug', () => {
it('prefers the upstream identity', () => {
expect(deriveRepoSlug({ upstream: { owner: 'up', repo: 'stream' } })).toEqual({
owner: 'up',
repo: 'stream'
})
})
it('preserves an Enterprise upstream host', () => {
expect(
deriveRepoSlug({
@@ -53,44 +17,4 @@ describe('deriveRepoSlug', () => {
})
).toEqual({ owner: 'up', repo: 'stream', host: 'github.corp.example' })
})
it('parses an SSH remote URL', () => {
expect(
deriveRepoSlug({ gitRemoteIdentity: { remoteUrl: 'git@github.com:acme/widgets.git' } })
).toEqual({ owner: 'acme', repo: 'widgets' })
})
it('parses an HTTPS remote URL', () => {
expect(
deriveRepoSlug({ gitRemoteIdentity: { remoteUrl: 'https://github.com/acme/widgets' } })
).toEqual({ owner: 'acme', repo: 'widgets' })
})
it('returns null when no slug can be derived', () => {
expect(deriveRepoSlug({})).toBeNull()
})
})
describe('findRepoMatchingSlug', () => {
const repos: PasteRepoCandidate[] = [
{ id: 'a', displayName: 'A', slug: { owner: 'acme', repo: 'widgets' } },
{ id: 'b', displayName: 'B', slug: null }
]
it('caches a rejected optional repo slug probe as no match', async () => {
const client = {
sendRequest: async () => {
throw new Error('connection closed')
}
} as unknown as RpcClient
await expect(
findRepoMatchingSlugForPaste(
client,
repos,
{ owner: 'enterprise', repo: 'widgets' },
new Map()
)
).resolves.toBeNull()
})
})
+26 -102
View File
@@ -1,118 +1,46 @@
import { describe, expect, it } from 'vitest'
import { FakeSession } from '../transport/connection/mobile-endpoint-supervisor-test-fakes'
import type { RpcClient } from '../transport/rpc/rpc-client-contract'
import type { ConnectionState } from '../transport/connection/connection-state'
import { createWorktreeWithNameRetry } from './worktree-create-retry'
type Attempt = { method: string; params: Record<string, unknown> }
// Model both pending-frame rejection and leaving connected; replay waits on transport recovery.
function connectionController(): {
getState: () => ConnectionState
onStateChange: (listener: (state: ConnectionState) => void) => () => void
set: (next: ConnectionState) => void
} {
let state: ConnectionState = 'connected'
const listeners = new Set<(next: ConnectionState) => void>()
return {
getState: () => state,
onStateChange: (listener) => {
listeners.add(listener)
return () => listeners.delete(listener)
},
set: (next) => {
state = next
for (const listener of listeners) {
listener(next)
}
}
}
}
type Attempt = { method: string; params: unknown }
function scriptedClient(
outcomes: Array<
| { id: string; displayName?: string; warning?: string }
| { errorMessage: string }
// takesMs models how long the ambiguity took to SURFACE — a clean close is
// instant, a half-open socket waits out the liveness watchdog or the timeout.
// reconnectsAfterMs brings the transport back so the next replay can run.
| { throws: unknown; dropsConnection?: boolean; takesMs?: number; reconnectsAfterMs?: number }
>,
attempts: Attempt[],
connection?: ReturnType<typeof connectionController>,
// Use actual inbound timestamps so freshness survives suspension; absent timestamps fall back to send time.
lastInboundAt?: number | (() => number)
outcomes: ({ id: string; displayName?: string; warning?: string } | { errorMessage: string })[],
attempts: Attempt[]
): RpcClient {
let call = 0
return {
getState: () => connection?.getState() ?? 'connected',
getLastInboundAt: () =>
(typeof lastInboundAt === 'function' ? lastInboundAt() : lastInboundAt) ?? null,
onStateChange: (listener: (state: ConnectionState) => void) =>
connection?.onStateChange(listener) ?? (() => {}),
sendRequest: async (method: string, params?: unknown) => {
attempts.push({ method, params: (params ?? {}) as Record<string, unknown> })
const outcome = outcomes[Math.min(call, outcomes.length - 1)]!
call += 1
if ('throws' in outcome) {
if (outcome.takesMs !== undefined) {
await new Promise((resolve) => setTimeout(resolve, outcome.takesMs))
}
if (outcome.dropsConnection) {
connection?.set('reconnecting')
if (outcome.reconnectsAfterMs !== undefined) {
setTimeout(() => connection?.set('connected'), outcome.reconnectsAfterMs)
}
}
throw outcome.throws
}
if ('errorMessage' in outcome) {
return {
id: '1',
ok: false,
error: { code: 'x', message: outcome.errorMessage },
_meta: { runtimeId: 'r' }
}
}
const client = new FakeSession('connected')
client.sendRequest.mockImplementation(async (method: string, params?: unknown) => {
attempts.push({ method, params: params ?? {} })
const outcome = outcomes[Math.min(call, outcomes.length - 1)]!
call += 1
if ('errorMessage' in outcome) {
return {
id: '1',
ok: true,
result: {
worktree: {
id: outcome.id,
...(outcome.displayName !== undefined ? { displayName: outcome.displayName } : {})
},
...(outcome.warning !== undefined ? { warning: outcome.warning } : {})
},
ok: false,
error: { code: 'x', message: outcome.errorMessage },
_meta: { runtimeId: 'r' }
}
}
} as unknown as RpcClient
return {
id: '1',
ok: true,
result: {
worktree: {
id: outcome.id,
...(outcome.displayName !== undefined ? { displayName: outcome.displayName } : {})
},
...(outcome.warning !== undefined ? { warning: outcome.warning } : {})
},
_meta: { runtimeId: 'r' }
}
})
return client
}
describe('createWorktreeWithNameRetry', () => {
// Creation can succeed after PTY spawn failure; warning is the only host explanation.
// Unmarked errors are definite failures and must never enter ambiguous replay.
it('uses the host-selected display name after a collision retry', async () => {
const attempts: Attempt[] = []
const client = scriptedClient(
[{ errorMessage: 'already exists locally' }, { id: 'wt-host-name', displayName: 'topic-3' }],
attempts
)
await expect(
createWorktreeWithNameRetry({
client,
baseName: 'topic',
buildParams: (name) => ({ repo: 'id:r', name }),
worktreeCreateIdempotency: false
})
).resolves.toEqual({ worktreeId: 'wt-host-name', name: 'topic-3' })
})
it('falls back to the client candidate when an older host omits displayName', async () => {
const attempts: Attempt[] = []
const client = scriptedClient(
@@ -129,8 +57,4 @@ describe('createWorktreeWithNameRetry', () => {
})
).resolves.toEqual({ worktreeId: 'wt-legacy', name: 'topic-2' })
})
// Delivery-unknown uses WeakSet object identity; wrapping the rejection would lose evidence that the host may have created.
// Definite failures must not acquire delivery-unknown marks.
})
@@ -1,130 +0,0 @@
import { describe, expect, it } from 'vitest'
import {
shouldDismissKeyboardAfterTerminalSend,
type AgentSendKeyboardDismissalTab
} from './agent-send-keyboard-dismissal'
function terminalTab(overrides: Partial<AgentSendKeyboardDismissalTab> = {}) {
return { type: 'terminal', title: 'Terminal', ...overrides }
}
describe('shouldDismissKeyboardAfterTerminalSend', () => {
it('dismisses for a live agent session', () => {
expect(
shouldDismissKeyboardAfterTerminalSend(
terminalTab({ agentStatus: { agentType: 'claude' } }),
true
)
).toBe(true)
})
it('dismisses off launchAgent before the first agent-status update lands', () => {
expect(
shouldDismissKeyboardAfterTerminalSend(terminalTab({ launchAgent: 'codex' }), true)
).toBe(true)
})
it('keeps the keyboard when an agent send is rejected', () => {
expect(
shouldDismissKeyboardAfterTerminalSend(
terminalTab({ agentStatus: { agentType: 'claude' } }),
false
)
).toBe(false)
})
it('keeps the keyboard for a plain shell so back-to-back commands stay typeable', () => {
expect(shouldDismissKeyboardAfterTerminalSend(terminalTab(), true)).toBe(false)
expect(shouldDismissKeyboardAfterTerminalSend(terminalTab({ agentStatus: null }), true)).toBe(
false
)
})
it('treats a blank agent label as no agent', () => {
expect(
shouldDismissKeyboardAfterTerminalSend(terminalTab({ agentStatus: { agentType: '' } }), true)
).toBe(false)
expect(
shouldDismissKeyboardAfterTerminalSend(
terminalTab({ agentStatus: { agentType: ' ' } }),
true
)
).toBe(false)
expect(
shouldDismissKeyboardAfterTerminalSend(
terminalTab({
agentStatus: { agentType: null },
launchAgent: null
}),
true
)
).toBe(false)
})
it('falls through to launchAgent only when live status carries no agent', () => {
expect(
shouldDismissKeyboardAfterTerminalSend(
terminalTab({
agentStatus: { agentType: null },
launchAgent: 'claude'
}),
true
)
).toBe(true)
})
it('never dismisses for non-terminal tabs or a missing tab', () => {
expect(
shouldDismissKeyboardAfterTerminalSend(
{
type: 'markdown',
title: 'README.md',
agentStatus: { agentType: 'claude' }
},
true
)
).toBe(false)
expect(shouldDismissKeyboardAfterTerminalSend(null, true)).toBe(false)
expect(shouldDismissKeyboardAfterTerminalSend(undefined, true)).toBe(false)
})
it('does not authorize dismissal from unknown status or a display-only title', () => {
expect(
shouldDismissKeyboardAfterTerminalSend(
terminalTab({ agentStatus: { agentType: 'unknown' } }),
true
)
).toBe(false)
expect(
shouldDismissKeyboardAfterTerminalSend(terminalTab({ title: '✦ Gemini CLI' }), true)
).toBe(false)
})
it.each(['zsh', 'bash', 'pwsh'])(
'keeps the keyboard when identity-only done status is stale under %s',
(title) => {
expect(
shouldDismissKeyboardAfterTerminalSend(
terminalTab({
title,
agentStatus: { agentType: 'claude', state: 'done' },
launchAgent: 'claude'
}),
true
)
).toBe(false)
}
)
it('still dismisses for a completed agent under a non-shell title', () => {
expect(
shouldDismissKeyboardAfterTerminalSend(
terminalTab({
title: 'Terminal',
agentStatus: { agentType: 'claude', state: 'done' }
}),
true
)
).toBe(true)
})
})