diff --git a/config/scripts/runtime-verification/desktop-transport/verify-computer-native.mjs b/config/scripts/runtime-verification/desktop-transport/verify-computer-native.mjs index 574e3f6984e..f0c1e76f622 100644 --- a/config/scripts/runtime-verification/desktop-transport/verify-computer-native.mjs +++ b/config/scripts/runtime-verification/desktop-transport/verify-computer-native.mjs @@ -54,12 +54,6 @@ const checks = [ ], enabled: process.platform === 'linux' }, - { - name: 'Linux set_value tests', - command: 'python3', - args: ['native/computer-use-linux/set_value_test.py'], - enabled: true - }, { name: 'Windows provider PowerShell parse', command: process.platform === 'win32' ? 'powershell.exe' : 'pwsh', @@ -83,7 +77,7 @@ const checks = [ enabled: process.platform === 'win32' }, { - name: 'Windows snapshot renderer tests', + name: 'Windows pointer safety tests', command: 'powershell.exe', args: [ '-NoLogo', @@ -91,7 +85,7 @@ const checks = [ '-ExecutionPolicy', 'Bypass', '-File', - 'native/computer-use-windows/runtime-render.test.ps1' + 'native/computer-use-windows/runtime-pointer.test.ps1' ], enabled: process.platform === 'win32' }, diff --git a/mobile/src/files/mobile-artifact-kind.test.ts b/mobile/src/files/mobile-artifact-kind.test.ts deleted file mode 100644 index a72bd8f1cba..00000000000 --- a/mobile/src/files/mobile-artifact-kind.test.ts +++ /dev/null @@ -1,31 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { classifyMobileArtifact } from './mobile-artifact-kind' - -describe('classifyMobileArtifact', () => { - it('classifies raster image extensions (case-insensitive)', () => { - for (const p of ['a.png', 'b.JPG', 'c/d.jpeg', 'e.gif', 'f.webp', 'g.bmp', 'h.ico']) { - expect(classifyMobileArtifact(p)).toBe('image') - } - }) - - it('keeps svg off the raster image path', () => { - expect(classifyMobileArtifact('logo.SVG')).toBe('vector') - }) - - it('classifies html extensions', () => { - expect(classifyMobileArtifact('index.html')).toBe('html') - expect(classifyMobileArtifact('a/b/page.HTM')).toBe('html') - }) - - it('treats code/text/unknown as other', () => { - for (const p of ['main.ts', 'README.md', 'data.csv', 'notes', 'a.pdf', 'x.json']) { - expect(classifyMobileArtifact(p)).toBe('other') - } - }) - - it('treats a dotfile or no-extension path as other', () => { - expect(classifyMobileArtifact('.gitignore')).toBe('other') - expect(classifyMobileArtifact('Makefile')).toBe('other') - expect(classifyMobileArtifact('dir/.env')).toBe('other') - }) -}) diff --git a/mobile/src/home/tabs/home-usage-cards.test.ts b/mobile/src/home/tabs/home-usage-cards.test.ts index 085d4bfd6fb..b8757f26084 100644 --- a/mobile/src/home/tabs/home-usage-cards.test.ts +++ b/mobile/src/home/tabs/home-usage-cards.test.ts @@ -3,7 +3,7 @@ import type { AccountProviderRateLimits, AccountsSnapshot } from '../../components/account-usage-state' -import { selectHomeUsageCards, selectHomeUsageSections } from './home-usage-cards' +import { selectHomeUsageCards } from './home-usage-cards' function limits( provider: 'claude' | 'codex', @@ -75,23 +75,6 @@ describe('selectHomeUsageCards', () => { ]) }) - it('shows System default first while no managed account is active, metered only once it has quota', () => { - const withoutQuota = selectHomeUsageCards( - snapshot({ codex: { accounts: [{ id: 'x', email: 'x@example.com', updatedAt: 1 }] } }), - 'codex' - ) - expect(withoutQuota.map((card) => [card.accountId, card.active, card.metered])).toEqual([ - [null, true, false], - ['x', false, true] - ]) - - const withQuota = selectHomeUsageCards( - snapshot({ rateLimits: { codex: limits('codex', 40) } }), - 'codex' - ) - expect(withQuota.map((card) => [card.accountId, card.metered])).toEqual([[null, true]]) - }) - it('reads the Codex active account for the rate-limit runtime target', () => { const cards = selectHomeUsageCards( snapshot({ @@ -113,17 +96,3 @@ describe('selectHomeUsageCards', () => { ]) }) }) - -describe('selectHomeUsageSections', () => { - it('skips providers with nothing to show and drops an unfetched updatedAt', () => { - const sections = selectHomeUsageSections( - snapshot({ - codex: { accounts: [{ id: 'x', email: 'x@example.com', updatedAt: 1 }] }, - rateLimits: { codex: limits('codex', 5, { updatedAt: 0, status: 'idle' }) } - }) - ) - expect(sections.map((section) => [section.provider, section.updatedAt])).toEqual([ - ['codex', null] - ]) - }) -}) diff --git a/mobile/src/hooks/mobile-dictation-pending-audio-budget.test.ts b/mobile/src/hooks/mobile-dictation-pending-audio-budget.test.ts index 77190320f52..07d1dbac9a3 100644 --- a/mobile/src/hooks/mobile-dictation-pending-audio-budget.test.ts +++ b/mobile/src/hooks/mobile-dictation-pending-audio-budget.test.ts @@ -2,15 +2,6 @@ import { describe, expect, it } from 'vitest' import { MobileDictationPendingAudioBudget } from './mobile-dictation-pending-audio-budget' describe('MobileDictationPendingAudioBudget', () => { - it('caps pending raw PCM audio at thirty seconds', () => { - const budget = new MobileDictationPendingAudioBudget() - expect(budget.tryReserve(959_999)).toBe(true) - expect(budget.tryReserve(1)).toBe(true) - expect(budget.pendingAudioBytes).toBe(960_000) - expect(budget.tryReserve(1)).toBe(false) - expect(budget.pendingAudioBytes).toBe(960_000) - }) - it('releases completed chunks and clamps stale releases after reset', () => { const budget = new MobileDictationPendingAudioBudget(10) diff --git a/mobile/src/i18n/mobile-i18n.test.ts b/mobile/src/i18n/mobile-i18n.test.ts index d151b5fb37e..a2906b02959 100644 --- a/mobile/src/i18n/mobile-i18n.test.ts +++ b/mobile/src/i18n/mobile-i18n.test.ts @@ -1,5 +1,3 @@ -import { sayMobileAgentSessionFailure } from '../session/agent-session-failure-copy' -import { agentSessionFailureSentence } from '../../../src/shared/agent-session/failures/agent-session-failure-words' import { beforeEach, describe, expect, it, vi } from 'vitest' const pending = new Map) => void>() @@ -15,8 +13,6 @@ vi.mock('./locale-catalog-imports', () => ({ const { activateMobileUiLocale, getMobileUiLocale, mobileI18n, translate } = await import('./mobile-i18n') -const settle = () => new Promise((resolve) => setTimeout(resolve, 0)) - describe('activateMobileUiLocale', () => { beforeEach(async () => { pending.clear() @@ -36,18 +32,6 @@ describe('activateMobileUiLocale', () => { expect(translate('greeting', 'Hello')).toBe('こんにちは') }) - it('reads the existing saved uncertain fact through the current lazy failure translation table', async () => { - const sentence = () => - agentSessionFailureSentence({ kind: 'unconfirmed' }, 'row', {}, sayMobileAgentSessionFailure) - expect(sentence()).toBe("Couldn't confirm whether this was sent. It hasn't been resent.") - const spanish = activateMobileUiLocale('es') - pending.get('es')?.({ - session: { failure: { unconfirmed: 'El resultado sigue siendo desconocido.' } } - }) - await spanish - expect(sentence()).toBe('El resultado sigue siendo desconocido.') - }) - it('falls back to English when a catalog cannot load', async () => { failing.add('de') vi.spyOn(console, 'warn').mockImplementation(() => {}) @@ -55,19 +39,4 @@ describe('activateMobileUiLocale', () => { expect(getMobileUiLocale()).toBe('en') expect(translate('greeting', 'Hello')).toBe('Hello') }) - - it('picks CLDR plural forms and English fallbacks for missing keys', async () => { - const russian = activateMobileUiLocale('ru') - await settle() - pending.get('ru')?.({ - files_one: '{{count}} файл', - files_few: '{{count}} файла', - files_many: '{{count}} файлов' - }) - await russian - expect( - [1, 3, 5, 21].map((count) => translate('files_one', '{{count}} file', { count })) - ).toEqual(['1 файл', '3 файла', '5 файлов', '21 файл']) - expect(translate('untranslated', 'Still English')).toBe('Still English') - }) }) diff --git a/mobile/src/mobile-web-shell/bridge/bridge-audio-verbs.test.ts b/mobile/src/mobile-web-shell/bridge/bridge-audio-verbs.test.ts index 5c89a0ddf2e..19da0366f3b 100644 --- a/mobile/src/mobile-web-shell/bridge/bridge-audio-verbs.test.ts +++ b/mobile/src/mobile-web-shell/bridge/bridge-audio-verbs.test.ts @@ -148,17 +148,6 @@ describe('what the audio schemas refuse', () => { }) describe('the shell capture', () => { - it('surfaces a denied microphone as data rather than as a throw', async () => { - const { engine, calls } = createTestEngine({ permission: async () => 'denied' }) - const capture = createCapture(engine) - await expect(capture.serve('native.audio.start', { sampleRate: 16_000 })).resolves.toEqual({ - started: false, - sampleRate: 16_000, - permission: 'denied' - }) - expect(calls).toEqual([]) - }) - it('serves a partial drain from the front and keeps the rest for the next read', async () => { const { engine, emit } = createTestEngine() const capture = createCapture(engine) @@ -211,24 +200,6 @@ describe('the shell capture', () => { expect(next.interruption).toBeNull() }) - it('keeps a capture the OS handed back, and ends the two it took away', async () => { - const { engine, interrupt } = createTestEngine() - const capture = createCapture(engine) - await capture.serve('native.audio.start', { sampleRate: 16_000 }) - interrupt('ended') - const kept = audioReadResultSchema.parse( - await capture.serve('native.audio.read', { maxBytes: BRIDGE_AUDIO_RING_MAX_BYTES }) - ) - // Nonterminal interruption still reaches the page while the live capture keeps filling its ring. - expect(kept.interruption).toBe('ended') - expect(kept.recording).toBe(true) - interrupt('blocked') - const lost = audioReadResultSchema.parse( - await capture.serve('native.audio.read', { maxBytes: BRIDGE_AUDIO_RING_MAX_BYTES }) - ) - expect(lost.recording).toBe(false) - }) - it('refuses a read once the page has stopped', async () => { const { engine } = createTestEngine() const capture = createCapture(engine) @@ -264,24 +235,6 @@ describe('the shell capture', () => { expect(read.base64).toBe('') }) - it('replaces a capture a page left behind rather than refusing the new one', async () => { - // A page can reload or vanish mid-capture; only the shell sees that lifecycle, so a new start replaces the old capture. - const { engine, emit, log } = createTestEngine() - const capture = createCapture(engine) - await capture.serve('native.audio.start', { sampleRate: 16_000 }) - emit(pcm(2_048, 6)) - await expect(capture.serve('native.audio.start', { sampleRate: 16_000 })).resolves.toEqual({ - started: true, - sampleRate: 16_000, - permission: 'granted' - }) - expect(log.filter((entry) => entry === 'end')).toHaveLength(1) - const read = audioReadResultSchema.parse( - await capture.serve('native.audio.read', { maxBytes: BRIDGE_AUDIO_RING_MAX_BYTES }) - ) - expect(read.base64).toBe('') - }) - it('leaves one capture behind when two starts race the permission prompt', async () => { // Concurrent starts can both leave the OS prompt and reach listen; replacement must remove the earlier handlers rather than leak a ring nobody drains. const entered = gate() @@ -371,37 +324,9 @@ describe('the shell capture', () => { await expect(stopped).resolves.toEqual({ stopped: true, base64: '', droppedBytes: 0 }) expect(liveListeners()).toEqual({ microphone: 0, interruptions: 0 }) }) - - it('ends the capture when the page session does', async () => { - const { engine, log } = createTestEngine() - const capture = createCapture(engine) - await capture.serve('native.audio.start', { sampleRate: 16_000 }) - capture.dispose() - expect(log).toContain('end') - await expect(capture.serve('native.audio.read', { maxBytes: 16 })).rejects.toBeInstanceOf( - BridgeNativeVerbRefusedError - ) - }) }) describe('the screen the shell holds awake while it is capturing', () => { - it('takes the screen on a start and gives it back on a stop', async () => { - const { engine, screen } = createTestEngine() - const capture = createCapture(engine) - await capture.serve('native.audio.start', { sampleRate: 16_000 }) - expect(screen).toEqual(['+']) - await capture.serve('native.audio.stop', {}) - expect(screen).toEqual(['+', '-']) - }) - - it('gives it back when the page session ends with a capture still open', async () => { - const { engine, screen } = createTestEngine() - const capture = createCapture(engine) - await capture.serve('native.audio.start', { sampleRate: 16_000 }) - capture.dispose() - expect(screen).toEqual(['+', '-']) - }) - it('gives it back when the engine throws after the capture is open', async () => { const { engine, screen } = createTestEngine({ begin: () => { @@ -443,14 +368,4 @@ describe('the tail the stop reply carries', () => { expect(Array.from(decode(read.base64))).toEqual(Array.from(spoken)) expect(Array.from(decode(stopped.base64))).toEqual(Array.from(after)) }) - - it('leaves nothing behind for a second stop to answer with', async () => { - const { engine, emit } = createTestEngine() - const capture = createCapture(engine) - await capture.serve('native.audio.start', { sampleRate: 16_000 }) - emit(pcm(512, 5)) - await capture.serve('native.audio.stop', {}) - const again = audioStopResultSchema.parse(await capture.serve('native.audio.stop', {})) - expect(again).toEqual({ stopped: false, base64: '', droppedBytes: 0 }) - }) }) diff --git a/mobile/src/mobile-web-shell/bridge/bridge-client-inbound-frames.test.ts b/mobile/src/mobile-web-shell/bridge/bridge-client-inbound-frames.test.ts index cc1176e49fc..ba01674d9b1 100644 --- a/mobile/src/mobile-web-shell/bridge/bridge-client-inbound-frames.test.ts +++ b/mobile/src/mobile-web-shell/bridge/bridge-client-inbound-frames.test.ts @@ -77,31 +77,6 @@ describe('bridge client refusals and send failures', () => { expect(isRpcDeliveryUnknown(error)).toBe(true) }) - it('leaves a refused frame that names no open exchange to the diagnostic alone', async () => { - const page = createPageClient() - page.start() - const answer = page.client.sendRequest('worktree.ps') - page.deliver({ - v: BRIDGE_PROTOCOL_VERSION, - type: 'reply', - id: 'ZZZZZZZZZZZZZZZZZZZZZZ', - payload: { id: 'frame-1', ok: true } - }) - expect(page.diagnostics).toEqual([{ kind: 'refused', refusal: 'unrecognised-message' }]) - page.deliver({ - v: BRIDGE_PROTOCOL_VERSION, - type: 'reply', - id: idOf(page, 0), - payload: { id: 'frame-1', ok: true, result: 7, _meta: { runtimeId: 'runtime-a' } } - }) - await expect(answer).resolves.toEqual({ - id: 'frame-1', - ok: true, - result: 7, - _meta: { runtimeId: 'runtime-a' } - }) - }) - it('fails a request whose frame never left the page, without the delivery mark', async () => { let live = true const page = createPageClient({ diff --git a/mobile/src/mobile-web-shell/bridge/bridge-rpc-client-frames.test.ts b/mobile/src/mobile-web-shell/bridge/bridge-rpc-client-frames.test.ts index 14eccfa9f4c..5e7cc58b5b9 100644 --- a/mobile/src/mobile-web-shell/bridge/bridge-rpc-client-frames.test.ts +++ b/mobile/src/mobile-web-shell/bridge/bridge-rpc-client-frames.test.ts @@ -6,9 +6,7 @@ import './bridge-port-pair-test-harness' import './bridge-client-subscriptions' import { BRIDGE_PROTOCOL_VERSION, type BridgeHostMessage } from './bridge-envelope' import './bridge-client-init-handshake' -import { BridgeClientNotReadyError } from './bridge-rpc-client' import { - CONNECTION, INIT, createPageClient, eventFrame, @@ -60,19 +58,6 @@ describe('bridge client handshake', () => { }) }) -describe('bridge client before a session', () => { - it('drops a state frame that beat init rather than priming from it', () => { - const page = createPageClient() - page.deliver({ - v: BRIDGE_PROTOCOL_VERSION, - type: 'state', - connection: { ...CONNECTION, state: 'reconnecting' } - }) - expect(() => page.client.getState()).toThrow(BridgeClientNotReadyError) - expect(page.diagnostics).toEqual([]) - }) -}) - // Catch page-listener throws locally: iOS callAsyncJavaScript would otherwise reject an already-delivered frame. Retrying cannot fix the same listener failure (ruling 34 addendum). describe('bridge client after close', () => { diff --git a/mobile/src/mobile-web-shell/bridge/use-native-verbs.test.tsx b/mobile/src/mobile-web-shell/bridge/use-native-verbs.test.tsx deleted file mode 100644 index 5939d383360..00000000000 --- a/mobile/src/mobile-web-shell/bridge/use-native-verbs.test.tsx +++ /dev/null @@ -1,82 +0,0 @@ -import { act, create, type ReactTestRenderer } from 'react-test-renderer' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' - -// Avoid Expo imports through re-exported screen hooks; this test calls none of them. -vi.mock('../../transport/connection/host-client-hooks', () => ({ - useDisconnectHostClient: () => () => {}, - useForceReconnect: () => null, - useForgetHostClient: () => () => {}, - useHostClient: () => ({ client: null, clientId: null, state: 'disconnected' }), - usePrimeHosts: () => () => {}, - useRefreshHostClient: () => () => {} -})) - -import { RpcClientProvider } from '../../transport/connection/client-context.web' -import { BRIDGE_PROTOCOL_VERSION } from './bridge-envelope' -import { BRIDGE_NATIVE_VERB_NAMES } from './bridge-native-verbs' -import './bridge-port-pair-test-harness' -import { GRANTS, INIT, createPageClient } from './bridge-page-client-test-harness' -import { NativeVerbError, useNativeVerbs, type NativeVerbs } from './use-native-verbs' - -const mounted: ReactTestRenderer[] = [] - -const held: { verbs: NativeVerbs | null } = { verbs: null } - -function Screen(): null { - held.verbs = useNativeVerbs() - return null -} - -beforeEach(() => { - held.verbs = null -}) - -afterEach(() => { - act(() => { - for (const tree of mounted.splice(0)) { - tree.unmount() - } - }) - vi.useRealTimers() -}) - -// The typed member must reject desktop methods too; widened callers could otherwise bypass the raw-port inventory’s call shapes. - -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. - const page = createPageClient() - page.deliver({ ...INIT, grants: { ...GRANTS, native: [...BRIDGE_NATIVE_VERB_NAMES] } }) - act(() => { - create( - - - - ) - }) - const verbs = held.verbs - if (verbs === null) { - throw new Error('nothing mounted') - } - const read = verbs.readClipboardText().catch((error: unknown) => error) - const sent = page.frames().filter((frame) => frame.type === 'request') - const id = sent.at(-1)?.type === 'request' ? sent.at(-1)?.id : undefined - if (id === undefined) { - throw new Error('no request went out') - } - page.deliver({ - v: BRIDGE_PROTOCOL_VERSION, - type: 'error', - id, - error: { - category: 'BridgeNativeVerbRefusedError', - code: 'native_verb_something_new', - message: 'a verb from a later build', - isRpcDeliveryUnknown: false - } - }) - const caught = await read - expect(caught).toBeInstanceOf(NativeVerbError) - expect(caught instanceof NativeVerbError && caught.reason).toBe('unreported') - }) -}) diff --git a/mobile/src/mobile-web-shell/generation-store.test.ts b/mobile/src/mobile-web-shell/generation-store.test.ts index 4d381f688ba..e8bbca2a3f2 100644 --- a/mobile/src/mobile-web-shell/generation-store.test.ts +++ b/mobile/src/mobile-web-shell/generation-store.test.ts @@ -5,8 +5,7 @@ import type { MobileWebBundleFetchResult } from '../transport/web-bundle/mobile- import { computeMobileWebBundleId } from '../../../src/shared/mobile-web-bundle/manifest-contract' import { createFakeGenerationFileSystem as createFakeFileSystem, - FAKE_GENERATION_ROOT, - type FakeGenerationFileSystem as FakeFileSystem + FAKE_GENERATION_ROOT } from './generation-file-system-fake' const ROOT = FAKE_GENERATION_ROOT @@ -106,17 +105,6 @@ describe('generation store', () => { expect(fs.paths().some((path) => path.includes('/tmp'))).toBe(false) }) - it('replaces the previous generation when the build id changes', async () => { - const fs = createFakeFileSystem() - const store = createGenerationStore({ fileSystem: fs }) - - await activate(store, HOST) - await activate(store, HOST, buildResult(SECOND)) - - expect(fs.paths().some((path) => path.includes(BUILD))).toBe(false) - expect((await store.readActiveGeneration(HOST))?.buildId).toBe(SECOND_BUILD) - }) - it('reads two generations as no activation and drops the host tree', async () => { const fs = createFakeFileSystem() const store = createGenerationStore({ fileSystem: fs }) @@ -183,18 +171,6 @@ describe('generation store', () => { expect((await store.readActiveGeneration(oldest))?.buildId).toBe(BUILD) }) - it('returns the generation when an open cannot write the index', async () => { - const fs = createFakeFileSystem() - const store = createGenerationStore({ fileSystem: fs }) - const other = deriveHostCacheKey('other') - await activate(store, HOST) - await activate(store, other) - fs.failWritesAt('hosts.json') - - expect((await store.readActiveGeneration(HOST))?.buildId).toBe(BUILD) - expect(fs.text('hosts.json')).toBe(JSON.stringify([HOST, other])) - }) - it('never counts or evicts a host that is only mid-download', async () => { const fs = createFakeFileSystem() const store = createGenerationStore({ fileSystem: fs }) @@ -246,17 +222,6 @@ describe('generation store', () => { ]) }) - it('drops residue from an earlier attempt instead of staging over it', async () => { - const fs = createFakeFileSystem() - const store = createGenerationStore({ fileSystem: fs }) - const staging = `${HOST}/tmp/${BUILD}` - fs.seed(`${staging}/assets/orphan.js`, { kind: 'file', bytes: new Uint8Array(1) }) - - await store.stageGeneration(HOST, buildResult({})) - - expect(fs.paths().some((path) => path.endsWith('orphan.js'))).toBe(false) - }) - it('refuses a path that escapes the staged tree, and a host key that is not one', async () => { const fs = createFakeFileSystem() const store = createGenerationStore({ fileSystem: fs }) @@ -279,20 +244,6 @@ describe('generation store', () => { expect(fs.paths()).toEqual([]) }) - it('deletes one host tree without touching another', async () => { - const fs = createFakeFileSystem() - const other = deriveHostCacheKey('host-b') - const store = createGenerationStore({ fileSystem: fs }) - await activate(store, HOST) - await activate(store, other) - - await store.deleteHostCache(HOST) - - expect(await store.readActiveGeneration(HOST)).toBeNull() - expect((await store.readActiveGeneration(other))?.buildId).toBe(BUILD) - expect(fs.text('hosts.json')).toBe(JSON.stringify([other])) - }) - it('refuses a rename that did not carry the tree, as Android below API 26 can', async () => { const fs = createFakeFileSystem() const store = createGenerationStore({ fileSystem: fs }) @@ -322,17 +273,6 @@ describe('generation store', () => { expect(fs.paths().some((path) => path.startsWith(HOST))).toBe(false) }) - it('activates normally when the recency index cannot be read', async () => { - const fs = createFakeFileSystem() - const store = createGenerationStore({ fileSystem: fs }) - fs.seed('hosts.json', { kind: 'file', bytes: new TextEncoder().encode('[]') }) - fs.failReadsAt('hosts.json') - - await activate(store, HOST) - - expect((await store.readActiveGeneration(HOST))?.buildId).toBe(BUILD) - }) - it('replaces an entry named for the build id that is not a readable generation', async () => { const build = BUILD // Model a crash between rename and the post-rename manifest check. @@ -351,31 +291,6 @@ describe('generation store', () => { } }) - it('drops an aborted staging without touching the activation', async () => { - const fs = createFakeFileSystem() - const store = createGenerationStore({ fileSystem: fs }) - await activate(store, HOST) - - const staged = await store.stageGeneration(HOST, buildResult(SECOND)) - await store.abortStagedGeneration(staged) - - expect(fs.paths().some((path) => path.includes(SECOND_BUILD))).toBe(false) - expect((await store.readActiveGeneration(HOST))?.buildId).toBe(BUILD) - }) - - it('returns the activation even when the recency index cannot be written', async () => { - const fs = createFakeFileSystem() - const store = createGenerationStore({ fileSystem: fs }) - fs.failWritesAt('hosts.json') - - const staged = await store.stageGeneration(HOST, buildResult({})) - const active = await store.commitGeneration(staged) - - expect(active.buildId).toBe(BUILD) - expect((await store.readActiveGeneration(HOST))?.buildId).toBe(BUILD) - expect(fs.text('hosts.json')).toBeNull() - }) - it('refuses a handle whose staged tree is gone without touching the activation', async () => { const fs = createFakeFileSystem() const store = createGenerationStore({ fileSystem: fs }) @@ -470,41 +385,6 @@ describe('reusable assets for the next download', () => { }) }) -// Older builds could leave manifest-next.json after an interrupted rewrite; this reader must ignore it. -describe('a pending manifest left by an older build', () => { - const MANIFEST_PATH = `${HOST}/generations/${BUILD}/manifest.json` - const NEXT_PATH = `${HOST}/generations/${BUILD}/manifest-next.json` - - function seedPending(fs: FakeFileSystem): void { - const body = JSON.stringify({ ...buildResult({}).manifest, routes: [] }) - fs.seed(NEXT_PATH, { kind: 'file', bytes: new TextEncoder().encode(body) }) - } - - it('reads the manifest beside it and leaves it inert', async () => { - const fs = createFakeFileSystem() - const store = createGenerationStore({ fileSystem: fs }) - await activate(store, HOST) - const stored = fs.text(MANIFEST_PATH) - seedPending(fs) - - expect((await store.readActiveGeneration(HOST))?.buildId).toBe(BUILD) - - expect(fs.text(MANIFEST_PATH)).toBe(stored) - }) - - it('drops the host tree for a redownload when it is the only manifest left', async () => { - const fs = createFakeFileSystem() - const store = createGenerationStore({ fileSystem: fs }) - await activate(store, HOST) - seedPending(fs) - await fs.delete(`${ROOT}/${MANIFEST_PATH}`) - - expect(await store.readActiveGeneration(HOST)).toBeNull() - - expect(fs.paths().some((path) => path.startsWith(`${HOST}/generations`))).toBe(false) - }) -}) - // Commit deletes the old build first, so it must not run under a page still loading that build's chunks. describe('an update staged behind a live page', () => { it('stays staged while a page reads the old build, and the next read after it commits', async () => { diff --git a/mobile/src/mobile-web-shell/host-area-fold.test.tsx b/mobile/src/mobile-web-shell/host-area-fold.test.tsx index 6439116770d..15ea197dee7 100644 --- a/mobile/src/mobile-web-shell/host-area-fold.test.tsx +++ b/mobile/src/mobile-web-shell/host-area-fold.test.tsx @@ -101,19 +101,9 @@ describe('folding while the host-area page shows a session', () => { expect(dependencies.push.mock.calls).toEqual([[DETAIL]]) }) - it('stays on the list when the page was showing the list', async () => { - await foldAfterPageShows(HOST) - expect(dependencies.push).not.toHaveBeenCalled() - }) - it('leaves the stack alone from a host-route shell covered by a pushed session', async () => { await foldAfterPageShows(HOST, false) expect(dependencies.push).not.toHaveBeenCalled() expect(dependencies.dispatch).not.toHaveBeenCalled() }) - - it('stays on the list for an older page that never reports where it is', async () => { - await foldAfterPageShows(null) - expect(dependencies.push).not.toHaveBeenCalled() - }) }) diff --git a/mobile/src/mobile-web-shell/mobile-web-shell-failed-update-fallback.test.ts b/mobile/src/mobile-web-shell/mobile-web-shell-failed-update-fallback.test.ts deleted file mode 100644 index d4c7b198524..00000000000 --- a/mobile/src/mobile-web-shell/mobile-web-shell-failed-update-fallback.test.ts +++ /dev/null @@ -1,216 +0,0 @@ -import { createElement } from 'react' -import { act, create, type ReactTestRenderer } from 'react-test-renderer' -import { beforeEach, describe, expect, it, vi } from 'vitest' -import type { MobileWebBundleManifestRead } from '../transport/web-bundle/mobile-web-bundle-reply-schemas' -import type { - MobileWebShellSessionState, - MobileWebShellUpdateNotice -} from './mobile-web-shell-session-contract' - -// Exercise the real hook/store over in-memory disk; stub network and native modules. -type Doubles = { - connection: { client: object | null; state: string } - gates: { - statusPending: boolean - statusReadable: boolean - hostCapabilities: string[] - hostProtocolWindow: { protocolVersion: number; minCompatibleMobileVersion: number } - } - manifest: MobileWebBundleManifestRead | null - fetch: () => Promise -} - -const doubles = vi.hoisted((): Doubles => ({ - connection: { client: {}, state: 'connected' }, - gates: { - statusPending: false, - statusReadable: true, - hostCapabilities: [], - hostProtocolWindow: { protocolVersion: 10, minCompatibleMobileVersion: 1 } - }, - manifest: null, - fetch: () => Promise.reject(new Error('no fetch staged')) -})) - -vi.mock('expo-crypto', () => ({ getRandomBytes: (length: number) => new Uint8Array(length) })) -vi.mock('expo-file-system', () => ({ Directory: class {}, File: class {}, Paths: { cache: '' } })) -vi.mock('react-native', () => ({ AppState: {} })) -vi.mock('../transport/encryption/mobile-session-id-encoding', () => ({ - encodeBase64Url: () => 'session-id' -})) -vi.mock('../components/host-protocol-gates-context', () => ({ - useHostProtocolGates: () => doubles.gates -})) -vi.mock('../transport/connection/host-client-hooks', () => ({ - useHostClient: () => doubles.connection -})) -vi.mock('../transport/rpc/rpc-operation', () => ({ - defineRpcOperation: (definition: unknown) => definition, - runRpcOperation: async () => { - if (doubles.manifest === null) { - throw new Error('the test reached the host with no manifest staged') - } - return { manifest: doubles.manifest } - } -})) -vi.mock('../transport/web-bundle/mobile-web-bundle-fetch', () => ({ - fetchMobileWebBundle: () => doubles.fetch() -})) - -import { - computeMobileWebBundleId, - MOBILE_WEB_BUNDLE_SCHEMA_VERSION, - type MobileWebBundleAsset -} from '../../../src/shared/mobile-web-bundle/manifest-contract' -import { MOBILE_WEB_BUNDLE_CAPABILITY } from '../../../src/shared/mobile-web-bundle/mobile-web-bundle-capability' -import type { MobileWebBundleFetchResult } from '../transport/web-bundle/mobile-web-bundle-fetch' -import { MobileWebBundleFetchError } from '../transport/web-bundle/mobile-web-bundle-fetch-refusal' -import { MobileWebBundleManifestReadSchema } from '../transport/web-bundle/mobile-web-bundle-reply-schemas' -import { - createFakeGenerationFileSystem, - FAKE_GENERATION_ROOT, - type FakeGenerationFileSystem -} from './generation-file-system-fake' -import { createGenerationStore } from './generation-store' -import { deriveHostCacheKey } from './host-cache-key' -import { useMobileWebShellSession } from './use-mobile-web-shell-session' - -const HOST_ID = 'host-1' -const HOST_KEY = deriveHostCacheKey(HOST_ID) -const ROUTE_PATHNAME = '/h/host-1' -const ROUTE_PATTERN = '/h/[hostId]' - -function assetsFilled(fill: number) { - return [ - { path: 'index.html', sha256: `${fill}`.repeat(64), byteLength: 4, contentType: 'text/html' }, - { - path: 'assets/app.js', - sha256: `${fill + 1}`.repeat(64), - byteLength: 2, - contentType: 'text/javascript' - } - ] -} - -const GOOD_ASSETS = assetsFilled(1) -const NEWER_ASSETS = assetsFilled(5) -const TOTAL_BYTES = 6 -// Derive ids from assets so cached fixtures pass the manifest digest check. - -function manifestOf( - assets: readonly MobileWebBundleAsset[], - runtimeProtocolVersion = 5 -): MobileWebBundleManifestRead { - return MobileWebBundleManifestReadSchema.parse({ - schemaVersion: MOBILE_WEB_BUNDLE_SCHEMA_VERSION, - buildId: computeMobileWebBundleId(assets), - minCompatibleRuntimeProtocolVersion: 2, - runtimeProtocolVersion, - pageVersion: 1, - entrypoint: 'index.html', - totalBytes: TOTAL_BYTES, - assets, - routes: [{ pathname: ROUTE_PATTERN, grants: ['navigate'] }] - }) -} - -const GOOD_MANIFEST = manifestOf(GOOD_ASSETS) -const NEWER_MANIFEST = manifestOf(NEWER_ASSETS) - -function fetchResultFor(manifest: MobileWebBundleManifestRead): MobileWebBundleFetchResult { - return { - manifest, - assets: new Map( - manifest.assets.map((asset) => [asset.path, new Uint8Array(asset.byteLength).fill(7)]) - ), - reused: [], - totalBytes: TOTAL_BYTES, - elapsedMs: 1 - } -} - -// Stage/commit N through the real store so fallback reads the tree a successful download actually leaves. -async function cacheGeneration( - fileSystem: FakeGenerationFileSystem, - manifest: MobileWebBundleManifestRead = GOOD_MANIFEST -): Promise { - const store = createGenerationStore({ fileSystem }) - await store.commitGeneration(await store.stageGeneration(HOST_KEY, fetchResultFor(manifest))) -} - -function refuseTheAssets(): Promise { - return Promise.reject( - new MobileWebBundleFetchError( - 'asset-short', - 'bundle asset assets/app.js ended at 1 of 2 declared bytes' - ) - ) -} - -type Mounted = { - unmount: () => Promise - state: () => MobileWebShellSessionState - updateNotice: () => MobileWebShellUpdateNotice | null -} - -async function mountRoute(fileSystem: FakeGenerationFileSystem): Promise { - const latest: { - state: MobileWebShellSessionState - updateNotice: MobileWebShellUpdateNotice | null - } = { state: { kind: 'checking' }, updateNotice: null } - function Probe() { - const session = useMobileWebShellSession({ - hostId: HOST_ID, - routePathname: ROUTE_PATHNAME, - runtime: { - createStore: () => createGenerationStore({ fileSystem }), - mintSessionId: () => 'session-id', - claimSpareSessionId: async () => null, - now: () => 0, - setForegroundTimer: () => () => {} - } - }) - latest.state = session.state - latest.updateNotice = session.updateNotice - return null - } - const rendered: { tree: ReactTestRenderer | null } = { tree: null } - await act(async () => { - rendered.tree = create(createElement(Probe)) - }) - const tree = rendered.tree - if (tree === null) { - throw new Error('the hook did not mount') - } - return { - unmount: async () => { - await act(async () => { - tree.unmount() - }) - }, - state: () => latest.state, - updateNotice: () => latest.updateNotice - } -} - -describe('an update the shell refuses while the host is reachable', () => { - beforeEach(() => { - doubles.connection = { client: {}, state: 'connected' } - doubles.gates.hostCapabilities = [MOBILE_WEB_BUNDLE_CAPABILITY] - doubles.manifest = NEWER_MANIFEST - doubles.fetch = refuseTheAssets - }) - - it('records a failure whose error named an endpoint and a token without either', async () => { - doubles.fetch = () => - Promise.reject(new Error('dial wss://relay.example/pair?token=SECRET-123 refused')) - const fileSystem = createFakeGenerationFileSystem() - await cacheGeneration(fileSystem) - - await mountRoute(fileSystem) - - const log = await fileSystem.readText(`${FAKE_GENERATION_ROOT}/update-failures.json`) - expect(log).toContain('unrecognised-error') - expect(log).not.toMatch(/SECRET|token|\?|:\/\/|relay/) - }) -}) diff --git a/mobile/src/mobile-web-shell/mobile-web-shell-session.test.ts b/mobile/src/mobile-web-shell/mobile-web-shell-session.test.ts index dc09c0e9888..4c240a95290 100644 --- a/mobile/src/mobile-web-shell/mobile-web-shell-session.test.ts +++ b/mobile/src/mobile-web-shell/mobile-web-shell-session.test.ts @@ -177,17 +177,6 @@ describe('only the state that mounted the view hears the view', () => { // A finished WebView load can still have failed script evaluation; only page ready proves its code ran. describe('the page has to speak for the document that loaded', () => { - it('does nothing when the wait expires after the page has spoken', () => { - const step = run( - readySession().session, - { type: 'document-loaded' }, - { type: 'page-ready' }, - { type: 'page-ready-deadline' } - ) - expect(step.effects).toEqual([]) - expect(step.session.state.kind).toBe('ready') - }) - it('leaves a remounted document its own wait when the first one expires late', () => { const first = run(readySession().session, { type: 'document-loaded' }, { type: 'page-ready' }) const armed = first.session.flow @@ -245,15 +234,6 @@ describe('a cached page opened before the verdict', () => { ) } - it('checks for a newer build once the verdict opens, and stages it behind the page', () => { - const opened = run(openedWhileDialling().session, { type: 'gates-changed', gates: gates() }) - expect(opened.session.state).toMatchObject({ kind: 'ready', sessionId: 'session-early' }) - expect(opened.effects).toEqual([{ kind: 'read-manifest' }]) - const staged = run(opened.session, { type: 'manifest-read', manifest: NEWER }) - expect(staged.session.state).toMatchObject({ kind: 'ready', sessionId: 'session-early' }) - expect(staged.effects).toEqual([{ kind: 'stage-update' }]) - }) - it('stages the newer build when the manifest answers after the page document starts', () => { const opened = run(openedWhileDialling().session, { type: 'gates-changed', gates: gates() }) const asked = opened.session.flow diff --git a/mobile/src/navigation/route-handoff.web.test.tsx b/mobile/src/navigation/route-handoff.web.test.tsx index 6c78d9dea85..70d0ec474ce 100644 --- a/mobile/src/navigation/route-handoff.web.test.tsx +++ b/mobile/src/navigation/route-handoff.web.test.tsx @@ -2,10 +2,7 @@ import type { ReactElement } from 'react' import { act, create, type ReactTestRenderer } from 'react-test-renderer' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { BRIDGE_MAX_ROUTE_HREF_CHARS } from '../mobile-web-shell/bridge/bridge-caps' -import { - BRIDGE_NAVIGATE_BACK_NOTIFY, - BRIDGE_PROTOCOL_VERSION -} from '../mobile-web-shell/bridge/bridge-envelope' +import { BRIDGE_PROTOCOL_VERSION } from '../mobile-web-shell/bridge/bridge-envelope' import { createShellPageClient } from '../mobile-web-shell/bridge/page-bootstrap' import type { BridgeRpcClient } from '../mobile-web-shell/bridge/bridge-rpc-client' import type { RouteHandoff } from './route-handoff' @@ -125,12 +122,6 @@ function navigations(posted: readonly string[]): unknown[] { .filter((frame: { name?: string }) => frame.name === 'navigate') } -function backs(posted: readonly string[]): unknown[] { - return posted - .map((json) => JSON.parse(json)) - .filter((frame: { name?: string }) => frame.name === BRIDGE_NAVIGATE_BACK_NOTIFY) -} - const warned: unknown[][] = [] let restoreWarn: (() => void) | null = null @@ -211,20 +202,6 @@ describe('a target the shell would refuse', () => { }) }) -// The initial document has one history entry; Back must ask the native stack unless the page has pushed its own screens. -describe('a back this document cannot serve', () => { - it('falls through to this document when the shell granted no navigate', () => { - const { posted, handoff } = mount({ - ...INIT, - grants: { ...INIT.grants, native: [] }, - pageRoutes: [] - }) - handoff.back() - expect(backs(posted)).toEqual([]) - expect(router.back).toHaveBeenCalled() - }) -}) - // Wrap every href-taking router member; spreading navigate/prefetch untouched would bypass page-route policy. // Never hand prefetch to native navigate: a background optimization must not open a screen. @@ -237,57 +214,3 @@ describe('prefetch', () => { expect(router.push).not.toHaveBeenCalled() }) }) - -// Local targets run under the opener’s grants; hand off any target needing more so its own session receives the required capabilities. -describe('an in-page hop the session cannot cover', () => { - const TASKS = '/h/host-a/tasks' - const PAIRS = [ - { pathname: '/h/[hostId]', grants: ['navigate', 'storage', 'haptics'] }, - { - pathname: '/h/[hostId]/tasks', - grants: ['navigate', 'storage', 'externalLink', 'haptics', 'native.clipboard.write'] - } - ] - const withPairs = (native: string[]) => ({ - ...INIT, - grants: { ...INIT.grants, native }, - pageRoutes: ['/h/[hostId]', '/h/[hostId]/tasks'], - pageRouteGrants: PAIRS - }) - - it('stays in this document when the session already covers the target', () => { - const { posted, handoff } = mount( - withPairs(['navigate', 'storage', 'externalLink', 'haptics', 'native.clipboard.write']) - ) - handoff.push(TASKS) - expect(navigations(posted)).toEqual([]) - expect(router.push).toHaveBeenCalledWith(TASKS, undefined) - }) - - it('keeps a hop whose target declares a subset, which is C3.1 without its pairwise pin', () => { - const { posted, handoff } = mount({ - ...INIT, - grants: { ...INIT.grants, native: ['navigate', 'storage', 'externalLink', 'haptics'] }, - pageRoutes: ['/h/[hostId]/files/[worktreeId]', '/h/[hostId]/files/preview/[worktreeId]'], - pageRouteGrants: [ - { pathname: '/h/[hostId]/files/[worktreeId]', grants: ['navigate', 'storage', 'haptics'] }, - { pathname: '/h/[hostId]/files/preview/[worktreeId]', grants: ['navigate', 'haptics'] } - ] - }) - handoff.push('/h/host-a/files/preview/wt-1') - expect(navigations(posted)).toEqual([]) - expect(router.push).toHaveBeenCalledWith('/h/host-a/files/preview/wt-1', undefined) - }) - - it('keeps the old rule when the shell named no grants, so an older shell is unchanged', () => { - // Absent pairs preserve older-shell behavior; absence does not declare an empty grant list. - const { posted, handoff } = mount({ - ...INIT, - grants: { ...INIT.grants, native: ['navigate', 'storage', 'haptics'] }, - pageRoutes: ['/h/[hostId]', '/h/[hostId]/tasks'] - }) - handoff.push(TASKS) - expect(navigations(posted)).toEqual([]) - expect(router.push).toHaveBeenCalledWith(TASKS, undefined) - }) -}) diff --git a/mobile/src/notifications/notification-delivery-preferences.test.ts b/mobile/src/notifications/notification-delivery-preferences.test.ts index 7fe94c89692..c388ddc42c9 100644 --- a/mobile/src/notifications/notification-delivery-preferences.test.ts +++ b/mobile/src/notifications/notification-delivery-preferences.test.ts @@ -1,9 +1,5 @@ import { beforeEach, expect, it, vi } from 'vitest' import { AppState } from 'react-native' -import { - DEFAULT_NOTIFICATION_DELIVERY, - loadNotificationDeliveryPreferences -} from './notification-delivery-preferences' import { notificationViewingOfRoute, sessionOfPageLocation, @@ -52,8 +48,3 @@ it('suppresses the session a host list document shows inside itself, until its p setHostDocumentSession('host-1', sessionOfPageLocation('/h/host-1')) expect(shouldSuppressNotificationWhileViewing(event, 'host-1', true)).toBe(false) }) - -it('recovers defaults from malformed stored preferences', async () => { - storage.set('orca:notificationDeliveryPreferences', '{broken') - expect(await loadNotificationDeliveryPreferences()).toEqual(DEFAULT_NOTIFICATION_DELIVERY) -}) diff --git a/mobile/src/notifications/push-receive.test.ts b/mobile/src/notifications/push-receive.test.ts index fc3bc03b372..9c1b8832c9c 100644 --- a/mobile/src/notifications/push-receive.test.ts +++ b/mobile/src/notifications/push-receive.test.ts @@ -89,13 +89,6 @@ describe('shouldSuppressForegroundPush', () => { ).resolves.toBe(false) }) - it('suppresses pushes for an unpaired host', async () => { - vi.mocked(loadHostCatalog).mockResolvedValue([]) - await expect( - shouldSuppressForegroundPush(apnsData({ hostFingerprint, notificationSeq: 1 })) - ).resolves.toBe(true) - }) - it('suppresses a push after a matching persisted dismissal', async () => { const { rememberPushDismissal } = await import('./push-dismissal-watermarks') const payload = { diff --git a/mobile/src/pairing/mobile-relay-pairing-journal-store.test.ts b/mobile/src/pairing/mobile-relay-pairing-journal-store.test.ts index f95302adfbf..94b3518a72a 100644 --- a/mobile/src/pairing/mobile-relay-pairing-journal-store.test.ts +++ b/mobile/src/pairing/mobile-relay-pairing-journal-store.test.ts @@ -100,29 +100,6 @@ describe('mobile relay pairing journal store', () => { }) }) - it('records a provisional winner only for the active journal identity', async () => { - const journal = createMobileRelayPairingJournal({ - offer: offer as PairingOffer & { relay: NonNullable }, - hostId: 'host-1', - hostName: 'Blue Whale', - randomBytes: (length) => new Uint8Array(length).fill(7) - }) - await saveMobileRelayPairingJournal(journal) - - await updateMobileRelayPairingJournal(journal.metadata.journalId, (metadata) => ({ - ...metadata, - winner: 'direct', - authorizationMode: 'authenticated-direct' - })) - await expect( - updateMobileRelayPairingJournal('stale-journal', (metadata) => metadata) - ).rejects.toThrow(/stale/) - expect(JSON.parse(metadataRaw!)).toMatchObject({ - winner: 'direct', - authorizationMode: 'authenticated-direct' - }) - }) - it('treats metadata without its secret record as an incomplete crash', async () => { const journal = createMobileRelayPairingJournal({ offer: offer as PairingOffer & { relay: NonNullable }, @@ -150,32 +127,6 @@ describe('mobile relay pairing journal store', () => { expect(secretRaw).toBeNull() }) - it('replaces a journal that never selected an authorization path', async () => { - const journal = createMobileRelayPairingJournal({ - offer: offer as PairingOffer & { relay: NonNullable }, - hostId: 'host-1', - hostName: 'Blue Whale', - randomBytes: (length) => new Uint8Array(length).fill(10) - }) - await saveMobileRelayPairingJournal(journal) - const replacement = createMobileRelayPairingJournal({ - offer: offer as PairingOffer & { relay: NonNullable }, - hostId: 'host-2', - hostName: 'Red Panda', - randomBytes: (length) => new Uint8Array(length).fill(12) - }) - - const replacementSave = saveMobileRelayPairingJournal(replacement) - const staleUpdate = updateMobileRelayPairingJournal( - journal.metadata.journalId, - (metadata) => metadata - ) - - await expect(replacementSave).resolves.toBeUndefined() - await expect(staleUpdate).rejects.toThrow(/stale/) - await expect(loadMobileRelayPairingJournal()).resolves.toEqual(replacement) - }) - it('serializes a replacement behind an in-flight journal snapshot', async () => { const journal = createMobileRelayPairingJournal({ offer: offer as PairingOffer & { relay: NonNullable }, @@ -270,37 +221,6 @@ describe('mobile relay pairing journal store', () => { await expect(replacementSave).rejects.toThrow(/pairing in progress/) }) - it.each([ - ['winner', { winner: 'direct' as const }], - ['authorization mode', { authorizationMode: 'authenticated-direct' as const }] - ])( - 'refuses replacement while the attempt with a durable %s runs', - async (_name, authorization) => { - const created = createMobileRelayPairingJournal({ - offer: offer as PairingOffer & { relay: NonNullable }, - hostId: 'host-1', - hostName: 'Blue Whale', - randomBytes: (length) => new Uint8Array(length).fill(10) - }) - const journal = { - ...created, - metadata: { ...created.metadata, ...authorization } - } - - await saveMobileRelayPairingJournal(journal) - const replacement = createMobileRelayPairingJournal({ - offer: offer as PairingOffer & { relay: NonNullable }, - hostId: 'host-2', - hostName: 'Red Panda', - randomBytes: (length) => new Uint8Array(length).fill(12) - }) - await expect(saveMobileRelayPairingJournal(replacement)).rejects.toThrow( - /pairing in progress/ - ) - await expect(loadMobileRelayPairingJournal()).resolves.toEqual(journal) - } - ) - // New scans must supersede stranded authorized journals instead of blocking until expiry (#12518). it('makes a superseding scan wait for a publication in progress, and refuses a stale claim', async () => { diff --git a/mobile/src/pairing/pair-confirm-state.test.ts b/mobile/src/pairing/pair-confirm-state.test.ts deleted file mode 100644 index f3b5a2c2ade..00000000000 --- a/mobile/src/pairing/pair-confirm-state.test.ts +++ /dev/null @@ -1,43 +0,0 @@ -import { Buffer } from 'node:buffer' -import { describe, expect, it } from 'vitest' - -import { resolvePairConfirmRouteState } from './pair-confirm-state' -import type { PairingOffer } from '../../../src/shared/remote-runtime/pairing/mobile-relay-pairing-offer' - -function encodeOffer(offer: PairingOffer): string { - return Buffer.from(JSON.stringify(offer)) - .toString('base64') - .replace(/\+/g, '-') - .replace(/\//g, '_') - .replace(/=+$/g, '') -} - -describe('resolvePairConfirmRouteState', () => { - const offer: PairingOffer = { - v: 2, - endpoint: 'ws://192.168.1.10:6768', - deviceToken: 'token-abc', - publicKeyB64: 'pubkey-xyz' - } - - it('accepts a valid pairing code', () => { - expect(resolvePairConfirmRouteState(encodeOffer(offer))).toEqual({ - kind: 'ready', - offer, - errorMessage: '' - }) - }) - - it('accepts a full pairing URL', () => { - expect(resolvePairConfirmRouteState(`orca://pair#${encodeOffer(offer)}`)).toEqual({ - kind: 'ready', - offer, - errorMessage: '' - }) - expect(resolvePairConfirmRouteState(`orca://pair?code=${encodeOffer(offer)}`)).toEqual({ - kind: 'ready', - offer, - errorMessage: '' - }) - }) -}) diff --git a/mobile/src/platform/keyboard-persisting-taps.test.ts b/mobile/src/platform/keyboard-persisting-taps.test.ts deleted file mode 100644 index 22f08c0dfbd..00000000000 --- a/mobile/src/platform/keyboard-persisting-taps.test.ts +++ /dev/null @@ -1,87 +0,0 @@ -// @vitest-environment happy-dom -// RN Web ignores keyboardShouldPersistTaps; focusable Pressables take mousedown focus and close the IME. -// @vitest-environment happy-dom -// RN Web ignores keyboardShouldPersistTaps; focusable Pressables take mousedown focus and close the IME. - -import { afterEach, describe, expect, it, vi } from 'vitest' -import { keepTextFocusThroughTaps } from './keyboard-persisting-taps' - -import type * as ReactNative from 'react-native' - -vi.mock('react-native', () => vi.importActual('react-native-web')) - -function plant() { - const container = document.createElement('div') - const button = document.createElement('div') - button.tabIndex = 0 - const label = document.createElement('span') - button.appendChild(label) - const gap = document.createElement('span') - const field = document.createElement('input') - container.append(button, gap, field) - const liveInput = document.createElement('input') - document.body.append(container, liveInput) - return { container, label, gap, field, liveInput } -} - -function pressKeepsFocus(target: Element): boolean { - const event = new MouseEvent('mousedown', { bubbles: true, cancelable: true }) - target.dispatchEvent(event) - return event.defaultPrevented -} - -afterEach(() => { - document.body.innerHTML = '' -}) - -describe('keepTextFocusThroughTaps', () => { - it("keeps a text field's focus through a tap on a pressable, in both modes", () => { - for (const mode of ['always', 'handled'] as const) { - const { container, label, liveInput } = plant() - const release = keepTextFocusThroughTaps(container, mode) - liveInput.focus() - expect(pressKeepsFocus(label), mode).toBe(true) - release() - document.body.innerHTML = '' - } - }) - - it('lets a tap on nothing pressable dismiss only when taps are handled', () => { - const always = plant() - keepTextFocusThroughTaps(always.container, 'always') - always.liveInput.focus() - expect(pressKeepsFocus(always.gap)).toBe(true) - document.body.innerHTML = '' - - const handled = plant() - keepTextFocusThroughTaps(handled.container, 'handled') - handled.liveInput.focus() - expect(pressKeepsFocus(handled.gap)).toBe(false) - }) - - it('leaves focus alone when no text field holds it, or when the tap is on a text field', () => { - const { container, label, field, liveInput } = plant() - keepTextFocusThroughTaps(container, 'always') - expect(pressKeepsFocus(label)).toBe(false) - liveInput.focus() - expect(pressKeepsFocus(field)).toBe(false) - }) - - it('does not count a focusable ancestor above the container as a pressable in the bar', () => { - const outer = document.createElement('div') - outer.tabIndex = 0 - const { container, gap, liveInput } = plant() - outer.append(container) - document.body.prepend(outer) - keepTextFocusThroughTaps(container, 'handled') - liveInput.focus() - expect(pressKeepsFocus(gap)).toBe(false) - }) - - it('stops when released', () => { - const { container, label, liveInput } = plant() - keepTextFocusThroughTaps(container, 'always')() - liveInput.focus() - expect(pressKeepsFocus(label)).toBe(false) - }) -}) diff --git a/mobile/src/platform/native-speech.test.ts b/mobile/src/platform/native-speech.test.ts index 8e8bae4b5b7..62a5be12d16 100644 --- a/mobile/src/platform/native-speech.test.ts +++ b/mobile/src/platform/native-speech.test.ts @@ -94,18 +94,3 @@ describe('a recognizer that fails while its start is still resolving', () => { expect(await server.serve({ action: 'read' })).toMatchObject({ failure: 'failed' }) }) }) - -describe('a phone speech service too slow to answer', () => { - it('reports busy, not unsupported, so the next dictation asks again', async () => { - const engine: NativeSpeechEngine = { - ...engineWith('phone'), - availability: () => Promise.reject(Object.assign(new Error('slow'), { code: 'busy' })) - } - const server = createNativeSpeechServer(engine) - expect(await server.serve({ action: 'status', locale: 'en-US' })).toEqual({ - status: 'busy', - locale: null, - preference: 'phone' - }) - }) -}) diff --git a/mobile/src/session/agent-launch/mobile-new-tab-agent-options.test.ts b/mobile/src/session/agent-launch/mobile-new-tab-agent-options.test.ts deleted file mode 100644 index 639e76e1828..00000000000 --- a/mobile/src/session/agent-launch/mobile-new-tab-agent-options.test.ts +++ /dev/null @@ -1,12 +0,0 @@ -import { describe, expect, it } from 'vitest' - -import { orderMobileNewTabAgents } from './mobile-new-tab-agent-options' - -describe('mobile new-tab agent options', () => { - it('orders the enabled detected default first', () => { - expect(orderMobileNewTabAgents('codex', ['gemini', 'codex', 'claude'], ['gemini'])).toEqual([ - 'codex', - 'claude' - ]) - }) -}) diff --git a/mobile/src/session/agent-session-failure-copy.test.ts b/mobile/src/session/agent-session-failure-copy.test.ts deleted file mode 100644 index 13d469e14f9..00000000000 --- a/mobile/src/session/agent-session-failure-copy.test.ts +++ /dev/null @@ -1,55 +0,0 @@ -import { afterEach, expect, it } from 'vitest' -import { agentSessionFailureSentence } from '../../../src/shared/agent-session/failures/agent-session-failure-words' -import { activateMobileUiLocale } from '../i18n/mobile-i18n' -import { sayMobileAgentSessionFailure } from './agent-session-failure-copy' - -afterEach(async () => { - await activateMobileUiLocale('en') -}) - -it('gives new-chat guidance while keeping a missing conversation diagnostic private', () => { - expect( - agentSessionFailureSentence( - { - kind: 'savedConversationMissing', - detail: { text: 'No conversation found with session ID: private-id', audience: 'log' } - }, - 'row', - { agentName: 'Claude' }, - sayMobileAgentSessionFailure - ) - ).toBe("Claude couldn't find this chat's saved conversation. Start a new chat to continue.") -}) - -it.each([ - [ - 'en', - 'OMP has no model selected. Check your model selection and OMP sign-in, then send again.', - "OMP couldn't use @worker_be. Update OMP to 18.1.9 or later to keep it after a restart, or pick another model and send again." - ], - [ - 'de', - 'OMP hat kein Modell ausgewählt. Modellauswahl und OMP-Anmeldung prüfen und erneut senden.', - expect.stringContaining('OMP auf 18.1.9 oder neuer aktualisieren') - ] -] as const)( - 'words a missing OMP model and the update hint on the phone (%s)', - async (locale, none, update) => { - await activateMobileUiLocale(locale) - const say = (fact: Parameters[0]) => - agentSessionFailureSentence( - fact, - 'rejection', - { agentName: 'OMP' }, - sayMobileAgentSessionFailure - ) - expect(say({ kind: 'modelNotSelected' })).toBe(none) - expect( - say({ - kind: 'modelUnavailable', - detail: { text: '@worker_be', audience: 'log' }, - agentUpdate: '18.1.9' - }) - ).toEqual(update) - } -) diff --git a/mobile/src/session/mobile-prompt-controller.test.ts b/mobile/src/session/mobile-prompt-controller.test.ts index 23330511000..8b82f60e47a 100644 --- a/mobile/src/session/mobile-prompt-controller.test.ts +++ b/mobile/src/session/mobile-prompt-controller.test.ts @@ -19,8 +19,7 @@ import { sendButton, permissionAction, getController, - askAnswer, - getTree + askAnswer } from './__mocks__/mobile-prompt-controller' const client: RpcClient = { @@ -65,18 +64,6 @@ describe('prompt cards through the production controller, send contract and view } ) - it('shows a collapsed prompt again as a new wait', async () => { - await render({ tab: permissionTab }) - act(() => { - getTree().root.findByProps({ accessibilityLabel: 'Collapse' }).props.onPress() - }) - await render({ - tab: { ...permissionTab, agentStatus: { ...permissionTab.agentStatus, stateStartedAt: 20 } } - }) - expect(getController().nativeChatPermission).not.toBe(null) - expect(getController().nativeChatCollapsedPrompt).toBe(null) - }) - it('keeps an acknowledged Deny hidden after the chat screen remounts on a lingering status', async () => { await render({ tab: permissionTab }) await act(async () => { diff --git a/mobile/src/session/mobile-structured-agent-session-launch.test.ts b/mobile/src/session/mobile-structured-agent-session-launch.test.ts index 2218b37ac4e..b5b62c474c0 100644 --- a/mobile/src/session/mobile-structured-agent-session-launch.test.ts +++ b/mobile/src/session/mobile-structured-agent-session-launch.test.ts @@ -28,99 +28,6 @@ describe('mobile structured agent-session launch', () => { kind: 'unknown' }) }) - - it('treats malformed structured responses as unknown', async () => { - const client = clientReturning( - { ok: true, result: { supported: true } }, - { ok: true, result: { ok: true, value: { sessionId: '' } } } - ) - - await expect( - createMobileStructuredAgentSession(client, 'workspace-1', 'codex') - ).resolves.toMatchObject({ - kind: 'unknown' - }) - }) - - it.each(['structured_agent_session_unsupported', 'method_not_found'])( - 'treats a top-level %s as a definitive refusal', - async (code) => { - const client = clientReturning( - { ok: true, result: { supported: true } }, - { ok: false, error: { code, message: 'structured create unavailable' } } - ) - - await expect( - createMobileStructuredAgentSession(client, 'workspace-1', 'codex') - ).resolves.toEqual({ - kind: 'failed', - message: 'structured create unavailable' - }) - } - ) - - it.each(['agent_session_operation_unknown', 'runtime_error', 'future_unknown_code'])( - 'keeps a top-level %s outcome unknown', - async (code) => { - const client = clientReturning( - { ok: true, result: { supported: true } }, - { ok: false, error: { code, message: 'create outcome ambiguous' } } - ) - - await expect( - createMobileStructuredAgentSession(client, 'workspace-1', 'codex') - ).resolves.toEqual({ - kind: 'unknown', - message: 'create outcome ambiguous' - }) - } - ) - - it('treats an envelope unsupported refusal as definitive', async () => { - const client = clientReturning( - { ok: true, result: { supported: true } }, - { - ok: true, - result: { - ok: false, - refusal: { - code: 'structured_agent_session_unsupported', - message: 'structured create unavailable' - } - } - } - ) - - await expect( - createMobileStructuredAgentSession(client, 'workspace-1', 'codex') - ).resolves.toEqual({ - kind: 'failed', - message: 'structured create unavailable' - }) - }) - - it.each(['agent_session_operation_unknown', 'agent_session_ownership_unknown', 'future_code'])( - 'keeps an envelope %s refusal unknown', - async (code) => { - const client = clientReturning( - { ok: true, result: { supported: true } }, - { - ok: true, - result: { - ok: false, - refusal: { code, message: 'create outcome ambiguous' } - } - } - ) - - await expect( - createMobileStructuredAgentSession(client, 'workspace-1', 'codex') - ).resolves.toEqual({ - kind: 'unknown', - message: 'create outcome ambiguous' - }) - } - ) }) it('settles a proven missing-original fork refusal but keeps a lost earlier attempt unknown', async () => { diff --git a/mobile/src/session/mobile-structured-send-delivery.test.ts b/mobile/src/session/mobile-structured-send-delivery.test.ts deleted file mode 100644 index c6c718702d4..00000000000 --- a/mobile/src/session/mobile-structured-send-delivery.test.ts +++ /dev/null @@ -1,173 +0,0 @@ -import { describe, expect, it } from 'vitest' -import type { AgentJournalDispatchState } from '../../../src/shared/agent-session/journal/agent-session-journal-types' -import type { AgentSessionSendResult } from '../../../src/shared/agent-session/agent-session-wire' -import { DISPATCH_REJECTED_CANCELLED } from '../../../src/shared/agent-session/requests/structured-agent-session-dispatch-rejection' -import { STRUCTURED_AGENT_SESSION_SUBMISSION_MISSING } from '../../../src/shared/agent-session/requests/structured-agent-session-send-evidence' -import { mobileStructuredSendDelivery } from './mobile-structured-send-delivery' -import type { StructuredAgentSessionMutationCallResult } from './mobile-structured-agent-session-rpc' -import { structuredSendResultFixture } from './structured-agent-send-result.test-fixture' - -function accepted( - dispatchState: AgentJournalDispatchState, - reason: string | null = null -): StructuredAgentSessionMutationCallResult { - return { status: 'accepted', value: structuredSendResultFixture(dispatchState, reason) } -} - -describe('mobileStructuredSendDelivery', () => { - it.each([ - ['a sign-in rejection', 'Sign in to Grok with `grok login`.', { kind: 'notSignedIn' as const }], - ['a content rejection', 'Claude does not support .bmp', undefined], - ['a write failure', 'provider_write_failed: broken pipe', undefined] - ])('leaves %s to its recorded row', (_name, reason, rejection) => { - const value = structuredSendResultFixture('rejected', reason) - if (rejection && 'submission' in value) { - value.submission.rejection = rejection - } - expect(mobileStructuredSendDelivery({ status: 'accepted', value })).toEqual({ - outcome: 'accepted', - error: null - }) - }) - - it('distinguishes transport doubt from an admitted unknown ordinary message', () => { - expect(mobileStructuredSendDelivery({ status: 'unknown' })).toEqual({ - outcome: 'unknown', - error: null - }) - expect( - mobileStructuredSendDelivery(accepted('unknown', STRUCTURED_AGENT_SESSION_SUBMISSION_MISSING)) - ).toEqual({ outcome: 'unknown', error: null }) - expect(mobileStructuredSendDelivery(accepted('unknown'))).toEqual({ - outcome: 'accepted', - error: null - }) - }) - - it.each(['accepted', 'pending'] as const)('reports a written %s send as accepted', (state) => { - expect(mobileStructuredSendDelivery(accepted(state))).toEqual({ - outcome: 'accepted', - error: null - }) - }) - - it.each(['waiting', 'dispatched', 'returned'] as const)( - 'lets the host own its %s queued message without an optimistic bubble', - (state) => { - expect( - mobileStructuredSendDelivery({ - status: 'accepted', - value: { - clientMessageId: 'client-1', - queued: { messageId: 'client-1', position: 1, state } - } - }) - ).toEqual({ outcome: 'queued', error: null }) - } - ) - - it('hands back a withdrawn card instead of silently sending again', () => { - expect( - mobileStructuredSendDelivery({ - status: 'accepted', - value: { - clientMessageId: 'client-1', - queued: { messageId: 'client-1', position: 1, state: 'withdrawn' } - } - }) - ).toEqual({ outcome: 'rejected', error: 'Message not sent' }) - }) - - it('keeps a handed-off queued message unconfirmed until the stream identifies it', () => { - const value = structuredSendResultFixture('accepted') - if (!('submission' in value)) { - throw new Error('expected a submission answer') - } - expect( - mobileStructuredSendDelivery({ - status: 'accepted', - value: { - clientMessageId: 'draft-id', - submission: { - ...value.submission, - clientMessageId: 'fresh-id', - queuedMessageId: 'draft-id' - } - } - }) - ).toEqual({ outcome: 'unknown', error: null }) - }) - - it('fails closed when a malformed answer has no submission', () => { - expect(mobileStructuredSendDelivery({ status: 'accepted', value: JSON.parse('{}') })).toEqual({ - outcome: 'unknown', - error: null - }) - }) - - it('lets a kept queued card hold the text after a provider rejection', () => { - const value = structuredSendResultFixture('rejected', 'Orca restarted before this was sent.') - if (!('submission' in value)) { - throw new Error('expected a submission answer') - } - value.submission.keptAsQueuedMessageId = 'card-id' - expect(mobileStructuredSendDelivery({ status: 'accepted', value })).toEqual({ - outcome: 'queued', - error: null - }) - }) - - it.each([ - { reason: DISPATCH_REJECTED_CANCELLED, typed: false }, - { reason: 'This message was withdrawn before the agent started it.', typed: true } - ])('leaves a stopped submission in its existing chat row (typed $typed)', ({ reason, typed }) => { - const value = structuredSendResultFixture('rejected', reason) - if (typed && 'submission' in value) { - value.submission.rejection = { kind: 'cancelled' } - } - expect(mobileStructuredSendDelivery({ status: 'accepted', value })).toEqual({ - outcome: 'accepted', - error: null - }) - }) - - it.each([ - ['agent_session_operation_invalid', 'Invalid operation'], - ['agent_session_checkpoint_stale', 'Fence moved'], - ['agent_session_operation_expired', 'Operation expired'], - ['agent_session_operation_conflict', 'Operation conflict'] - ] as const)('reports the current %s refusal', (code, message) => { - expect( - mobileStructuredSendDelivery({ - status: 'refused', - code, - message, - failure: { kind: 'refused', code } - }) - ).toEqual({ - outcome: 'rejected', - error: message - }) - }) - - it('preserves an unknown operation refusal as uncertainty', () => { - expect( - mobileStructuredSendDelivery({ - status: 'refused', - code: 'agent_session_operation_unknown', - message: 'Outcome unknown', - failure: { kind: 'refused', code: 'agent_session_operation_unknown' } - }) - ).toEqual({ outcome: 'unknown', error: null }) - }) - - it('reports a request failure without consulting earlier sends', () => { - expect( - mobileStructuredSendDelivery({ - status: 'failed', - message: 'Your message was not sent. Send it again.', - failure: { kind: 'failed' } - }) - ).toEqual({ outcome: 'rejected', error: 'Your message was not sent. Send it again.' }) - }) -}) diff --git a/mobile/src/session/native-chat/agent-session/mobile-structured-agent-session-unnamed-stop.test.ts b/mobile/src/session/native-chat/agent-session/mobile-structured-agent-session-unnamed-stop.test.ts deleted file mode 100644 index fbc778f03f8..00000000000 --- a/mobile/src/session/native-chat/agent-session/mobile-structured-agent-session-unnamed-stop.test.ts +++ /dev/null @@ -1,76 +0,0 @@ -import { describe, expect, it, vi } from 'vitest' -import type { StructuredAgentSessionState } from '../../../../../src/shared/agent-session/structured-agent-session-reducer' -import type { RpcClient } from '../../../transport/rpc/rpc-client-contract' -import { requestMobileStructuredAgentSessionCancel } from '../../mobile-structured-agent-session-cancel' - -type SentParams = Record & { envelope: { clientOperationId: string } } - -function recordingClient(sent: SentParams[]): RpcClient { - const sendRequest = async (_method: string, params: SentParams) => { - sent.push(params) - return { ok: true, result: { ok: true, value: { cancelled: true } }, _meta: { runtimeId: 'r' } } - } - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: cancel reaches only `sendRequest`. - return { sendRequest } as unknown as RpcClient -} - -function state(turnId: string | null): StructuredAgentSessionState { - const items = turnId - ? [ - { - itemId: 'status-1', - revision: 1, - sequence: 1, - observedAt: 10, - body: { kind: 'status', text: 'Working', turnLifecycle: { turnId, state: 'running' } } - } - ] - : [] - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: cancel reads only the fence and the running turn. - return { fence: 3, items } as unknown as StructuredAgentSessionState -} - -function press(input: { - sent: SentParams[] - turnId: string | null - hostStopsConversation: boolean | null - prompt?: { itemId: string; expectedRevision: number } - promptCancelSupported?: boolean -}) { - const onSendError = vi.fn() - const pressed = requestMobileStructuredAgentSessionCancel({ - client: recordingClient(input.sent), - sessionId: 'session-1', - enabled: true, - stateRef: { current: state(input.turnId) }, - promptCancelSupported: input.promptCancelSupported ?? true, - ...(input.prompt ? { prompt: input.prompt } : {}), - hostAnswersRepeatedStops: true, - hostStopsConversation: input.hostStopsConversation, - inFlight: new Map(), - onSendError - }) - return { pressed, onSendError } -} - -describe('phone Stop against a host that stops what the chat has in flight', () => { - it('names no turn while a turn runs either', async () => { - const sent: SentParams[] = [] - expect(await press({ sent, turnId: 'turn-1', hostStopsConversation: true }).pressed).toBe(true) - expect(sent[0]).not.toHaveProperty('turnId') - }) - - it("keeps naming a card's turn when the host cannot take the card's identity", async () => { - const sent: SentParams[] = [] - const prompt = { itemId: 'prompt-1', expectedRevision: 2 } - await press({ - sent, - turnId: 'turn-1', - hostStopsConversation: true, - prompt, - promptCancelSupported: false - }).pressed - expect(sent[0]).toMatchObject({ turnId: 'turn-1' }) - expect(sent[0]).not.toHaveProperty('prompt') - }) -}) diff --git a/mobile/src/session/native-chat/agent-session/use-mobile-structured-agent-session-read-failure.test.tsx b/mobile/src/session/native-chat/agent-session/use-mobile-structured-agent-session-read-failure.test.tsx deleted file mode 100644 index aa9c0983057..00000000000 --- a/mobile/src/session/native-chat/agent-session/use-mobile-structured-agent-session-read-failure.test.tsx +++ /dev/null @@ -1,94 +0,0 @@ -// Preserve typed final read refusals beside their words so unreadable history cannot render a sendable composer. - -import { createElement } from 'react' -import { act, type ReactTestRenderer } from 'react-test-renderer' -import { createWithQueryClient } from '../../../test-support/query-client-test-renderer' -import { afterEach, beforeEach, expect, it, vi } from 'vitest' -import type { RpcClient } from '../../../transport/rpc/rpc-client-contract' -import { useMobileStructuredAgentSession } from '../../use-mobile-structured-agent-session' -import { CAPABLE, SESSION_ID, ok } from './use-mobile-structured-agent-session-queued.test-fixture' - -const asyncStorage = vi.hoisted(() => ({ - getItem: vi.fn(async () => null), - setItem: vi.fn(async () => undefined), - removeItem: vi.fn(async () => undefined) -})) - -vi.mock('@react-native-async-storage/async-storage', () => ({ default: asyncStorage })) - -let renderer: ReactTestRenderer | null = null -let hook: ReturnType | null = null -let listener: ((value: unknown) => void) | null = null -const sendRequest = vi.fn() -const client: RpcClient = { - sendRequest, - subscribe: vi.fn((_method, _params, onData) => { - if (_method === 'agentSession.subscribe') { - listener = onData - } - return vi.fn() - }), - updateTerminalSubscriptionViewport: () => {}, - getState: () => 'connected', - getReconnectAttempt: () => 0, - getLastConnectedAt: () => null, - onStateChange: () => () => {}, - notifyForeground: () => {}, - close: () => {} -} - -function Harness(): null { - hook = useMobileStructuredAgentSession({ - client, - pairedHostClient: client, - sessionId: SESSION_ID, - sourceIdentity: 'host-a\0workspace-a', - enabled: true, - connected: true, - agent: 'claude', - hostSupport: CAPABLE, - appendComposerText: () => true, - onSendError: vi.fn() - }) - return null -} - -function refusedRead(reason: string) { - const error = { - code: 'runtime_error', - message: 'agent_session_journal_unreadable', - data: { refusal: { code: 'agent_session_journal_unreadable', details: { reason } } } - } - return { type: 'error', message: error.message, error } -} - -async function readFailedWith(reason: string) { - act(() => { - renderer = createWithQueryClient(createElement(Harness)) - }) - await vi.waitFor(() => expect(listener).toEqual(expect.any(Function))) - act(() => listener?.(refusedRead(reason))) - return hook!.session -} - -beforeEach(() => { - vi.clearAllMocks() - - sendRequest.mockImplementation(async (method) => - method === 'agentSession.options' ? ok({ models: [], current: {} }) : ok({}) - ) -}) - -afterEach(() => { - act(() => renderer?.unmount()) - renderer = null - hook = null - listener = null -}) - -it('reads a failure that can clear as one the chat keeps trying past', async () => { - expect(await readFailedWith('journalUnavailable')).toMatchObject({ - status: 'error', - readFailedFinally: false - }) -}) diff --git a/mobile/src/session/native-chat/agent-session/use-mobile-structured-agent-session.cut-turn-notice.test.tsx b/mobile/src/session/native-chat/agent-session/use-mobile-structured-agent-session.cut-turn-notice.test.tsx deleted file mode 100644 index c29e1229c36..00000000000 --- a/mobile/src/session/native-chat/agent-session/use-mobile-structured-agent-session.cut-turn-notice.test.tsx +++ /dev/null @@ -1,89 +0,0 @@ -import { createElement } from 'react' -import { snapshotEvent } from './use-mobile-structured-agent-session-queued.test-fixture' -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 type { AgentJournalRenderItem } from '../../../../../src/shared/agent-session/journal/agent-session-journal-types' -import type { AgentSessionSubscribeEvent } from '../../../../../src/shared/agent-session/agent-session-wire' -import type { RpcClient } from '../../../transport/rpc/rpc-client-contract' -import type { RpcResponse } from '../../../transport/rpc/rpc-wire-types' -import { useMobileStructuredAgentSession } from '../../use-mobile-structured-agent-session' -import { ANSWERED_PROMPT_ITEMS } from '../input/mobile-native-chat-answered-prompts.test-fixture' - -vi.mock('@react-native-async-storage/async-storage', () => ({ - default: { getItem: vi.fn(async () => null), setItem: vi.fn(), removeItem: vi.fn() } -})) - -function snapshot(items: AgentJournalRenderItem[]): AgentSessionSubscribeEvent { - return snapshotEvent({ items }) -} - -describe('useMobileStructuredAgentSession transcript', () => { - let renderer: ReactTestRenderer | null = null - afterEach(() => { - act(() => renderer?.unmount()) - renderer = null - }) - - async function mount(agent: string, items: AgentJournalRenderItem[]) { - let listener: ((value: unknown) => void) | null = null - const client: Pick = { - getState: () => 'connected', - onStateChange: () => () => {}, - sendRequest: vi.fn(async (): Promise => ({ - id: 'response-1', - ok: true, - result: {}, - _meta: { runtimeId: 'runtime-1' } - })), - subscribe: vi.fn((_method: string, _params: unknown, onData: (value: unknown) => void) => { - if (_method === 'agentSession.subscribe') { - listener = onData - } - return () => {} - }) - } - const rendered: { hook: ReturnType | null } = { - hook: null - } - function Harness(): null { - rendered.hook = useMobileStructuredAgentSession({ - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the hook's request, subscription and connection members are provided. - client: client as RpcClient, - pairedHostClient: null, - sessionId: 'session-1', - enabled: true, - connected: true, - hostSupport: null, - agent, - onSendError: vi.fn() - }) - return null - } - act(() => { - renderer = createWithQueryClient(createElement(Harness)) - }) - await vi.waitFor(() => expect(listener).toEqual(expect.any(Function))) - - act(() => listener?.(snapshot(items))) - return rendered - } - - it('draws an answered approval and question as receipts, never as their raw tool lines', async () => { - const rendered = await mount('claude', ANSWERED_PROMPT_ITEMS) - await vi.waitFor(() => expect(rendered.hook?.session.messages.length).toBeGreaterThan(0)) - - const { session, receipts } = rendered.hook! - expect( - session.messages.some((message) => - message.blocks.some( - (block) => block.type === 'tool-call' && block.name === 'AskUserQuestion' - ) - ) - ).toBe(false) - expect(session.messages.flatMap((message) => receipts.get(message.id)?.kind ?? [])).toEqual([ - 'approval', - 'question' - ]) - }) -}) diff --git a/mobile/src/session/native-chat/composer/MobileNativeChatComposer.keyboard.web.test.tsx b/mobile/src/session/native-chat/composer/MobileNativeChatComposer.keyboard.web.test.tsx index 928ca7efe92..e1cee3abee1 100644 --- a/mobile/src/session/native-chat/composer/MobileNativeChatComposer.keyboard.web.test.tsx +++ b/mobile/src/session/native-chat/composer/MobileNativeChatComposer.keyboard.web.test.tsx @@ -173,27 +173,6 @@ describe('mobile composer modifier submit in the paired web page', () => { expect(input.value).toBe('retained draft') }) - it.each([true, false])( - 'sends raw text with alternate intent, retaining focus on accepted:%s', - async (accepted) => { - onSend.mockResolvedValue(accepted) - await render() - expect((await key({ metaKey: true })).defaultPrevented).toBe(true) - expect(onSend).toHaveBeenCalledExactlyOnceWith(' hello ', { alternate: true }) - expect(document.activeElement).toBe(field()) - expect(field().value).toBe(' hello ') - } - ) - - it('uses Ctrl on Android and leaves Cmd alone', async () => { - vi.spyOn(navigator, 'userAgent', 'get').mockReturnValue('Android') - await render() - expect((await key({ metaKey: true })).defaultPrevented).toBe(false) - expect(onSend).not.toHaveBeenCalled() - expect((await key({ ctrlKey: true })).defaultPrevented).toBe(true) - expect(onSend).toHaveBeenCalledExactlyOnceWith(' hello ', { alternate: true }) - }) - it.each([ {}, { shiftKey: true }, @@ -210,30 +189,6 @@ describe('mobile composer modifier submit in the paired web page', () => { expect(field().value).toBe(' hello ') }) - it('consumes a refused send without changing the draft or focus', async () => { - await render({ sendDisabled: true }) - expect((await key({ metaKey: true })).defaultPrevented).toBe(true) - expect(onSend).not.toHaveBeenCalled() - expect(field().value).toBe(' hello ') - expect(document.activeElement).toBe(field()) - }) - - it.each([ - { sendFollowUp: { action: 'queue', offersChoice: true }, alternateSteers: true }, - { sendFollowUp: { action: 'steer', offersChoice: true }, alternateSteers: false }, - { sendFollowUp: { action: 'queue', offersChoice: false }, alternateSteers: false }, - { sendFollowUp: null, alternateSteers: false } - ] as const)( - 'hands an empty chord to the head card, saying whether its other way is steer: %j', - async ({ sendFollowUp, alternateSteers }) => { - const steerHead = { steers: () => true, run: vi.fn(() => true), light: vi.fn() } - await render({ value: '', sendFollowUp, steerHead }) - expect((await key({ metaKey: true })).defaultPrevented).toBe(true) - expect(steerHead.run).toHaveBeenCalledExactlyOnceWith(alternateSteers) - expect(onSend).not.toHaveBeenCalled() - } - ) - it('holding Cmd alone on an empty composer shows Steer queued in Send, lights the head card and sends it on a press', async () => { vi.spyOn(document, 'hasFocus').mockReturnValue(true) const steerHead = { steers: () => true, run: vi.fn(() => true), light: vi.fn() } @@ -259,13 +214,6 @@ describe('mobile composer modifier submit in the paired web page', () => { expect(steerHead.light).toHaveBeenLastCalledWith(false) }) - it('saves a queued edit without alternate intent', async () => { - await render({ editSession: { cancel: vi.fn(), refuseCommand: () => false, locked: false } }) - expect((await key({ metaKey: true })).defaultPrevented).toBe(true) - expect(onSend).toHaveBeenCalledExactlyOnceWith(' hello ') - expect(document.activeElement).toBe(field()) - }) - it.each([ { value: '@rea', expected: '@README.md ', filePaths: ['README.md', 'src/read.ts'] }, { value: '/comp', expected: '/compact ', filePaths: [] } diff --git a/mobile/src/session/native-chat/composer/MobileNativeChatComposer.paste.web.test.tsx b/mobile/src/session/native-chat/composer/MobileNativeChatComposer.paste.web.test.tsx deleted file mode 100644 index 089dad5cdea..00000000000 --- a/mobile/src/session/native-chat/composer/MobileNativeChatComposer.paste.web.test.tsx +++ /dev/null @@ -1,108 +0,0 @@ -// @vitest-environment happy-dom -import { act, type ComponentProps } from 'react' -import { createRoot, type Root } from 'react-dom/client' -import type * as ReactNative from 'react-native' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { MobileNativeChatComposer } from './MobileNativeChatComposer' - -vi.mock('react-native', () => vi.importActual('react-native-web')) -vi.mock('./MobileNativeChatComposerField', () => import('./MobileNativeChatComposerField.web')) -vi.mock('../../../platform/keyboard-occlusion', () => ({ useKeyboardOcclusion: () => 0 })) -vi.mock('lucide-react-native', () => ({ - Plus: () => null, - AtSign: () => null, - Image: () => null, - Package: () => null, - Paperclip: () => null, - Terminal: () => null -})) -vi.mock('../../../components/ActionSheetModal', () => ({ ActionSheetModal: () => null })) -vi.mock('../input/MobileNativeChatSessionOptionPickers', () => ({ - MobileNativeChatSessionOptionPickers: () => null -})) -vi.mock('./MobileNativeChatComposerMic', () => ({ MobileNativeChatComposerMic: () => null })) -vi.mock('./MobileNativeChatContextUsageRing', () => ({ - useMobileNativeChatContextRing: () => ({ barProps: {}, ring: null }) -})) -vi.mock('./MobileNativeChatSendButton', () => ({ MobileNativeChatSendButton: () => null })) -vi.mock('./MobileNativeChatEditActions', () => ({ MobileNativeChatEditActions: () => null })) -vi.mock('./MobileNativeChatComposerAttachments', () => ({ - MobileNativeChatComposerAttachments: () => null -})) -vi.mock('./MobileNativeChatComposerMenu', () => ({ - MobileNativeChatComposerSuggestions: () => null -})) - -type ComposerProps = ComponentProps - -describe('pasting into the mobile composer in the paired web page', () => { - let root: Root - let container: HTMLDivElement - const onPasteImages = vi.fn() - const onAttachPastedText = vi.fn() - - beforeEach(() => { - onPasteImages.mockReset() - onAttachPastedText.mockReset() - container = document.createElement('div') - document.body.append(container) - root = createRoot(container) - }) - - afterEach(async () => { - await act(async () => root.unmount()) - container.remove() - }) - - async function render(props: Partial = {}) { - await act(async () => - root.render( - 0} - getComposerEditGeneration={() => 0} - value="" - onChangeText={vi.fn()} - onSend={vi.fn()} - onPasteImages={onPasteImages} - structured={{ - catalog: { reported: [], conversationCommands: [] }, - files: [], - onRemoveFile: vi.fn(), - onSlashMenuOpen: vi.fn(), - onAttachPastedText - }} - {...props} - /> - ) - ) - } - - function paste(text: string, image?: File): Event { - const event = new Event('paste', { bubbles: true, cancelable: true }) - Object.defineProperty(event, 'clipboardData', { - value: { - items: image ? [{ type: image.type, getAsFile: () => image }] : [], - files: image ? [image] : [], - getData: (format: string) => (format === 'text/plain' ? text : '') - } - }) - const field = container.querySelector('textarea') - if (!field) { - throw new Error('Composer field missing') - } - field.dispatchEvent(event) - return event - } - - it('turns a 32 KB paste into a pasted-text file and leaves shorter text to the field', async () => { - await render() - const long = 'a'.repeat(32 * 1024) - expect(paste(long).defaultPrevented).toBe(true) - expect(onAttachPastedText).toHaveBeenCalledExactlyOnceWith(long) - - expect(paste(long.slice(1)).defaultPrevented).toBe(false) - expect(onAttachPastedText).toHaveBeenCalledTimes(1) - expect(onPasteImages).not.toHaveBeenCalled() - }) -}) diff --git a/mobile/src/session/native-chat/composer/MobileNativeChatComposer.test.ts b/mobile/src/session/native-chat/composer/MobileNativeChatComposer.test.ts index d080a7c80bc..cd06bec969a 100644 --- a/mobile/src/session/native-chat/composer/MobileNativeChatComposer.test.ts +++ b/mobile/src/session/native-chat/composer/MobileNativeChatComposer.test.ts @@ -1,4 +1,4 @@ -import { createElement, StrictMode, type ComponentProps, type ReactNode } from 'react' +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 { afterEach, describe, expect, it, vi } from 'vitest' @@ -365,29 +365,6 @@ describe('MobileNativeChatComposer', () => { expect(input().props.selection).toBeUndefined() }) - it('dismisses an accepted send after Strict Mode replays mount effects', async () => { - vi.mocked(Keyboard.dismiss).mockClear() - await act(async () => { - renderer = create( - createElement( - StrictMode, - null, - createElement(MobileNativeChatComposer, { - value: 'hello', - onChangeText: vi.fn(), - onSend: vi.fn().mockResolvedValue(true), - sendSurfaceId: 'tab-a', - getSendCompletionGeneration: getCurrentSendCompletionGeneration - }) - ) - ) - }) - - await act(async () => sendButton().props.onPress()) - - expect(Keyboard.dismiss).toHaveBeenCalledTimes(1) - }) - 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 diff --git a/mobile/src/session/native-chat/composer/mobile-native-chat-image-attachment.test.ts b/mobile/src/session/native-chat/composer/mobile-native-chat-image-attachment.test.ts deleted file mode 100644 index e296b975b2c..00000000000 --- a/mobile/src/session/native-chat/composer/mobile-native-chat-image-attachment.test.ts +++ /dev/null @@ -1,88 +0,0 @@ -import { describe, expect, it, vi } from 'vitest' -import type { RpcClient } from '../../../transport/rpc/rpc-client-contract' -import type { RpcResponse, RpcSuccess } from '../../../transport/rpc/rpc-wire-types' -import { uploadMobileNativeChatImages } from './mobile-native-chat-image-attachment' - -function ok(id: string, result: unknown): RpcSuccess { - return { id, ok: true, result, _meta: { runtimeId: 'runtime-1' } } -} - -function methodNotFound(id: string): RpcResponse { - return { - id, - ok: false, - error: { code: 'method_not_found', message: 'no' }, - _meta: { runtimeId: 'r' } - } -} - -function clientWithResponses(responses: RpcResponse[]): Pick & { - calls: { method: string; params: unknown }[] -} { - const calls: { method: string; params: unknown }[] = [] - return { - calls, - sendRequest: vi.fn(async (method: string, params?: unknown) => { - calls.push({ method, params }) - const response = responses.shift() - if (!response) { - throw new Error(`unexpected request: ${method}`) - } - return response - }) - } -} - -describe('uploadMobileNativeChatImages', () => { - it('uploads all three selected images in picker order', async () => { - const client = clientWithResponses([ - methodNotFound('start-a'), - ok('save-a', '/tmp/a.png'), - methodNotFound('start-b'), - ok('save-b', '/tmp/b.png'), - methodNotFound('start-c'), - ok('save-c', '/tmp/c.png') - ]) - - const order: string[] = [] - async function* pickImages() { - for (const image of [ - { base64: 'AAAA', uri: 'file:///a.jpg' }, - { base64: 'BBBB', uri: 'file:///b.jpg' }, - { base64: 'CCCC', uri: 'file:///c.jpg' } - ]) { - order.push(`read:${image.uri}`) - yield image - } - } - const result = await uploadMobileNativeChatImages('library', { - client, - getConnectionId: async () => 'conn-7', - pickImages, - onImageUploaded: (image) => order.push(`uploaded:${image.previewUri}`) - }) - - expect(result).toEqual([ - { - path: '/tmp/a.png', - previewUri: 'file:///a.jpg' - }, - { - path: '/tmp/b.png', - previewUri: 'file:///b.jpg' - }, - { - path: '/tmp/c.png', - previewUri: 'file:///c.jpg' - } - ]) - expect(order).toEqual([ - 'read:file:///a.jpg', - 'uploaded:file:///a.jpg', - 'read:file:///b.jpg', - 'uploaded:file:///b.jpg', - 'read:file:///c.jpg', - 'uploaded:file:///c.jpg' - ]) - }) -}) diff --git a/native/computer-use-linux/runtime_keyboard_test.py b/native/computer-use-linux/runtime_keyboard_test.py index 17e0267ef5c..f95b1199bdb 100644 --- a/native/computer-use-linux/runtime_keyboard_test.py +++ b/native/computer-use-linux/runtime_keyboard_test.py @@ -8,7 +8,6 @@ import time import types import unittest from pathlib import Path -from unittest import mock class FakeKeySynthType: @@ -44,26 +43,8 @@ runtime = load_runtime() class RuntimeKeyboardTest(unittest.TestCase): - def setUp(self): - self.events = [] - patcher = mock.patch.object( - runtime.Atspi, "generate_keyboard_event", lambda *args: self.events.append(args) - ) - patcher.start() - self.addCleanup(patcher.stop) - def test_missing_xdotool_preserves_ascii_and_refuses_unicode(self): - with mock.patch.object(runtime.shutil, "which", return_value=None), mock.patch.dict( - runtime.os.environ, {"XDG_SESSION_TYPE": "x11"} - ): - runtime.type_text("Hello") - runtime.press_key("a") - self.assertEqual(self.events, [(0, "Hello", FakeKeySynthType.STRING), (0, "a", FakeKeySynthType.STRING)]) - self.events.clear() - with self.assertRaisesRegex(RuntimeError, "unsupported capability"): - runtime.type_text("café Ω") - self.assertEqual(self.events, []) @unittest.skipIf(sys.platform == "win32", "the Linux bridge uses POSIX termination") def test_termination_stops_the_typing_child(self): @@ -112,16 +93,7 @@ class RuntimeKeyboardTest(unittest.TestCase): except ProcessLookupError: pass - def run_hotkey(self, raw): - with mock.patch.object(runtime.shutil, "which", return_value="/usr/bin/xdotool"), mock.patch.object( - runtime.subprocess, "run" - ) as run: - runtime.hotkey(raw) - return run.call_args.args[0] - def test_hotkey_lowercases_letters_so_xdotool_does_not_add_shift(self): - self.assertEqual(self.run_hotkey("CmdOrCtrl+A"), ["/usr/bin/xdotool", "key", "ctrl+a"]) - self.assertEqual(self.run_hotkey("ctrl+shift+T"), ["/usr/bin/xdotool", "key", "ctrl+shift+t"]) diff --git a/native/computer-use-linux/runtime_render_test.py b/native/computer-use-linux/runtime_render_test.py index d8d64382d7c..d39c8112a08 100644 --- a/native/computer-use-linux/runtime_render_test.py +++ b/native/computer-use-linux/runtime_render_test.py @@ -202,18 +202,6 @@ class SnapshotFixture(ExitStack): class RuntimeRenderTest(unittest.TestCase): - def test_key_requests_reject_missing_payload_without_input(self): - root = FakeAccessible("frame", "Editor") - root.get_state_set = lambda: FakeStateSet(FakeStateType.ACTIVE) - with SnapshotFixture(root), \ - patch.object(runtime.Atspi, "generate_keyboard_event", create=True) as keyboard, \ - patch.object(runtime.subprocess, "run") as process: - for payload in ({}, {"key": None}, {"key": ""}): - with self.subTest(payload=payload): - with self.assertRaisesRegex(RuntimeError, "key is required"): - runtime.run_operation({"tool": "press_key", "app": "Fixture", "noScreenshot": True, **payload}) - keyboard.assert_not_called() - process.assert_not_called() def test_focus_search_keeps_transient_accessible_wrappers_alive(self): class TransientNode: @@ -230,58 +218,7 @@ class RuntimeRenderTest(unittest.TestCase): self.assertIsNotNone(focused) self.assertEqual(focused.depth, 30) - def test_snapshot_keeps_semantics_and_image_when_child_geometry_stalls(self): - late = FakeAccessible("button", "Continue") - root = FakeAccessible("frame", "Editor", children=[ - FakeAccessible("button", "Healthy"), - *[FakeAccessible("button", f"Slow {i}") for i in range(4)], late, - ]) - for semantic_delay, stall_children in ((3.1, False), (16, True)): - with self.subTest(semantic_delay=semantic_delay), SnapshotFixture(root) as fixture: - late.read = False - fixture.delays = {root: 1, **{node: 20 if stall_children else 0 for node in root.children[1:-1]}} - def delayed_name(): - if not getattr(late, "read", False): - fixture.clock += semantic_delay - late.read = True - return "" if fixture.stalled else "Continue" - late.get_name = delayed_name - late.get_n_actions = lambda: 1 - late.get_action_name = lambda _: "click" - snapshot = runtime.make_snapshot("Fixture", True, window_index=0) - self.assertLessEqual(fixture.clock - fixture.captured_at, 3) - self.assertEqual(fixture.timeout, (800, 15000)) - elements = snapshot["elements"] - self.assertEqual([item["name"] for item in elements], [root.name, *[n.name for n in root.children]]) - self.assertEqual([item["index"] for item in elements], list(range(7))) - self.assertEqual(elements[-1]["runtimeId"], [0, 5]) - self.assertEqual(elements[-1]["actions"], ["click"]) - self.assertEqual(snapshot["treeLines"][-1], "\t6 button Continue") - self.assertFalse(snapshot["truncation"]["truncated"]) - self.assertEqual(snapshot["windowBounds"], fixture.bounds[root].to_json()) - self.assertEqual(json.loads(snapshot["screenshotPngBase64"]), fixture.bounds[root].to_json()) - self.assertEqual(elements[0]["frame"], runtime.Rect(0, 0, 300, 400).to_json()) - self.assertEqual(elements[1]["frame"], runtime.Rect(10, 20, 300, 400).to_json()) - self.assertTrue(all((item["frame"] is None) == stall_children for item in elements[2:])) - def test_nonstandard_window_selection_and_fresh_restored_capture(self): - for query, index, delay, restore in (("Fixture", None, 1, False), - ("pid:42", 1, 1, False), ("Editor", 1, 0, True)): - with self.subTest(query=query), SnapshotFixture( - FakeAccessible("panel", "Editor", children=[FakeAccessible("button", "Save")]) - ) as fixture: - root = fixture.root - fixture.app.children.insert(0, FakeAccessible("label", "Unrelated")) - fixture.delays[root] = delay - def move(): - fixture.bounds[root] = runtime.Rect(500, 200, 300, 400) - fixture.bounds[root.children[0]] = runtime.Rect(510, 220, 300, 400) - fixture.restore = move - snapshot = runtime.make_snapshot(query, True, window_index=index, restore=restore) - self.assertEqual(snapshot["windowIndex"], 1) - self.assertEqual(snapshot["windowBounds"]["x"], 500 if restore else 100) - self.assertEqual(snapshot["elements"][1]["frame"]["x"], 10) - self.assertEqual(json.loads(snapshot["screenshotPngBase64"]), fixture.bounds[root].to_json()) def test_window_only_protection_preserves_completed_semantic_action(self): button = FakeAccessible("button", "Continue") @@ -310,30 +247,6 @@ class RuntimeRenderTest(unittest.TestCase): runtime.run_operation({"tool": "click", "app": "Fixture"}) self.assertEqual(effects, ["clicked"]) - def test_click_activates_the_window_only_for_pointer_fallback(self): - button = FakeAccessible("button", "Continue") - button.get_n_actions = lambda: 1 - button.get_action_name = lambda _: "click" - button.do_action = lambda _: True - label = FakeAccessible("label", "Status") - for target, expected_path, expected_calls in ( - (button, "accessibility", []), - (label, "synthetic", ["restore", "pointer"]), - ): - with self.subTest(path=expected_path), SnapshotFixture( - FakeAccessible("frame", "Editor", children=[button, label]) - ) as fixture: - calls = [] - def restore(): - calls.append("restore") - fixture.root.get_state_set = lambda: FakeStateSet(FakeStateType.ACTIVE) - fixture.restore = restore - snapshot = runtime.make_snapshot("Fixture", False) - element = next(item for item in snapshot["elements"] if item["name"] == target.name) - with patch.object(runtime, "click_at", lambda *_: calls.append("pointer")): - result = runtime.run_operation({"tool": "click", "app": "Fixture", "element": element, "noScreenshot": True}) - self.assertEqual(result["action"]["path"], expected_path) - self.assertEqual(calls, expected_calls) def test_pointer_input_waits_for_activation_and_uses_restored_geometry(self): operations = ( @@ -622,46 +535,6 @@ class RuntimeRenderTest(unittest.TestCase): indexes = [item["index"] for item in snapshot["elements"]] self.assertEqual(len(indexes), len(set(indexes))) - def test_geometry_skips_insufficient_budget_and_restores_action_timeout(self): - clock = [0.0] - timeouts = [] - - def fail(): - raise TimeoutError("unresponsive geometry") - - with patch.object(runtime.time, "monotonic", side_effect=lambda: clock[0]), \ - patch.object(runtime.Atspi, "set_timeout", side_effect=lambda *args: timeouts.append(args), create=True): - reader = runtime.GeometryReader() - clock[0] = 2.96 - calls = [] - self.assertIsNone(reader.read(lambda: calls.append("called"))) - self.assertEqual(calls, []) - self.assertEqual(timeouts, []) - clock[0] = 2.9 - self.assertIsNone(reader.read(fail)) - self.assertGreaterEqual(timeouts[0][0], 50) - self.assertLessEqual(timeouts[0][0], 100) - self.assertEqual(timeouts[0][1], -1) - self.assertEqual(timeouts[-1], (800, 15000)) - - - def test_wide_labeled_controls_never_enumerate_suppressed_children(self): - roles = ( - "button", "check box", "checkbox", "combo box", "heading", "link", - "menu item", "page tab", "push button", "radio button", - ) - for role in roles: - with self.subTest(role=role): - root = FakeAccessible( - role, "Save", children=[FakeAccessible("text", str(i)) for i in range(10000)] - ) - - records, lines, truncation = render(root) - - self.assertEqual([item["runtimeId"] for item in records], [[0]]) - self.assertEqual(lines, [f"0 {role} Save"]) - self.assertEqual(root.counter["child_reads"], 0) - self.assertFalse(truncation["truncated"]) @@ -671,31 +544,9 @@ class RuntimeRenderTest(unittest.TestCase): - def test_node_limit_keeps_exact_prefix_and_truncation(self): - root = FakeAccessible( - "document", - "Results", - children=[FakeAccessible("text", f"Item {index}") for index in range(runtime.MAX_NODES)], - ) - records, _, truncation = render(root) - self.assertEqual(len(records), runtime.MAX_NODES) - self.assertEqual(records[-1]["name"], f"Item {runtime.MAX_NODES - 2}") - self.assertTrue(truncation["truncated"]) - self.assertFalse(truncation["maxDepthReached"]) - def test_depth_limit_keeps_exact_prefix_and_flag(self): - root = FakeAccessible("document", "Depth 65") - for depth in range(runtime.MAX_DEPTH, -1, -1): - root = FakeAccessible("document", f"Depth {depth}", children=[root]) - - records, _, truncation = render(root) - - self.assertEqual(len(records), runtime.MAX_DEPTH + 1) - self.assertEqual(records[-1]["name"], f"Depth {runtime.MAX_DEPTH}") - self.assertTrue(truncation["truncated"]) - self.assertTrue(truncation["maxDepthReached"]) if __name__ == "__main__": diff --git a/native/computer-use-linux/set_value_test.py b/native/computer-use-linux/set_value_test.py deleted file mode 100644 index 05059585950..00000000000 --- a/native/computer-use-linux/set_value_test.py +++ /dev/null @@ -1,35 +0,0 @@ -import importlib.util -import sys -import types -import unittest -from pathlib import Path -from unittest import mock - - -def load_runtime(): - editable_text = types.SimpleNamespace(set_text_contents=lambda editable, value: editable.update(text=value) or True) - repository = types.ModuleType("gi.repository") - repository.Atspi = types.SimpleNamespace(EditableText=editable_text) - gi = types.ModuleType("gi") - gi.repository = repository - gi.require_version = lambda *_: None - path = Path(__file__).with_name("runtime.py") - with mock.patch.dict(sys.modules, {"gi": gi, "gi.repository": repository}): - spec = importlib.util.spec_from_file_location("orca_linux_runtime_set_value_test", path) - module = importlib.util.module_from_spec(spec) - spec.loader.exec_module(module) - return module - - -class SetValueTest(unittest.TestCase): - def test_sets_text_on_bindings_without_is_editable_text(self): - # Why: at-spi2-core < 2.53 (e.g. Ubuntu 24.04) does not expose Accessible.is_editable_text to GI. - editable = {"text": ""} - node = types.SimpleNamespace(get_editable_text_iface=lambda: editable, get_value_iface=lambda: None) - - self.assertTrue(load_runtime().set_value(node, "hello")) - self.assertEqual(editable["text"], "hello") - - -if __name__ == "__main__": - unittest.main() diff --git a/native/computer-use-windows/runtime-render.test.ps1 b/native/computer-use-windows/runtime-render.test.ps1 deleted file mode 100644 index 21312676530..00000000000 --- a/native/computer-use-windows/runtime-render.test.ps1 +++ /dev/null @@ -1,195 +0,0 @@ -$ErrorActionPreference = "Stop" - -function Assert-TestEqual($Actual, $Expected, [string]$Label) { - if ($Actual -ne $Expected) { - throw "$Label expected '$Expected', received '$Actual'" - } -} - -Add-Type -TypeDefinition @" -using System.Collections; -using System.Collections.Generic; - -public sealed class OrcaRenderTestCounter { - public int FindAll; -} - -public sealed class OrcaRenderTestBounds { - public bool IsEmpty = true; - public double X; - public double Y; - public double Width; - public double Height; -} - -public sealed class OrcaRenderTestControlType { - public string ProgrammaticName = ""; -} - -public sealed class OrcaRenderTestCurrent { - public string AutomationId = ""; - public OrcaRenderTestBounds BoundingRectangle = new OrcaRenderTestBounds(); - public string ClassName = "fake"; - public OrcaRenderTestControlType ControlType = new OrcaRenderTestControlType(); - public bool IsPassword; - public string LocalizedControlType = ""; - public string Name = ""; - public long NativeWindowHandle; -} - -public sealed class OrcaRenderTestPatternCurrent { - public bool IsSelected; - public string Value = ""; -} - -public sealed class OrcaRenderTestPattern { - public OrcaRenderTestPatternCurrent Current = new OrcaRenderTestPatternCurrent(); -} - -public sealed class OrcaRenderTestCollection : IEnumerable { - private readonly OrcaRenderTestElement[] values; - - public OrcaRenderTestCollection(OrcaRenderTestElement[] values) { - this.values = values; - } - - public int Count { - get { return values.Length; } - } - - public OrcaRenderTestElement Item(int index) { - return values[index]; - } - - public IEnumerator GetEnumerator() { - return values.GetEnumerator(); - } -} - -public sealed class OrcaRenderTestElement { - public readonly List Children = - new List(); - public OrcaRenderTestCounter Counter = new OrcaRenderTestCounter(); - public readonly OrcaRenderTestCurrent Current = new OrcaRenderTestCurrent(); - public bool FailFindAll; - public int RuntimeIdValue; - public string ValueText = ""; - - public OrcaRenderTestCollection FindAll(object scope, object condition) { - Counter.FindAll++; - if (FailFindAll) { - throw new System.InvalidOperationException("defunct node"); - } - return new OrcaRenderTestCollection(Children.ToArray()); - } - - public OrcaRenderTestPattern GetCurrentPattern(object pattern) { - OrcaRenderTestPattern result = new OrcaRenderTestPattern(); - result.Current.Value = ValueText; - return result; - } - - public int[] GetRuntimeId() { - return new int[] { RuntimeIdValue }; - } - - public object[] GetSupportedPatterns() { - return new object[0]; - } -} -"@ - -function New-TestCounter { - New-Object -TypeName OrcaRenderTestCounter -} - -function New-TestElement { - param( - [string]$Role, - [string]$Name = "", - [string]$Value = "", - [object[]]$Children = @(), - $Counter = $(New-TestCounter), - [switch]$FailFindAll, - [int]$RuntimeId = 1 - ) - $element = New-Object -TypeName OrcaRenderTestElement - $element.Counter = $Counter - $element.FailFindAll = [bool]$FailFindAll - $element.RuntimeIdValue = $RuntimeId - $element.ValueText = $Value - $element.Current.ControlType.ProgrammaticName = $Role - $element.Current.LocalizedControlType = $Role - $element.Current.Name = $Name - foreach ($child in @($Children)) { - [void]$element.Children.Add($child) - } - $element -} - -$operationPath = Join-Path ([IO.Path]::GetTempPath()) ("orca-runtime-render-test-" + [guid]::NewGuid() + ".json") -try { - Set-Content -LiteralPath $operationPath -Encoding UTF8 -Value '{"tool":"handshake"}' - $runtimeOutput = . (Join-Path $PSScriptRoot "runtime.ps1") -OperationPath $operationPath - $handshake = $runtimeOutput | ConvertFrom-Json - Assert-TestEqual $handshake.ok $true "runtime handshake" - - $counter = New-TestCounter - $tabs = @() - for ($index = 0; $index -lt 10; $index++) { - $value = if ($index -eq 9) { "1" } else { "" } - $tabs += New-TestElement -Role "tab item" -Name "Tab $index" -Value $value -Counter $counter -RuntimeId ($index + 10) - } - $buttons = @() - for ($index = 0; $index -lt 10; $index++) { - $buttons += New-TestElement -Role "button" -Name "Other $index" -Counter $counter -RuntimeId ($index + 30) - } - $tabList = New-TestElement -Role "tab" -Name "Tabs" -Children $tabs -Counter $counter -RuntimeId 2 - $root = New-TestElement -Role "window" -Name "Browser" -Children (@($tabList) + $buttons) -Counter $counter - $tree = Render-OrcaTree $root $null $true - $indexes = @($tree.elements | ForEach-Object { [int]$_.index }) - Assert-TestEqual (@($tree.elements | Where-Object { $_.name -eq "Tab 0" }).Count) 0 "compacted inactive tab" - Assert-TestEqual (@($indexes | Sort-Object -Unique).Count) $indexes.Count "compacted browser unique indexes" - - $originalMaxNodes = $MaxNodes - try { - $MaxNodes = 3 - $counter = New-TestCounter - $children = @() - for ($index = 0; $index -lt 3; $index++) { - $children += New-TestElement -Role "text" -Name "Item $index" -Counter $counter -RuntimeId ($index + 2) - } - $root = New-TestElement -Role "document" -Name "Results" -Children $children -Counter $counter - $tree = Render-OrcaTree $root $null - Assert-TestEqual $tree.elements.Count 3 "node limit record count" - Assert-TestEqual ([string]$tree.elements[-1].name) "Item 1" "node limit prefix" - Assert-TestEqual $tree.truncation.truncated $true "node limit truncation" - Assert-TestEqual $tree.truncation.maxDepthReached $false "node limit depth flag" - } finally { - $MaxNodes = $originalMaxNodes - } - - $originalMaxDepth = $MaxDepth - try { - $MaxDepth = 2 - $counter = New-TestCounter - $root = New-TestElement -Role "document" -Name "Depth 3" -Counter $counter -RuntimeId 4 - for ($depth = 2; $depth -ge 0; $depth--) { - $root = New-TestElement -Role "document" -Name "Depth $depth" -Children @($root) -Counter $counter -RuntimeId ($depth + 1) - } - $tree = Render-OrcaTree $root $null - Assert-TestEqual $tree.elements.Count 3 "depth limit record count" - Assert-TestEqual ([string]$tree.elements[-1].name) "Depth 2" "depth limit prefix" - Assert-TestEqual $tree.truncation.truncated $true "depth limit truncation" - Assert-TestEqual $tree.truncation.maxDepthReached $true "depth limit flag" - } finally { - $MaxDepth = $originalMaxDepth - } - - & (Join-Path $PSHOME "powershell.exe") -NoLogo -NoProfile -File (Join-Path $PSScriptRoot "runtime-pointer.test.ps1") - if ($LASTEXITCODE -ne 0) { throw "Windows pointer tests failed" } - - Write-Output "windows-snapshot-render-tests-ok" -} finally { - Remove-Item -LiteralPath $operationPath -Force -ErrorAction SilentlyContinue -} diff --git a/native/wayland-clipboard/protocol_test.py b/native/wayland-clipboard/protocol_test.py index 0304b3b22a5..9562be3ccd1 100644 --- a/native/wayland-clipboard/protocol_test.py +++ b/native/wayland-clipboard/protocol_test.py @@ -185,24 +185,11 @@ class ClipboardProtocolTests(unittest.TestCase): self.assertIsNone(server.source) self.assertEqual(result.stdout, b"") - def test_missing_display_rejects_without_echoing_text(self): - with tempfile.TemporaryDirectory() as directory: - result = subprocess.run([BINARY], input=b"private text", capture_output=True, - env={**os.environ, "XDG_RUNTIME_DIR": directory, "WAYLAND_DISPLAY": "missing"}, timeout=3) - self.assertEqual(result.returncode, 69) - self.assertNotIn(b"private text", result.stdout + result.stderr) - def test_size_limit_precedes_selection_publication(self): with DataControlServer("ext_data_control") as server: self.assertEqual(server.copy(b"x" * (16 * 1024 * 1024 + 1)).returncode, 65) self.assertIsNone(server.source) - def test_probe_does_not_write(self): - with DataControlServer("ext_data_control") as server: - result = subprocess.run([BINARY, "--probe"], capture_output=True, env=server.environment(), timeout=3) - self.assertEqual(result.returncode, 0) - self.assertIsNone(server.source) - def test_replacement_during_ack_is_success_but_device_loss_is_failure(self): for event, status in (("cancelled", 0), ("finished", 70), ("seat removal", 70)): with self.subTest(event=event), DataControlServer("ext_data_control", event) as server: diff --git a/src/main/ai-vault-search/session-search-tool-purge.test.ts b/src/main/ai-vault-search/session-search-tool-purge.test.ts index 700dd5d17d8..8402ae6fb71 100644 --- a/src/main/ai-vault-search/session-search-tool-purge.test.ts +++ b/src/main/ai-vault-search/session-search-tool-purge.test.ts @@ -121,30 +121,6 @@ function newPurge(db: HarnessDb, closed = () => false, onChange = (): void => {} }) } -it('persists a high-water mark so later passes skip already-scanned rowids', async () => { - const index = await openSessionSearchHarness('ss-tool-purge-mark') - try { - addSyntheticSession(index.db, { id: 1, text: 'userkept', rows: 300 }) - addSyntheticSession(index.db, { id: 2, role: 'tool', text: 'toolremoved', rows: 300 }) - const purge = newPurge(index.db) - await purge.request() - expect(countTool(index.db)).toBe(0) - const mark = Number(readMeta(index.db, 'tool_purge_scanned_rowid')) - expect(mark).toBeGreaterThanOrEqual(600) - expect(readMeta(index.db, 'tool_purge_floor_rowid')).toBeUndefined() - - // Without the floor trigger, a row below the mark is invisible to later passes: no rescan. - index.db.exec('DROP TRIGGER search_tool_purge_floor') - index.db.exec('DELETE FROM messages WHERE id = 1') - index.db.exec("INSERT INTO messages(id, session_row_id, role) VALUES (1, 1, 'tool')") - await purge.request() - expect(countTool(index.db)).toBe(1) - expect(Number(readMeta(index.db, 'tool_purge_scanned_rowid'))).toBe(mark) - } finally { - await index.close() - } -}) - it('purges legacy tool rows written after the mark, including reused tail rowids', async () => { const index = await openSessionSearchHarness('ss-tool-purge-downgrade') try { diff --git a/src/main/ephemeral-vm/recipe-vm-asleep.test.ts b/src/main/ephemeral-vm/recipe-vm-asleep.test.ts deleted file mode 100644 index ced2e3ae9cc..00000000000 --- a/src/main/ephemeral-vm/recipe-vm-asleep.test.ts +++ /dev/null @@ -1,83 +0,0 @@ -import { afterEach, describe, expect, it, vi } from 'vitest' -import type { EphemeralVmRuntimeRecord } from '../../shared/ephemeral-vm-runtimes' - -type VmRow = Partial -type MockState = { runtimes: VmRow[]; environmentVm: (VmRow & { workspaceId: string }) | null } - -const mocks = vi.hoisted((): MockState => ({ runtimes: [], environmentVm: null })) - -vi.mock('../../shared/ephemeral-vm-runtime-store', () => ({ - listEphemeralVmRuntimes: () => mocks.runtimes -})) -vi.mock('../../shared/remote-runtime/host-store/runtime-environment-store', () => ({ - resolveEnvironment: (_root: string, id: string) => ({ id }) -})) -vi.mock('../../shared/ephemeral-vm-environment-sleep', async (importOriginal) => ({ - ...(await importOriginal>()), - findEnvironmentEphemeralVmRuntime: () => mocks.environmentVm ?? undefined -})) - -import { isRecipeVmEnvironmentAsleep, isRecipeVmSshTargetAsleep } from './recipe-vm-asleep' -import { - registerRecipeVmWaker, - type RecipeVmWaker -} from '../runtime/workspaces/sleep/recipe-vm-waker-registry' -import type { RecipeVmState } from '../runtime/workspaces/sleep/recipe-vm-operations' - -function waker(state: (recordSuspended: boolean) => RecipeVmState): RecipeVmWaker { - return { - state: (_workspaceId, recordSuspended) => state(recordSuspended), - noteOpened: vi.fn(), - holdOpen: vi.fn(), - openEnvironment: vi.fn() - } -} - -afterEach(() => { - registerRecipeVmWaker(null) - mocks.runtimes = [] - mocks.environmentVm = null -}) - -describe('recipe VM asleep predicate', () => { - it('holds a suspended VM until its wake is under way', () => { - mocks.environmentVm = { id: 'vm-1', workspaceId: 'ws-1', status: 'suspended' } - let waking = false - registerRecipeVmWaker(waker((suspended) => (waking ? 'waking' : suspended ? 'asleep' : 'up'))) - - expect(isRecipeVmEnvironmentAsleep('/data', 'env-1')).toBe(true) - waking = true - expect(isRecipeVmEnvironmentAsleep('/data', 'env-1')).toBe(false) - }) - - it('never holds a running VM or an environment no VM serves', () => { - registerRecipeVmWaker(waker((suspended) => (suspended ? 'asleep' : 'up'))) - expect(isRecipeVmEnvironmentAsleep('/data', 'env-1')).toBe(false) - mocks.environmentVm = { id: 'vm-1', workspaceId: 'ws-1', status: 'running' } - expect(isRecipeVmEnvironmentAsleep('/data', 'env-1')).toBe(false) - }) - - it('does not hold a VM whose suspend is still running: a failed suspend leaves it up', () => { - mocks.environmentVm = { id: 'vm-1', workspaceId: 'ws-1', status: 'running' } - registerRecipeVmWaker(waker(() => 'asleep')) - expect(isRecipeVmEnvironmentAsleep('/data', 'env-1')).toBe(false) - }) - - it('reads the stored record on a host with no waker', () => { - mocks.environmentVm = { id: 'vm-1', workspaceId: 'ws-1', status: 'resume_failed' } - expect(isRecipeVmEnvironmentAsleep('/data', 'env-1')).toBe(true) - }) - - it('matches a VM to its Orca-owned SSH host and skips every other host', () => { - registerRecipeVmWaker(waker((suspended) => (suspended ? 'asleep' : 'up'))) - mocks.runtimes = [ - { id: 'vm-1', workspaceId: 'ws-1', status: 'suspended' }, - { id: 'vm-2', workspaceId: 'ws-2', status: 'running', sshTargetId: 'runtime-ssh-vm-2' }, - { id: 'vm-3', workspaceId: 'ws-3', status: 'cleaned' } - ] - expect(isRecipeVmSshTargetAsleep('/data', 'runtime-ssh-vm-1')).toBe(true) - expect(isRecipeVmSshTargetAsleep('/data', 'runtime-ssh-vm-2')).toBe(false) - expect(isRecipeVmSshTargetAsleep('/data', 'runtime-ssh-vm-3')).toBe(false) - expect(isRecipeVmSshTargetAsleep('/data', 'my-own-host')).toBe(false) - }) -}) diff --git a/src/main/ephemeral-vm/workspace-resume-lost-contact.test.ts b/src/main/ephemeral-vm/workspace-resume-lost-contact.test.ts index f304ac0d9a2..71435f43eac 100644 --- a/src/main/ephemeral-vm/workspace-resume-lost-contact.test.ts +++ b/src/main/ephemeral-vm/workspace-resume-lost-contact.test.ts @@ -92,39 +92,6 @@ describe('opening a workspace whose VM host Orca gave up reaching', () => { mocks.updateStatus.mockClear() }) - it('runs the recipe resume, reconnects the VM and reopens its server', async () => { - vi.useFakeTimers() - state.sshStatus = 'reconnection-failed' - mocks.resume.mockResolvedValue(RESUMED) - - await resumeEphemeralVmWorkspace(STORE, 'workspace-1', REQUEST) - await vi.runAllTimersAsync() - - expect(mocks.resume).toHaveBeenCalledTimes(1) - expect(mocks.connect).toHaveBeenCalledTimes(1) - expect(mocks.reconnectControl).toHaveBeenCalledWith('env-vm') - expect(mocks.refreshStatus).toHaveBeenCalledWith({ reconnect: true }) - }) - - it('leaves a VM alone while its host answers, is reconnecting, or was never dialed', async () => { - for (const sshStatus of [undefined, 'connected', 'reconnecting', 'connecting'] as const) { - state.sshStatus = sshStatus - await expect(resumeEphemeralVmWorkspace(STORE, 'workspace-1', REQUEST)).resolves.toBe( - state.record - ) - } - expect(mocks.resume).not.toHaveBeenCalled() - expect(mocks.connect).not.toHaveBeenCalled() - }) - - it('leaves a host the user disconnected, and a paired VM, to their own reconnects', async () => { - state.sshStatus = 'reconnection-failed' - await resumeEphemeralVmWorkspace(STORE, 'workspace-1', { ...REQUEST, sshHeld: true }) - state.record = { ...UP_RECORD, connectionMode: 'paired', sshTargetId: undefined } - await resumeEphemeralVmWorkspace(STORE, 'workspace-1', REQUEST) - expect(mocks.resume).not.toHaveBeenCalled() - }) - it('keeps the record as it was when the recovery fails, so reconnects go on', async () => { state.sshStatus = 'reconnection-failed' mocks.resume.mockResolvedValue({ diff --git a/src/main/ipc/runtime-environments/runtime-environment-status-owner-asleep.test.ts b/src/main/ipc/runtime-environments/runtime-environment-status-owner-asleep.test.ts index 4bdb7660248..c0565e30e48 100644 --- a/src/main/ipc/runtime-environments/runtime-environment-status-owner-asleep.test.ts +++ b/src/main/ipc/runtime-environments/runtime-environment-status-owner-asleep.test.ts @@ -61,10 +61,4 @@ describe('status probe of a sleeping VM server', () => { expect(mocks.send).not.toHaveBeenCalled() expect(mocks.resolveManaged).not.toHaveBeenCalled() }) - - it('probes again once the VM is awake', async () => { - mocks.asleep = false - await owner().refresh({ timeoutMs: 1_000 }) - expect(mocks.send).toHaveBeenCalledTimes(1) - }) }) diff --git a/src/main/ssh/connection/ssh-host-sleep-hold.test.ts b/src/main/ssh/connection/ssh-host-sleep-hold.test.ts index 282afc9ab8c..0445b788d35 100644 --- a/src/main/ssh/connection/ssh-host-sleep-hold.test.ts +++ b/src/main/ssh/connection/ssh-host-sleep-hold.test.ts @@ -85,18 +85,6 @@ describe('SSH host of a sleeping VM', () => { expect(created.count).toBe(0) }) - it('connects once the VM is no longer asleep, and never holds other hosts', async () => { - let asleep = true - setSshHostAsleepCheck(() => asleep) - const manager = new SshConnectionManager({ onStateChange: vi.fn() }) - - // Only Orca-owned VM hosts are ever held. - await expect(manager.connect(target('user-host'))).resolves.toBeDefined() - asleep = false - await expect(manager.connect(target(VM_TARGET_ID))).resolves.toBeDefined() - expect(created.count).toBe(2) - }) - it('stops the reconnect ladder, including a retry armed before the sleep', async () => { vi.useFakeTimers() let asleep = false @@ -114,12 +102,4 @@ describe('SSH host of a sleeping VM', () => { expect(attempts()).toBe(0) }) - - it('keeps an unreadable VM record from stranding a host', async () => { - setSshHostAsleepCheck(() => { - throw new Error('store unreadable') - }) - const manager = new SshConnectionManager({ onStateChange: vi.fn() }) - await expect(manager.connect(target(VM_TARGET_ID))).resolves.toBeDefined() - }) })