test: retire low-value mobile composer and CDP suites (#41699)

Co-authored-by: OrcaWin <293788423+OrcaWin@users.noreply.github.com>
This commit is contained in:
OrcaWin
2026-11-12 15:52:58 -08:00
committed by GitHub
co-authored by OrcaWin
parent bb21570c65
commit b546bd0a23
9 changed files with 2 additions and 1107 deletions
@@ -900,13 +900,11 @@
"src/main/browser/webauthn/browser-webauthn-account-picker.test.ts": 78,
"src/main/browser/webauthn/browser-webauthn-profile-delete.test.ts": 358,
"src/main/browser/cdp/commands/cdp-bridge-integration.test.ts": 28361,
"src/main/browser/cdp/transport/cdp-client-response-writer.test.ts": 279,
"src/main/browser/cdp/commands/cdp-print-to-pdf.test.ts": 68,
"src/main/browser/cdp/commands/cdp-screenshot.test.ts": 415,
"src/main/browser/cdp/transport/cdp-ws-proxy-first-paint.test.ts": 366,
"src/main/browser/cdp/transport/cdp-ws-proxy-host-admission.test.ts": 576,
"src/main/browser/cdp/transport/cdp-ws-proxy-input-focus.test.ts": 360,
"src/main/browser/cdp/transport/cdp-ws-proxy-malformed-messages.test.ts": 305,
"src/main/browser/cdp/transport/cdp-ws-proxy-origin.test.ts": 262,
"src/main/browser/cdp/transport/cdp-ws-proxy-startup-lifetime.test.ts": 326,
"src/main/browser/cdp/transport/cdp-ws-proxy.test.ts": 2756,
@@ -1,138 +0,0 @@
import '../../../transport/rpc/rpc-delivery-ambiguity'
import { activateMobileUiLocale } from '../../../i18n/mobile-i18n'
import './use-mobile-native-chat-image-attachments'
import './mobile-native-chat-draft-store'
import {
readMobileNativeChatDraftInputs,
updateMobileNativeChatDraftInputs
} from './mobile-native-chat-draft-inputs'
import './use-mobile-native-chat-drafts'
import './use-mobile-structured-native-chat-send-bridge'
import '../mobile-native-chat-scope-key'
import '../agent-session/use-mobile-structured-agent-session'
import '../agent-session/use-mobile-structured-agent-session-queued.test-fixture'
import '../../structured-agent-send-result.test-fixture'
import { findByHostType } from '../../../test-support/react-test-renderer-host-nodes'
import '../agent-session/mobile-structured-agent-session-host-support'
import '../../../../../src/shared/agent-session/agent-session-runtime-capabilities'
import '../input/use-mobile-structured-agent-options'
import '../input/use-mobile-structured-agent-options.test-fixture'
import { createElement, type ComponentProps } from 'react'
import { act, type ReactTestRenderer } from 'react-test-renderer'
import { createWithQueryClient } from '../../../test-support/query-client-test-renderer'
import { afterEach, describe, expect, it, vi } from 'vitest'
import { MobileNativeChatComposer as NativeChatComposer } from './MobileNativeChatComposer'
vi.mock('../../../components/MobileSwitch', () => ({ MobileSwitch: 'Switch' }))
vi.mock('./MobileNativeChatContextUsageRing', () => ({
useMobileNativeChatContextRing: () => ({ barProps: {}, ring: null })
}))
vi.mock('../../../platform/media-picker', () => ({
useMediaPicker: () => ({ pickImages: async () => [] })
}))
vi.mock('@react-native-async-storage/async-storage', () => ({
default: { getItem: async () => null, setItem: async () => {}, removeItem: async () => {} }
}))
const getNoComposerEditGeneration = () => 0
function MobileNativeChatComposer({
getComposerEditGeneration = getNoComposerEditGeneration,
...props
}: Omit<ComponentProps<typeof NativeChatComposer>, 'getComposerEditGeneration'> & {
getComposerEditGeneration?: () => number
}): React.JSX.Element {
return createElement(NativeChatComposer, { ...props, getComposerEditGeneration })
}
// BottomDrawer also carries the option pager, which loads Reanimated at import.
vi.mock('react-native-reanimated', async () =>
(await import('../../../test-support/reanimated-pager-stub')).reanimatedPagerStub()
)
vi.mock('react-native', async () => {
const React = await import('react')
return {
...(await import('../../../test-support/react-native-motion-stub')).reactNativeMotionStub(),
ActivityIndicator: 'ActivityIndicator',
Image: 'Image',
Keyboard: { dismiss: vi.fn() },
Platform: { OS: 'ios' },
Pressable: 'Pressable',
ScrollView: ({ children, ...props }: { children?: React.ReactNode }) =>
React.createElement('ScrollView', props, children),
StyleSheet: {
create: (styles: unknown) => styles,
hairlineWidth: 1
},
Text: 'Text',
TextInput: 'TextInput',
View: 'View'
}
})
vi.mock('lucide-react-native', () => ({
ArrowUp: 'ArrowUp',
AtSign: 'AtSign',
Image: 'Image',
Paperclip: 'Paperclip',
Check: 'Check',
ChevronDown: 'ChevronDown',
ChevronLeft: 'ChevronLeft',
ChevronRight: 'ChevronRight',
CornerDownRight: 'CornerDownRight',
FileText: 'FileText',
Goal: 'Goal',
PencilRuler: 'PencilRuler',
ListEnd: 'ListEnd',
Mic: 'Mic',
Package: 'Package',
Plus: 'Plus',
ShieldAlert: 'ShieldAlert',
Square: 'Square',
Terminal: 'Terminal',
X: 'X'
}))
vi.mock('../../../components/bottom-drawer/mounted-bottom-drawer', () => ({
MountedBottomDrawer: 'BottomDrawer'
}))
vi.mock('../../../components/bottom-drawer/bottom-drawer-modal-host-scope', () => ({
useBottomDrawerModalHost: () => null
}))
describe('MobileNativeChatComposer on a structured chat', () => {
let renderer: ReactTestRenderer | null = null
afterEach(async () => {
act(() => renderer?.unmount())
renderer = null
await activateMobileUiLocale('en')
})
it('forgets inline picked skill identity after its token is removed and retyped', async () => {
const scope = 'removed-skill'
updateMobileNativeChatDraftInputs(scope, () => ({
images: [],
files: [],
skills: [{ name: 'review', path: '/remote/SKILL.md' }]
}))
await act(async () => {
renderer = createWithQueryClient(
createElement(MobileNativeChatComposer, {
draftScopeKey: scope,
value: '$review draft',
editSession: { cancel: vi.fn(), locked: false, refuseCommand: () => false },
onChangeText: vi.fn(),
onSend: async () => false,
sendSurfaceId: scope,
getSendCompletionGeneration: getNoComposerEditGeneration
})
)
})
const input = () => findByHostType(renderer!.root, 'TextInput')
await act(async () => input().props.onChangeText('draft'))
await act(async () => input().props.onChangeText('$review draft'))
expect(readMobileNativeChatDraftInputs(scope).skills).toEqual([])
})
})
@@ -1,6 +1,5 @@
import { createElement, type ComponentProps, type ReactNode } from 'react'
import { act, create, type ReactTestInstance, type ReactTestRenderer } from 'react-test-renderer'
import { Keyboard } from 'react-native'
import { act, create, type ReactTestRenderer } from 'react-test-renderer'
import { afterEach, describe, expect, it, vi } from 'vitest'
import {
useMobileNativeChatDraft,
@@ -8,10 +7,7 @@ import {
} from './mobile-native-chat-draft-store'
import { MobileNativeChatComposer as NativeChatComposer } from './MobileNativeChatComposer'
import {
findAllByHostType,
findByHostType
} from '../../../test-support/react-test-renderer-host-nodes'
import { findByHostType } from '../../../test-support/react-test-renderer-host-nodes'
import { captureMobileNativeChatTextDestination } from './mobile-native-chat-draft-inputs'
@@ -79,49 +75,12 @@ vi.mock('../../../components/bottom-drawer/bottom-drawer-modal-host-scope', () =
describe('MobileNativeChatComposer', () => {
let renderer: ReactTestRenderer | null = null
const getCurrentSendCompletionGeneration = () => 0
afterEach(() => {
act(() => renderer?.unmount())
renderer = null
})
async function render(
onSend: (text: string) => Promise<boolean>,
onChangeText: (text: string) => void,
isAttaching = false,
sendSurfaceId = 'tab-a',
getSendCompletionGeneration = () => 0
) {
let composerEditGeneration = 0
await act(async () => {
renderer = create(
createElement(MobileNativeChatComposer, {
value: ' hello ',
onChangeText: (text) => {
composerEditGeneration += 1
onChangeText(text)
},
onSend,
sendSurfaceId,
getSendCompletionGeneration,
getComposerEditGeneration: () => composerEditGeneration,
isAttaching
})
)
})
}
function sendButton(): ReactTestInstance {
if (!renderer) {
throw new Error('Composer was not rendered')
}
return renderer.root.find(
(node) =>
String(node.type) === 'Pressable' && node.props.accessibilityLabel === 'Send message'
)
}
it('appends dictation until a selection is read, then replaces the selection it started on', async () => {
const scope = 'dictation-ordinary'
setMobileNativeChatDraftText(scope, 'Ok')
@@ -157,384 +116,4 @@ describe('MobileNativeChatComposer', () => {
say('now')
expect(input().props.value).toBe('Ok there now')
})
it('locks pickers during a pending send while keeping Stop and the next draft usable', async () => {
// Apply during the host’s body/Enter delay would become part of the prompt.
let releaseSend: ((accepted: boolean) => void) | undefined
const onSend = vi.fn(
() =>
new Promise<boolean>((resolve) => {
releaseSend = resolve
})
)
const controller = {
snapshot: [
{
id: 'model',
label: 'Model',
category: 'model' as const,
kind: {
type: 'select' as const,
choices: [
{ value: 'sonnet', label: 'Sonnet 5' },
{ value: 'opus', label: 'Opus 4.8' }
]
},
valueSource: 'unknown' as const,
transport: 'catalog' as const,
settable: true
}
],
pendingId: null,
setOption: vi.fn(),
invokeAction: vi.fn(),
recordCommand: vi.fn()
}
const onStop = vi.fn()
const draw = (value: string) =>
createElement(MobileNativeChatComposer, {
value,
onChangeText: vi.fn(),
onSend,
sendSurfaceId: 'tab-a',
getSendCompletionGeneration: getCurrentSendCompletionGeneration,
sessionOptions: { isWorking: false, controller },
stop: { onStop, held: false }
})
await act(async () => {
renderer = create(draw('run the tests'))
})
const modelPill = () =>
renderer!.root.find(
(node) =>
String(node.type) === 'Pressable' && node.props.accessibilityLabel === 'Model, Model'
)
expect(modelPill().props.accessibilityState).toMatchObject({ disabled: false })
let pressed!: Promise<void>
await act(async () => {
pressed = sendButton().props.onPress()
await Promise.resolve()
})
expect(onSend).toHaveBeenCalled()
await act(async () => renderer!.update(draw('')))
await act(async () => renderer!.update(draw('next draft')))
await act(async () =>
renderer!.root.findByProps({ accessibilityLabel: 'Stop the agent' }).props.onPress()
)
expect(onStop).toHaveBeenCalledTimes(1)
expect(onSend).toHaveBeenCalledTimes(1)
expect(findByHostType(renderer!.root, 'TextInput').props.value).toBe('next draft')
expect(modelPill().props.accessibilityState).toMatchObject({ disabled: true })
await act(async () => {
releaseSend?.(true)
await pressed
})
expect(modelPill().props.accessibilityState).toMatchObject({ disabled: false })
expect(sendButton().props.disabled).toBe(false)
})
it('retains an editable draft through a send lock and can send it after unlocking', async () => {
const onSend = vi.fn().mockResolvedValue(true)
const onChangeText = vi.fn()
vi.mocked(Keyboard.dismiss).mockClear()
const draw = (disabled: boolean, value = 'half-typed') =>
createElement(MobileNativeChatComposer, {
value,
onChangeText,
onSend,
sendSurfaceId: 'tab-a',
getSendCompletionGeneration: getCurrentSendCompletionGeneration,
disabled
})
await act(async () => {
renderer = create(draw(false))
})
const input = () => findByHostType(renderer!.root, 'TextInput')
const originalInput = input()
await act(async () => input().props.onFocus())
await act(async () => renderer!.update(draw(true)))
// Do not revoke editable: iOS resigns first responder and closes the keyboard.
expect(input()).toBe(originalInput)
expect(input().props.editable).not.toBe(false)
expect(sendButton().props).toMatchObject({ disabled: true })
await act(async () => sendButton().props.onPress())
expect(onSend).not.toHaveBeenCalled()
expect(onChangeText).not.toHaveBeenCalled()
expect(input().props.value).toBe('half-typed')
expect(Keyboard.dismiss).not.toHaveBeenCalled()
await act(async () => input().props.onChangeText('finished draft'))
expect(onChangeText).toHaveBeenCalledWith('finished draft')
await act(async () => renderer!.update(draw(true, 'finished draft')))
expect(input().props.value).toBe('finished draft')
await act(async () => renderer!.update(draw(false, 'finished draft')))
expect(input()).toBe(originalInput)
expect(sendButton().props).toMatchObject({ disabled: false })
await act(async () => sendButton().props.onPress())
expect(onSend).toHaveBeenCalledExactlyOnceWith('finished draft')
})
it('holds each picker through dismissal and restores only pill-displaced focus', async () => {
const focus = vi.fn()
const controller = {
snapshot: ['model', 'effort'].map((id) => ({
id,
label: id,
category: id === 'model' ? ('model' as const) : ('thought_level' as const),
kind: { type: 'select' as const, choices: [] },
valueSource: 'unknown' as const,
transport: 'catalog' as const,
settable: true
})),
pendingId: null,
setOption: vi.fn(),
invokeAction: vi.fn(),
recordCommand: vi.fn(),
optionPickerRequest: { id: 'model', sequence: 0 }
}
const draw = () =>
createElement(MobileNativeChatComposer, {
value: '',
onChangeText: vi.fn(),
onSend: vi.fn().mockResolvedValue(true),
sendSurfaceId: 'tab-a',
getSendCompletionGeneration: getCurrentSendCompletionGeneration,
sessionOptions: { controller, isWorking: false }
})
await act(async () => {
renderer = create(draw(), {
createNodeMock: (element) => (element.type === 'TextInput' ? { focus } : null)
})
})
const field = () => findByHostType(renderer!.root, 'TextInput')
const press = async (label: string) =>
act(async () => renderer!.root.findByProps({ accessibilityLabel: label }).props.onPress())
expect(findAllByHostType(renderer!.root, 'BottomDrawer')).toHaveLength(0)
await act(async () => field().props.onFocus())
await press('Model, Model')
await act(async () => field().props.onBlur())
await press('Effort, Not set')
await press('Back to models')
await press('Done')
await act(async () => findByHostType(renderer!.root, 'BottomDrawer').props.onHidden())
expect(focus).toHaveBeenCalledTimes(1)
for (const id of ['model', 'effort']) {
await act(async () => field().props.onFocus())
controller.optionPickerRequest = { id, sequence: controller.optionPickerRequest.sequence + 1 }
await act(async () => renderer!.update(draw()))
await act(async () => field().props.onBlur())
await act(async () => findByHostType(renderer!.root, 'BottomDrawer').props.onClose())
await act(async () => findByHostType(renderer!.root, 'BottomDrawer').props.onHidden())
expect(focus).toHaveBeenCalledTimes(1)
}
await act(async () => renderer!.unmount())
await act(async () => {
renderer = create(draw())
})
expect(findAllByHostType(renderer!.root, 'BottomDrawer')).toHaveLength(0)
})
it('moves the caret to the insert point after an autocomplete pick, then releases control', async () => {
const onChangeText = vi.fn()
await act(async () => {
renderer = create(
createElement(MobileNativeChatComposer, {
value: '/c',
onChangeText,
onSend: vi.fn().mockResolvedValue(true),
sendSurfaceId: 'tab-a',
getSendCompletionGeneration: getCurrentSendCompletionGeneration,
agent: 'claude'
})
)
})
const input = () => findByHostType(renderer!.root, 'TextInput')
expect(input().props.selection).toBeUndefined()
await act(async () =>
input().props.onSelectionChange({ nativeEvent: { selection: { end: 2 } } })
)
const clear = renderer!.root.find(
(node) => node.props.accessibilityLabel === '/clear' && node.props.onPress !== undefined
)
await act(async () => clear.props.onPress())
expect(onChangeText).toHaveBeenCalledWith('/clear ')
expect(input().props.selection).toEqual({ start: 7, end: 7 })
await act(async () =>
input().props.onSelectionChange({ nativeEvent: { selection: { end: 7 } } })
)
expect(input().props.selection).toBeUndefined()
})
it('does not dismiss a newly focused composer when an old accepted send settles', async () => {
vi.mocked(Keyboard.dismiss).mockClear()
let resolveSend: ((accepted: boolean) => void) | null = null
const onSend = vi.fn(
() =>
new Promise<boolean>((resolve) => {
resolveSend = resolve
})
)
await render(onSend, vi.fn())
let pendingSend!: Promise<void>
await act(async () => {
pendingSend = sendButton().props.onPress()
await Promise.resolve()
})
await act(async () => {
renderer!.update(
createElement(MobileNativeChatComposer, {
value: 'new surface draft',
onChangeText: vi.fn(),
onSend: vi.fn().mockResolvedValue(true),
sendSurfaceId: 'tab-b',
getSendCompletionGeneration: getCurrentSendCompletionGeneration
})
)
})
await act(async () => {
resolveSend?.(true)
await pendingSend
})
expect(Keyboard.dismiss).not.toHaveBeenCalled()
})
it('does not dismiss after a newer edit on the same surface', async () => {
vi.mocked(Keyboard.dismiss).mockClear()
let resolveSend: ((accepted: boolean) => void) | null = null
const onSend = vi.fn(
() =>
new Promise<boolean>((resolve) => {
resolveSend = resolve
})
)
await render(onSend, vi.fn())
let pendingSend!: Promise<void>
await act(async () => {
pendingSend = sendButton().props.onPress()
await Promise.resolve()
})
const input = findByHostType(renderer!.root, 'TextInput')
await act(async () => input.props.onChangeText('newer draft'))
await act(async () => {
resolveSend?.(true)
await pendingSend
})
expect(Keyboard.dismiss).not.toHaveBeenCalled()
})
it('does not dismiss after autocomplete mutates the same surface', async () => {
vi.mocked(Keyboard.dismiss).mockClear()
let editGeneration = 0
let resolveSend: ((accepted: boolean) => void) | null = null
const onSend = vi.fn(
() =>
new Promise<boolean>((resolve) => {
resolveSend = resolve
})
)
await act(async () => {
renderer = create(
createElement(MobileNativeChatComposer, {
value: '/c',
onChangeText: () => {
editGeneration += 1
},
onSend,
sendSurfaceId: 'tab-a',
getSendCompletionGeneration: getCurrentSendCompletionGeneration,
getComposerEditGeneration: () => editGeneration,
agent: 'claude'
})
)
})
const input = findByHostType(renderer!.root, 'TextInput')
await act(async () => input.props.onSelectionChange({ nativeEvent: { selection: { end: 2 } } }))
let pendingSend!: Promise<void>
await act(async () => {
pendingSend = sendButton().props.onPress()
await Promise.resolve()
})
const suggestion = renderer!.root.find(
(node) => node.props.accessibilityLabel === '/clear' && node.props.onPress !== undefined
)
await act(async () => suggestion.props.onPress())
await act(async () => {
resolveSend?.(true)
await pendingSend
})
expect(Keyboard.dismiss).not.toHaveBeenCalled()
})
it('does not dismiss after dictation mutates the controlled draft', async () => {
vi.mocked(Keyboard.dismiss).mockClear()
let editGeneration = 0
let resolveSend: ((accepted: boolean) => void) | null = null
const onSend = vi.fn(
() =>
new Promise<boolean>((resolve) => {
resolveSend = resolve
})
)
const props = {
value: 'hello',
onChangeText: vi.fn(),
onSend,
sendSurfaceId: 'tab-a',
getSendCompletionGeneration: getCurrentSendCompletionGeneration,
getComposerEditGeneration: () => editGeneration
}
await act(async () => {
renderer = create(createElement(MobileNativeChatComposer, props))
})
let pendingSend!: Promise<void>
await act(async () => {
pendingSend = sendButton().props.onPress()
await Promise.resolve()
})
editGeneration += 1
await act(async () => {
renderer!.update(
createElement(MobileNativeChatComposer, { ...props, value: 'hello dictated text' })
)
})
await act(async () => {
resolveSend?.(true)
await pendingSend
})
expect(Keyboard.dismiss).not.toHaveBeenCalled()
})
it('does not dismiss after its retained route loses focus', async () => {
vi.mocked(Keyboard.dismiss).mockClear()
let generation = 0
let resolveSend: ((accepted: boolean) => void) | null = null
const onSend = vi.fn(
() =>
new Promise<boolean>((resolve) => {
resolveSend = resolve
})
)
await render(onSend, vi.fn(), false, 'tab-a', () => generation)
let pendingSend!: Promise<void>
await act(async () => {
pendingSend = sendButton().props.onPress()
await Promise.resolve()
})
generation += 1
await act(async () => {
resolveSend?.(true)
await pendingSend
})
expect(Keyboard.dismiss).not.toHaveBeenCalled()
})
})
@@ -1,93 +0,0 @@
import { describe, expect, it } from 'vitest'
import type { NativeChatMessage } from '../../../../../src/shared/native-chat/native-chat-types'
import {
findLandedImagePreviewEchoes,
type PendingImagePreviewEcho
} from './mobile-native-chat-draft-reconcile'
function userText(id: string, text: string): NativeChatMessage {
return {
id,
role: 'user',
blocks: [{ type: 'text', text }],
timestamp: null,
source: 'transcript'
}
}
function pending(
id: string,
images: string[],
matchingOccurrence?: number
): PendingImagePreviewEcho {
return { id, text: '', images, sentAt: 0, matchingOccurrence, afterMessageId: null }
}
describe('mobile native chat image preview reconciliation', () => {
it('does not bind a glued image echo to an ordinary row with the same prefix', () => {
const messages = [
userText('ordinary', 'look at this later'),
userText('source', '[Image: source: /tmp/a.png]'),
userText('prompt', 'look at this[Image #1] is it still working?')
]
const preview = { ...pending('pending', ['file:///a.jpg']), text: 'look at this' }
expect(findLandedImagePreviewEchoes(messages, [preview])).toEqual([
{ pendingId: 'pending', messageId: 'prompt', images: ['file:///a.jpg'] }
])
})
it('keeps separate adjacent image-only sends independently reconcilable', () => {
const landed = findLandedImagePreviewEchoes(
[
userText('source-a', '[Image: source: /tmp/a.png]'),
userText('source-b', '[Image: source: /tmp/b.png]')
],
[pending('pending-a', ['file:///a.jpg']), pending('pending-b', ['file:///b.jpg'], 2)]
)
expect(landed).toEqual([
{ pendingId: 'pending-a', messageId: 'source-a', images: ['file:///a.jpg'] },
{ pendingId: 'pending-b', messageId: 'source-b', images: ['file:///b.jpg'] }
])
})
it('waits for a complete multi-image turn as transcript source frames stream in', () => {
const entry = pending('pending', ['file:///a.jpg', 'file:///b.jpg'])
const sourceA = userText('source-a', '[Image: source: /tmp/a.png]')
const sourceB = userText('source-b', '[Image: source: /tmp/b.png]')
expect(findLandedImagePreviewEchoes([sourceA], [entry])).toEqual([])
expect(findLandedImagePreviewEchoes([sourceA, sourceB], [entry])).toEqual([])
expect(
findLandedImagePreviewEchoes(
[sourceA, sourceB, userText('prompt', '[Image #1] [Image #2]')],
[entry]
)
).toEqual([
{
pendingId: 'pending',
messageId: 'prompt',
images: ['file:///a.jpg', 'file:///b.jpg']
}
])
})
it('binds past an older identical photo whose source row was the send boundary', () => {
const messages = [
userText('old-source', '[Image: source: /tmp/old.png]'),
userText('old-prompt', 'look[Image #1]'),
userText('new-source', '[Image: source: /tmp/new.png]'),
userText('new-prompt', 'look[Image #1]')
]
const preview = {
...pending('pending', ['file:///new.jpg']),
text: 'look',
afterMessageId: 'old-source'
}
expect(findLandedImagePreviewEchoes(messages, [preview])).toEqual([
{ pendingId: 'pending', messageId: 'new-prompt', images: ['file:///new.jpg'] }
])
})
})
@@ -1,53 +0,0 @@
import { createElement } from 'react'
import { act, create, type ReactTestRenderer } from 'react-test-renderer'
import { afterEach, expect, it } from 'vitest'
import { returnMobileNativeChatMessageToComposer } from './mobile-native-chat-message-hand-back'
import {
readMobileNativeChatDraftInputs,
updateMobileNativeChatDraftInputs
} from './mobile-native-chat-draft-inputs'
import {
closeMobileNativeChatTabDraft,
setMobileNativeChatDraftText,
useMobileNativeChatDraft
} from './mobile-native-chat-draft-store'
let renderer: ReactTestRenderer | null = null
let text = ''
afterEach(() => {
act(() => renderer?.unmount())
closeMobileNativeChatTabDraft('scope')
renderer = null
})
function Harness(): null {
text = useMobileNativeChatDraft('scope')
return null
}
it('appends a rewound message after the typed draft, its images after the attached ones, once', () => {
act(() => {
renderer = create(createElement(Harness))
})
act(() => {
setMobileNativeChatDraftText('scope', 'typed first')
updateMobileNativeChatDraftInputs('scope', (inputs) => ({
...inputs,
images: [{ id: 'held', path: '/host/held.png', previewUri: 'file:///held.png' }]
}))
})
const blocks = [
{ type: 'text' as const, text: 'look at [Image #1]' },
{ type: 'image-ref' as const, path: '/host/shot.png' }
]
act(() => returnMobileNativeChatMessageToComposer('scope', 'rewound-user', blocks))
act(() => returnMobileNativeChatMessageToComposer('scope', 'rewound-user', blocks))
expect(text).toBe('typed first\n\nlook at [Image #2]')
expect(readMobileNativeChatDraftInputs('scope').images).toEqual([
{ id: 'held', path: '/host/held.png', previewUri: 'file:///held.png' },
{ id: 'rewound-user-1', path: '/host/shot.png', previewUri: '/host/shot.png' }
])
})
@@ -1,64 +0,0 @@
import { createElement } from 'react'
import { act, create, type ReactTestRenderer } from 'react-test-renderer'
import { afterEach, describe, expect, it } from 'vitest'
import { useMobileNativeChatInputLease } from './use-mobile-native-chat-input-lease'
type Lease = ReturnType<typeof useMobileNativeChatInputLease>
describe('useMobileNativeChatInputLease', () => {
let renderer: ReactTestRenderer | null = null
let lease: Lease | null = null
afterEach(() => {
act(() => renderer?.unmount())
renderer = null
lease = null
})
function Harness({ connected }: { connected: boolean }): null {
lease = useMobileNativeChatInputLease({ activeHandle: 'terminal', connected })
return null
}
it('unlocks only after acknowledgement and clears on disconnect', async () => {
await act(async () => {
renderer = create(createElement(Harness, { connected: true }))
})
expect(lease?.ready).toBe(false)
expect(lease?.lockReason).toBe('waiting')
act(() => lease?.markReady('terminal'))
expect(lease?.ready).toBe(true)
expect(lease?.lockReason).toBeNull()
act(() => {
lease?.clear()
})
expect(lease?.ready).toBe(false)
act(() => lease?.markReady('terminal'))
expect(lease?.ready).toBe(true)
await act(async () => renderer?.update(createElement(Harness, { connected: false })))
expect(lease?.ready).toBe(false)
expect(lease?.lockReason).toBe('disconnected')
})
it('reports whether a clear actually dropped a lease', async () => {
await act(async () => {
renderer = create(createElement(Harness, { connected: true }))
})
expect(lease?.clear('terminal')).toBe(false)
expect(lease?.clear()).toBe(false)
act(() => lease?.markReady('terminal'))
let dropped: boolean | undefined
act(() => {
dropped = lease?.clear('terminal')
})
expect(dropped).toBe(true)
expect(lease?.ready).toBe(false)
expect(lease?.clear('terminal')).toBe(false)
act(() => lease?.markReady('other'))
expect(lease?.clear()).toBe(true)
})
})
@@ -1,143 +0,0 @@
import { createElement } from 'react'
import { act, create, type ReactTestRenderer } from 'react-test-renderer'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import {
useMobileNativeChatSendError,
type MobileNativeChatCommandRefusalCauses
} from './use-mobile-native-chat-send-error'
type HookApi = ReturnType<typeof useMobileNativeChatSendError>
describe('useMobileNativeChatSendError', () => {
let renderer: ReactTestRenderer | null = null
const apiRef = { current: null as HookApi | null }
const showToast = vi.fn()
function Harness({
scopeKey,
bannerMounted = true,
causes = null
}: {
scopeKey: string | null
bannerMounted?: boolean
causes?: MobileNativeChatCommandRefusalCauses | null
}): null {
const api = useMobileNativeChatSendError({ scopeKey, showToast })
api.bannerMountedRef.current = bannerMounted
api.keepWhile(causes)
apiRef.current = api
return null
}
function api(): HookApi {
if (!apiRef.current) {
throw new Error('Harness was not rendered')
}
return apiRef.current
}
async function render(scopeKey: string | null = 'terminal-1'): Promise<void> {
await act(async () => {
renderer = create(createElement(Harness, { scopeKey }))
})
}
beforeEach(() => {
apiRef.current = null
showToast.mockClear()
vi.useFakeTimers()
})
afterEach(() => {
act(() => renderer?.unmount())
renderer = null
vi.useRealTimers()
})
async function showing(causes: MobileNativeChatCommandRefusalCauses): Promise<void> {
await act(async () => {
renderer?.update(createElement(Harness, { scopeKey: 'terminal-1', causes }))
})
}
it('a /clear refused while the agent works goes when the agent stops, and stays gone', async () => {
const line = "The agent is still working. Run /clear when it's done."
await render()
await showing({ working: true, prompt: false })
await act(async () => api().show(line, { refusedWhile: 'working' }))
expect(api().message).toBe(line)
await showing({ working: true, prompt: false })
expect(api().message).toBe(line)
await showing({ working: false, prompt: false })
expect(api().message).toBeNull()
await showing({ working: true, prompt: false })
expect(api().message).toBeNull()
})
it('a failure naming nothing the phone shows, or background tasks it cannot see, stays', async () => {
await render()
await act(async () => api().show('Message not sent'))
await showing({ working: false, prompt: false })
expect(api().message).toBe('Message not sent')
await act(async () =>
api().show('Background tasks are still running.', { refusedWhile: 'background' })
)
await showing({ working: false, prompt: false })
expect(api().message).toBe('Background tasks are still running.')
})
it('drops a held failure when the scope changes', async () => {
await render('terminal-1')
await act(async () => api().show('a'))
expect(api().message).toBe('a')
await act(async () => {
renderer?.update(createElement(Harness, { scopeKey: 'terminal-2' }))
})
expect(api().message).toBeNull()
await act(async () => {
renderer?.update(createElement(Harness, { scopeKey: 'terminal-1' }))
})
expect(api().message).toBeNull()
})
it('toasts a deferred failure that resolves after the user switched tabs', async () => {
await render('terminal-1')
const showFromTabA = api().show
await act(async () => {
renderer?.update(createElement(Harness, { scopeKey: 'terminal-2' }))
})
await act(async () => showFromTabA('Message not sent'))
expect(api().message).toBeNull()
expect(showToast).toHaveBeenCalledWith('Message not sent', 1600)
})
it('does not let a stale scope clear the banner the live scope is showing', async () => {
await render('terminal-1')
const clearFromTabA = api().clear
await act(async () => {
renderer?.update(createElement(Harness, { scopeKey: 'terminal-2' }))
})
await act(async () => api().show('b'))
await act(async () => clearFromTabA())
expect(api().message).toBe('b')
})
it('toasts a failure that resolves after the route unmounted', async () => {
await render()
const showWhileMounted = api().show
act(() => renderer?.unmount())
renderer = null
// Unmount must clear the render-written mounted ref so late failures can fall back to toast.
await act(async () => showWhileMounted('Delivery unconfirmed'))
expect(showToast).toHaveBeenCalledWith('Delivery unconfirmed', 1600)
})
})
@@ -1,116 +0,0 @@
import { once } from 'node:events'
import { setImmediate as nextTurn } from 'node:timers/promises'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { WebSocket, WebSocketServer } from 'ws'
import { CdpClientResponseWriter } from './cdp-client-response-writer'
const MiB = 1024 * 1024
describe('CDP outbound backpressure', () => {
let server: WebSocketServer
let peer: WebSocket
let socket: WebSocket
let writer: CdpClientResponseWriter
beforeEach(async () => {
server = new WebSocketServer({ host: '127.0.0.1', port: 0 })
await once(server, 'listening')
const address = server.address()
if (!address || typeof address === 'string') {
throw new Error('Expected TCP address')
}
const accepted = new Promise<WebSocket>((resolve) => server.once('connection', resolve))
peer = new WebSocket(`ws://127.0.0.1:${address.port}`)
await once(peer, 'open')
socket = await accepted
writer = new CdpClientResponseWriter(() => socket)
})
afterEach(async () => {
writer.forgetClient(socket)
vi.useRealTimers()
vi.restoreAllMocks()
socket.terminate()
peer.terminate()
await new Promise<void>((resolve) => server.close(() => resolve()))
})
it('drains replies and events in order with their original session correlation', () => {
vi.useFakeTimers()
const buffered = vi.spyOn(socket, 'bufferedAmount', 'get').mockReturnValue(9 * MiB)
const send = vi.spyOn(socket, 'send').mockImplementation(() => {})
writer.recordRequestSessionId(socket, 7, { sessionId: 'session-one' })
writer.sendResult(7, { ok: true })
writer.send({ method: 'Page.loadEventFired', sessionId: 'session-one' })
writer.recordRequestSessionId(socket, 8, { sessionId: 'session-two' })
writer.sendError(8, 'failed')
expect(send).not.toHaveBeenCalled()
buffered.mockReturnValue(0)
vi.advanceTimersByTime(25)
expect(send.mock.calls.map(([frame]) => JSON.parse(String(frame)))).toEqual([
{ id: 7, result: { ok: true }, sessionId: 'session-one' },
{ method: 'Page.loadEventFired', sessionId: 'session-one' },
{ id: 8, error: { code: -32000, message: 'failed' }, sessionId: 'session-two' }
])
expect(vi.getTimerCount()).toBe(0)
})
it.each(['forget', 'close'] as const)('releases a parked queue on %s', (boundary) => {
vi.useFakeTimers()
const initialCloseListeners = socket.listenerCount('close')
const buffered = vi.spyOn(socket, 'bufferedAmount', 'get').mockReturnValue(9 * MiB)
const send = vi.spyOn(socket, 'send').mockImplementation(() => {})
writer.sendResult(1, { value: 'abandoned' })
expect(vi.getTimerCount()).toBe(1)
if (boundary === 'forget') {
writer.forgetClient(socket)
} else {
socket.emit('close', 1000, Buffer.alloc(0))
}
buffered.mockReturnValue(0)
vi.advanceTimersByTime(100)
expect(send).not.toHaveBeenCalled()
expect(vi.getTimerCount()).toBe(0)
expect(socket.listenerCount('close')).toBeLessThanOrEqual(initialCloseListeners)
})
it('terminates a real stalled reader before native buffering follows all produced bytes', async () => {
peer.pause()
const payload = 'x'.repeat(64 * 1024)
let peakBuffered = 0
for (let index = 0; index < 2048; index++) {
writer.send({ method: 'Runtime.consoleAPICalled', params: { data: payload } })
peakBuffered = Math.max(peakBuffered, socket.bufferedAmount)
if (index % 16 === 0) {
await nextTurn()
}
if (socket.readyState !== WebSocket.OPEN) {
break
}
}
expect(peakBuffered).toBeLessThan(9 * MiB)
expect(socket.readyState).not.toBe(WebSocket.OPEN)
})
it('delivers a transient burst completely to a reading client', async () => {
const frames: string[] = []
const allReceived = new Promise<void>((resolve) => {
peer.on('message', (frame) => {
frames.push(frame.toString())
if (frames.length === 192) {
resolve()
}
})
})
const payload = 'y'.repeat(64 * 1024)
for (let index = 0; index < 192; index++) {
writer.sendResult(index, { data: payload })
}
await allReceived
expect(frames).toEqual(
Array.from({ length: 192 }, (_, id) => JSON.stringify({ id, result: { data: payload } }))
)
expect(socket.readyState).toBe(WebSocket.OPEN)
})
})
@@ -1,75 +0,0 @@
import { once } from 'node:events'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import type WebSocket from 'ws'
import { CdpWsProxy } from './cdp-ws-proxy'
import {
connect,
createMockWebContents,
getSendCommandMethods,
mockAsWebContents,
sendAndReceive,
type MockWebContents
} from './cdp-ws-proxy-test-harness'
vi.mock('electron', () => ({ webContents: { fromId: vi.fn() } }))
function nextMessage(client: WebSocket): Promise<Record<string, unknown>> {
return new Promise((resolve) => {
client.once('message', (data) => resolve(JSON.parse(data.toString())))
})
}
describe('CdpWsProxy malformed client messages', () => {
let mock: MockWebContents
let proxy: CdpWsProxy
let endpoint: string
beforeEach(async () => {
mock = createMockWebContents()
proxy = new CdpWsProxy(mockAsWebContents(mock), () => () => {})
endpoint = await proxy.start()
})
afterEach(async () => {
await proxy.stop()
})
it.each([
'{"id":1,"method":42}',
'{"id":1,"method":"DOM.enable","params":[]}',
'{"id":1,"method":"DOM.enable","sessionId":42}'
])('answers malformed command %s with an error and keeps the client usable', async (raw) => {
const client = await connect(endpoint)
try {
const reply = nextMessage(client)
client.send(raw)
expect(await reply).toEqual({
id: 1,
error: { code: -32000, message: 'Invalid CDP request' }
})
expect(getSendCommandMethods(mock)).not.toContain('DOM.enable')
const next = await sendAndReceive(client, { id: 2, method: 'Browser.getVersion' })
expect(next).toMatchObject({ id: 2, result: expect.any(Object) })
} finally {
client.close()
}
})
it('contains an invalid UTF-8 frame and serves the next client', async () => {
const malformed = await connect(endpoint)
const closed = once(malformed, 'close')
malformed.send(Buffer.from([0xff]), { binary: false })
await closed
const next = await connect(endpoint)
try {
expect(await sendAndReceive(next, { id: 1, method: 'Browser.getVersion' })).toMatchObject({
id: 1,
result: expect.any(Object)
})
} finally {
next.close()
}
})
})