From aeda9fadd8b33ca21ee3bafb5f6f1dd3dad0169b Mon Sep 17 00:00:00 2001 From: OrcaWin Date: Thu, 5 Nov 2026 12:15:00 -0800 Subject: [PATCH] test: remove 180 low-value scanner, password and browser tests (#38647) Co-authored-by: OrcaWin <293788423+OrcaWin@users.noreply.github.com> --- .../workflows/zcode-transcript-contract.yml | 2 +- .../scripts/ci/sharding/ci-shard-timings.json | 5 - ...sion-scanner-codex-non-user-origin.test.ts | 255 ----------- ...ssion-scanner-opencode-wsl-routing.test.ts | 219 ---------- .../session-scanner-scope-cwd-facts.test.ts | 72 ---- ...session-transcript-message-content.test.ts | 214 +-------- .../browser-password-chromium-import.test.ts | 36 +- .../browser-password-csv-import.test.ts | 103 +---- .../browser-password-guest-payloads.test.ts | 55 --- .../browser-password-guest-service.test.ts | 51 --- .../browser-password-login-tracker.test.ts | 168 -------- .../browser-password-origin.test.ts | 60 +-- .../browser-password-save-decision.test.ts | 50 --- .../browser-password-save-prompts.test.ts | 31 -- .../browser-password-store.test.ts | 166 +------ .../browser-password-vaults.test.ts | 10 - ...-browser-bridge-capture-paint-hold.test.ts | 243 ----------- ...t-browser-bridge-command-transport.test.ts | 381 ---------------- .../agent-browser-bridge-expected-url.test.ts | 205 --------- ...ent-browser-bridge-host-revocation.test.ts | 408 +----------------- ...gent-browser-bridge-keypress-input.test.ts | 291 ------------- .../agent-browser-bridge-mouse-input.test.ts | 260 ----------- 22 files changed, 9 insertions(+), 3276 deletions(-) delete mode 100644 src/main/ai-vault/scanners/codex/session-scanner-codex-non-user-origin.test.ts delete mode 100644 src/main/ai-vault/scanners/opencode/reader-transport/session-scanner-opencode-wsl-routing.test.ts delete mode 100644 src/main/browser-passwords/browser-password-guest-payloads.test.ts delete mode 100644 src/main/browser-passwords/browser-password-save-decision.test.ts delete mode 100644 src/main/browser/agent-browser/agent-browser-bridge-capture-paint-hold.test.ts delete mode 100644 src/main/browser/agent-browser/agent-browser-bridge-command-transport.test.ts delete mode 100644 src/main/browser/agent-browser/agent-browser-bridge-mouse-input.test.ts diff --git a/.github/workflows/zcode-transcript-contract.yml b/.github/workflows/zcode-transcript-contract.yml index dcb5430c5b1..859a6ec9823 100644 --- a/.github/workflows/zcode-transcript-contract.yml +++ b/.github/workflows/zcode-transcript-contract.yml @@ -41,4 +41,4 @@ jobs: bun-version-file: config/.bun-version no-cache: true - name: Verify SQLite ordering, legacy readers, and host routing - run: pnpm test src/main/native-chat/transcript-zcode.test.ts src/main/native-chat/transcript-opencode.test.ts src/main/native-chat/transcript-opencode-sqlite-query.test.ts src/main/native-chat/transcript-opencode2-sqlite.test.ts src/main/native-chat/transcript-opencode-semantic-fidelity.test.ts src/main/native-chat/transcript-opencode-read-bounds.test.ts src/main/native-chat/transcript-opencode-subscribe.test.ts src/main/ai-vault/scanners/zcode/session-scanner-zcode.test.ts src/main/ai-vault/scanners/opencode/reader-transport/opencode-wsl-runtime-preparation.test.ts src/main/ai-vault/scanners/opencode/reader-transport/session-scanner-opencode-wsl-routing.test.ts src/shared/native-chat/transcript/native-chat-transcript-projection.test.ts src/renderer/src/components/native-chat/structured-agent-session-transcript-order.test.ts + run: pnpm test src/main/native-chat/transcript-zcode.test.ts src/main/native-chat/transcript-opencode.test.ts src/main/native-chat/transcript-opencode-sqlite-query.test.ts src/main/native-chat/transcript-opencode2-sqlite.test.ts src/main/native-chat/transcript-opencode-semantic-fidelity.test.ts src/main/native-chat/transcript-opencode-read-bounds.test.ts src/main/native-chat/transcript-opencode-subscribe.test.ts src/main/ai-vault/scanners/zcode/session-scanner-zcode.test.ts src/main/ai-vault/scanners/opencode/reader-transport/opencode-wsl-runtime-preparation.test.ts src/shared/native-chat/transcript/native-chat-transcript-projection.test.ts src/renderer/src/components/native-chat/structured-agent-session-transcript-order.test.ts diff --git a/config/scripts/ci/sharding/ci-shard-timings.json b/config/scripts/ci/sharding/ci-shard-timings.json index 00e5b76b1c1..ee7be4339c4 100644 --- a/config/scripts/ci/sharding/ci-shard-timings.json +++ b/config/scripts/ci/sharding/ci-shard-timings.json @@ -946,7 +946,6 @@ "src/main/ai-vault/scanners/codebuddy/session-scanner-codebuddy-source.test.ts": 465, "src/main/ai-vault/scanners/codex/session-scanner-codex-dual-root.test.ts": 517, "src/main/ai-vault/scanners/codex/session-scanner-codex-fast-path.test.ts": 392, - "src/main/ai-vault/scanners/codex/session-scanner-codex-non-user-origin.test.ts": 153, "src/main/ai-vault/scanners/codex/session-scanner-codex-parser.test.ts": 195, "src/main/ai-vault/scanners/codex/session-scanner-codex-title-index.test.ts": 295, "src/main/ai-vault/scanners/codex/session-scanner-codex-tool-records.test.ts": 177, @@ -993,7 +992,6 @@ "src/main/ai-vault/scanners/opencode/sqlite/session-scanner-opencode-sqlite-scan-scope.test.ts": 54, "src/main/ai-vault/scanners/opencode/reader-transport/session-scanner-opencode-sqlite-worker-client.test.ts": 181, "src/main/ai-vault/scanners/opencode/sqlite/session-scanner-opencode-sqlite.test.ts": 410, - "src/main/ai-vault/scanners/opencode/reader-transport/session-scanner-opencode-wsl-routing.test.ts": 200, "src/main/ai-vault/scanners/opencode2/session-scanner-opencode2-message.test.ts": 138, "src/main/ai-vault/scanners/opencode2/session-scanner-opencode2-sqlite.test.ts": 306, "src/main/ai-vault/parse-cache/session-scanner-parse-cache-agents.test.ts": 544, @@ -1115,12 +1113,9 @@ "src/main/bitbucket/status-no-decrypt.test.ts": 256, "src/main/updater/browser-sidecar-owner.test.ts": 53, "src/main/browser/agent-browser/agent-browser-action-effects.test.ts": 487, - "src/main/browser/agent-browser/agent-browser-bridge-capture-paint-hold.test.ts": 610, - "src/main/browser/agent-browser/agent-browser-bridge-command-transport.test.ts": 820, "src/main/browser/agent-browser/agent-browser-bridge-host-revocation.test.ts": 1017, "src/main/browser/agent-browser/agent-browser-bridge-javascript-dialog.test.ts": 358, "src/main/browser/agent-browser/agent-browser-bridge-keypress-input.test.ts": 752, - "src/main/browser/agent-browser/agent-browser-bridge-mouse-input.test.ts": 525, "src/main/browser/agent-browser/agent-browser-bridge-navigation.test.ts": 588, "src/main/browser/agent-browser/agent-browser-bridge-pointer-input.test.ts": 394, "src/main/browser/agent-browser/agent-browser-bridge-raw-process-retention.test.ts": 1027, diff --git a/src/main/ai-vault/scanners/codex/session-scanner-codex-non-user-origin.test.ts b/src/main/ai-vault/scanners/codex/session-scanner-codex-non-user-origin.test.ts deleted file mode 100644 index 97135c7090a..00000000000 --- a/src/main/ai-vault/scanners/codex/session-scanner-codex-non-user-origin.test.ts +++ /dev/null @@ -1,255 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { readCodexNonUserOrigin } from './session-scanner-codex-non-user-origin' - -// Mirror the provider union: spawn fields nest under thread_spawn and may also be copied onto the payload. -function spawnedPayload(threadSpawn: unknown, payloadCopies: Record = {}) { - return { - id: 'child-thread', - cwd: '/repo/app', - thread_source: 'subagent', - source: { subagent: { thread_spawn: threadSpawn } }, - ...payloadCopies - } -} - -describe('readCodexNonUserOrigin', () => { - it('keeps every field of a stated spawn record, including a null role', () => { - const origin = readCodexNonUserOrigin( - spawnedPayload({ - parent_thread_id: '01a06e83-42af-7741-b975-ab54925540f9', - depth: 1, - agent_path: '/root/readiness_final_fresh', - agent_nickname: 'Pascal', - agent_role: null - }) - ) - - expect(origin).toEqual({ - source: 'subagent', - kind: 'thread_spawn', - kindLabel: null, - threadSource: 'subagent', - parentage: { - parentThreadId: '01a06e83-42af-7741-b975-ab54925540f9', - depth: 1, - agentNickname: 'Pascal', - agentRole: null, - agentPath: '/root/readiness_final_fresh' - } - }) - }) - - it('reads the agent_type spelling of the role, nested and on the payload', () => { - expect(readCodexNonUserOrigin(spawnedPayload({ agent_type: 'explorer' }))?.parentage).toEqual({ - parentThreadId: null, - depth: null, - agentNickname: null, - agentRole: 'explorer', - agentPath: null - }) - expect( - readCodexNonUserOrigin(spawnedPayload({}, { agent_type: 'reviewer' }))?.parentage?.agentRole - ).toBe('reviewer') - }) - - it('reads the role the payload copied beside the spawn record', () => { - expect( - readCodexNonUserOrigin(spawnedPayload({}, { agent_role: 'explorer' }))?.parentage?.agentRole - ).toBe('explorer') - }) - - it('classifies a non-spawn thread by its tag instead of calling it a role', () => { - // Review has no spawn record; its parent, if present, comes from the payload. - const origin = readCodexNonUserOrigin({ - id: 'child-thread', - thread_source: 'subagent', - source: { subagent: 'review' }, - parent_thread_id: '019f49cb-7af8-7e01-946a-274c65fe6103' - }) - - expect(origin).toEqual({ - source: 'subagent', - kind: 'review', - kindLabel: null, - threadSource: 'subagent', - parentage: { - parentThreadId: '019f49cb-7af8-7e01-946a-274c65fe6103', - depth: null, - agentNickname: null, - agentRole: null, - agentPath: null - } - }) - }) - - it('classifies a compaction thread that states no parent at all', () => { - expect(readCodexNonUserOrigin({ id: 'child-thread', source: { subagent: 'compact' } })).toEqual( - { - source: 'subagent', - kind: 'compact', - kindLabel: null, - threadSource: null, - parentage: null - } - ) - expect( - readCodexNonUserOrigin({ id: 'child-thread', source: { subagent: 'memory_consolidation' } }) - ?.kind - ).toBe('memory_consolidation') - }) - - it('keeps the label of a tag that carries free text', () => { - expect( - readCodexNonUserOrigin({ id: 'child-thread', source: { subagent: { other: 'gardener' } } }) - ).toEqual({ - source: 'subagent', - kind: 'other', - kindLabel: 'gardener', - threadSource: null, - parentage: null - }) - }) - - it('classifies machinery Codex ran for itself, not only agents it spawned', () => { - // Internal machinery may omit thread_source; the structural tag must still exclude it. - expect( - readCodexNonUserOrigin({ id: 'child-thread', source: { internal: 'guardian' } }) - ).toEqual({ - source: 'internal', - kind: 'guardian', - kindLabel: null, - threadSource: null, - parentage: null - }) - expect( - readCodexNonUserOrigin({ - id: 'child-thread', - source: { internal: 'memory_consolidation' } - })?.kind - ).toBe('memory_consolidation') - }) - - it('keeps every thread the user started, whatever its source tag', () => { - for (const source of ['cli', 'vscode', 'exec', 'mcp', 'unknown', { custom: 'acme' }]) { - expect(readCodexNonUserOrigin({ id: 'user-thread', source })).toBeNull() - } - }) - - it('degrades field by field when a spawn record is malformed', () => { - const origin = readCodexNonUserOrigin( - spawnedPayload({ - parent_thread_id: 12345, - agent_nickname: 'Mendel', - agent_role: 'explorer' - }) - ) - - expect(origin?.parentage).toEqual({ - parentThreadId: null, - depth: null, - agentNickname: 'Mendel', - agentRole: 'explorer', - agentPath: null - }) - }) - - it('rejects a depth that contradicts being a child', () => { - expect(readCodexNonUserOrigin(spawnedPayload({ depth: 0 }))?.parentage).toBeNull() - expect(readCodexNonUserOrigin(spawnedPayload({ depth: 1.5 }))?.parentage).toBeNull() - expect(readCodexNonUserOrigin(spawnedPayload({ depth: '2' }))?.parentage).toBeNull() - }) - - it('still reports the origin when no part of the spawn is readable', () => { - const origin = readCodexNonUserOrigin(spawnedPayload(true)) - - expect(origin).toEqual({ - source: 'subagent', - kind: 'thread_spawn', - kindLabel: null, - threadSource: 'subagent', - parentage: null - }) - }) - - it('reports a subagent source that states no spawn at all', () => { - const origin = readCodexNonUserOrigin({ - id: 'child-thread', - source: { subagent: { thread_spawn: null } } - }) - - expect(origin).toEqual({ - source: 'subagent', - kind: 'thread_spawn', - kindLabel: null, - threadSource: null, - parentage: null - }) - }) - - it('keeps a thread whose source states no readable tag at all', () => { - for (const source of [false, true, 0, 1, '', ' ', [], {}, { a: 1, b: 2 }]) { - expect(readCodexNonUserOrigin({ id: 'user-thread', source })).toBeNull() - } - }) - - it('classifies on the outer tag even when the kind beneath it is unreadable', () => { - // The outer non-user tag remains authoritative even when future releases change its contents. - for (const subagent of [false, 0, '', [], { type: 'review', extra: 1 }]) { - expect(readCodexNonUserOrigin({ id: 'child-thread', source: { subagent } })).toEqual({ - source: 'subagent', - kind: null, - kindLabel: null, - threadSource: null, - parentage: null - }) - } - }) - - it('keeps a forked user thread, whose lineage is not a spawn parent', () => { - expect( - readCodexNonUserOrigin({ - id: 'user-thread', - thread_source: 'user', - forked_from_id: '019f49cb-7af8-7e01-946a-274c65fe6103' - }) - ).toBeNull() - expect( - readCodexNonUserOrigin({ - id: 'user-thread', - forked_from_id: '019f49cb-7af8-7e01-946a-274c65fe6103' - }) - ).toBeNull() - }) - - it('lets a stated user thread_source outrank a subagent source', () => { - expect( - readCodexNonUserOrigin({ - id: 'user-thread', - thread_source: 'user', - source: { subagent: { thread_spawn: { parent_thread_id: 'other' } } } - }) - ).toBeNull() - }) - - it('reads the camelCase thread_source spelling', () => { - expect(readCodexNonUserOrigin({ id: 'child', threadSource: 'subagent' })).toEqual({ - source: null, - kind: null, - kindLabel: null, - threadSource: 'subagent', - parentage: null - }) - }) - - it('keeps top-level threads whose thread_source is a client feature label', () => { - // Codex Desktop automation runs and agent-created threads are the user's own work. - for (const threadSource of ['automation', 'agent_created_thread']) { - expect( - readCodexNonUserOrigin({ id: 'run', source: 'vscode', thread_source: threadSource }) - ).toBeNull() - } - expect( - readCodexNonUserOrigin({ id: 'review', thread_source: 'guardian_review' })?.threadSource - ).toBe('guardian_review') - }) -}) diff --git a/src/main/ai-vault/scanners/opencode/reader-transport/session-scanner-opencode-wsl-routing.test.ts b/src/main/ai-vault/scanners/opencode/reader-transport/session-scanner-opencode-wsl-routing.test.ts deleted file mode 100644 index 3eb86a604de..00000000000 --- a/src/main/ai-vault/scanners/opencode/reader-transport/session-scanner-opencode-wsl-routing.test.ts +++ /dev/null @@ -1,219 +0,0 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import type { AiVaultScanIssue } from '../../../../../shared/ai-vault/contracts/ai-vault-types' -import { createAccumulator, finalizeSession } from '../../../session-scanner-accumulator' -import type { SessionFileCandidate } from '../../../session-scanner-types' -import type * as wslClientModule from './session-scanner-opencode-wsl-client' -import { withOpenCodeSqliteScanScope } from '../sqlite/session-scanner-opencode-sqlite-scan-scope' - -const mocks = vi.hoisted(() => ({ - native: { - list: vi.fn(async (): Promise => []), - parse: vi.fn(async () => null), - capture: vi.fn(async () => ({ session: null, messages: [] })) - }, - guest: vi.fn() -})) -vi.mock('./session-scanner-opencode-sqlite-worker-client', () => ({ - OpenCodeSqliteWorkerClient: class { - list = mocks.native.list - parse = mocks.native.parse - capture = mocks.native.capture - } -})) -vi.mock('./session-scanner-opencode-wsl-client', async (importOriginal) => ({ - ...(await importOriginal()), - openCodeWslClient: mocks.guest -})) -import { - captureOpenCode2SqliteSessionViaWorker, - captureOpenCodeSqliteSessionViaWorker, - listOpenCode2SqliteSessionsViaWorker, - listOpenCodeSqliteSessionsViaWorker, - parseOpenCode2SqliteSessionViaWorker, - parseOpenCodeSqliteSessionViaWorker -} from './session-scanner-opencode-sqlite-worker-spawn' - -const ubuntu = '//wsl.localhost/Ubuntu/home/ada/opencode.db' -const debian = '//wsl$/Debian/home/ada/opencode.db' -const native = 'C:/Users/ada/opencode.db' -const guest = '/home/ada/opencode.db' - -function row(path: string) { - return { - agent: 'opencode' as const, - codexHome: null, - file: { path: `${path}#same-session`, mtimeMs: 1, modifiedAt: new Date(1).toISOString() } - } -} -function session() { - const accumulator = createAccumulator({ - agent: 'opencode', - sessionId: 'same-session', - file: row(guest).file - }) - accumulator.title = 'Session' - accumulator.cwd = '/home/ada/repo' - return finalizeSession(accumulator, 'linux') -} - -beforeEach(() => { - vi.clearAllMocks() - vi.spyOn(process, 'platform', 'get').mockReturnValue('win32') -}) -afterEach(() => { - vi.useRealTimers() - vi.restoreAllMocks() -}) - -describe('OpenCode SQLite execution-host routes', () => { - it('budgets WSL preparation while retaining a native source that already answered', async () => { - vi.useFakeTimers() - mocks.native.list.mockResolvedValueOnce([row(native)]) - mocks.guest.mockImplementationOnce((_distro, _path, signal: AbortSignal | undefined) => { - if (!signal) { - throw new Error('Missing scoped preparation signal') - } - return new Promise((_resolve, reject) => - signal.addEventListener('abort', () => reject(signal.reason), { once: true }) - ) - }) - const issues: AiVaultScanIssue[] = [] - const result = withOpenCodeSqliteScanScope(() => - listOpenCodeSqliteSessionsViaWorker({ - dbPaths: [native, ubuntu], - limit: 2, - issues - }) - ) - await vi.advanceTimersByTimeAsync(45_000) - expect((await result).map((entry) => entry.file.path)).toEqual([`${native}#same-session`]) - expect(issues).toEqual([ - expect.objectContaining({ - path: ubuntu, - kind: 'scope', - message: expect.stringContaining('45s work budget') - }) - ]) - mocks.guest.mockResolvedValueOnce({ list: vi.fn(async () => [row(guest)]) }) - const recoveredIssues: AiVaultScanIssue[] = [] - const recovered = await withOpenCodeSqliteScanScope(() => - listOpenCodeSqliteSessionsViaWorker({ - dbPaths: [ubuntu], - limit: 2, - issues: recoveredIssues - }) - ) - expect(recovered).toHaveLength(1) - expect(recoveredIssues).toEqual([]) - }) - - it('separates native and distro databases and preserves equal IDs in different distros', async () => { - const list = vi.fn(async (args) => [row(args.dbPaths[0])]) - mocks.guest.mockResolvedValue({ list }) - mocks.native.list.mockResolvedValueOnce([row(native)]) - const issues: AiVaultScanIssue[] = [] - const result = await listOpenCodeSqliteSessionsViaWorker({ - dbPaths: [native, ubuntu, debian], - limit: 2, - issues - }) - expect(result.map((entry) => entry.file.path)).toEqual([ - `${native}#same-session`, - `${ubuntu}#same-session`, - `${debian}#same-session` - ]) - expect(mocks.native.list).toHaveBeenCalledWith(expect.objectContaining({ dbPaths: [native] })) - expect(list).toHaveBeenCalledTimes(2) - expect(list.mock.calls.every(([args]) => args.dbPaths[0] === guest)).toBe(true) - expect(mocks.guest).toHaveBeenNthCalledWith(1, 'Ubuntu', ubuntu, undefined) - expect(mocks.guest).toHaveBeenNthCalledWith(2, 'Debian', debian, undefined) - expect(issues).toEqual([]) - }) - - it('maps guest list issues back to the original database and omits unavailable distros', async () => { - mocks.guest - .mockResolvedValueOnce({ - list: vi.fn(async (args) => { - args.issues.push({ agent: 'opencode2', path: guest, message: 'locked' }) - return [] - }) - }) - .mockRejectedValueOnce(new Error('Distro stopped')) - const issues: AiVaultScanIssue[] = [] - await listOpenCode2SqliteSessionsViaWorker({ dbPaths: [ubuntu, debian], limit: 2, issues }) - expect(issues).toEqual( - expect.arrayContaining([ - expect.objectContaining({ path: ubuntu, message: 'locked' }), - expect.objectContaining({ path: debian, kind: 'scope', message: 'Distro stopped' }) - ]) - ) - expect(mocks.native.list).not.toHaveBeenCalled() - }) - - it.each([ - ['v1', parseOpenCodeSqliteSessionViaWorker, captureOpenCodeSqliteSessionViaWorker, undefined], - [ - 'v2', - parseOpenCode2SqliteSessionViaWorker, - captureOpenCode2SqliteSessionViaWorker, - 'opencode2' - ] - ] as const)( - 'routes %s parse/capture to Linux and restores the caller identity', - async (_label, parse, capture, agent) => { - const parsed = session() - const messages = [{ role: 'user' as const, text: 'Complete transcript', timestamp: null }] - const reader = { - parse: vi.fn(async () => parsed), - capture: vi.fn(async () => ({ session: parsed, messages })) - } - mocks.guest.mockResolvedValue(reader) - const controller = new AbortController() - const args = { - dbPath: ubuntu, - sessionId: 'same-session', - platform: 'win32' as const, - signal: controller.signal - } - expect(await parse({ ...args, fullFirstUserPrompt: true })).toMatchObject({ - id: `local:opencode:same-session:${ubuntu}`, - filePath: ubuntu, - cwd: '/home/ada/repo', - executionHostPlatform: 'linux' - }) - expect(reader.parse).toHaveBeenCalledWith({ - ...args, - dbPath: guest, - platform: 'linux', - fullFirstUserPrompt: true, - ...(agent ? { agent } : {}) - }) - expect(await capture(args)).toMatchObject({ session: { filePath: ubuntu }, messages }) - expect(reader.capture).toHaveBeenCalledWith({ - ...args, - dbPath: guest, - platform: 'linux', - ...(agent ? { agent } : {}) - }) - expect(mocks.native.parse).not.toHaveBeenCalled() - expect(mocks.native.capture).not.toHaveBeenCalled() - } - ) - - it('propagates cancellation instead of returning an empty successful list', async () => { - const controller = new AbortController() - mocks.guest.mockImplementationOnce(async () => { - controller.abort(new Error('cancelled')) - throw new Error('cancelled') - }) - await expect( - listOpenCodeSqliteSessionsViaWorker({ - dbPaths: [ubuntu], - limit: 1, - issues: [], - signal: controller.signal - }) - ).rejects.toThrow('cancelled') - expect(mocks.native.list).not.toHaveBeenCalled() - }) -}) diff --git a/src/main/ai-vault/session-scanner-scope-cwd-facts.test.ts b/src/main/ai-vault/session-scanner-scope-cwd-facts.test.ts index 0558b6deabd..4f22a5f5c62 100644 --- a/src/main/ai-vault/session-scanner-scope-cwd-facts.test.ts +++ b/src/main/ai-vault/session-scanner-scope-cwd-facts.test.ts @@ -2,8 +2,6 @@ import { appendFile, mkdir, mkdtemp, rm, stat, utimes, writeFile } from 'node:fs import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, expect, it, vi } from 'vitest' -import type * as WslTranscriptFsAccess from '../native-chat/wsl-transcript-fs-access' -import { grokEncodedCwdDirName } from '../../shared/grok-session-paths' import { flushSessionParseCachePersist, initSessionParseCachePersistence, @@ -16,26 +14,6 @@ import { SessionParseCacheDatabase } from './parse-cache/session-parse-cache-dat import { parseAgentSessionFileCached } from './parse-cache/session-scanner-parse-cache' import { isolatedScanRoots, jsonLines } from './session-scanner-test-fixtures' -const reads = vi.hoisted((): string[] => []) -vi.mock('../native-chat/wsl-transcript-fs-access', async (importOriginal) => { - const actual = await importOriginal() - return { - ...actual, - wslGatedReadFile: (...args: Parameters) => { - reads.push(String(args[0])) - return actual.wslGatedReadFile(...args) - }, - readTranscriptSlice: (...args: Parameters) => { - reads.push(String(args[0])) - return actual.readTranscriptSlice(...args) - }, - openTranscriptReadStream: (...args: Parameters) => { - reads.push(String(args[0])) - return actual.openTranscriptReadStream(...args) - } - } -}) - let tempRoots: string[] = [] afterEach(async () => { @@ -44,7 +22,6 @@ afterEach(async () => { resetSessionParseCacheForTests() await Promise.all(tempRoots.map((root) => rm(root, { recursive: true, force: true }))) tempRoots = [] - reads.length = 0 }) it.each([false, true])('keeps cold authority with read failure=%s', async (failReads) => { @@ -131,24 +108,6 @@ it.each([false, true])('keeps cold authority with read failure=%s', async (failR } }) -async function writeGrokSession(sessionsDir: string, id: string, cwd: string, day: number) { - const dir = join(sessionsDir, grokEncodedCwdDirName(cwd) ?? 'unknown', id) - await mkdir(dir, { recursive: true }) - const timestamp = new Date(Date.UTC(2026, 9, day, 10)) - const summary = join(dir, 'summary.json') - await writeFile( - summary, - JSON.stringify({ - info: { id, cwd }, - created_at: timestamp.toISOString(), - updated_at: timestamp.toISOString() - }) - ) - await writeFile(join(dir, 'chat_history.jsonl'), jsonLines([{ type: 'user', content: id }])) - await utimes(summary, timestamp, timestamp) - return dir -} - async function writeRollout(sessionsDir: string, id: string, cwd: string, day: number) { const timestamp = new Date(Date.UTC(2026, 9, day, 10)) const dir = join(sessionsDir, '2026', '10', String(day).padStart(2, '0')) @@ -168,34 +127,3 @@ async function writeRollout(sessionsDir: string, id: string, cwd: string, day: n await utimes(path, timestamp, timestamp) return path } - -it('settles out-of-scope transcripts once and reads none of them after a restart', async () => { - const root = await mkdtemp(join(tmpdir(), 'orca-scope-cwd-facts-')) - tempRoots.push(root) - const roots = isolatedScanRoots(root) - const persistence = { filePath: join(root, 'user-data', 'parse-cache.json'), appVersion: 'test' } - initSessionParseCachePersistence(persistence) - const others: string[] = [] - for (const day of [15, 14, 13]) { - others.push(await writeGrokSession(roots.grokSessionsDir, `other-${day}`, '/other', day)) - } - const quiet = await writeGrokSession(roots.grokSessionsDir, 'repo-1', '/repo', 1) - const elsewhere = await writeRollout(roots.codexSessionsDir, 'other-2', '/other', 2) - const scan = () => - scanAiVaultSessions({ ...roots, platform: 'linux', limit: 1, scopePaths: ['/repo'] }) - - const listed = (await scan()).sessions.map((session) => session.cwd) - expect(listed.filter((cwd) => cwd === '/repo')).toHaveLength(1) - expect(reads).not.toContain(join(others[2], 'chat_history.jsonl')) - - await flushSessionParseCachePersist() - resetSessionParseCachePersistenceForTests() - resetSessionParseCacheForTests() - initSessionParseCachePersistence(persistence) - reads.length = 0 - - const relisted = (await scan()).sessions.filter((session) => session.cwd === '/repo') - expect(relisted.map((session) => session.filePath)).toEqual([join(quiet, 'summary.json')]) - expect(reads.filter((path) => path.startsWith(root))).toEqual([]) - expect(reads).not.toContain(elsewhere) -}) diff --git a/src/main/ai-vault/transcripts/session-transcript-message-content.test.ts b/src/main/ai-vault/transcripts/session-transcript-message-content.test.ts index 03de553bea4..fef6ef094fe 100644 --- a/src/main/ai-vault/transcripts/session-transcript-message-content.test.ts +++ b/src/main/ai-vault/transcripts/session-transcript-message-content.test.ts @@ -1,122 +1,10 @@ -import { expect, it, vi } from 'vitest' -import { - transcriptMessageFromText, - transcriptMessagesFromDecodedMessage, - transcriptMessagesFromContent -} from './session-transcript-message-content' +import { expect, it } from 'vitest' +import { transcriptMessagesFromDecodedMessage } from './session-transcript-message-content' import { decodeSessionMessage } from './session-decoded-message' const AT = '2026-05-01T10:00:00.000Z' const MESSAGE_LIMIT = 256 * 1024 -it('keeps a plain string turn under the record role', () => { - expect(transcriptMessagesFromContent('user', 'just words', AT)).toEqual([ - { role: 'user', text: 'just words', timestamp: AT } - ]) -}) - -it('drops turns whose role a consumer cannot use', () => { - expect(transcriptMessagesFromContent('system', 'boot', AT)).toEqual([]) - expect(transcriptMessagesFromContent('unknown', 'noise', AT)).toEqual([]) -}) - -it('joins text blocks and appends tool blocks as their own messages', () => { - expect( - transcriptMessagesFromContent( - 'assistant', - [ - { type: 'text', text: 'first' }, - { type: 'tool_use', name: 'Bash', input: { command: 'ls -la', description: 'ignored' } }, - { type: 'thinking', text: 'second' }, - { type: 'image', source: {} } - ], - AT - ) - ).toEqual([ - { role: 'assistant', text: 'first\nsecond', timestamp: AT }, - { role: 'tool', text: 'Bash: ls -la', timestamp: AT } - ]) -}) - -it('accepts the capitalised Text block Codex writes for a completed agent message', () => { - expect( - transcriptMessagesFromContent('assistant', [{ type: 'Text', text: 'the reply' }], AT) - ).toEqual([{ role: 'assistant', text: 'the reply', timestamp: AT }]) -}) - -it('reads a tool result carried on a user record as a tool message', () => { - expect( - transcriptMessagesFromContent( - 'user', - [{ type: 'tool_result', content: [{ type: 'text', text: 'exit 0' }] }], - AT - ) - ).toEqual([{ role: 'tool', text: 'exit 0', timestamp: AT }]) -}) - -it('names a tool call even with no recognisable argument', () => { - expect( - transcriptMessagesFromContent('assistant', [{ type: 'tool_use', name: 'Read', input: {} }], AT) - ).toEqual([{ role: 'tool', text: 'Read', timestamp: AT }]) -}) - -it('emits nothing for blank or absent content', () => { - expect(transcriptMessagesFromContent('user', ' ', AT)).toEqual([]) - expect(transcriptMessagesFromContent('user', null, AT)).toEqual([]) - expect(transcriptMessagesFromContent('assistant', [{ type: 'tool_use' }], AT)).toEqual([]) -}) - -it('does not apply the list preview cap', () => { - const long = 'x'.repeat(5000) - const [message] = transcriptMessagesFromContent('user', [{ type: 'text', text: long }], AT) - expect(message.text).toHaveLength(5000) -}) - -it.each([ - { tail: [], truncated: false }, - { tail: ['', null, { type: 'image', source: {} }], truncated: false }, - { - tail: [ - { type: 'image', source: {} }, - { type: 'text', text: 'later' } - ], - truncated: true - } -])( - 'only flags a full tool result when later text is omitted: $truncated', - ({ tail, truncated }) => { - const [message] = transcriptMessagesFromContent( - 'user', - [ - { - type: 'tool_result', - content: [{ type: 'text', text: 'x'.repeat(MESSAGE_LIMIT) }, ...tail] - } - ], - AT - ) - expect(message.text).toBe('x'.repeat(MESSAGE_LIMIT)) - expect(message.textTruncated).toBe(truncated ? true : undefined) - } -) - -it('reports size limits and preserves truncation from an earlier limit', () => { - expect( - transcriptMessageFromText('user', 'x'.repeat(MESSAGE_LIMIT), AT)?.textTruncated - ).toBeUndefined() - const clipped = transcriptMessageFromText('user', `${'x'.repeat(MESSAGE_LIMIT - 1)}😀`, AT) - expect(clipped?.text).toBe('x'.repeat(MESSAGE_LIMIT - 1)) - expect(clipped?.textTruncated).toBe(true) - expect(transcriptMessageFromText('tool', 'short prefix', AT, true)?.textTruncated).toBe(true) - expect( - transcriptMessagesFromContent( - 'assistant', - [{ type: 'tool_use', name: 'Bash', input: { command: 'x'.repeat(2001) } }], - AT - )[0]?.textTruncated - ).toBe(true) -}) - it('reads tool-result parts lazily and can project the same decoded result again', () => { const decoded = decodeSessionMessage( 'user', @@ -143,101 +31,3 @@ it('reads tool-result parts lazily and can project the same decoded result again ]) } }) - -it('bounds joins for a large multi-block turn and keeps its later tool messages', () => { - const blockText = 'x'.repeat(1024 * 1024) - const content = [ - ...Array.from({ length: 72 }, () => ({ type: 'text', text: blockText })), - { type: 'tool_use', name: 'Read', input: { path: 'after-large-text' } }, - { - type: 'tool_result', - content: [ - { type: 'text', text: 'header' }, - { type: 'text', text: blockText.repeat(50) }, - { type: 'text', text: 'ignored after the existing result cap' } - ] - }, - { type: 'tool_use', name: 'Bash', input: { command: 'pwd' } }, - { type: 'tool_result', content: 'finished' } - ] - const join = Array.prototype.join - let largestJoinedLength = 0 - const spy = vi.spyOn(Array.prototype, 'join').mockImplementation(function ( - this: unknown[], - separator - ) { - let length = Math.max(0, this.length - 1) * (separator ?? ',').length - for (const value of this) { - length += typeof value === 'string' ? value.length : 0 - } - largestJoinedLength = Math.max(largestJoinedLength, length) - return join.call(this, separator) - }) - let messages - try { - messages = transcriptMessagesFromContent('assistant', content, AT) - } finally { - spy.mockRestore() - } - expect(messages).toEqual([ - { role: 'assistant', text: 'x'.repeat(MESSAGE_LIMIT), timestamp: AT, textTruncated: true }, - { role: 'tool', text: 'Read: after-large-text', timestamp: AT }, - { - role: 'tool', - text: `header\n${'x'.repeat(MESSAGE_LIMIT - 7)}`, - timestamp: AT, - textTruncated: true - }, - { role: 'tool', text: 'Bash: pwd', timestamp: AT }, - { role: 'tool', text: 'finished', timestamp: AT } - ]) - expect(largestJoinedLength).toBeLessThanOrEqual(MESSAGE_LIMIT + 1) -}) - -it('bounds joined text at newline and raw surrogate boundaries', () => { - const cases = [ - { - parts: ['x'.repeat(MESSAGE_LIMIT - 2), '\ud800'], - text: `${'x'.repeat(MESSAGE_LIMIT - 2)}\n\ud800`, - truncated: false - }, - { - parts: ['x'.repeat(MESSAGE_LIMIT - 1), '\ud800'], - text: `${'x'.repeat(MESSAGE_LIMIT - 1)}\n`, - truncated: true - }, - { - parts: [`${'x'.repeat(MESSAGE_LIMIT - 1)}\ud800`, 'later'], - text: 'x'.repeat(MESSAGE_LIMIT - 1), - truncated: true - }, - { - parts: ['x'.repeat(MESSAGE_LIMIT - 2), '\ud800\udc00', 'later'], - text: `${'x'.repeat(MESSAGE_LIMIT - 2)}\n`, - truncated: true - }, - { - parts: ['x'.repeat(MESSAGE_LIMIT - 3), '\ud800\udc00', 'later'], - text: `${'x'.repeat(MESSAGE_LIMIT - 3)}\n\ud800\udc00`, - truncated: true - }, - { - parts: ['x'.repeat(MESSAGE_LIMIT), '', 'later'], - text: 'x'.repeat(MESSAGE_LIMIT), - truncated: true - }, - { - parts: ['', '', '\ud800', '\udfff', '\u0000'], - text: '\n\n\ud800\n\udfff\n\u0000', - truncated: false - }, - { parts: [' '.repeat(MESSAGE_LIMIT), 'visible beyond the cap'], text: null, truncated: false } - ] - for (const { parts, text, truncated } of cases) { - expect(transcriptMessagesFromContent('user', parts, AT)).toEqual( - text === null - ? [] - : [{ role: 'user', text, timestamp: AT, ...(truncated ? { textTruncated: true } : {}) }] - ) - } -}) diff --git a/src/main/browser-passwords/browser-password-chromium-import.test.ts b/src/main/browser-passwords/browser-password-chromium-import.test.ts index 6cedd281539..65e680215ff 100644 --- a/src/main/browser-passwords/browser-password-chromium-import.test.ts +++ b/src/main/browser-passwords/browser-password-chromium-import.test.ts @@ -11,12 +11,11 @@ import type { EncryptionKeyResult } from '../browser/cookies/sources/browser-coo type FixtureState = { root: string key: EncryptionKeyResult | null - keyRequests: number snapshotPaths: string[] } const { state } = vi.hoisted(() => { - const state: FixtureState = { root: '', key: null, keyRequests: 0, snapshotPaths: [] } + const state: FixtureState = { root: '', key: null, snapshotPaths: [] } return { state } }) @@ -27,7 +26,6 @@ vi.mock('../browser/cookies/sources/browser-cookie-source-profiles', async (impo vi.mock('../browser/cookies/sources/browser-cookie-key', () => ({ getEncryptionKey: () => { - state.keyRequests += 1 return state.key } })) @@ -105,7 +103,6 @@ describe('readChromiumBrowserPasswords', () => { beforeEach(() => { state.root = mkdtempSync(join(tmpdir(), 'orca-chromium-passwords-test-')) state.key = { mode: 'aes-128-cbc', keysByVersion: { v10: cbcKey } } - state.keyRequests = 0 state.snapshotPaths = [] }) @@ -152,35 +149,4 @@ describe('readChromiumBrowserPasswords', () => { expect(state.snapshotPaths).toHaveLength(2) expect(state.snapshotPaths.some((path) => existsSync(path))).toBe(false) }) - - it('never fetches the key when every value is app-bound', async () => { - writeLoginDatabase('Login Data', [ - { origin: 'https://bound.test/', username: 'u', password: Buffer.from('v20opaque') } - ]) - const result = await readChromiumBrowserPasswords({ - browserFamily: 'chrome', - profileDirectory: 'Default' - }) - expect(result).toEqual({ ok: true, rows: [], undecryptable: 1 }) - expect(state.keyRequests).toBe(0) - }) - - it('fails when the key is unavailable', async () => { - writeLoginDatabase('Login Data', [ - { origin: 'https://a.test/', username: 'u', password: encryptV10('secret') } - ]) - state.key = null - expect( - await readChromiumBrowserPasswords({ browserFamily: 'chrome', profileDirectory: 'Default' }) - ).toMatchObject({ ok: false, reason: 'key-unavailable' }) - }) - - it('reports a profile without login databases, and refuses unsafe profile names', async () => { - expect( - await readChromiumBrowserPasswords({ browserFamily: 'chrome', profileDirectory: 'Default' }) - ).toMatchObject({ ok: false, reason: 'not-found' }) - expect( - await readChromiumBrowserPasswords({ browserFamily: 'chrome', profileDirectory: '../x' }) - ).toMatchObject({ ok: false, reason: 'invalid-profile' }) - }) }) diff --git a/src/main/browser-passwords/browser-password-csv-import.test.ts b/src/main/browser-passwords/browser-password-csv-import.test.ts index 6e3b3627f7b..1a587bbc6ab 100644 --- a/src/main/browser-passwords/browser-password-csv-import.test.ts +++ b/src/main/browser-passwords/browser-password-csv-import.test.ts @@ -1,73 +1,5 @@ import { describe, expect, it } from 'vitest' -import { - BROWSER_PASSWORD_CSV_MAX_BYTES, - BROWSER_PASSWORD_CSV_MAX_ROWS, - parseBrowserPasswordCsv -} from './browser-password-csv-import' - -const login = { url: 'https://example.com/login', username: 'alice', password: 'p@ss' } - -describe('parseBrowserPasswordCsv headers', () => { - it('reads a Chrome export', () => { - const result = parseBrowserPasswordCsv( - 'name,url,username,password,note\r\nexample.com,https://example.com/login,alice,p@ss,hi\r\n' - ) - expect(result).toEqual({ rows: [{ ...login, note: 'hi', name: 'example.com' }], invalid: 0 }) - }) - - it('reads a Firefox export', () => { - const result = parseBrowserPasswordCsv( - '"url","username","password","httpRealm","formActionOrigin","guid","timeCreated","timeLastUsed","timePasswordChanged"\n' + - '"https://example.com/login","alice","p@ss",,"https://example.com","{abc}","1","2","3"\n' - ) - expect(result.rows).toEqual([{ ...login, note: '', name: '' }]) - }) - - it('reads a Safari export', () => { - const result = parseBrowserPasswordCsv( - 'Title,URL,Username,Password,Notes,OTPAuth\nExample,https://example.com/login,alice,p@ss,n,\n' - ) - expect(result.rows).toEqual([{ ...login, note: 'n', name: 'Example' }]) - }) - - it('reads a Bitwarden export', () => { - const result = parseBrowserPasswordCsv( - 'folder,favorite,type,name,notes,fields,reprompt,login_uri,login_username,login_password,login_totp\n' + - ',,login,Example,n,,0,https://example.com/login,alice,p@ss,\n' - ) - expect(result.rows).toEqual([{ ...login, note: 'n', name: 'Example' }]) - }) - - it('reads a LastPass export', () => { - const result = parseBrowserPasswordCsv( - 'url,username,password,totp,extra,name,grouping,fav\nhttps://example.com/login,alice,p@ss,,n,Example,,0\n' - ) - expect(result.rows).toEqual([{ ...login, note: 'n', name: 'Example' }]) - }) - - it('prefers username over an earlier email column', () => { - const result = parseBrowserPasswordCsv( - 'type,name,url,email,username,password,note\nlogin,Ex,https://example.com/login,a@x.com,alice,p@ss,\n' - ) - expect(result.rows[0]?.username).toBe('alice') - }) - - it('matches headers case-insensitively after trimming', () => { - const result = parseBrowserPasswordCsv( - ' URL , Login , Password \nhttps://example.com/login,alice,p@ss\n' - ) - expect(result.rows).toEqual([{ ...login, note: '', name: '' }]) - }) - - it('reports missing required columns', () => { - expect(parseBrowserPasswordCsv('name,url,password\nx,https://a.com,p\n')).toEqual({ - rows: [], - invalid: 0, - error: 'missing-columns' - }) - expect(parseBrowserPasswordCsv('').error).toBe('missing-columns') - }) -}) +import { parseBrowserPasswordCsv } from './browser-password-csv-import' describe('parseBrowserPasswordCsv RFC 4180', () => { it('handles BOM, quotes, escaped quotes, embedded newlines and no trailing newline', () => { @@ -84,37 +16,4 @@ describe('parseBrowserPasswordCsv RFC 4180', () => { } ]) }) - - it('skips blank lines and fills short rows with empty fields', () => { - const result = parseBrowserPasswordCsv('url,username,password\n\nhttps://a.com,bob\n') - expect(result.rows).toEqual([ - { url: 'https://a.com', username: 'bob', password: '', note: '', name: '' } - ]) - }) -}) - -describe('parseBrowserPasswordCsv limits', () => { - it('refuses text over 1 MB', () => { - const text = `url,username,password\n${'x'.repeat(BROWSER_PASSWORD_CSV_MAX_BYTES)}` - expect(parseBrowserPasswordCsv(text).error).toBe('too-large') - }) - - it('refuses more than 3000 rows', () => { - const body = 'https://a.com,u,p\n'.repeat(BROWSER_PASSWORD_CSV_MAX_ROWS + 1) - expect(parseBrowserPasswordCsv(`url,username,password\n${body}`).error).toBe('too-many-rows') - const atLimit = 'https://a.com,u,p\n'.repeat(BROWSER_PASSWORD_CSV_MAX_ROWS) - expect(parseBrowserPasswordCsv(`url,username,password\n${atLimit}`).rows).toHaveLength( - BROWSER_PASSWORD_CSV_MAX_ROWS - ) - }) - - it('counts rows over a field limit as invalid', () => { - const longUrl = `https://a.com/${'x'.repeat(2048)}` - const longPassword = 'p'.repeat(1001) - const result = parseBrowserPasswordCsv( - `url,username,password\n${longUrl},u,p\nhttps://a.com,u,${longPassword}\nhttps://a.com,u,p\n` - ) - expect(result.invalid).toBe(2) - expect(result.rows).toHaveLength(1) - }) }) diff --git a/src/main/browser-passwords/browser-password-guest-payloads.test.ts b/src/main/browser-passwords/browser-password-guest-payloads.test.ts deleted file mode 100644 index 8e910b1a2fa..00000000000 --- a/src/main/browser-passwords/browser-password-guest-payloads.test.ts +++ /dev/null @@ -1,55 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { - readBrowserPasswordCapture, - readBrowserPasswordFieldFocused, - readBrowserPasswordFormSummaries, - readBrowserPasswordSubmitted -} from './browser-password-guest-payloads' - -const summary = { - formSignature: 'form-1', - kind: 'login', - usernameFieldName: 'email', - passwordFieldName: 'password', - action: null -} - -describe('browser password guest payloads', () => { - it('reads a well-formed capture and normalises empty values to null', () => { - expect( - readBrowserPasswordCapture({ ...summary, username: '', password: 'pw', newPassword: null }) - ).toEqual({ ...summary, username: null, password: 'pw', newPassword: null }) - }) - - it('refuses unknown form kinds, non-string values and oversized secrets', () => { - expect(readBrowserPasswordCapture({ ...summary, kind: 'admin', password: 'pw' })).toBeNull() - expect(readBrowserPasswordCapture({ ...summary, password: 42 })).toBeNull() - expect(readBrowserPasswordCapture({ ...summary, password: 'x'.repeat(1001) })).toBeNull() - expect(readBrowserPasswordCapture(null)).toBeNull() - }) - - it('requires a known submit source', () => { - const capture = { ...summary, username: 'ada', password: 'pw', newPassword: null } - expect(readBrowserPasswordSubmitted({ ...capture, source: 'enter' })?.source).toBe('enter') - expect(readBrowserPasswordSubmitted({ ...capture, source: 'script' })).toBeNull() - }) - - it('refuses a form list with any malformed form', () => { - expect(readBrowserPasswordFormSummaries({ forms: [summary] })).toEqual([summary]) - expect(readBrowserPasswordFormSummaries({ forms: [summary, { formSignature: 1 }] })).toBeNull() - }) - - it('reads a focused field and rejects non-finite geometry', () => { - const focused = { - fieldToken: 't', - formSignature: 'form-1', - role: 'password', - rect: { x: 1, y: 2, width: 3, height: 4 }, - viewportWidth: 800 - } - expect(readBrowserPasswordFieldFocused(focused)).toEqual(focused) - expect( - readBrowserPasswordFieldFocused({ ...focused, rect: { ...focused.rect, x: Infinity } }) - ).toBeNull() - }) -}) diff --git a/src/main/browser-passwords/browser-password-guest-service.test.ts b/src/main/browser-passwords/browser-password-guest-service.test.ts index daa03d31f44..dae21dd25a0 100644 --- a/src/main/browser-passwords/browser-password-guest-service.test.ts +++ b/src/main/browser-passwords/browser-password-guest-service.test.ts @@ -89,57 +89,6 @@ function setup() { return { guest, event } } -describe('native password picker keyboard handoff', () => { - it('preserves the field during focus transfer, then invalidates it on navigation', () => { - const { guest, event } = setup() - const preventDefault = vi.fn() - guest.emit('before-input-event', { preventDefault }, { type: 'keyDown', key: 'ArrowDown' }) - expect(preventDefault).toHaveBeenCalledOnce() - expect(renderer.focus).toHaveBeenCalledOnce() - expect(renderer.send).toHaveBeenCalledWith( - 'browserPasswords:fieldFocus', - expect.objectContaining({ fieldToken: 'field', keyboardSelection: true }) - ) - renderer.send.mockClear() - handlers.get(channels.fieldBlurred)?.(event, { fieldToken: 'field', reason: 'focusout' }) - expect(renderer.send).not.toHaveBeenCalled() - guest.emit('did-start-navigation', { isMainFrame: true, isSameDocument: false, initiator: {} }) - expect(renderer.send).toHaveBeenCalledWith('browserPasswords:fieldBlur', { - browserPageId: 'page', - fieldToken: 'field' - }) - }) - - it('still dismisses on viewport invalidation if no focusout accompanied the transfer', () => { - const { guest, event } = setup() - guest.emit( - 'before-input-event', - { preventDefault: vi.fn() }, - { type: 'keyDown', key: 'ArrowDown' } - ) - renderer.send.mockClear() - handlers.get(channels.fieldBlurred)?.(event, { fieldToken: 'field' }) - expect(renderer.send).toHaveBeenCalledWith('browserPasswords:fieldBlur', { - browserPageId: 'page', - fieldToken: 'field' - }) - }) - - it.each(['agent', 'modified'] as const)('does not enter the picker for %s input', (source) => { - const { guest } = setup() - injecting.mockReturnValue(source === 'agent') - const preventDefault = vi.fn() - guest.emit( - 'before-input-event', - { preventDefault }, - { type: 'keyDown', key: 'ArrowDown', control: source === 'modified' } - ) - expect(preventDefault).not.toHaveBeenCalled() - expect(renderer.focus).not.toHaveBeenCalled() - expect(renderer.send).not.toHaveBeenCalled() - }) -}) - describe('fill after Touch ID', () => { it('refuses to send the password when the page navigated while the prompt was up', async () => { const { guest } = setup() diff --git a/src/main/browser-passwords/browser-password-login-tracker.test.ts b/src/main/browser-passwords/browser-password-login-tracker.test.ts index 755fbfa7c1e..7e2fe599f78 100644 --- a/src/main/browser-passwords/browser-password-login-tracker.test.ts +++ b/src/main/browser-passwords/browser-password-login-tracker.test.ts @@ -54,167 +54,6 @@ function setup(): { } describe('BrowserPasswordLoginTracker', () => { - it.each(['returned-form', 'http-error', 'timeout'])( - 'does not revive a rejected %s attempt on a later page navigation', - (failure) => { - const { tracker, succeeded, runTimers } = setup() - tracker.typed(ORIGIN, capture()) - tracker.submitted(ORIGIN, capture()) - if (failure === 'timeout') { - runTimers() - } else { - tracker.navigationStarted(true) - tracker.navigated(failure === 'http-error' ? 401 : 200) - tracker.documentReady() - if (failure === 'returned-form') { - tracker.pageForms([capture()]) - } - } - tracker.navigationStarted(true) - tracker.navigated(200) - tracker.documentReady() - runTimers() - expect(succeeded).toEqual([]) - } - ) - - it('forgets a provisional password when its field is erased', () => { - const { tracker, succeeded, runTimers } = setup() - tracker.typed(ORIGIN, capture()) - tracker.typed(ORIGIN, capture({ password: null })) - tracker.navigationStarted(true) - tracker.navigated(200) - tracker.documentReady() - runTimers() - expect(succeeded).toEqual([]) - }) - - it.each(['password', null])( - 'recognizes a returned form when inferred kind changes with field name %j', - (passwordFieldName) => { - const { tracker, succeeded, runTimers } = setup() - tracker.submitted(ORIGIN, capture({ kind: 'signup', passwordFieldName })) - tracker.navigationStarted(true) - tracker.navigated(200) - tracker.documentReady() - tracker.pageForms([ - { ...capture({ passwordFieldName }), formSignature: 'new-document', kind: 'change' } - ]) - runTimers() - expect(succeeded).toEqual([]) - } - ) - - it('keeps a valid attempt through an intermediate script redirect', () => { - const { tracker, succeeded, advance } = setup() - tracker.submitted(ORIGIN, capture()) - tracker.navigationStarted(true) - tracker.navigated(200) - tracker.documentReady() - advance(2000) - tracker.navigationStarted(true) - advance(1000) - expect(succeeded).toEqual([]) - tracker.navigated(200) - tracker.documentReady() - advance(2500) - expect(succeeded).toHaveLength(1) - }) - - it('offers a classic form POST once the next page settles without the form', () => { - const { tracker, succeeded, runTimers } = setup() - tracker.typed(ORIGIN, capture()) - tracker.submitted(ORIGIN, capture()) - tracker.navigationStarted(true) - tracker.navigated(200) - tracker.documentReady() - tracker.pageForms([]) - runTimers() - expect(succeeded).toEqual([{ origin: ORIGIN, capture: capture(), username: 'ada@example.com' }]) - }) - - it('treats an HTTP error on the next page as a failed login', () => { - const { tracker, succeeded, runTimers } = setup() - tracker.submitted(ORIGIN, capture()) - tracker.navigationStarted(true) - tracker.navigated(401) - runTimers() - expect(succeeded).toEqual([]) - }) - - it('treats the same form showing up again as a failed login', () => { - const { tracker, succeeded, runTimers } = setup() - tracker.submitted(ORIGIN, capture()) - tracker.navigationStarted(true) - tracker.navigated(200) - tracker.documentReady() - // A fresh document gives the form a new signature; its field names still match. - tracker.pageForms([{ ...capture(), formSignature: 'form-2' }]) - runTimers() - expect(succeeded).toEqual([]) - }) - - it('waits for a slow next page to be ready before judging it', () => { - const { tracker, succeeded, advance } = setup() - tracker.submitted(ORIGIN, capture()) - tracker.navigationStarted(true) - tracker.navigated(200) - advance(10_000) - tracker.documentReady() - tracker.pageForms([{ ...capture(), formSignature: 'form-2' }]) - advance(10_000) - expect(succeeded).toEqual([]) - }) - - it('counts a single-page login when the submitted form goes away', () => { - const { tracker, succeeded } = setup() - tracker.submitted(ORIGIN, capture()) - tracker.formGone('form-1') - expect(succeeded).toHaveLength(1) - }) - - it('drops a single-page attempt whose form is still there after the failure window', () => { - const { tracker, succeeded, advance } = setup() - tracker.submitted(ORIGIN, capture()) - advance(6000) - tracker.formGone('form-1') - expect(succeeded).toEqual([]) - }) - - it('treats a page-started navigation after typing as a submit the page script performed', () => { - const { tracker, succeeded, runTimers } = setup() - tracker.typed(ORIGIN, capture()) - tracker.navigationStarted(true) - tracker.navigated(200) - tracker.documentReady() - runTimers() - expect(succeeded).toHaveLength(1) - }) - - it('forgets typed values when the user navigates away from the address bar', () => { - const { tracker, succeeded, runTimers } = setup() - tracker.typed(ORIGIN, capture()) - tracker.navigationStarted(false) - tracker.navigated(200) - tracker.documentReady() - runTimers() - expect(succeeded).toEqual([]) - }) - - it('carries the username from a username-first step onto the password step', () => { - const { tracker, succeeded } = setup() - tracker.submitted( - ORIGIN, - capture({ formSignature: 'step-1', kind: 'username-only', password: null }) - ) - const passwordStep = capture({ formSignature: 'step-2', username: null }) - tracker.submitted(ORIGIN, passwordStep) - tracker.formGone('step-2') - expect(succeeded).toEqual([ - { origin: ORIGIN, capture: passwordStep, username: 'ada@example.com' } - ]) - }) - it('does not lend a username across sites or after five minutes', () => { const { tracker, succeeded, advance } = setup() tracker.submitted( @@ -232,11 +71,4 @@ describe('BrowserPasswordLoginTracker', () => { tracker.formGone('step-4') expect(succeeded.map((login) => login.username)).toEqual([null, null]) }) - - it('never offers a username on its own', () => { - const { tracker, succeeded } = setup() - tracker.submitted(ORIGIN, capture({ kind: 'username-only', password: null })) - tracker.formGone('form-1') - expect(succeeded).toEqual([]) - }) }) diff --git a/src/main/browser-passwords/browser-password-origin.test.ts b/src/main/browser-passwords/browser-password-origin.test.ts index 007ce08b539..3cd01ef51e3 100644 --- a/src/main/browser-passwords/browser-password-origin.test.ts +++ b/src/main/browser-passwords/browser-password-origin.test.ts @@ -1,46 +1,5 @@ import { describe, expect, it } from 'vitest' -import { - matchBrowserPasswordEntries, - registrableDomainOf, - toBrowserPasswordOrigin -} from './browser-password-origin' - -describe('toBrowserPasswordOrigin', () => { - it('keeps scheme, host and non-default port only', () => { - expect(toBrowserPasswordOrigin('https://user:pw@Example.COM/login?x=1#frag')).toBe( - 'https://example.com' - ) - expect(toBrowserPasswordOrigin('http://example.com:80/a')).toBe('http://example.com') - expect(toBrowserPasswordOrigin('https://example.com:443')).toBe('https://example.com') - expect(toBrowserPasswordOrigin('https://example.com:8443/')).toBe('https://example.com:8443') - expect(toBrowserPasswordOrigin('http://localhost:3000')).toBe('http://localhost:3000') - }) - - it('serialises IDN hosts as punycode', () => { - expect(toBrowserPasswordOrigin('https://bücher.de/')).toBe('https://xn--bcher-kva.de') - }) - - it('rejects non-web schemes and garbage', () => { - expect(toBrowserPasswordOrigin('ftp://example.com')).toBeNull() - expect(toBrowserPasswordOrigin('android://hash@com.example/')).toBeNull() - expect(toBrowserPasswordOrigin('file:///etc/passwd')).toBeNull() - expect(toBrowserPasswordOrigin('example.com')).toBeNull() - expect(toBrowserPasswordOrigin('')).toBeNull() - }) -}) - -describe('registrableDomainOf', () => { - it('returns eTLD+1 including private suffixes', () => { - expect(registrableDomainOf('https://accounts.google.com')).toBe('google.com') - expect(registrableDomainOf('https://a.b.example.co.uk')).toBe('example.co.uk') - expect(registrableDomainOf('https://alice.github.io')).toBe('alice.github.io') - }) - - it('returns the bare host for IPs and localhost', () => { - expect(registrableDomainOf('http://127.0.0.1:8080')).toBe('127.0.0.1') - expect(registrableDomainOf('http://localhost:3000')).toBe('localhost') - }) -}) +import { matchBrowserPasswordEntries } from './browser-password-origin' describe('matchBrowserPasswordEntries', () => { const entry = (id: string, origin: string, updatedAt = 0, lastUsedAt: number | null = null) => ({ @@ -67,21 +26,4 @@ describe('matchBrowserPasswordEntries', () => { expect(pages.exact).toEqual([]) expect(pages.sameSite).toEqual([]) }) - - it('sorts by last used, then updated, newest first', () => { - const entries = [ - entry('old', 'https://example.com', 1, null), - entry('newer-update', 'https://example.com', 5, null), - entry('used', 'https://example.com', 0, 10) - ] - expect( - matchBrowserPasswordEntries(entries, 'https://example.com').exact.map((e) => e.id) - ).toEqual(['used', 'newer-update', 'old']) - }) - - it('matches nothing for a non-web page', () => { - expect(matchBrowserPasswordEntries([entry('a', 'https://example.com')], 'about:blank')).toEqual( - { exact: [], sameSite: [] } - ) - }) }) diff --git a/src/main/browser-passwords/browser-password-save-decision.test.ts b/src/main/browser-passwords/browser-password-save-decision.test.ts deleted file mode 100644 index 3d40c93fe58..00000000000 --- a/src/main/browser-passwords/browser-password-save-decision.test.ts +++ /dev/null @@ -1,50 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { decideBrowserPasswordSave } from './browser-password-save-decision' - -const saved = [ - { id: 'a', username: 'ada', password: 'one' }, - { id: 'b', username: 'grace', password: 'two' } -] - -describe('decideBrowserPasswordSave', () => { - it('offers a new save for an unknown username', () => { - expect( - decideBrowserPasswordSave({ username: 'linus', password: 'x', formKind: 'login', saved }) - ).toEqual({ kind: 'save', username: 'linus', password: 'x' }) - }) - - it('only records a use for a known pair', () => { - expect( - decideBrowserPasswordSave({ username: 'ada', password: 'one', formKind: 'login', saved }) - ).toEqual({ kind: 'none', usedEntryId: 'a' }) - }) - - it('offers an update when a known username signs in with a new password', () => { - expect( - decideBrowserPasswordSave({ username: ' ada ', password: 'new', formKind: 'login', saved }) - ).toEqual({ kind: 'update', entryId: 'a', username: 'ada', password: 'new' }) - }) - - it('matches by password when the form has no username', () => { - expect( - decideBrowserPasswordSave({ username: null, password: 'two', formKind: 'login', saved }) - ).toEqual({ kind: 'none', usedEntryId: 'b' }) - }) - - it('updates the only saved login from a change-password form without a username', () => { - expect( - decideBrowserPasswordSave({ - username: null, - password: 'rotated', - formKind: 'change', - saved: [saved[0]] - }) - ).toEqual({ kind: 'update', entryId: 'a', username: 'ada', password: 'rotated' }) - }) - - it('saves without a username when nothing matches and the account is ambiguous', () => { - expect( - decideBrowserPasswordSave({ username: null, password: 'rotated', formKind: 'change', saved }) - ).toEqual({ kind: 'save', username: '', password: 'rotated' }) - }) -}) diff --git a/src/main/browser-passwords/browser-password-save-prompts.test.ts b/src/main/browser-passwords/browser-password-save-prompts.test.ts index b02eb377291..16cb9027b82 100644 --- a/src/main/browser-passwords/browser-password-save-prompts.test.ts +++ b/src/main/browser-passwords/browser-password-save-prompts.test.ts @@ -71,17 +71,6 @@ afterEach(() => { }) describe('offerBrowserPasswordSave', () => { - it('offers to save a new login and stores it only when the user says save', () => { - offer('pw-1') - expect(lastPrompt()).toMatchObject({ mode: 'save', origin: ORIGIN, username: 'ada' }) - expect(store.list()).toEqual({ ok: true, value: [] }) - expect( - respondToBrowserPasswordSavePrompt({ promptId: lastPrompt().promptId, action: 'save' }) - ).toBe(true) - const entries = store.list() - expect(entries.ok && entries.value.map((entry) => entry.username)).toEqual(['ada']) - }) - it('does not let a pending offer recreate a deleted vault', () => { offer('pw-1') const promptId = lastPrompt().promptId @@ -90,24 +79,4 @@ describe('offerBrowserPasswordSave', () => { expect(respondToBrowserPasswordSavePrompt({ promptId, action: 'save' })).toBe(false) expect(store.list()).toEqual({ ok: true, value: [] }) }) - - it('stays quiet on a site the user said never to save for', () => { - store.addNever(ORIGIN) - offer('pw-1') - expect(lastPrompt()).toBeUndefined() - }) - - it('offers an update when a saved username signs in with a new password', () => { - const added = store.add({ origin: ORIGIN, username: 'ada', password: 'old' }) - const id = added.ok ? added.value.entry.id : '' - offer('new') - expect(lastPrompt()).toMatchObject({ mode: 'update' }) - respondToBrowserPasswordSavePrompt({ promptId: lastPrompt().promptId, action: 'save' }) - expect(store.getPassword(id)).toEqual({ ok: true, value: 'new' }) - }) - - it('never sends the password to the renderer', () => { - offer('top-secret') - expect(JSON.stringify(send.mock.calls)).not.toContain('top-secret') - }) }) diff --git a/src/main/browser-passwords/browser-password-store.test.ts b/src/main/browser-passwords/browser-password-store.test.ts index 69687b40677..d2b55342a12 100644 --- a/src/main/browser-passwords/browser-password-store.test.ts +++ b/src/main/browser-passwords/browser-password-store.test.ts @@ -1,4 +1,4 @@ -import { chmodSync, existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs' +import { chmodSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, beforeEach, describe, expect, it } from 'vitest' @@ -81,105 +81,6 @@ describe('BrowserPasswordStore', () => { expect(newStore().listNever()).toEqual({ ok: true, value: [] }) }) - it('updates the password instead of adding when origin and username already exist', () => { - const store = newStore() - const first = store.add({ origin: 'https://a.test', username: 'u', password: 'one' }) - clock = 2000 - const second = store.add({ origin: 'https://a.test/x', username: 'u', password: 'two' }) - const third = store.add({ origin: 'https://a.test', username: 'other', password: 'three' }) - expect(second.ok && second.value.created).toBe(false) - expect(third.ok && third.value.created).toBe(true) - const firstId = first.ok ? first.value.entry.id : '' - expect(second.ok && second.value.entry).toMatchObject({ - id: firstId, - createdAt: 1000, - updatedAt: 2000 - }) - expect(newStore().getPassword(firstId)).toEqual({ ok: true, value: 'two' }) - const list = newStore().list() - expect(list.ok && list.value).toHaveLength(2) - }) - - it('rejects non-web origins and empty passwords', () => { - const store = newStore() - expect(store.add({ origin: 'file:///x', username: 'u', password: 'p' })).toEqual({ - ok: false, - reason: 'invalid-origin' - }) - expect(store.add({ origin: 'https://a.test', username: 'u', password: '' })).toEqual({ - ok: false, - reason: 'invalid-password' - }) - expect(existsSync(filePath)).toBe(false) - }) - - it('edits, marks used, finds and removes entries', () => { - const store = newStore() - const a = store.add({ origin: 'https://login.a.test', username: 'u1', password: 'p1' }) - const b = store.add({ origin: 'https://www.a.test', username: 'u2', password: 'p2' }) - const aId = a.ok ? a.value.entry.id : '' - const bId = b.ok ? b.value.entry.id : '' - clock = 5000 - expect(store.markUsed(aId).ok).toBe(true) - expect(store.updatePassword(bId, 'p2b').ok).toBe(true) - - const reopened = newStore() - const found = reopened.findForOrigin('https://login.a.test') - expect(found.ok && found.value.exact.map((e) => e.id)).toEqual([aId]) - expect(found.ok && found.value.sameSite.map((e) => e.id)).toEqual([bId]) - expect(reopened.getPassword(bId)).toEqual({ ok: true, value: 'p2b' }) - expect(reopened.list()).toMatchObject({ - ok: true, - value: [ - { id: aId, lastUsedAt: 5000 }, - { id: bId, updatedAt: 5000 } - ] - }) - - expect(reopened.updateUsername(aId, 'renamed').ok).toBe(true) - expect(newStore().list()).toMatchObject({ value: [{ username: 'renamed' }, {}] }) - - expect(reopened.remove(aId)).toEqual({ ok: true, value: true }) - expect(newStore().getPassword(aId)).toEqual({ ok: false, reason: 'not-found' }) - expect(newStore().remove(aId)).toEqual({ ok: false, reason: 'not-found' }) - }) - - it('refuses a username rename that would collide on the same origin', () => { - const store = newStore() - store.add({ origin: 'https://a.test', username: 'one', password: 'p' }) - const two = store.add({ origin: 'https://a.test', username: 'two', password: 'p' }) - expect(store.updateUsername(two.ok ? two.value.entry.id : '', 'one')).toEqual({ - ok: false, - reason: 'duplicate' - }) - }) - - it('fails closed without writing when the secret store reports a protection gap', () => { - installFakeSecretStore({ gap: 'Linux is storing secrets with basic_text.' }) - const store = newStore() - expect(store.availability()).toEqual({ - available: false, - reason: 'Linux is storing secrets with basic_text.' - }) - expect(store.add({ origin: 'https://a.test', username: 'u', password: 'p' })).toEqual({ - ok: false, - reason: 'unavailable', - message: 'Linux is storing secrets with basic_text.' - }) - expect(store.addNever('https://a.test').ok).toBe(false) - expect(store.importRows([{ origin: 'https://a.test', username: 'u', password: 'p' }]).ok).toBe( - false - ) - expect(existsSync(filePath)).toBe(false) - }) - - it('fails closed when encryption is unavailable', () => { - installFakeSecretStore({ available: false }) - expect(newStore().availability().available).toBe(false) - _resetSecretStoreForTests() - expect(newStore().availability().available).toBe(false) - }) - it('never overwrites a vault it cannot unseal', () => { newStore().add({ origin: 'https://a.test', username: 'u', password: 'p' }) const before = readFileSync(filePath, 'utf8') @@ -230,58 +131,6 @@ describe('BrowserPasswordStore', () => { } ) - it('summarises an import: imported, duplicates, conflicts and invalid rows', () => { - const store = newStore() - store.add({ origin: 'https://a.test', username: 'u', password: 'saved' }) - clock = 9000 - const result = store.importRows([ - { origin: 'https://a.test/login', username: 'u', password: 'saved' }, - { origin: 'https://a.test', username: 'u', password: 'different' }, - { origin: 'https://b.test', username: 'v', password: 'new', createdAt: 500 }, - { origin: 'https://b.test/again', username: 'v', password: 'new' }, - { origin: 'https://b.test', username: 'v', password: 'changed' }, - { origin: 'android://com.example', username: 'x', password: 'p' }, - { origin: 'https://c.test', username: 'x', password: '' }, - { origin: 'https://c.test', username: '', password: 'username-less' } - ]) - expect(result).toEqual({ - ok: true, - value: { imported: 2, duplicates: 2, conflicts: 2, invalid: 2, undecryptable: 0 } - }) - const reopened = newStore() - const entries = reopened.list() - expect(entries.ok && entries.value.map((e) => [e.origin, e.username, e.createdAt])).toEqual([ - ['https://a.test', 'u', 1000], - ['https://b.test', 'v', 500], - ['https://c.test', '', 9000] - ]) - const aId = entries.ok ? entries.value[0].id : '' - expect(reopened.getPassword(aId)).toEqual({ ok: true, value: 'saved' }) - }) - - it('keeps notes sealed apart from the index and drops them with their entry', () => { - const store = newStore() - const added = store.add({ origin: 'https://a.test', username: 'u', password: 'p' }) - const id = added.ok ? added.value.entry.id : '' - expect(store.getNote(id)).toEqual({ ok: true, value: '' }) - store.updateNote(id, 'recovery codes in the safe') - expect(readFileSync(filePath, 'utf8')).not.toContain('recovery codes') - expect(newStore().getNote(id)).toEqual({ ok: true, value: 'recovery codes in the safe' }) - store.updateNote(id, '') - expect(newStore().getNote(id)).toEqual({ ok: true, value: '' }) - store.updateNote(id, 'again') - store.remove(id) - expect(newStore().getNote(id)).toEqual({ ok: true, value: '' }) - }) - - it('imports notes with their rows', () => { - const store = newStore() - store.importRows([{ origin: 'https://n.test', username: 'u', password: 'p', note: 'hi' }]) - const entries = store.list() - const id = entries.ok ? entries.value[0].id : '' - expect(store.getNote(id)).toEqual({ ok: true, value: 'hi' }) - }) - it('refuses a password copied under another entry in the file', () => { const store = newStore() const bank = store.add({ origin: 'https://bank.test', username: 'u', password: 'bank-pw' }) @@ -296,17 +145,4 @@ describe('BrowserPasswordStore', () => { expect(reopened.getPassword(evilId)).toMatchObject({ ok: false, reason: 'unavailable' }) expect(reopened.getPassword(bankId)).toEqual({ ok: true, value: 'bank-pw' }) }) - - it('deletes the vault file', () => { - const store = newStore() - store.add({ origin: 'https://a.test', username: 'u', password: 'p' }) - expect(store.deleteFile()).toEqual({ ok: true, value: true }) - expect(existsSync(filePath)).toBe(false) - expect(store.list()).toMatchObject({ ok: false, reason: 'unavailable' }) - expect( - store.importRows([{ origin: 'https://late.test', username: 'u', password: 'p' }]) - ).toMatchObject({ ok: false, reason: 'unavailable' }) - expect(existsSync(filePath)).toBe(false) - expect(newStore().list()).toEqual({ ok: true, value: [] }) - }) }) diff --git a/src/main/browser-passwords/browser-password-vaults.test.ts b/src/main/browser-passwords/browser-password-vaults.test.ts index 4b8ef6b3de2..59e5d60befd 100644 --- a/src/main/browser-passwords/browser-password-vaults.test.ts +++ b/src/main/browser-passwords/browser-password-vaults.test.ts @@ -29,16 +29,6 @@ describe('deleteBrowserPasswordVault', () => { rmSync(dir, { recursive: true, force: true }) }) - it('deletes the file and forgets the cached vault', () => { - getBrowserPasswordVault('default').add({ - origin: 'https://a.test', - username: 'u', - password: 'p' - }) - expect(deleteBrowserPasswordVault('default')).toEqual({ ok: true, value: true }) - expect(getBrowserPasswordVault('default').list()).toEqual({ ok: true, value: [] }) - }) - it('deletes the captured vault after an Orca profile switch without touching its replacement', () => { const original = getBrowserPasswordVault('default') original.add({ origin: 'https://a.test', username: 'original', password: 'p' }) diff --git a/src/main/browser/agent-browser/agent-browser-bridge-capture-paint-hold.test.ts b/src/main/browser/agent-browser/agent-browser-bridge-capture-paint-hold.test.ts deleted file mode 100644 index 74d2d54dd5b..00000000000 --- a/src/main/browser/agent-browser/agent-browser-bridge-capture-paint-hold.test.ts +++ /dev/null @@ -1,243 +0,0 @@ -import type * as BrowserErrorTypes from '../browser-error' -import { describe, it, expect, vi, beforeEach } from 'vitest' - -const { execFileMock, webContentsFromIdMock, existsSyncMock, readFileSyncMock, stdinWrites } = - vi.hoisted(() => ({ - execFileMock: vi.fn(), - webContentsFromIdMock: vi.fn(), - existsSyncMock: vi.fn(() => false), - readFileSyncMock: vi.fn(() => Buffer.from('')), - stdinWrites: [] as string[] - })) - -vi.mock('child_process', () => ({ execFile: execFileMock })) -vi.mock('fs', () => ({ - existsSync: existsSyncMock, - readFileSync: readFileSyncMock, - accessSync: vi.fn(), - chmodSync: vi.fn(), - constants: { X_OK: 1 } -})) -vi.mock('os', () => ({ platform: () => 'darwin', arch: () => 'arm64' })) -vi.mock('electron', () => { - return { - app: { getPath: vi.fn(() => '/app'), getAppPath: vi.fn(() => '/project'), isPackaged: false }, - webContents: { fromId: webContentsFromIdMock } - } -}) -const { CdpWsProxyMock } = vi.hoisted(() => { - const instances: unknown[] = [] - const MockClass = vi.fn().mockImplementation(function ( - this: Record, - _wc: unknown - ) { - this._wc = _wc - this.start = vi.fn(async () => 'ws://127.0.0.1:9222') - this.stop = vi.fn(async () => {}) - this.getPort = vi.fn(() => 9222) - instances.push(this) - }) - return { CdpWsProxyMock: Object.assign(MockClass, { instances }) } -}) - -vi.mock('../cdp/transport/cdp-ws-proxy', () => ({ - CdpWsProxy: CdpWsProxyMock -})) -vi.mock('../browser-error', () => ({ - BrowserError: class BrowserError extends Error { - code: string - constructor(code: string, message: string) { - super(message) - this.code = code - } - } -})) - -vi.mock('../cdp/commands/cdp-bridge', async () => { - const { BrowserError } = await vi.importMock('../browser-error') - return { BrowserError } -}) - -import { AgentBrowserBridge } from './agent-browser-bridge' -import { - createSucceedWith, - mockBrowserManager, - mockWebContents, - overrideBridgeWebContentsLookup, - resetAgentBrowserBridgeMocks, - type ExecFileCallback -} from './agent-browser-bridge-test-harness' - -overrideBridgeWebContentsLookup(AgentBrowserBridge.prototype, webContentsFromIdMock) - -const succeedWith = createSucceedWith(execFileMock, stdinWrites) - -describe('AgentBrowserBridge', () => { - let bridge: AgentBrowserBridge - - beforeEach(() => { - resetAgentBrowserBridgeMocks({ - webContentsFromIdMock, - existsSyncMock, - readFileSyncMock, - stdinWrites, - cdpWsProxyInstances: CdpWsProxyMock.instances - }) - bridge = new AgentBrowserBridge(mockBrowserManager()) - bridge.setActiveTab(100) - }) - - it('holds only the guest, never paint, for commands that do not capture pixels', async () => { - const releases: ReturnType[] = [] - const holdGuestActive = vi.fn(() => { - const release = vi.fn() - releases.push(release) - return release - }) - const holdPaintForCapture = vi.fn(() => () => {}) - const printToPDF = vi.fn(async () => Buffer.from('pdf')) - const b = new AgentBrowserBridge( - mockBrowserManager(undefined, undefined, { holdGuestActive, holdPaintForCapture }) - ) - b.setActiveTab(100) - webContentsFromIdMock.mockReturnValue({ ...mockWebContents(100), printToPDF }) - - succeedWith({ snapshot: 'tree' }) - await b.snapshot() - await b.click('@e1') - await b.mouseClick(10, 20) - await b.exec('get title') - await expect(b.pdf()).resolves.toEqual({ data: Buffer.from('pdf').toString('base64') }) - - expect(holdPaintForCapture).not.toHaveBeenCalled() - expect(holdGuestActive.mock.calls).toEqual([[100], [100], [100], [100], [100]]) - expect(releases.map((release) => release.mock.calls.length)).toEqual([1, 1, 1, 1, 1]) - }) - - it('holds only executing commands and resolves a queued command against the replacement guest', async () => { - const tabs = new Map([['tab-1', 100]]) - const holds: number[] = [] - const released: number[] = [] - const b = new AgentBrowserBridge( - mockBrowserManager(tabs, undefined, { - holdGuestActive: (id) => { - holds.push(id) - return () => released.push(id) - } - }) - ) - const oldGuest = mockWebContents(100) - const replacement = mockWebContents(200) - let finish = (_value: unknown): void => {} - oldGuest.debugger.sendCommand.mockImplementation( - () => new Promise((resolve) => (finish = resolve)) - ) - replacement.debugger.sendCommand.mockResolvedValue({ result: { value: 'replacement' } }) - webContentsFromIdMock.mockImplementation((id: number) => (id === 100 ? oldGuest : replacement)) - b.setActiveTab(100) - - const first = b.evaluate('first', undefined, 'tab-1') - const firstResult = expect(first).rejects.toMatchObject({ code: 'browser_tab_changed' }) - const second = b.evaluate('second', undefined, 'tab-1') - const holdsWhileQueued = [...holds] - expect(released).toEqual([]) - tabs.set('tab-1', 200) - finish({ result: { value: 'old' } }) - - await firstResult - await expect(second).resolves.toMatchObject({ result: 'replacement' }) - expect(holdsWhileQueued).toEqual([100]) - expect(holds).toEqual([100, 200]) - expect(released).toEqual([100, 200]) - }) - - it('drops queued commands without acquiring the guest and holds running work until it settles', async () => { - const release = vi.fn() - const holdGuestActive = vi.fn(() => release) - const b = new AgentBrowserBridge(mockBrowserManager(undefined, undefined, { holdGuestActive })) - b.setActiveTab(100) - const guest = mockWebContents(100) - let finish = (_value: unknown): void => {} - guest.debugger.sendCommand.mockImplementation( - () => new Promise((resolve) => (finish = resolve)) - ) - webContentsFromIdMock.mockReturnValue(guest) - - const running = b.evaluate('first') - const queued = b.evaluate('second') - const queuedResult = expect(queued).rejects.toMatchObject({ code: 'browser_tab_closed' }) - await b.onPageClosed('tab-1') - await queuedResult - expect(holdGuestActive.mock.calls).toEqual([[100]]) - expect(release).not.toHaveBeenCalled() - - finish({ result: { value: 'finished' } }) - await running - expect(release).toHaveBeenCalledTimes(1) - }) - - it('releases the background hold when session setup fails', async () => { - const release = vi.fn() - const holdGuestActive = vi.fn(() => release) - const b = new AgentBrowserBridge(mockBrowserManager(undefined, undefined, { holdGuestActive })) - b.setActiveTab(100) - CdpWsProxyMock.mockImplementationOnce(function (this: Record) { - this.start = vi.fn(async () => { - throw new Error('cannot start proxy') - }) - }) - succeedWith(null) - - await expect(b.snapshot()).rejects.toThrow('cannot start proxy') - expect(holdGuestActive).toHaveBeenCalledWith(100) - expect(release).toHaveBeenCalledTimes(1) - }) - - it('captures full-page screenshots directly through CDP using CSS layout bounds', async () => { - const wc = mockWebContents(100) - wc.debugger.sendCommand.mockImplementation((method: string) => { - if (method === 'Page.getLayoutMetrics') { - return Promise.resolve({ - cssContentSize: { width: 600.2, height: 900.4 }, - contentSize: { width: 1200.4, height: 1800.8 } - }) - } - if (method === 'Page.captureScreenshot') { - return Promise.resolve({ data: 'full-cdp-shot' }) - } - return Promise.resolve({}) - }) - webContentsFromIdMock.mockReturnValue(wc) - - execFileMock.mockImplementation( - (_bin: string, _args: string[], _opts: unknown, cb: ExecFileCallback) => { - cb(null, JSON.stringify({ success: true, data: null }), '') - } - ) - - const release = vi.fn() - const holdPaintForCapture = vi.fn(() => release) - const b = new AgentBrowserBridge( - mockBrowserManager(undefined, undefined, { holdPaintForCapture }) - ) - b.setActiveTab(100) - - await expect(b.fullPageScreenshot('png')).resolves.toEqual({ - data: 'full-cdp-shot', - format: 'png' - }) - - expect(wc.debugger.sendCommand).toHaveBeenNthCalledWith(1, 'Page.getLayoutMetrics', {}) - expect(wc.debugger.sendCommand).toHaveBeenNthCalledWith(2, 'Page.captureScreenshot', { - format: 'png', - captureBeyondViewport: true, - clip: { x: 0, y: 0, width: 601, height: 901, scale: 1 } - }) - expect(holdPaintForCapture).toHaveBeenCalledWith(100) - expect(release).toHaveBeenCalledTimes(1) - const screenshotCall = execFileMock.mock.calls.find((call: unknown[]) => - (call[1] as string[]).includes('screenshot') - ) - expect(screenshotCall).toBeUndefined() - }) -}) diff --git a/src/main/browser/agent-browser/agent-browser-bridge-command-transport.test.ts b/src/main/browser/agent-browser/agent-browser-bridge-command-transport.test.ts deleted file mode 100644 index 5fa2a3fe1a5..00000000000 --- a/src/main/browser/agent-browser/agent-browser-bridge-command-transport.test.ts +++ /dev/null @@ -1,381 +0,0 @@ -import type * as BrowserErrorTypes from '../browser-error' -import { describe, it, expect, vi, beforeEach } from 'vitest' - -const { - execFileMock, - webContentsFromIdMock, - existsSyncMock, - readFileSyncMock, - readFileMock, - rmMock, - createFromBufferMock, - stdinWrites -} = vi.hoisted(() => ({ - execFileMock: vi.fn(), - webContentsFromIdMock: vi.fn(), - existsSyncMock: vi.fn(() => false), - readFileSyncMock: vi.fn(() => Buffer.from('')), - readFileMock: vi.fn(), - rmMock: vi.fn(async () => {}), - createFromBufferMock: vi.fn(), - stdinWrites: [] as string[] -})) - -vi.mock('child_process', () => ({ execFile: execFileMock })) -vi.mock('fs', () => ({ - existsSync: existsSyncMock, - readFileSync: readFileSyncMock, - accessSync: vi.fn(), - chmodSync: vi.fn(), - constants: { X_OK: 1 } -})) -vi.mock('fs/promises', () => ({ readFile: readFileMock, rm: rmMock })) -vi.mock('os', () => ({ platform: () => 'darwin', arch: () => 'arm64' })) -vi.mock('electron', () => { - return { - app: { getPath: vi.fn(() => '/app'), getAppPath: vi.fn(() => '/project'), isPackaged: false }, - webContents: { fromId: webContentsFromIdMock }, - nativeImage: { createFromBuffer: createFromBufferMock } - } -}) -const { CdpWsProxyMock } = vi.hoisted(() => { - const instances: unknown[] = [] - const MockClass = vi.fn().mockImplementation(function ( - this: Record, - _wc: unknown - ) { - this._wc = _wc - this.start = vi.fn(async () => 'ws://127.0.0.1:9222') - this.stop = vi.fn(async () => {}) - this.getPort = vi.fn(() => 9222) - instances.push(this) - }) - return { CdpWsProxyMock: Object.assign(MockClass, { instances }) } -}) - -vi.mock('../cdp/transport/cdp-ws-proxy', () => ({ - CdpWsProxy: CdpWsProxyMock -})) -vi.mock('../browser-error', () => ({ - BrowserError: class BrowserError extends Error { - code: string - constructor(code: string, message: string) { - super(message) - this.code = code - } - } -})) - -vi.mock('../cdp/commands/cdp-bridge', async () => { - const { BrowserError } = await vi.importMock('../browser-error') - return { BrowserError } -}) - -import { AgentBrowserBridge } from './agent-browser-bridge' -import { - agentBrowserCommandsIn, - answerAgentBrowserCommands, - createSucceedWith, - mockBrowserManager, - mockWebContents, - overrideBridgeWebContentsLookup, - resetAgentBrowserBridgeMocks, - succeedRecordingAgentBrowserSpawns, - type ExecFileCallback -} from './agent-browser-bridge-test-harness' - -overrideBridgeWebContentsLookup(AgentBrowserBridge.prototype, webContentsFromIdMock) - -const succeedWith = createSucceedWith(execFileMock, stdinWrites) - -function failWith(error: string): void { - execFileMock.mockImplementation( - (_bin: string, _args: string[], _opts: unknown, cb: ExecFileCallback) => { - cb(null, JSON.stringify({ success: false, error }), '') - } - ) -} - -function pngHeader(width: number, height: number): Buffer { - const header = Buffer.alloc(24) - Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]).copy(header) - header.writeUInt32BE(13, 8) - header.write('IHDR', 12, 'ascii') - header.writeUInt32BE(width, 16) - header.writeUInt32BE(height, 20) - return header -} - -const CDP_DISCOVERY_FAILURE = - 'Auto-launch failed: All CDP discovery methods failed: connect ECONNREFUSED 127.0.0.1:9222; WebSocket connect failed' - -describe('AgentBrowserBridge', () => { - let bridge: AgentBrowserBridge - - beforeEach(() => { - resetAgentBrowserBridgeMocks({ - webContentsFromIdMock, - existsSyncMock, - readFileSyncMock, - stdinWrites, - cdpWsProxyInstances: CdpWsProxyMock.instances - }) - bridge = new AgentBrowserBridge(mockBrowserManager()) - bridge.setActiveTab(100) - }) - - it('keeps CDP discovery failures generic while the tab session is still live', async () => { - failWith(CDP_DISCOVERY_FAILURE) - await expect(bridge.snapshot()).rejects.toMatchObject({ - code: 'browser_error', - message: CDP_DISCOVERY_FAILURE - }) - }) - - it('maps in-flight CDP discovery failures to tab not found after the session disappears', async () => { - let releaseSnapshot: (() => void) | null = null - answerAgentBrowserCommands(execFileMock, stdinWrites, (command, cb) => { - if (command[0] === 'snapshot') { - releaseSnapshot = () => { - cb(null, JSON.stringify({ success: false, error: CDP_DISCOVERY_FAILURE }), '') - } - return - } - cb(null, JSON.stringify({ success: true, data: null }), '') - }) - - const snapshotPromise = bridge.snapshot() - - await vi.waitFor(() => { - expect(releaseSnapshot).not.toBeNull() - }) - ;(bridge as unknown as { sessions: Map }).sessions.delete('orca-tab-tab-1') - releaseSnapshot!() - - await expect(snapshotPromise).rejects.toMatchObject({ - code: 'browser_tab_not_found', - message: 'Browser page tab-1 is no longer available' - }) - }) - - it('maps target disappearance during session creation to tab not found', async () => { - const wc = mockWebContents(100) - webContentsFromIdMock.mockImplementationOnce(() => wc).mockImplementationOnce(() => null) - - await expect(bridge.snapshot(undefined, 'tab-1')).rejects.toMatchObject({ - code: 'browser_tab_not_found', - message: 'Browser page tab-1 is no longer available' - }) - }) - - it('passes typed snapshot options to agent-browser as its flags', async () => { - const spawns = succeedRecordingAgentBrowserSpawns(execFileMock, stdinWrites, { - snapshot: 'tree' - }) - - await bridge.snapshot(undefined, undefined, { - interactive: true, - compact: true, - depth: 2, - selector: '#main form', - urls: true, - delta: true - }) - - expect(spawns.find(({ command }) => command[0] === 'snapshot')?.command).toEqual([ - 'snapshot', - '-i', - '-c', - '-d', - '2', - '-s', - '#main form', - '-u', - '--delta' - ]) - }) - - it('returns screenshots in CSS pixels and deletes the file agent-browser wrote', async () => { - const wc = mockWebContents(100) - // A 15px classic scrollbar narrows the CSS width; the height still gives the true 2x ratio. - wc.debugger.sendCommand.mockResolvedValue({ - cssVisualViewport: { clientWidth: 785, clientHeight: 600 } - }) - webContentsFromIdMock.mockReturnValue(wc) - const resized = { toPNG: () => Buffer.from('css-png') } - const resize = vi.fn(() => resized) - createFromBufferMock.mockReturnValue({ resize }) - readFileMock.mockResolvedValue(pngHeader(1600, 1200)) - const spawns = succeedRecordingAgentBrowserSpawns(execFileMock, stdinWrites, { - path: '/ab-tmp/shot.png', - changed: true - }) - - await expect(bridge.screenshot({ ifChanged: true })).resolves.toEqual({ - data: Buffer.from('css-png').toString('base64'), - format: 'png', - changed: true - }) - expect(spawns.find(({ command }) => command[0] === 'screenshot')?.command).toEqual([ - 'screenshot', - expect.stringMatching(/^\/app\/orca-screenshot-[\w-]+\.png$/), - '--if-changed', - '--screenshot-format', - 'png' - ]) - expect(resize).toHaveBeenCalledWith({ width: 800, quality: 'best' }) - expect(rmMock).toHaveBeenCalledWith('/ab-tmp/shot.png', { force: true }) - }) - - it('strips --cdp and --session from exec commands', async () => { - succeedWith({ output: 'ok' }) - await bridge.exec( - 'dblclick @e3 --cdp ws://evil --session hijack --cdp=ws://evil-equals --session=hijack-equals' - ) - - const execCall = execFileMock.mock.calls.find((c: unknown[]) => - (c[1] as string[]).includes('dblclick') - ) - const args = execCall![1] as string[] - expect(args.join(' ')).not.toContain('ws://evil') - expect(args.join(' ')).not.toContain('ws://evil-equals') - expect(args.join(' ')).not.toContain('hijack') - expect(args.join(' ')).not.toContain('hijack-equals') - expect(args).toContain('dblclick') - expect(args).toContain('@e3') - }) - - it('returns browser_timeout for timed conditional waits without recycling the session', async () => { - const killedError = Object.assign(new Error('timeout'), { killed: true }) - answerAgentBrowserCommands(execFileMock, stdinWrites, (command, cb) => { - if (command[0] === 'wait') { - cb(killedError, '', '') - return - } - cb(null, JSON.stringify({ success: true, data: { snapshot: 'fresh' } }), '') - }) - - for (let i = 0; i < 3; i++) { - await expect(bridge.wait({ selector: '.missing', timeout: 1200 })).rejects.toThrow( - 'Timed out waiting for browser condition after 1200ms.' - ) - } - - await bridge.snapshot() - - expect(CdpWsProxyMock.instances).toHaveLength(1) - }) - - it('passes stderr through as error message on execFile failure', async () => { - execFileMock.mockImplementation( - (_bin: string, args: string[], _opts: unknown, cb: ExecFileCallback) => { - if (args.includes('close')) { - cb(null, JSON.stringify({ success: true, data: null }), '') - return - } - cb(new Error('exit code 1'), '', 'daemon crashed: segfault') - } - ) - await expect(bridge.snapshot()).rejects.toThrow('daemon crashed: segfault') - }) - - it('falls back to error.message when stderr is empty', async () => { - execFileMock.mockImplementation( - (_bin: string, args: string[], _opts: unknown, cb: ExecFileCallback) => { - if (args.includes('close')) { - cb(null, JSON.stringify({ success: true, data: null }), '') - return - } - cb(new Error('Command failed'), '', '') - } - ) - await expect(bridge.snapshot()).rejects.toThrow('Command failed') - }) - - it('drops the daemon lifecycle agent-browser adds to every result', async () => { - // Real agent-browser 0.39.4 batch reply. - const reply = - '[{"command":["click","@e2"],"error":null,"result":{"clicked":"@e2","lifecycle":{"effectiveLaunch":{"browserLaunched":true,"engine":"chrome","launchHash":520248349195465926},"launched":false,"relaunchedBrowser":false,"restartedBackground":false,"restoreStatus":"not_configured","reused":true,"saveStatus":"not_attempted"}},"success":true}]' - answerAgentBrowserCommands(execFileMock, stdinWrites, (_command, cb) => cb(null, reply, '')) - await expect(bridge.click('@e2')).resolves.toEqual({ clicked: '@e2' }) - }) - - it('returns every step of a passthrough batch, including one that failed', async () => { - // Real agent-browser 0.39.4 reply; it exits 1 because a step failed. - const reply = - '[{"command":["get","title"],"error":null,"result":{"title":"Login","lifecycle":{"reused":true}},"success":true},{"command":["click","@e999"],"error":"Unknown ref: e999","result":null,"success":false}]' - answerAgentBrowserCommands(execFileMock, stdinWrites, (command, cb) => - command[0] === 'batch' ? cb(new Error('Command failed'), reply, '') : cb(null, '{}', '') - ) - await expect(bridge.exec('batch "get title" "click @e999"')).resolves.toEqual([ - { command: ['get', 'title'], error: null, result: { title: 'Login' }, success: true }, - { command: ['click', '@e999'], error: 'Unknown ref: e999', result: null, success: false } - ]) - }) - - it('returns a passthrough batch that stopped at its first step as that step', async () => { - // `batch --bail` whose first step fails replies with one entry, like Orca's own batches. - const reply = - '[{"command":["click","@e999"],"error":"Unknown ref: e999","result":null,"success":false}]' - answerAgentBrowserCommands(execFileMock, stdinWrites, (command, cb) => - command[0] === 'batch' ? cb(new Error('Command failed'), reply, '') : cb(null, '{}', '') - ) - await expect(bridge.exec('batch --bail "click @e999" "get url"')).resolves.toEqual([ - { command: ['click', '@e999'], error: 'Unknown ref: e999', result: null, success: false } - ]) - }) - - it('ends stdin for passthrough commands so a bare batch does not wait for input', async () => { - // Real agent-browser 0.39.4 reply to a batch whose stdin closed empty. - const reply = - '{"error":"Invalid JSON input: EOF while parsing a value at line 1 column 0.","success":false}' - answerAgentBrowserCommands(execFileMock, stdinWrites, (command, cb) => - command[0] === 'batch' ? cb(new Error('Command failed'), reply, '') : cb(null, '{}', '') - ) - await expect(bridge.exec('batch')).rejects.toThrow('Invalid JSON input') - }) - - it("adds effects to an agent's click and costs a person's click nothing extra", async () => { - webContentsFromIdMock.mockReturnValue(mockWebContents(100)) - answerAgentBrowserCommands(execFileMock, stdinWrites, (command, cb) => { - const data = - command[0] === 'snapshot' - ? { snapshot: { kind: 'unchanged', baseRevision: 1, revision: 2 } } - : { clicked: '@e2' } - cb(null, JSON.stringify({ success: true, data }), '') - }) - - await expect(bridge.click('@e2')).resolves.toEqual({ clicked: '@e2' }) - expect(agentBrowserCommandsIn(stdinWrites)).toEqual([['click', '@e2']]) - - const agentBridge = new AgentBrowserBridge( - mockBrowserManager(undefined, undefined, { - beginAgentCommand: () => ({ agent: true, run: (execute) => execute(), end: () => {} }), - observePageEvents: () => () => {} - }) - ) - agentBridge.setActiveTab(100) - await expect(agentBridge.click('@e2')).resolves.toMatchObject({ - clicked: '@e2', - effects: { page: 'unchanged' } - }) - }) - - // agent-browser 0.39.2+ wording when it cannot re-resolve a ref by role and name. - it.each([ - 'Stale ref for role=button name=Approve cannot be recovered: several elements now match. Run snapshot again and use a fresh ref.', - 'Could not locate element with role=link name=Back to basic' - ])('reports a ref whose element is gone as stale: %s', async (message) => { - failWith(message) - await expect(bridge.click('@e2')).rejects.toMatchObject({ code: 'browser_stale_ref' }) - }) - - it('returns browser_error with truncated output for malformed JSON', async () => { - execFileMock.mockImplementation( - (_bin: string, _args: string[], _opts: unknown, cb: ExecFileCallback) => { - cb(null, 'Error: not json output', '') - } - ) - await expect(bridge.snapshot()).rejects.toThrow('Unexpected output from agent-browser') - }) -}) diff --git a/src/main/browser/agent-browser/agent-browser-bridge-expected-url.test.ts b/src/main/browser/agent-browser/agent-browser-bridge-expected-url.test.ts index b15fdf6d814..05eb1ebbfc7 100644 --- a/src/main/browser/agent-browser/agent-browser-bridge-expected-url.test.ts +++ b/src/main/browser/agent-browser/agent-browser-bridge-expected-url.test.ts @@ -36,8 +36,6 @@ const { CdpWsProxyMock } = vi.hoisted(() => { return { CdpWsProxyMock: Object.assign(MockClass, { instances }) } }) vi.mock('../cdp/transport/cdp-ws-proxy', () => ({ CdpWsProxy: CdpWsProxyMock })) - -import { isRecord } from '../../../shared/agent-status/child-work/agent-status-child-work-value-guards' import { runInRemoteCliBrowserScope } from '../../runtime/desktop-browser-bridge/remote-cli-browser-scope' import { runWithRequestedPageUrl } from '../cdp/input/browser-expected-page-url' import { AgentBrowserBridge } from './agent-browser-bridge' @@ -56,9 +54,6 @@ overrideBridgeWebContentsLookup(AgentBrowserBridge.prototype, webContentsFromIdM const A = 'https://chat.example/chat/a' const B = 'https://chat.example/chat/b' -const PAGE = 'tab-1' - -const keyOf = (params: unknown): unknown => (isRecord(params) ? params.key : undefined) const expecting = (url: string, run: () => T): T => runWithRequestedPageUrl({ expectUrl: url }, run) @@ -117,51 +112,6 @@ describe('commands that expect a page URL', () => { bridge = makeBridge() }) - it('refuses a same-origin route it was not meant for, with nothing sent to the page', async () => { - url = B - - await expect(expecting(A, () => bridge.click('@e3'))).rejects.toMatchObject({ - code: 'browser_expected_url_mismatch', - data: { expectedUrl: A, actualUrl: B, browserPageId: PAGE, mayHaveStarted: false } - }) - - expect(commands.filter(([name]) => name === 'click')).toEqual([]) - }) - - it('acts on the expected URL and names the page and URL it checked', async () => { - await expect(expecting(A, () => bridge.click('@e3'))).resolves.toMatchObject({ - browserPageId: PAGE, - checkedUrl: A - }) - - expect(commands).toContainEqual(['click', '@e3']) - }) - - it('leaves a command without an expected URL unchecked and its result unchanged', async () => { - url = B - - await expect(bridge.click('@e3')).resolves.toEqual({}) - - expect(commands).toContainEqual(['click', '@e3']) - }) - - it('checks when its turn comes, not when it was asked', async () => { - const finishAhead = holdHover() - const ahead = bridge.hover('@e1') - await vi.waitFor(() => expect(commands).toContainEqual(['hover', '@e1'])) - - const queued = expecting(A, () => bridge.click('@e3')) - url = B - finishAhead() - - await expect(ahead).resolves.toBeDefined() - await expect(queued).rejects.toMatchObject({ - code: 'browser_expected_url_mismatch', - data: { actualUrl: B, mayHaveStarted: false } - }) - expect(commands).not.toContainEqual(['click', '@e3']) - }) - it('keeps each queued command to its own expected URL', async () => { const finishAhead = holdHover() // This caller's scope is the one the queue keeps running under for everything behind it. @@ -181,152 +131,6 @@ describe('commands that expect a page URL', () => { expect(commands).not.toContainEqual(['click', '@elsewhere']) }) - it('checks the guest that replaced the page while the command waited', async () => { - const finishAhead = holdHover() - const tabs = new Map([[PAGE, 100]]) - bridge = new AgentBrowserBridge( - mockBrowserManager(tabs, undefined, { getInFlightNavigationUrl: () => null }) - ) - bridge.setActiveTab(100) - webContentsFromIdMock.mockImplementation((id: number) => - id === 200 ? mockWebContents(200, B) : guest - ) - const ahead = bridge.hover('@e1', undefined, PAGE) - await vi.waitFor(() => expect(commands).toContainEqual(['hover', '@e1'])) - - const queued = expecting(A, () => bridge.goto(B, undefined, PAGE)) - tabs.set(PAGE, 200) - finishAhead() - - await ahead - await expect(queued).rejects.toMatchObject({ - code: 'browser_expected_url_mismatch', - data: { actualUrl: B } - }) - }) - - it('fails as a closed page when the page goes away while the command waits', async () => { - const finishAhead = holdHover() - const ahead = bridge.hover('@e1') - await vi.waitFor(() => expect(commands).toContainEqual(['hover', '@e1'])) - - const queued = expecting(A, () => bridge.click('@e3')) - webContentsFromIdMock.mockReturnValue(null) - finishAhead() - - await ahead.catch(() => undefined) - await expect(queued).rejects.toMatchObject({ code: 'browser_tab_not_found' }) - expect(commands).not.toContainEqual(['click', '@e3']) - }) - - it('refuses while the document is being replaced by a navigation elsewhere', async () => { - inFlightUrl = B - - await expect(expecting(A, () => bridge.click('@e3'))).rejects.toMatchObject({ - data: { expectedUrl: A, actualUrl: B, mayHaveStarted: false } - }) - expect(commands).not.toContainEqual(['click', '@e3']) - }) - - it('refuses while the outgoing document is still up on the way to the expected URL', async () => { - url = B - inFlightUrl = A - - await expect(expecting(A, () => bridge.click('@e3'))).rejects.toMatchObject({ - data: { actualUrl: B } - }) - }) - - it('rechecks between a fill reading its element and writing to it', async () => { - const send = vi.spyOn(guest.debugger, 'sendCommand') - answer = (command, cb) => { - if (command[0] === 'get') { - url = B - } - cb(null, JSON.stringify({ success: true, data: {} }), '') - } - - await expect(expecting(A, () => bridge.fill('@e2', 'reply'))).rejects.toMatchObject({ - code: 'browser_expected_url_mismatch', - data: { actualUrl: B, mayHaveStarted: true } - }) - expect(send.mock.calls.filter(([method]) => method === 'Runtime.callFunctionOn')).toEqual([]) - }) - - it('rechecks between typed runs, so keys after a navigating Enter never land', async () => { - guest.debugger.sendCommand.mockImplementation(async (method, params) => { - if (method === 'Input.dispatchKeyEvent' && keyOf(params) === 'Enter') { - url = B - } - return {} - }) - - await expect(expecting(A, () => bridge.type('one\ntwo'))).rejects.toMatchObject({ - data: { actualUrl: B, mayHaveStarted: true } - }) - - const keys = guest.debugger.sendCommand.mock.calls - .filter(([method]) => method === 'Input.dispatchKeyEvent') - .map(([, params]) => keyOf(params)) - expect(keys).toContain('Enter') - expect(keys).not.toContain('t') - }) - - it('rechecks after finding where a guest’s keys go, right before they are sent', async () => { - guest.getType.mockReturnValue('webview') - guest.debugger.sendCommand.mockImplementation(async () => { - url = B - return {} - }) - - await expect(expecting(A, () => bridge.keypress('Enter'))).rejects.toMatchObject({ - data: { actualUrl: B, mayHaveStarted: false } - }) - - expect(guest.sendInputEvent).not.toHaveBeenCalled() - expect( - guest.debugger.sendCommand.mock.calls.filter( - ([method]) => method === 'Input.dispatchKeyEvent' - ) - ).toEqual([]) - }) - - it('stops inserting chunks once the route moves', async () => { - answer = (command, cb) => { - if (command[1] === 'inserttext') { - url = B - } - cb(null, JSON.stringify({ success: true, data: {} }), '') - } - - await expect( - expecting(A, () => bridge.keyboardInsertText('x'.repeat(9000))) - ).rejects.toMatchObject({ data: { actualUrl: B, mayHaveStarted: true } }) - - expect(commands.filter(([, sub]) => sub === 'inserttext')).toHaveLength(1) - }) - - it('reads what a navigating action caused after its own check has passed', async () => { - bridge = makeBridge({ - beginAgentCommand: () => ({ - agent: true, - run: (execute: () => Promise) => execute(), - end: () => {} - }), - observePageEvents: () => () => {} - }) - answer = (command, cb) => { - if (command[0] === 'click') { - url = B - } - cb(null, JSON.stringify({ success: true, data: { kind: 'delta', tree: 'changed' } }), '') - } - - const result = await expecting(A, () => bridge.click('@e3')) - - expect(result).toMatchObject({ browserPageId: PAGE, checkedUrl: A, effects: { url: B } }) - }) - it('does not tell an SSH host the URL of a page that moved somewhere it may not drive', async () => { const SECRET = 'file:///Users/me/secret.pdf' // The last await before the input goes out. @@ -347,13 +151,4 @@ describe('commands that expect a page URL', () => { expect(JSON.stringify(failure)).not.toContain('secret') expect(String(failure)).not.toContain('secret') }) - - it('checks a dialog answer before it reaches the page', async () => { - url = B - - await expect(expecting(A, () => bridge.dialogAccept())).rejects.toMatchObject({ - code: 'browser_expected_url_mismatch', - data: { actualUrl: B } - }) - }) }) diff --git a/src/main/browser/agent-browser/agent-browser-bridge-host-revocation.test.ts b/src/main/browser/agent-browser/agent-browser-bridge-host-revocation.test.ts index f9712b67a4f..4475116ab00 100644 --- a/src/main/browser/agent-browser/agent-browser-bridge-host-revocation.test.ts +++ b/src/main/browser/agent-browser/agent-browser-bridge-host-revocation.test.ts @@ -39,33 +39,18 @@ const { CdpWsProxyMock } = vi.hoisted(() => { vi.mock('../cdp/transport/cdp-ws-proxy', () => ({ CdpWsProxy: CdpWsProxyMock })) import { AgentBrowserBridge } from './agent-browser-bridge' +import { runInRemoteCliBrowserScope } from '../../runtime/desktop-browser-bridge/remote-cli-browser-scope' import { - captureRemoteCliBrowserScope, - runInRemoteCliBrowserScope -} from '../../runtime/desktop-browser-bridge/remote-cli-browser-scope' -import { - assertRemoteCliPageAccess, - runUnderRemoteCliPageAdmission -} from '../routing/input-ownership/remote-cli-page-admission' -import { - answerAgentBrowserCommands, - createFakeAgentBrowserChild, mockBrowserManager, mockWebContents, overrideBridgeWebContentsLookup, - resetAgentBrowserBridgeMocks, - type ExecFileCallback + resetAgentBrowserBridgeMocks } from './agent-browser-bridge-test-harness' overrideBridgeWebContentsLookup(AgentBrowserBridge.prototype, webContentsFromIdMock) const WORKSPACE = 'repo-host::/srv/app' -/** Simulate a helper CDP step at the page proxy. */ -function assertHelperStepAdmitted(): void { - runUnderRemoteCliPageAdmission(100, () => assertRemoteCliPageAccess(100)) -} - function dispatchedMouseEvents(wc: ReturnType): unknown[] { return wc.debugger.sendCommand.mock.calls.filter((call) => call[0] === 'Input.dispatchMouseEvent') } @@ -85,122 +70,6 @@ describe('AgentBrowserBridge under a host revocation', () => { bridge.setActiveTab(100) }) - it('stops a long type at the next run once the host is revoked', async () => { - const wc = mockWebContents(100) - wc.getType.mockReturnValue('webview') - let resumeTyping = (): void => {} - const paused = new Promise((resolve) => { - resumeTyping = resolve - }) - let evaluations = 0 - wc.debugger.sendCommand.mockImplementation(async (method: string) => { - if (method === 'Runtime.evaluate') { - evaluations += 1 - // The first run's settle wait: hold it while the host is revoked. - if (evaluations === 2) { - await paused - } - return { result: { type: 'object', subtype: 'null' } } - } - return {} - }) - webContentsFromIdMock.mockReturnValue(wc) - const revoked = new AbortController() - - const typing = runInRemoteCliBrowserScope( - WORKSPACE, - () => bridge.type('x'.repeat(2000), undefined, 'tab-1'), - revoked.signal - ) - await vi.waitFor(() => expect(evaluations).toBe(2)) - const sentBeforeRevocation = wc.sendInputEvent.mock.calls.length - revoked.abort() - resumeTyping() - - await expect(typing).rejects.toMatchObject({ code: 'desktop_browser_bridge_unavailable' }) - expect(wc.sendInputEvent.mock.calls.length).toBe(sentBeforeRevocation) - }) - - it('never presses the mouse once the host is revoked during a running click', async () => { - const wc = mockWebContents(100) - let answerHitTest = (): void => {} - wc.debugger.sendCommand.mockImplementation(async (method: string) => { - if (method === 'Runtime.evaluate') { - await new Promise((resolve) => { - answerHitTest = resolve - }) - return { result: { value: { x: 10, y: 20, adjusted: false, handled: false } } } - } - return {} - }) - webContentsFromIdMock.mockReturnValue(wc) - const revoked = new AbortController() - - const click = runInRemoteCliBrowserScope( - WORKSPACE, - () => bridge.mouseClick(10, 20, 'left', undefined, 'tab-1', 18), - revoked.signal - ) - await vi.waitFor(() => - expect(wc.debugger.sendCommand).toHaveBeenCalledWith('Runtime.evaluate', expect.anything()) - ) - revoked.abort() - answerHitTest() - - await expect(click).rejects.toMatchObject({ code: 'desktop_browser_bridge_unavailable' }) - expect(dispatchedMouseEvents(wc)).toHaveLength(0) - }) - - it('holds the page against a running helper click once the host is revoked', async () => { - const helperCallbacks: ExecFileCallback[] = [] - answerAgentBrowserCommands(execFileMock, stdinWrites, (command, cb) => { - if (command[0] === 'click') { - helperCallbacks.push(cb) - } else { - cb(null, JSON.stringify({ success: true, data: null }), '') - } - }) - const revoked = new AbortController() - - const click = runInRemoteCliBrowserScope( - WORKSPACE, - () => bridge.click('@e1', undefined, 'tab-1'), - revoked.signal - ) - await vi.waitFor(() => expect(helperCallbacks).toHaveLength(1)) - expect(() => assertHelperStepAdmitted()).not.toThrow() - - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: every instance the hoisted mock constructs has a vi.fn stop. - const proxy = CdpWsProxyMock.instances.at(-1) as { stop: ReturnType } - let heldWhenRetired = false - proxy.stop.mockImplementation(async () => { - try { - assertHelperStepAdmitted() - } catch { - heldWhenRetired = true - } - }) - revoked.abort() - expect(() => assertHelperStepAdmitted()).toThrow('stopped sharing') - await vi.waitFor(() => expect(proxy.stop).toHaveBeenCalled()) - helperCallbacks[0]!( - null, - JSON.stringify({ success: false, error: 'The Orca desktop stopped sharing its browser' }), - '' - ) - - await expect(click).rejects.toMatchObject({ code: 'desktop_browser_bridge_unavailable' }) - expect(() => assertHelperStepAdmitted()).not.toThrow() - // Daemon retirement must precede releasing the page's admission hold. - expect(heldWhenRetired).toBe(true) - expect(execFileMock).toHaveBeenCalledWith( - expect.anything(), - expect.arrayContaining(['close']), - expect.anything(), - expect.anything() - ) - }) - it('still runs a desktop-local command queued behind a host command that was revoked', async () => { const wc = mockWebContents(100) let answerHitTest = (): void => {} @@ -236,78 +105,6 @@ describe('AgentBrowserBridge under a host revocation', () => { ]) }) - it('never hit-tests (which can activate the element) once revoked during the focus wait', async () => { - let grantFocus = (): void => {} - const release = vi.fn() - const guardUserFocusForAgentInput = vi.fn( - () => - new Promise<() => void>((resolve) => { - grantFocus = () => resolve(release) - }) - ) - bridge = new AgentBrowserBridge( - mockBrowserManager(undefined, undefined, { guardUserFocusForAgentInput }) - ) - bridge.setActiveTab(100) - const wc = mockWebContents(100) - wc.getType.mockReturnValue('webview') - wc.debugger.sendCommand.mockResolvedValue({}) - webContentsFromIdMock.mockReturnValue(wc) - const revoked = new AbortController() - - const click = runInRemoteCliBrowserScope( - WORKSPACE, - () => bridge.mouseClick(10, 20, 'left', undefined, 'tab-1', 18), - revoked.signal - ) - await vi.waitFor(() => expect(guardUserFocusForAgentInput).toHaveBeenCalled()) - revoked.abort() - grantFocus() - - await expect(click).rejects.toMatchObject({ code: 'desktop_browser_bridge_unavailable' }) - // Only the read-only first-paint probe, sent before the focus wait, may reach the page. - expect(wc.debugger.sendCommand).not.toHaveBeenCalledWith( - 'Runtime.evaluate', - expect.not.objectContaining({ - expression: expect.stringContaining("getEntriesByType('paint')") - }) - ) - expect(dispatchedMouseEvents(wc)).toHaveLength(0) - expect(release).toHaveBeenCalled() - }) - - it('lets go off the page of a press that landed just before the host was revoked', async () => { - const wc = mockWebContents(100) - const revoked = new AbortController() - wc.debugger.sendCommand.mockImplementation(async (method: string, params?: unknown) => { - if (method === 'Runtime.evaluate') { - return { result: { value: { x: 10, y: 20, adjusted: false, handled: false } } } - } - if ( - typeof params === 'object' && - params !== null && - 'type' in params && - params.type === 'mousePressed' - ) { - revoked.abort() - } - return {} - }) - webContentsFromIdMock.mockReturnValue(wc) - - const click = runInRemoteCliBrowserScope( - WORKSPACE, - () => bridge.mouseClick(10, 20, 'left', undefined, 'tab-1', 18), - revoked.signal - ) - - await expect(click).rejects.toMatchObject({ code: 'desktop_browser_bridge_unavailable' }) - expect(dispatchedMouseEvents(wc)).toEqual([ - ['Input.dispatchMouseEvent', expect.objectContaining({ type: 'mousePressed', x: 10 })], - ['Input.dispatchMouseEvent', expect.objectContaining({ type: 'mouseReleased', x: -1, y: -1 })] - ]) - }) - describe('a press a finished host command left held', () => { function hostCommand( host: AbortController, @@ -348,206 +145,5 @@ describe('AgentBrowserBridge under a host revocation', () => { expect.objectContaining({ type: 'mouseReleased', x: -1, y: -1, button: 'left' }) ]) }) - - it('is not let go of again once a later command of that host released it', async () => { - const wc = mockWebContents(100) - wc.debugger.sendCommand.mockResolvedValue({}) - webContentsFromIdMock.mockReturnValue(wc) - const host = new AbortController() - - await hostCommand(host, () => bridge.mouseDown('left', undefined, 'tab-1')) - await hostCommand(host, () => bridge.mouseUp('left', undefined, 'tab-1')) - host.abort() - await Promise.resolve() - - expect(mouseTypes(wc)).toEqual(['mousePressed', 'mouseReleased']) - }) - - it("survives a later command's own cancel, and goes when the host does", async () => { - const wc = mockWebContents(100) - wc.debugger.sendCommand.mockResolvedValue({}) - webContentsFromIdMock.mockReturnValue(wc) - const host = new AbortController() - await hostCommand(host, () => bridge.mouseDown('left', undefined, 'tab-1')) - const cancel = new AbortController() - cancel.abort() - - await expect( - hostCommand(host, () => bridge.mouseMove(30, 40, undefined, 'tab-1'), cancel.signal) - ).rejects.toMatchObject({ code: 'desktop_browser_bridge_unavailable' }) - expect(mouseTypes(wc)).toEqual(['mousePressed']) - - host.abort() - await vi.waitFor(() => expect(mouseTypes(wc)).toEqual(['mousePressed', 'mouseReleased'])) - }) - - it("is no longer the host's once the desktop presses that button itself", async () => { - const wc = mockWebContents(100) - wc.debugger.sendCommand.mockResolvedValue({}) - webContentsFromIdMock.mockReturnValue(wc) - const host = new AbortController() - await hostCommand(host, () => bridge.mouseDown('left', undefined, 'tab-1')) - await bridge.mouseUp('left', undefined, 'tab-1') - await bridge.mouseDown('left', undefined, 'tab-1') - - host.abort() - await Promise.resolve() - - expect(mouseTypes(wc)).toEqual(['mousePressed', 'mouseReleased', 'mousePressed']) - }) - - it("lets go in the page's turn, before a desktop press queued after the host ended", async () => { - const wc = mockWebContents(100) - wc.debugger.sendCommand.mockResolvedValue({}) - webContentsFromIdMock.mockReturnValue(wc) - const host = new AbortController() - await hostCommand(host, () => bridge.mouseDown('left', undefined, 'tab-1')) - - host.abort() - await bridge.mouseDown('left', undefined, 'tab-1') - - expect(mouseTypes(wc)).toEqual(['mousePressed', 'mouseReleased', 'mousePressed']) - expect(dispatchedMouseEvents(wc)[2]).toEqual([ - 'Input.dispatchMouseEvent', - expect.objectContaining({ type: 'mousePressed', buttons: 1 }) - ]) - }) - - it("is another host's once that host presses it, and stays down when the first ends", async () => { - const wc = mockWebContents(100) - wc.debugger.sendCommand.mockResolvedValue({}) - webContentsFromIdMock.mockReturnValue(wc) - const first = new AbortController() - const second = new AbortController() - await hostCommand(first, () => bridge.mouseDown('left', undefined, 'tab-1')) - await hostCommand(second, () => bridge.mouseDown('left', undefined, 'tab-1')) - - first.abort() - await bridge.mouseMove(1, 2, undefined, 'tab-1') - expect(mouseTypes(wc)).toEqual(['mousePressed', 'mousePressed']) - - second.abort() - await vi.waitFor(() => expect(mouseTypes(wc)).toHaveLength(3)) - }) - - it('lets go exactly once when the attachment ends during the command that pressed', async () => { - const wc = mockWebContents(100) - const host = new AbortController() - wc.debugger.sendCommand.mockImplementation(async (_method: string, params?: unknown) => { - if (typeof params === 'object' && params !== null && 'type' in params) { - if (params.type === 'mousePressed') { - host.abort() - } - } - return {} - }) - webContentsFromIdMock.mockReturnValue(wc) - - // The press landed before revocation, so the command succeeds. - await hostCommand(host, () => bridge.mouseDown('left', undefined, 'tab-1')) - await bridge.mouseMove(1, 2, undefined, 'tab-1') - - expect(mouseTypes(wc)).toEqual(['mousePressed', 'mouseReleased']) - }) - - it("stays the host's when the desktop's own press of it fails", async () => { - const wc = mockWebContents(100) - wc.debugger.sendCommand.mockResolvedValue({}) - webContentsFromIdMock.mockReturnValue(wc) - const host = new AbortController() - await hostCommand(host, () => bridge.mouseDown('left', undefined, 'tab-1')) - wc.debugger.sendCommand.mockRejectedValueOnce(new Error('page busy')) - await expect(bridge.mouseDown('left', undefined, 'tab-1')).rejects.toThrow() - - host.abort() - - await vi.waitFor(() => - expect(mouseTypes(wc)).toEqual(['mousePressed', 'mousePressed', 'mouseReleased']) - ) - }) - - it('keeps reporting a button the desktop still holds when it lets go of the host one', async () => { - const wc = mockWebContents(100) - wc.debugger.sendCommand.mockResolvedValue({}) - webContentsFromIdMock.mockReturnValue(wc) - const host = new AbortController() - await hostCommand(host, () => bridge.mouseDown('left', undefined, 'tab-1')) - await bridge.mouseDown('right', undefined, 'tab-1') - - host.abort() - - await vi.waitFor(() => expect(mouseTypes(wc)).toHaveLength(3)) - expect(dispatchedMouseEvents(wc)[2]).toEqual([ - 'Input.dispatchMouseEvent', - expect.objectContaining({ type: 'mouseReleased', button: 'left', buttons: 2 }) - ]) - }) - - it('lets go, when the host ends, of a press a later command of it made again', async () => { - const wc = mockWebContents(100) - wc.debugger.sendCommand.mockResolvedValue({}) - webContentsFromIdMock.mockReturnValue(wc) - const host = new AbortController() - await hostCommand(host, () => bridge.mouseDown('left', undefined, 'tab-1')) - await hostCommand(host, () => bridge.mouseUp('left', undefined, 'tab-1')) - await hostCommand(host, () => bridge.mouseDown('left', undefined, 'tab-1')) - - host.abort() - - await vi.waitFor(() => - expect(mouseTypes(wc)).toEqual([ - 'mousePressed', - 'mouseReleased', - 'mousePressed', - 'mouseReleased' - ]) - ) - }) - }) - - it("starts the page's CDP proxy outside the host's scope, so it outlives that host's request", async () => { - let startedInHostScope: boolean | undefined - CdpWsProxyMock.mockImplementationOnce(function (this: Record) { - this.start = vi.fn(async () => { - startedInHostScope = captureRemoteCliBrowserScope().bridged - return 'ws://127.0.0.1:9222' - }) - this.stop = vi.fn(async () => {}) - this.getPort = vi.fn(() => 9222) - CdpWsProxyMock.instances.push(this) - }) - execFileMock.mockImplementation( - (_bin: string, _args: string[], _opts: unknown, cb: ExecFileCallback) => { - cb(null, JSON.stringify({ success: true, data: null }), '') - return createFakeAgentBrowserChild({ stdin: { on: vi.fn(), end: vi.fn() } }) - } - ) - - await runInRemoteCliBrowserScope(WORKSPACE, () => bridge.click('@e1', undefined, 'tab-1')) - - expect(startedInHostScope).toBe(false) - }) - - it('never reports the URL or title of a desktop page a snapshot ended up on', async () => { - let admitted = true - answerAgentBrowserCommands(execFileMock, stdinWrites, (command, cb) => { - if (command[0] === 'snapshot') { - // The page navigates to a desktop-local document while agent-browser answers. - admitted = false - } - cb(null, JSON.stringify({ success: true, data: { snapshot: 'tree' } }), '') - }) - webContentsFromIdMock.mockReturnValue( - mockWebContents(100, 'file:///Users/me/notes.txt', 'notes') - ) - - await expect( - runInRemoteCliBrowserScope( - WORKSPACE, - () => bridge.snapshot(undefined, 'tab-1'), - undefined, - () => admitted - ) - ).rejects.toMatchObject({ code: 'desktop_browser_bridge_unrouted' }) }) }) diff --git a/src/main/browser/agent-browser/agent-browser-bridge-keypress-input.test.ts b/src/main/browser/agent-browser/agent-browser-bridge-keypress-input.test.ts index da67f208439..86924a5931b 100644 --- a/src/main/browser/agent-browser/agent-browser-bridge-keypress-input.test.ts +++ b/src/main/browser/agent-browser/agent-browser-bridge-keypress-input.test.ts @@ -48,7 +48,6 @@ vi.mock('../cdp/transport/cdp-ws-proxy', () => ({ import { AgentBrowserBridge } from './agent-browser-bridge' import { - agentBrowserCommandsIn, createSucceedWith, mockBrowserManager, mockWebContents, @@ -61,21 +60,6 @@ overrideBridgeWebContentsLookup(AgentBrowserBridge.prototype, webContentsFromIdM const succeedWith = createSucceedWith(execFileMock, stdinWrites) -function isRecord(value: unknown): value is Record { - return typeof value === 'object' && value !== null -} - -function isStringArray(value: unknown): value is string[] { - return Array.isArray(value) && value.every((entry) => typeof entry === 'string') -} - -function keyEventCalls(wc: MockWebContents): Record[] { - return wc.debugger.sendCommand.mock.calls - .filter(([method]) => method === 'Input.dispatchKeyEvent') - .map(([, params]) => params) - .filter(isRecord) -} - describe('AgentBrowserBridge keypress input', () => { let bridge: AgentBrowserBridge let wc: MockWebContents @@ -95,234 +79,6 @@ describe('AgentBrowserBridge keypress input', () => { webContentsFromIdMock.mockImplementation((id: number) => (id === 100 ? wc : null)) }) - it('dispatches a printable key over CDP without spawning agent-browser', async () => { - await expect(bridge.keypress('a', undefined, 'tab-1')).resolves.toEqual({ pressed: 'a' }) - - expect(execFileMock).not.toHaveBeenCalled() - expect(CdpWsProxyMock.instances).toHaveLength(0) - expect(wc.debugger.sendCommand.mock.calls).toHaveLength(2) - expect(keyEventCalls(wc)).toEqual([ - { - type: 'keyDown', - windowsVirtualKeyCode: 65, - nativeVirtualKeyCode: 65, - key: 'a', - code: 'KeyA', - modifiers: 0, - location: 0, - text: 'a', - unmodifiedText: 'a' - }, - { - type: 'keyUp', - windowsVirtualKeyCode: 65, - nativeVirtualKeyCode: 65, - key: 'a', - code: 'KeyA', - modifiers: 0, - location: 0 - } - ]) - }) - - it("sends a key to an embedded guest directly so it never lands in the user's focus", async () => { - wc.getType.mockReturnValue('webview') - - await expect(bridge.keypress('Enter', undefined, 'tab-1')).resolves.toEqual({ - pressed: 'Enter' - }) - - expect(wc.focus).not.toHaveBeenCalled() - expect(keyEventCalls(wc)).toEqual([]) - expect(wc.sendInputEvent.mock.calls.map(([event]) => event)).toEqual([ - { type: 'keyDown', keyCode: 'Enter', modifiers: [], skipIfUnhandled: true }, - { type: 'char', keyCode: '\r', modifiers: [], skipIfUnhandled: true }, - { type: 'keyUp', keyCode: 'Enter', modifiers: [], skipIfUnhandled: true } - ]) - }) - - it('types & as shifted 7 instead of colliding with the ArrowUp virtual key code', async () => { - await bridge.keypress('&', undefined, 'tab-1') - - expect(keyEventCalls(wc)[0]).toMatchObject({ - type: 'keyDown', - windowsVirtualKeyCode: 55, - modifiers: 8, - text: '&' - }) - }) - - it('dispatches editing and navigation keys as rawKeyDown with no text', async () => { - await bridge.keypress('ArrowDown', undefined, 'tab-1') - - expect(keyEventCalls(wc)[0]).toMatchObject({ - type: 'rawKeyDown', - windowsVirtualKeyCode: 40, - key: 'ArrowDown' - }) - expect(keyEventCalls(wc)[0]).not.toHaveProperty('text') - }) - - it('carries modifier masks for shortcuts', async () => { - await expect(bridge.keypress('Ctrl+Shift+K', undefined, 'tab-1')).resolves.toEqual({ - pressed: 'Ctrl+Shift+K' - }) - - expect(keyEventCalls(wc)[0]).toMatchObject({ - type: 'rawKeyDown', - windowsVirtualKeyCode: 75, - modifiers: 10 - }) - }) - - it('reports the modifier bit on a bare Shift keydown but not on its keyup', async () => { - await bridge.keypress('Shift', undefined, 'tab-1') - - expect(keyEventCalls(wc)[0]).toMatchObject({ - type: 'rawKeyDown', - windowsVirtualKeyCode: 16, - code: 'ShiftLeft', - modifiers: 8, - location: 1 - }) - expect(keyEventCalls(wc)[1]).toMatchObject({ type: 'keyUp', modifiers: 0, location: 1 }) - }) - - it('keeps held modifiers on the keyup of a non-modifier shortcut key', async () => { - await bridge.keypress('Ctrl+Shift+K', undefined, 'tab-1') - - expect(keyEventCalls(wc)[1]).toMatchObject({ type: 'keyUp', modifiers: 10 }) - }) - - it('presses Enter with its carriage-return text so fields submit', async () => { - await bridge.keypress('Enter', undefined, 'tab-1') - - expect(keyEventCalls(wc)[0]).toMatchObject({ - type: 'keyDown', - windowsVirtualKeyCode: 13, - text: '\r' - }) - }) - - it('dispatches a non-US printable character as an IME-style event in process', async () => { - await expect(bridge.keypress('é', undefined, 'tab-1')).resolves.toEqual({ pressed: 'é' }) - - expect(execFileMock).not.toHaveBeenCalled() - expect(keyEventCalls(wc)[0]).toMatchObject({ - type: 'keyDown', - windowsVirtualKeyCode: 229, - key: 'é', - code: '', - text: 'é', - unmodifiedText: 'é' - }) - expect(keyEventCalls(wc)[1]).toMatchObject({ type: 'keyUp', windowsVirtualKeyCode: 229 }) - }) - - it('falls back to agent-browser for a key name the table cannot express', async () => { - succeedWith({ pressed: 'MediaPlayPause' }) - - await expect(bridge.keypress('MediaPlayPause', undefined, 'tab-1')).resolves.toEqual({ - pressed: 'MediaPlayPause' - }) - - expect(keyEventCalls(wc)).toHaveLength(0) - expect(agentBrowserCommandsIn(stdinWrites)).toContainEqual(['press', 'MediaPlayPause']) - }) - - it('rejects with tab not found when the page is gone', async () => { - webContentsFromIdMock.mockReturnValue(null) - - await expect(bridge.keypress('a', undefined, 'tab-1')).rejects.toMatchObject({ - code: 'browser_tab_not_found' - }) - }) - - // Target resolution and dispatch each look up the page; exhaust lookups to simulate destruction. - function killPageAfterLookups(lookups: number): () => number { - let remaining = lookups - webContentsFromIdMock.mockImplementation((id: number) => { - if (id !== 100 || remaining === 0) { - return null - } - remaining -= 1 - return wc - }) - return () => remaining - } - - it('rejects with tab not found when the page dies after its target is resolved', async () => { - const remaining = killPageAfterLookups(1) - - await expect(bridge.keypress('a', undefined, 'tab-1')).rejects.toMatchObject({ - code: 'browser_tab_not_found' - }) - expect(remaining()).toBe(0) - expect(keyEventCalls(wc)).toHaveLength(0) - }) - - it('rejects with tab not found when the page dies mid-dispatch', async () => { - const remaining = killPageAfterLookups(2) - wc.debugger.sendCommand.mockRejectedValue(new Error('Inspected target navigated or closed')) - - await expect(bridge.keypress('a', undefined, 'tab-1')).rejects.toMatchObject({ - code: 'browser_tab_not_found' - }) - expect(remaining()).toBe(0) - }) - - it('reports a dispatch failure on a live page as a browser error', async () => { - wc.debugger.sendCommand.mockRejectedValue(new Error('Debugger is not attached to the target')) - - await expect(bridge.keypress('a', undefined, 'tab-1')).rejects.toMatchObject({ - code: 'browser_error', - message: expect.stringContaining('Debugger is not attached to the target') - }) - }) - - it('reports a debugger attach failure as a browser error', async () => { - wc.debugger.isAttached.mockReturnValue(false) - wc.debugger.attach.mockImplementation(() => { - throw new Error('Another debugger is already attached to the debug target') - }) - - await expect(bridge.keypress('a', undefined, 'tab-1')).rejects.toMatchObject({ - code: 'browser_error' - }) - expect(keyEventCalls(wc)).toHaveLength(0) - }) - - it('types text as a keydown and keyup per character, which key-driven editors need', async () => { - await expect(bridge.type('Hi\n', undefined, 'tab-1')).resolves.toEqual({ typed: true }) - - expect(execFileMock).not.toHaveBeenCalled() - expect(keyEventCalls(wc).map(({ type, key, text }) => [type, key, text])).toEqual([ - ['keyDown', 'H', 'H'], - ['keyUp', 'H', undefined], - ['keyDown', 'i', 'i'], - ['keyUp', 'i', undefined], - ['keyDown', 'Enter', '\r'], - ['keyUp', 'Enter', undefined] - ]) - }) - - it('inserts characters no key types, in order with the typed ones', async () => { - const order: string[] = [] - wc.debugger.sendCommand.mockImplementation(async (method: string, params: unknown) => { - if (isRecord(params) && params.type === 'keyDown') { - order.push(`key ${String(params.key)}`) - } else if (method === 'Input.insertText' && isRecord(params)) { - order.push(`text ${String(params.text)}`) - } - return {} - }) - - await bridge.type('a😀b', undefined, 'tab-1') - - expect(order).toEqual(['key a', 'text 😀', 'key b']) - expect(execFileMock).not.toHaveBeenCalled() - }) - describe.each(['a', 'MediaPlayPause'])('target admission for %s', (key) => { function registerTwoWorkspaces(): MockWebContents { const otherPage = mockWebContents(200) @@ -346,42 +102,6 @@ describe('AgentBrowserBridge keypress input', () => { return otherPage } - it('rejects unscoped input before dispatch or helper startup across workspaces', async () => { - const otherPage = registerTwoWorkspaces() - succeedWith({ pressed: key }) - - await expect(bridge.keypress(key)).rejects.toMatchObject({ - code: 'browser_target_ambiguous' - }) - - expect(wc.debugger.sendCommand).not.toHaveBeenCalled() - expect(otherPage.debugger.sendCommand).not.toHaveBeenCalled() - expect(execFileMock).not.toHaveBeenCalled() - expect(CdpWsProxyMock.instances).toHaveLength(0) - }) - - it.each([ - { worktreeId: undefined, browserPageId: 'tab-1' }, - { worktreeId: 'workspace-1', browserPageId: undefined } - ])('targets the selected workspace despite another active page: %j', async (target) => { - const otherPage = registerTwoWorkspaces() - succeedWith({ pressed: key }) - - await expect(bridge.keypress(key, target.worktreeId, target.browserPageId)).resolves.toEqual({ - pressed: key - }) - - expect(otherPage.debugger.sendCommand).not.toHaveBeenCalled() - if (key === 'a') { - expect(keyEventCalls(wc)).toHaveLength(2) - expect(execFileMock).not.toHaveBeenCalled() - } else { - const argumentsList = execFileMock.mock.calls.map(([, args]) => args).filter(isStringArray) - expect(argumentsList.some((args) => args.includes('orca-tab-tab-1'))).toBe(true) - expect(argumentsList.some((args) => args.includes('orca-tab-tab-2'))).toBe(false) - } - }) - it('rejects a page belonging to another workspace before input or helper startup', async () => { const otherPage = registerTwoWorkspaces() succeedWith({ pressed: key }) @@ -394,16 +114,5 @@ describe('AgentBrowserBridge keypress input', () => { expect(execFileMock).not.toHaveBeenCalled() expect(CdpWsProxyMock.instances).toHaveLength(0) }) - - it('preserves unscoped input when only one live page is available', async () => { - succeedWith({ pressed: key }) - await expect(bridge.keypress(key)).resolves.toEqual({ pressed: key }) - if (key === 'a') { - expect(keyEventCalls(wc)).toHaveLength(2) - expect(execFileMock).not.toHaveBeenCalled() - } else { - expect(execFileMock).toHaveBeenCalled() - } - }) }) }) diff --git a/src/main/browser/agent-browser/agent-browser-bridge-mouse-input.test.ts b/src/main/browser/agent-browser/agent-browser-bridge-mouse-input.test.ts deleted file mode 100644 index 3bb6596585e..00000000000 --- a/src/main/browser/agent-browser/agent-browser-bridge-mouse-input.test.ts +++ /dev/null @@ -1,260 +0,0 @@ -import type * as BrowserErrorTypes from '../browser-error' -import { describe, it, expect, vi, beforeEach } from 'vitest' - -const { execFileMock, webContentsFromIdMock, existsSyncMock, readFileSyncMock, stdinWrites } = - vi.hoisted(() => ({ - execFileMock: vi.fn(), - webContentsFromIdMock: vi.fn(), - existsSyncMock: vi.fn(() => false), - readFileSyncMock: vi.fn(() => Buffer.from('')), - stdinWrites: [] as string[] - })) - -vi.mock('child_process', () => ({ execFile: execFileMock })) -vi.mock('fs', () => ({ - existsSync: existsSyncMock, - readFileSync: readFileSyncMock, - accessSync: vi.fn(), - chmodSync: vi.fn(), - constants: { X_OK: 1 } -})) -vi.mock('os', () => ({ platform: () => 'darwin', arch: () => 'arm64' })) -vi.mock('electron', () => { - return { - app: { getPath: vi.fn(() => '/app'), getAppPath: vi.fn(() => '/project'), isPackaged: false }, - webContents: { fromId: webContentsFromIdMock } - } -}) -const { CdpWsProxyMock } = vi.hoisted(() => { - const instances: unknown[] = [] - const MockClass = vi.fn().mockImplementation(function ( - this: Record, - _wc: unknown - ) { - this._wc = _wc - this.start = vi.fn(async () => 'ws://127.0.0.1:9222') - this.stop = vi.fn(async () => {}) - this.getPort = vi.fn(() => 9222) - instances.push(this) - }) - return { CdpWsProxyMock: Object.assign(MockClass, { instances }) } -}) - -vi.mock('../cdp/transport/cdp-ws-proxy', () => ({ - CdpWsProxy: CdpWsProxyMock -})) -vi.mock('../browser-error', () => ({ - BrowserError: class BrowserError extends Error { - code: string - constructor(code: string, message: string) { - super(message) - this.code = code - } - } -})) - -vi.mock('../cdp/commands/cdp-bridge', async () => { - const { BrowserError } = await vi.importMock('../browser-error') - return { BrowserError } -}) - -import { AgentBrowserBridge } from './agent-browser-bridge' -import { - createSucceedWith, - mockBrowserManager, - mockWebContents, - overrideBridgeWebContentsLookup, - resetAgentBrowserBridgeMocks -} from './agent-browser-bridge-test-harness' - -overrideBridgeWebContentsLookup(AgentBrowserBridge.prototype, webContentsFromIdMock) - -describe('AgentBrowserBridge', () => { - let bridge: AgentBrowserBridge - - beforeEach(() => { - resetAgentBrowserBridgeMocks({ - webContentsFromIdMock, - existsSyncMock, - readFileSyncMock, - stdinWrites, - cdpWsProxyInstances: CdpWsProxyMock.instances - }) - bridge = new AgentBrowserBridge(mockBrowserManager()) - bridge.setActiveTab(100) - }) - - it('guards the user’s focus instead of focusing an embedded guest on click', async () => { - const release = vi.fn() - const guardUserFocusForAgentInput = vi.fn(async () => release) - bridge = new AgentBrowserBridge( - mockBrowserManager(undefined, undefined, { guardUserFocusForAgentInput }) - ) - bridge.setActiveTab(100) - const wc = mockWebContents(100) - wc.getType.mockReturnValue('webview') - wc.debugger.sendCommand.mockImplementation(async (method: string) => { - if (method === 'Input.dispatchMouseEvent') { - expect(release).not.toHaveBeenCalled() - } - return method === 'Runtime.evaluate' ? { result: { value: null } } : {} - }) - webContentsFromIdMock.mockReturnValue(wc) - - await bridge.mouseClick(10, 20, 'left', undefined, 'tab-1') - - expect(wc.focus).not.toHaveBeenCalled() - expect(guardUserFocusForAgentInput).toHaveBeenCalledWith(100) - expect(release).toHaveBeenCalledTimes(1) - expect( - wc.debugger.sendCommand.mock.calls.filter((call) => call[0] === 'Input.dispatchMouseEvent') - ).toHaveLength(2) - }) - - it('uses the runtime mobile tap path when a nearby DOM target is handled', async () => { - const creditPageInput = vi.fn() - bridge = new AgentBrowserBridge(mockBrowserManager(undefined, undefined, { creditPageInput })) - bridge.setActiveTab(100) - const wc = mockWebContents(100) - wc.debugger.sendCommand.mockImplementation(async (method: string) => { - if (method === 'Runtime.evaluate') { - // The DOM click fires no guest input event; a link it opens must already know who tapped. - expect(creditPageInput).toHaveBeenCalledWith(100) - return { result: { value: { x: 12, y: 34, adjusted: true, handled: true } } } - } - return {} - }) - webContentsFromIdMock.mockReturnValue(wc) - - const result = await bridge.mouseClick(10, 20, 'left', undefined, 'tab-1', 18) - - expect(result).toEqual({ - clicked: { x: 12, y: 34, button: 'left', adjusted: true, handled: true } - }) - expect(wc.debugger.sendCommand).toHaveBeenCalledWith( - 'Runtime.evaluate', - expect.objectContaining({ returnByValue: true, silent: true }) - ) - expect( - wc.debugger.sendCommand.mock.calls.some((call) => call[0] === 'Input.dispatchMouseEvent') - ).toBe(false) - }) - - it('falls back to CDP mouse events when runtime does not handle a mobile tap', async () => { - const wc = mockWebContents(100) - wc.debugger.sendCommand.mockImplementation(async (method: string) => { - if (method === 'Runtime.evaluate') { - return { result: { value: { x: 10, y: 20, adjusted: false, handled: false } } } - } - return {} - }) - webContentsFromIdMock.mockReturnValue(wc) - - await expect(bridge.mouseClick(10, 20, 'left', undefined, 'tab-1', 18)).resolves.toEqual({ - clicked: { x: 10, y: 20, button: 'left', adjusted: false, handled: false } - }) - - const mouseCalls = wc.debugger.sendCommand.mock.calls.filter( - (call) => call[0] === 'Input.dispatchMouseEvent' - ) - expect(mouseCalls).toHaveLength(2) - expect(mouseCalls[0]?.[1]).toMatchObject({ type: 'mousePressed', x: 10, y: 20 }) - expect(mouseCalls[1]?.[1]).toMatchObject({ type: 'mouseReleased', x: 10, y: 20 }) - }) - - it('passes mobile click modifiers through to CDP mouse events', async () => { - const wc = mockWebContents(100) - wc.debugger.sendCommand.mockImplementation(async (method: string) => { - if (method === 'Runtime.evaluate') { - return { result: { value: { x: 10, y: 20, adjusted: false, handled: false } } } - } - return {} - }) - webContentsFromIdMock.mockReturnValue(wc) - - await bridge.mouseClick(10, 20, 'left', undefined, 'tab-1', 18, ['cmd', 'shift']) - - const mouseCalls = wc.debugger.sendCommand.mock.calls.filter( - (call) => call[0] === 'Input.dispatchMouseEvent' - ) - expect(mouseCalls[0]?.[1]).toMatchObject({ type: 'mousePressed', modifiers: 12 }) - expect(mouseCalls[1]?.[1]).toMatchObject({ type: 'mouseReleased', modifiers: 12 }) - }) - - it('keeps adjusted mobile tap coordinates but uses CDP for modifier clicks', async () => { - const wc = mockWebContents(100) - wc.debugger.sendCommand.mockImplementation(async (method: string) => { - if (method === 'Runtime.evaluate') { - return { result: { value: { x: 12, y: 34, adjusted: true, handled: false } } } - } - return {} - }) - webContentsFromIdMock.mockReturnValue(wc) - - await expect( - bridge.mouseClick(10, 20, 'left', undefined, 'tab-1', 18, ['cmd']) - ).resolves.toEqual({ - clicked: { x: 12, y: 34, button: 'left', adjusted: true, handled: false } - }) - - const evaluateCall = wc.debugger.sendCommand.mock.calls.find( - (call) => call[0] === 'Runtime.evaluate' - ) - expect((evaluateCall?.[1] as { expression?: string } | undefined)?.expression).toContain( - 'const allowDomActivation = false' - ) - const mouseCalls = wc.debugger.sendCommand.mock.calls.filter( - (call) => call[0] === 'Input.dispatchMouseEvent' - ) - expect(mouseCalls).toHaveLength(2) - expect(mouseCalls[0]?.[1]).toMatchObject({ type: 'mousePressed', x: 12, y: 34, modifiers: 4 }) - expect(mouseCalls[1]?.[1]).toMatchObject({ type: 'mouseReleased', x: 12, y: 34, modifiers: 4 }) - }) - - function touchEmulationCalls(wc: ReturnType): unknown[] { - return wc.debugger.sendCommand.mock.calls - .filter((call) => call[0] === 'Emulation.setTouchEmulationEnabled') - .map((call) => call[1]) - } - - it('turns on touch for a mobile device, which agent-browser leaves off', async () => { - const wc = mockWebContents(100) - webContentsFromIdMock.mockReturnValue(wc) - createSucceedWith(execFileMock, stdinWrites)({ device: 'iPhone 15', width: 393, mobile: true }) - - await bridge.setDevice('iPhone 15', undefined, 'tab-1') - - expect(touchEmulationCalls(wc)).toEqual([{ enabled: true, maxTouchPoints: 5 }]) - }) - - it('matches touch to the mobile flag of a viewport', async () => { - const wc = mockWebContents(100) - webContentsFromIdMock.mockReturnValue(wc) - - await bridge.setViewport(390, 844, 3, true, undefined, 'tab-1') - await bridge.setViewport(1280, 800, 1, false, undefined, 'tab-1') - - expect(touchEmulationCalls(wc)).toEqual([ - { enabled: true, maxTouchPoints: 5 }, - { enabled: false } - ]) - }) - it("sizes the page's pane to the viewport it sets, so a wider page scrolls instead of being cut off", async () => { - const wc = mockWebContents(100) - webContentsFromIdMock.mockReturnValue(wc) - const showAgentViewportInPane = vi.fn() - bridge = new AgentBrowserBridge( - mockBrowserManager(undefined, undefined, { showAgentViewportInPane }) - ) - bridge.setActiveTab(100) - - await bridge.setViewport(1280, 900, 1, false, undefined, 'tab-1') - - expect(showAgentViewportInPane).toHaveBeenCalledWith(100, { - width: 1280, - height: 900, - deviceScaleFactor: 1, - mobile: false - }) - }) -})