|
| 1 | +import { createTestDeviceInventoryGateways } from '../../__tests__/test-utils/device-inventory-gateways.ts'; |
| 2 | +import { legacyDispatchCapture } from './legacy-snapshot-capture-fixture.ts'; |
| 3 | +import { test, expect, vi, beforeEach } from 'vitest'; |
| 4 | +import os from 'node:os'; |
| 5 | +import path from 'node:path'; |
| 6 | +import { getResolveTargetDeviceMock } from './request-router-dispatch-mocks.ts'; |
| 7 | +import { mkdtempForTestSync } from '../../__tests__/test-utils/tmp-dir.ts'; |
| 8 | + |
| 9 | +vi.mock('../device-ready.ts', () => ({ ensureDeviceReady: vi.fn(async () => {}) })); |
| 10 | +vi.mock('../../utils/host-process.ts', async (importOriginal) => { |
| 11 | + const actual = await importOriginal<typeof import('../../utils/host-process.ts')>(); |
| 12 | + return { ...actual, readProcessStartTime: vi.fn(() => 'test-process-start') }; |
| 13 | +}); |
| 14 | +// Opening a session runs owned-lease cleanup, which pattern-kills stale xcodebuild runners with a |
| 15 | +// real `pkill -f`; the session ids here are fabricated, so stub the tool seam (#1824). |
| 16 | +vi.mock('../../platforms/apple/core/tool-provider.ts', async (importOriginal) => { |
| 17 | + const actual = |
| 18 | + await importOriginal<typeof import('../../platforms/apple/core/tool-provider.ts')>(); |
| 19 | + return { |
| 20 | + ...actual, |
| 21 | + runAppleToolCommand: vi.fn(async () => ({ exitCode: 0, stdout: '', stderr: '' })), |
| 22 | + }; |
| 23 | +}); |
| 24 | + |
| 25 | +import { |
| 26 | + createRequestHandler, |
| 27 | + lifecycleDeviceRuntimeGateway, |
| 28 | +} from './test-device-runtime-gateway.ts'; |
| 29 | +import { LeaseRegistry } from '../lease-registry.ts'; |
| 30 | +import { ensureDeviceReady } from '../device-ready.ts'; |
| 31 | +import { awaitFixtureReadiness } from './application-lifecycle-runtime-fixture.ts'; |
| 32 | +import { makeSessionStore } from '../../__tests__/test-utils/store-factory.ts'; |
| 33 | +import type { DeviceInfo } from '@agent-device/kernel/device'; |
| 34 | +import type { DaemonRequest, DaemonResponse } from '../types.ts'; |
| 35 | + |
| 36 | +/** |
| 37 | + * The production route for the #2031/#1394 defect: a request without `--session` resolves the |
| 38 | + * store key `cwd:<hash>:default`, loads THAT entry, and hands it to a recovery producer whose |
| 39 | + * record is only named `default`. Every recovery below must name the store key, because |
| 40 | + * `--session default` marks the session explicit and therefore addresses a different session. |
| 41 | + * |
| 42 | + * The address is never hand-written here — it is read back from the store the router wrote, so a |
| 43 | + * regression that reverts to `SessionState.name` cannot be papered over by an updated constant. |
| 44 | + */ |
| 45 | +const SCOPED_ADDRESS_PATTERN = /^cwd:[0-9a-f]{16}:default$/; |
| 46 | + |
| 47 | +const mockResolveTargetDevice = vi.mocked(getResolveTargetDeviceMock()); |
| 48 | +const mockEnsureDeviceReady = vi.mocked(ensureDeviceReady); |
| 49 | +const mockAwaitFixtureReadiness = vi.mocked(awaitFixtureReadiness); |
| 50 | + |
| 51 | +function makeIosDevice(id: string): DeviceInfo { |
| 52 | + return { |
| 53 | + platform: 'apple', |
| 54 | + id, |
| 55 | + name: `iPhone ${id}`, |
| 56 | + kind: 'simulator', |
| 57 | + target: 'mobile', |
| 58 | + booted: true, |
| 59 | + }; |
| 60 | +} |
| 61 | + |
| 62 | +function createHandler(sessionStore: ReturnType<typeof makeSessionStore>) { |
| 63 | + return createRequestHandler({ |
| 64 | + logPath: path.join(os.tmpdir(), 'daemon.log'), |
| 65 | + token: 'test-token', |
| 66 | + sessionStore, |
| 67 | + leaseRegistry: new LeaseRegistry(), |
| 68 | + deviceRuntimeGateway: lifecycleDeviceRuntimeGateway, |
| 69 | + deviceInventoryGateways: createTestDeviceInventoryGateways(), |
| 70 | + trackDownloadableArtifact: () => 'artifact-id', |
| 71 | + }); |
| 72 | +} |
| 73 | + |
| 74 | +/** A request as the CLI sends it when the caller passed no `--session`: named, but not explicit. */ |
| 75 | +function implicitRequest(params: { |
| 76 | + command: string; |
| 77 | + cwd: string; |
| 78 | + requestId: string; |
| 79 | + flags?: Record<string, unknown>; |
| 80 | + meta?: Record<string, unknown>; |
| 81 | +}): DaemonRequest { |
| 82 | + return { |
| 83 | + token: 'test-token', |
| 84 | + session: 'default', |
| 85 | + command: params.command, |
| 86 | + positionals: [], |
| 87 | + flags: params.flags ?? {}, |
| 88 | + meta: { requestId: params.requestId, cwd: params.cwd, ...params.meta }, |
| 89 | + } as DaemonRequest; |
| 90 | +} |
| 91 | + |
| 92 | +/** Opens the implicit session and returns the store key the router filed it under. */ |
| 93 | +async function openImplicitSession( |
| 94 | + handler: ReturnType<typeof createHandler>, |
| 95 | + sessionStore: ReturnType<typeof makeSessionStore>, |
| 96 | + cwd: string, |
| 97 | +): Promise<string> { |
| 98 | + const response = await handler( |
| 99 | + implicitRequest({ command: 'open', cwd, requestId: 'req-implicit-open' }), |
| 100 | + ); |
| 101 | + expect(response.ok).toBe(true); |
| 102 | + const refs = sessionStore.listRefs(); |
| 103 | + expect(refs).toHaveLength(1); |
| 104 | + const address = refs[0]!.address; |
| 105 | + // The defect in one line: the record is named `default`, the store key is not. |
| 106 | + expect(refs[0]!.session.name).toBe('default'); |
| 107 | + expect(address).toMatch(SCOPED_ADDRESS_PATTERN); |
| 108 | + return address; |
| 109 | +} |
| 110 | + |
| 111 | +function errorHint(response: DaemonResponse): string { |
| 112 | + expect(response.ok).toBe(false); |
| 113 | + if (response.ok) return ''; |
| 114 | + return String(response.error.hint ?? ''); |
| 115 | +} |
| 116 | + |
| 117 | +function expectAddressableRecovery(hint: string, address: string): void { |
| 118 | + expect(hint).toContain(`--session ${address}`); |
| 119 | + expect(hint).not.toMatch(/--session default\b/); |
| 120 | +} |
| 121 | + |
| 122 | +beforeEach(() => { |
| 123 | + legacyDispatchCapture.mockReset(); |
| 124 | + legacyDispatchCapture.mockResolvedValue({}); |
| 125 | + mockResolveTargetDevice.mockReset(); |
| 126 | + mockEnsureDeviceReady.mockReset(); |
| 127 | + mockEnsureDeviceReady.mockResolvedValue(undefined); |
| 128 | + mockAwaitFixtureReadiness.mockReset(); |
| 129 | + mockAwaitFixtureReadiness.mockResolvedValue(undefined); |
| 130 | +}); |
| 131 | + |
| 132 | +test('device-in-use against an implicit session names its store key, not "default"', async () => { |
| 133 | + const sessionStore = makeSessionStore('agent-device-router-address-'); |
| 134 | + const cwd = mkdtempForTestSync('agent-device-scope-'); |
| 135 | + const device = makeIosDevice('SIM-IN-USE'); |
| 136 | + mockResolveTargetDevice.mockResolvedValue(device); |
| 137 | + const handler = createHandler(sessionStore); |
| 138 | + const address = await openImplicitSession(handler, sessionStore, cwd); |
| 139 | + |
| 140 | + const response = await handler({ |
| 141 | + token: 'test-token', |
| 142 | + session: 'checkout', |
| 143 | + command: 'open', |
| 144 | + positionals: [], |
| 145 | + flags: { platform: 'ios' }, |
| 146 | + meta: { requestId: 'req-explicit-open', cwd, sessionExplicit: true }, |
| 147 | + } as DaemonRequest); |
| 148 | + |
| 149 | + expect(response.ok).toBe(false); |
| 150 | + if (response.ok) return; |
| 151 | + expect(response.error.code).toBe('DEVICE_IN_USE'); |
| 152 | + expect(response.error.message).toContain(`session "${address}"`); |
| 153 | + expect(response.error.details?.session).toBe(address); |
| 154 | + expectAddressableRecovery(errorHint(response), address); |
| 155 | + expect(errorHint(response)).toContain(`agent-device close --session ${address}`); |
| 156 | +}); |
| 157 | + |
| 158 | +test('selector conflict on an implicit session names its store key, not "default"', async () => { |
| 159 | + const sessionStore = makeSessionStore('agent-device-router-address-'); |
| 160 | + const cwd = mkdtempForTestSync('agent-device-scope-'); |
| 161 | + mockResolveTargetDevice.mockResolvedValue(makeIosDevice('SIM-BOUND')); |
| 162 | + const handler = createHandler(sessionStore); |
| 163 | + const address = await openImplicitSession(handler, sessionStore, cwd); |
| 164 | + |
| 165 | + const response = await handler( |
| 166 | + implicitRequest({ |
| 167 | + command: 'home', |
| 168 | + cwd, |
| 169 | + requestId: 'req-selector-conflict', |
| 170 | + flags: { udid: 'SIM-OTHER' }, |
| 171 | + }), |
| 172 | + ); |
| 173 | + |
| 174 | + expect(response.ok).toBe(false); |
| 175 | + if (response.ok) return; |
| 176 | + expect(response.error.code).toBe('INVALID_ARGS'); |
| 177 | + expect(response.error.message).toContain(`Session "${address}"`); |
| 178 | + expectAddressableRecovery(errorHint(response), address); |
| 179 | +}); |
| 180 | + |
| 181 | +test('lock-policy conflict on an implicit session names its store key, not "default"', async () => { |
| 182 | + const sessionStore = makeSessionStore('agent-device-router-address-'); |
| 183 | + const cwd = mkdtempForTestSync('agent-device-scope-'); |
| 184 | + mockResolveTargetDevice.mockResolvedValue(makeIosDevice('SIM-LOCKED')); |
| 185 | + const handler = createHandler(sessionStore); |
| 186 | + const address = await openImplicitSession(handler, sessionStore, cwd); |
| 187 | + |
| 188 | + const response = await handler( |
| 189 | + implicitRequest({ |
| 190 | + command: 'home', |
| 191 | + cwd, |
| 192 | + requestId: 'req-lock-conflict', |
| 193 | + flags: { udid: 'SIM-OTHER' }, |
| 194 | + meta: { lockPolicy: 'reject' }, |
| 195 | + }), |
| 196 | + ); |
| 197 | + |
| 198 | + expect(response.ok).toBe(false); |
| 199 | + if (response.ok) return; |
| 200 | + expect(response.error.code).toBe('INVALID_ARGS'); |
| 201 | + expect(response.error.message).toContain(`session "${address}"`); |
| 202 | + expect(response.error.details?.session).toBe(address); |
| 203 | + expectAddressableRecovery(errorHint(response), address); |
| 204 | +}); |
| 205 | + |
| 206 | +test('session list reports the address an implicit session answers to alongside its name', async () => { |
| 207 | + const sessionStore = makeSessionStore('agent-device-router-address-'); |
| 208 | + const cwd = mkdtempForTestSync('agent-device-scope-'); |
| 209 | + mockResolveTargetDevice.mockResolvedValue(makeIosDevice('SIM-LISTED')); |
| 210 | + const handler = createHandler(sessionStore); |
| 211 | + const address = await openImplicitSession(handler, sessionStore, cwd); |
| 212 | + |
| 213 | + const response = await handler( |
| 214 | + implicitRequest({ command: 'session_list', cwd, requestId: 'req-session-list' }), |
| 215 | + ); |
| 216 | + |
| 217 | + expect(response.ok).toBe(true); |
| 218 | + if (!response.ok) return; |
| 219 | + const sessions = response.data?.sessions as { name: string; address: string }[] | undefined; |
| 220 | + expect(sessions).toHaveLength(1); |
| 221 | + expect(sessions?.[0]?.name).toBe('default'); |
| 222 | + expect(sessions?.[0]?.address).toBe(address); |
| 223 | + expect(sessions?.[0]?.address).toMatch(SCOPED_ADDRESS_PATTERN); |
| 224 | +}); |
0 commit comments