diff --git a/packages/daemon/src/core/session-recovery-hints.ts b/packages/daemon/src/core/session-recovery-hints.ts index 2a75abbbda..5919c66134 100644 --- a/packages/daemon/src/core/session-recovery-hints.ts +++ b/packages/daemon/src/core/session-recovery-hints.ts @@ -5,6 +5,16 @@ import { errorResponse, type DaemonFailureResponse } from '@agent-device/kernel/ export type SessionRecoveryContext = 'device-in-use' | 'selector-conflict'; +/** + * How much a reply may say about the session that holds a device. `named` reports that session's + * address; `anonymous` answers the same reply without it. The caller passes `anonymous` for the + * session of another client on a proxy shared under one token — a leased or tenant-scoped session + * its request may not see — where an address is another client's session handle and naming it + * would confirm that the session exists and holds this device (#4923). A local session of another + * workspace keeps its address: that is the handle `close --session` takes from there (#2580). + */ +export type HeldSessionNaming = 'named' | 'anonymous'; + export type SessionRecoveryOptions = { /** Whether the request disagrees with the bound session on *platform*, the one conflict another * platform's implicit session actually answers. */ @@ -51,16 +61,26 @@ export function buildSessionRecoveryHint( export function buildDeviceInUseBySessionError( inUse: SessionRef, device: DeviceInfo, - options: SessionRecoveryOptions = {}, + options: SessionRecoveryOptions, + naming: HeldSessionNaming, ): DaemonFailureResponse { - return errorResponse('DEVICE_IN_USE', `Device is already in use by session "${inUse.address}".`, { - session: inUse.address, - deviceId: device.id, - deviceName: device.name, - ...(options.waitedMs === undefined ? {} : { waitedMs: options.waitedMs }), - hint: buildSessionRecoveryHint(inUse, 'device-in-use', options), - dispatched: 'no', - }); + return errorResponse( + 'DEVICE_IN_USE', + naming === 'named' + ? `Device is already in use by session "${inUse.address}".` + : GENERIC_IN_USE_MESSAGE, + { + ...(naming === 'named' ? { session: inUse.address } : {}), + deviceId: device.id, + deviceName: device.name, + ...(options.waitedMs === undefined ? {} : { waitedMs: options.waitedMs }), + hint: + naming === 'named' + ? buildSessionRecoveryHint(inUse, 'device-in-use', options) + : buildAnonymousInUseHint(options), + dispatched: 'no', + }, + ); } /** @@ -160,6 +180,20 @@ const HOLDER_MAY_BE_FOREIGN = 'The holding session may belong to another agent o const CHOOSE_ANOTHER_DEVICE = 'Run agent-device devices and open another device with a device selector. '; +/** What every caller may learn about a holder it may not see: that there is one (#4923). */ +export const GENERIC_IN_USE_MESSAGE = 'Device is already in use by another session.'; + +/** + * The recovery text when the holder stays unnamed: the device and the wait are still the caller's + * moves; the session is not. + */ +function buildAnonymousInUseHint(options: SessionRecoveryOptions): string { + return ( + `${describeOpenWaitAttempt(options)}${HOLDER_MAY_BE_FOREIGN}${CHOOSE_ANOTHER_DEVICE}${waitForDeviceHint(options)}` + + 'Run agent-device session list to see the sessions this request can act on.' + ); +} + /** * The record of a spent `--wait` budget, phrased so a caller that already waited is not told to * wait again. Only an `open` can wait, so this is the only place the budget is spoken of. diff --git a/packages/daemon/src/server/__tests__/request-router-open-claim.test.ts b/packages/daemon/src/server/__tests__/request-router-open-claim.test.ts index 348d6934e5..8fdde37e3c 100644 --- a/packages/daemon/src/server/__tests__/request-router-open-claim.test.ts +++ b/packages/daemon/src/server/__tests__/request-router-open-claim.test.ts @@ -231,6 +231,8 @@ test('an owner reopen that lost the device mid-flight reports the loss instead o expect(reopened.ok).toBe(false); if (!reopened.ok) { expect(reopened.error.code).toBe('DEVICE_IN_USE'); + // The claim belongs to another daemon's state dir, so its recorded owner stays: the caller + // has to reach it through that workspace (#4923 keeps the cross-worktree recovery). expect(reopened.error.message).toContain('shared'); } expect(inspectDeviceClaims({ udid: device.id }, process.env)[0]?.claim?.ownerToken).toBe( diff --git a/packages/daemon/src/server/http/http-server-proxy-reply-visibility.test.ts b/packages/daemon/src/server/http/http-server-proxy-reply-visibility.test.ts new file mode 100644 index 0000000000..20534ca136 --- /dev/null +++ b/packages/daemon/src/server/http/http-server-proxy-reply-visibility.test.ts @@ -0,0 +1,408 @@ +// Two clients share one proxy token, so both are one tenant to the daemon and differ only by the +// lease id they carry. Neither a `devices` list, a busy-device `open`, nor a claim-conflict refusal +// may carry the holder's session address to a caller that may not see it (#4923). The caller that +// carries the holder's lease id — the one the lease was allocated to — keeps learning the name. +import fs from 'node:fs'; +import path from 'node:path'; +import { afterEach, beforeEach, expect, test } from 'vitest'; +import { createDaemonProxyServer } from '@agent-device/proxy'; +import { + closeLoopbackServer, + createTestHostEnvironment, + IOS_SIMULATOR, + listenOnLoopback, + mkdtempForTestSync, + skipWhenLoopbackUnavailable, +} from '@agent-device/test-kit'; +import { createTestDeviceInventoryGateways } from '@agent-device/device-selection/inventory-gateways-fixtures'; +import { acquireDeviceClaim } from '@agent-device/daemon-contracts/device-claims'; +import { createDaemonHttpServer } from './http-server.ts'; +import { + createRequestHandler, + lifecycleDeviceRuntimeGateway, +} from '../../__tests__/support/test-device-runtime-gateway.ts'; +import { retainOrphanedDeviceClaims } from '../../__tests__/support/device-claim-store.ts'; +import { makeIosAppSession } from '../../__tests__/support/session-factories.ts'; +import { makeSessionStore } from '../../__tests__/support/store-factory.ts'; +import { fakeCreateCommandSurface } from '../../__tests__/support/command-surface-fake.ts'; +import { tenantScopedSessionName } from '../../core/session-tenant-scope.ts'; +import { LeaseRegistry } from '../../resources/lease-registry.ts'; + +const PROXY_TOKEN = 'shared-proxy-token'; +const TENANT = 'e2b'; +const HOLDER = 'agentA'; +const PEER = 'agentB'; +const DEVICE = IOS_SIMULATOR; +/** The holder's own lease scope, as its client sends it; `proxy` names a route, not an instance. */ +const HOLDER_SCOPE = { + tenantId: TENANT, + runId: 'run-a', + leaseProvider: 'proxy', + clientId: 'client-a', + deviceKey: 'ios:mobile:sim-1', +} as const; +/** The peer's own lease scope: same tenant, its own run, and no lease bound to this device. */ +const PEER_SCOPE = { + tenantId: TENANT, + runId: 'run-b', + leaseProvider: 'proxy', + clientId: 'client-b', + deviceKey: 'ios:mobile:sim-2', +} as const; + +type RpcBody = { + result?: { ok?: boolean; data?: Record & { lease?: { leaseId: string } } }; + error?: { + data?: { code?: string; message?: string; hint?: string; details?: Record }; + }; +}; + +async function sendCommand( + url: string, + token: string, + params: Record, +): Promise { + const response = await fetch(url, { + method: 'POST', + headers: { authorization: `Bearer ${token}`, 'content-type': 'application/json' }, + body: JSON.stringify({ + jsonrpc: '2.0', + id: 1, + method: 'agent_device.command', + params, + }), + }); + return (await response.json()) as RpcBody; +} + +let world: Awaited> | undefined; +let previousClaimsDir: string | undefined; +let claimsDir: string; + +beforeEach(async (context) => { + if (await skipWhenLoopbackUnavailable(context)) return; + claimsDir = mkdtempForTestSync('agent-device-proxy-reply-visibility-claims-'); + previousClaimsDir = process.env.AGENT_DEVICE_CLAIMS_DIR; + process.env.AGENT_DEVICE_CLAIMS_DIR = claimsDir; + world = await startProxiedDaemon(); +}); + +afterEach(async () => { + await world?.close(); + world = undefined; + if (previousClaimsDir === undefined) delete process.env.AGENT_DEVICE_CLAIMS_DIR; + else process.env.AGENT_DEVICE_CLAIMS_DIR = previousClaimsDir; + fs.rmSync(claimsDir, { recursive: true, force: true }); +}); + +async function startProxiedDaemon() { + const sessionStore = makeSessionStore('agent-device-proxy-reply-visibility-'); + const leaseRegistry = new LeaseRegistry(); + // No backend is named anywhere: admission defaults both the allocation and the request to the + // same backend, so each client admits exactly its own lease. + const holderLease = leaseRegistry.allocateLease(HOLDER_SCOPE); + const peerLease = leaseRegistry.allocateLease(PEER_SCOPE); + const holderSessionName = tenantScopedSessionName(TENANT, HOLDER); + sessionStore.publish( + holderSessionName, + makeIosAppSession(holderSessionName, { + sessionScope: { kind: 'tenant', id: TENANT }, + device: DEVICE, + lease: { + leaseId: holderLease.leaseId, + tenantId: TENANT, + runId: HOLDER_SCOPE.runId, + backend: holderLease.backend, + leaseProvider: HOLDER_SCOPE.leaseProvider, + clientId: HOLDER_SCOPE.clientId, + deviceKey: HOLDER_SCOPE.deviceKey, + }, + }), + ); + const handleRequest = createRequestHandler({ + host: createTestHostEnvironment(), + createCommandSurface: fakeCreateCommandSurface, + logPath: path.join( + mkdtempForTestSync('agent-device-proxy-reply-visibility-log-'), + 'daemon.log', + ), + token: 'daemon-token', + sessionStore, + leaseRegistry, + deviceInventoryGateways: createTestDeviceInventoryGateways({ + local: async () => [DEVICE], + }), + deviceRuntimeGateway: { + ...lifecycleDeviceRuntimeGateway, + inspectFacts: async (device) => { + const facts = await lifecycleDeviceRuntimeGateway.inspectFacts(device); + return { + ...facts, + operations: { ...facts.operations, shutdownTarget: { available: true } }, + }; + }, + }, + trackDownloadableArtifact: () => 'artifact-id', + }); + const daemon = await createDaemonHttpServer({ + token: 'daemon-token', + handleRequest, + env: {}, + cwd: process.cwd(), + }); + const daemonPort = await listenOnLoopback(daemon); + const proxy = createDaemonProxyServer({ + upstreamBaseUrl: `http://127.0.0.1:${daemonPort}`, + upstreamToken: 'daemon-token', + clientToken: PROXY_TOKEN, + }); + const proxyPort = await listenOnLoopback(proxy); + return { + holderLeaseId: holderLease.leaseId, + peerLeaseId: peerLease.leaseId, + holderSessionName, + sessionStore, + sendLocal: (params: Record) => + sendCommand(`http://127.0.0.1:${daemonPort}/rpc`, 'daemon-token', params), + /** Sends `command` as `session` with the given lease metadata and flags. */ + send: ( + session: string, + command: string, + params: { meta?: Record; flags?: Record } = {}, + positionals: string[] = [], + ) => + sendCommand(`http://127.0.0.1:${proxyPort}/agent-device/rpc`, PROXY_TOKEN, { + session, + command, + positionals, + flags: params.flags ?? {}, + meta: { + tenantId: TENANT, + sessionIsolation: 'tenant', + sessionExplicit: true, + ...params.meta, + }, + }), + /** Writes the live claim this daemon would have left for its holder session on this device. */ + seedHolderClaim: async () => { + const acquired = await acquireDeviceClaim({ + device: DEVICE, + session: tenantScopedSessionName(TENANT, HOLDER), + workspace: '/work/holder', + stateDir: sessionStore.resolveDaemonStateDir(), + env: process.env, + reconcileOrphanedDeviceClaim: retainOrphanedDeviceClaims, + }); + if (acquired.status !== 'acquired') throw new Error('fixture claim was not acquired'); + }, + close: async () => { + await closeLoopbackServer(proxy); + await closeLoopbackServer(daemon); + }, + }; +} + +function expectNoHolderName(body: RpcBody): void { + const serialized = JSON.stringify(body); + expect(serialized, serialized).not.toContain(HOLDER); +} + +test('the lease holder sees its own session in the claimed-device list', async () => { + if (!world) return; + await world.seedHolderClaim(); + + const asHolder = await world.send(HOLDER, 'devices', { + meta: { ...HOLDER_SCOPE, leaseId: world.holderLeaseId }, + }); + + expect(asHolder.result?.ok, JSON.stringify(asHolder)).toBe(true); + expect(JSON.stringify(asHolder)).toContain(HOLDER); +}); + +test('the peer client lists a claimed device without the holder session', async () => { + if (!world) return; + await world.seedHolderClaim(); + + const asPeer = await world.send(PEER, 'devices', { + meta: { ...PEER_SCOPE, leaseId: world.peerLeaseId }, + }); + + expect(asPeer.result?.ok, JSON.stringify(asPeer)).toBe(true); + expectNoHolderName(asPeer); +}); + +test('the peer client is refused a busy device without learning the holder session', async () => { + if (!world) return; + + const refusal = await world.send( + PEER, + 'open', + { + meta: { ...PEER_SCOPE, leaseId: world.peerLeaseId }, + flags: { waitMs: 400 }, + }, + ['com.example.app'], + ); + + expect(refusal.error?.data?.code, JSON.stringify(refusal)).toBe('DEVICE_IN_USE'); + expectNoHolderName(refusal); +}); + +test('the caller that carries the holder lease id still learns the holder session', async () => { + if (!world) return; + + // The lease's own scope labels with its id: the client the lease was allocated to. + const refusal = await world.send( + PEER, + 'open', + { + meta: { ...HOLDER_SCOPE, leaseId: world.holderLeaseId }, + flags: { waitMs: 400 }, + }, + ['com.example.app'], + ); + + expect(refusal.error?.data?.code, JSON.stringify(refusal)).toBe('DEVICE_IN_USE'); + expect(JSON.stringify(refusal)).toContain(HOLDER); +}); + +test('the peer client gets a claim conflict without the holder session', async () => { + if (!world) return; + // Close the holder's session-table entry so the refusal comes from the claim alone: the claim + // outliving its session is the case whose unverified owner label must not be confirmed. + await world.send(HOLDER, 'close', { meta: { ...HOLDER_SCOPE, leaseId: world.holderLeaseId } }); + await world.seedHolderClaim(); + + const refusal = await world.send( + PEER, + 'open', + { meta: { ...PEER_SCOPE, leaseId: world.peerLeaseId } }, + ['com.example.app'], + ); + + expect(refusal.error?.data?.code, JSON.stringify(refusal)).toBe('DEVICE_IN_USE'); + expect(String(refusal.error?.data?.details?.reason)).toMatch(/DEVICE_CLAIM/); + expectNoHolderName(refusal); +}); + +test('a proxy client is refused a device held by a local session without learning its name', async () => { + if (!world) return; + const localHolder = 'local-holder-session'; + world.sessionStore.retire(world.sessionStore.lookup(world.holderSessionName)!); + world.sessionStore.publish( + localHolder, + makeIosAppSession(localHolder, { + sessionScope: { kind: 'named-local' }, + device: DEVICE, + }), + ); + + const refusal = await world.send( + PEER, + 'open', + { + meta: { ...PEER_SCOPE, leaseId: world.peerLeaseId }, + flags: { waitMs: 400 }, + }, + ['com.example.app'], + ); + + expect(refusal.error?.data?.code, JSON.stringify(refusal)).toBe('DEVICE_IN_USE'); + expect(JSON.stringify(refusal)).not.toContain(localHolder); +}); + +test('a shared-token proxy client without tenant isolation does not learn a local holder name', async () => { + if (!world) return; + const localHolder = 'local-holder-unisolated'; + world.sessionStore.retire(world.sessionStore.lookup(world.holderSessionName)!); + world.sessionStore.publish( + localHolder, + makeIosAppSession(localHolder, { + sessionScope: { kind: 'named-local' }, + device: DEVICE, + }), + ); + + // The client keeps its lease metadata but sends no tenant isolation, so only the proxy's + // public-network admission marks it as remote. + const refusal = await world.send( + PEER, + 'open', + { + meta: { ...PEER_SCOPE, leaseId: world.peerLeaseId, sessionIsolation: undefined }, + flags: { waitMs: 400 }, + }, + ['com.example.app'], + ); + + expect(refusal.error?.data?.code, JSON.stringify(refusal)).toBe('DEVICE_IN_USE'); + expect(JSON.stringify(refusal)).not.toContain(localHolder); +}); + +test('implicit shutdown names a cwd-scoped holder only in its own workspace', async () => { + if (!world) return; + world.sessionStore.retire(world.sessionStore.lookup(world.holderSessionName)!); + const holderCwd = mkdtempForTestSync('agent-device-shutdown-holder-'); + const otherCwd = mkdtempForTestSync('agent-device-shutdown-other-'); + const flags = { platform: 'ios', udid: DEVICE.id }; + const opened = await world.sendLocal({ + command: 'open', + positionals: ['com.example.app'], + flags, + meta: { cwd: holderCwd }, + }); + expect(opened.result?.ok, JSON.stringify(opened)).toBe(true); + const holder = world.sessionStore.findByDevice(DEVICE.id)!; + expect(holder.session.sessionScope?.kind).toBe('cwd'); + expect(holder.session.lease).toBeUndefined(); + + const refused = await world.sendLocal({ + command: 'shutdown', + flags, + meta: { cwd: otherCwd }, + }); + expect(refused.error?.data?.code, JSON.stringify(refused)).toBe('DEVICE_IN_USE'); + expect(JSON.stringify(refused)).not.toContain(holder.address); + + const ownRefusal = await world.sendLocal({ + command: 'shutdown', + flags, + meta: { cwd: holderCwd }, + }); + expect(ownRefusal.error?.data).toMatchObject({ + code: 'DEVICE_IN_USE', + hint: `Run agent-device close --shutdown --session ${holder.address}`, + details: { session: holder.address }, + }); +}); + +test('an implicit open in another workspace does not name a leased cwd-scoped holder', async () => { + if (!world) return; + world.sessionStore.retire(world.sessionStore.lookup(world.holderSessionName)!); + const holderCwd = mkdtempForTestSync('agent-device-leased-open-holder-'); + const otherCwd = mkdtempForTestSync('agent-device-leased-open-other-'); + const scope = { tenantId: 'local', runId: 'workspace-holder' }; + const allocated = await world.sendLocal({ command: 'lease_allocate', meta: scope }); + const leaseId = allocated.result?.data?.lease?.leaseId; + expect(leaseId, JSON.stringify(allocated)).toBeTypeOf('string'); + + const open = { + command: 'open', + positionals: ['com.example.app'], + flags: { platform: 'ios', udid: DEVICE.id }, + }; + const opened = await world.sendLocal({ + ...open, + meta: { ...scope, cwd: holderCwd, leaseId }, + }); + expect(opened.result?.ok, JSON.stringify(opened)).toBe(true); + const holder = world.sessionStore.findByDevice(DEVICE.id)!; + expect(holder.session.sessionScope?.kind).toBe('cwd'); + expect(holder.session.lease).toMatchObject({ leaseId }); + expect(holder.session.lease?.leaseProvider).toBeUndefined(); + + const refused = await world.sendLocal({ ...open, meta: { cwd: otherCwd } }); + expect(refused.error?.data?.code, JSON.stringify(refused)).toBe('DEVICE_IN_USE'); + expect(JSON.stringify(refused)).not.toContain(holder.address); + expect(refused.error?.data?.details?.session).toBeUndefined(); +}); diff --git a/packages/daemon/src/server/request-router.ts b/packages/daemon/src/server/request-router.ts index c5d4aa7e86..31e9566d09 100644 --- a/packages/daemon/src/server/request-router.ts +++ b/packages/daemon/src/server/request-router.ts @@ -81,7 +81,10 @@ import { } from '@agent-device/selectors/parameterized-recorded-fill'; import { isConfinedToAppLease, scopeRequestSession } from '../sessions/request-admission.ts'; import { redactMacOsAppLeaseResponse } from '../resources/macos-app-lease.ts'; -import { resolveEffectiveSessionName } from '../sessions/session-routing.ts'; +import { + dropInvisibleClaimOwner, + resolveEffectiveSessionName, +} from '../sessions/session-routing.ts'; import { sessionIdleExpiredError } from './session-idle-expiry.ts'; import type { IdleSessionTombstone } from '../core/session-idle-tombstone.ts'; import { @@ -325,7 +328,17 @@ export function createRequestHandler(deps: RequestRouterDeps): DaemonInvokeFn { } catch (error) { response = finalizeThrownRequestError(error); } - return redactForMacOsAppLease(req, scope, await finalizeRequestBindingCleanup(scope, response)); + return redactForMacOsAppLease( + req, + scope, + dropInvisibleClaimOwner( + // The restricted, tenant-scoped request the scope runs under, the same one the app-lease + // redaction judges with: a caller-supplied `meta.cwd` never widens what it may learn. + scope?.req ?? req, + sessionStore, + await finalizeRequestBindingCleanup(scope, response), + ), + ); } // Not covered, by choice: a request refused before its scope exists that names no lease in its @@ -515,7 +528,11 @@ export function createRequestHandler(deps: RequestRouterDeps): DaemonInvokeFn { // This entry point registers a sensitive fill too, so it redacts that fill's error as well. return redactSensitiveFillResponse( req, - await finalizeRequestBindingCleanup(childScope, response), + dropInvisibleClaimOwner( + childScope?.req ?? req, + sessionStore, + await finalizeRequestBindingCleanup(childScope, response), + ), ); }; } diff --git a/packages/daemon/src/sessions/__tests__/open-device-contention-wait.test.ts b/packages/daemon/src/sessions/__tests__/open-device-contention-wait.test.ts index 7defc81400..a71a4d1ecb 100644 --- a/packages/daemon/src/sessions/__tests__/open-device-contention-wait.test.ts +++ b/packages/daemon/src/sessions/__tests__/open-device-contention-wait.test.ts @@ -1,7 +1,11 @@ import { test, expect, vi, afterEach } from 'vitest'; import { isRequestCanceledError } from '@agent-device/kernel/errors'; import type { CommandFlags } from '@agent-device/contracts/command'; -import { clearRequestCanceled, markRequestCanceled } from '@agent-device/host-kit/request'; +import { + clearRequestCanceled, + markRequestCanceled, + withRequestProgressSink, +} from '@agent-device/host-kit/request'; import { IOS_SIMULATOR, createLiveTestHostEnvironment } from '@agent-device/test-kit'; import { getFlagDefinitionsForKey } from '@agent-device/command-registry/flag-registry'; import { makeSessionStore } from '../../__tests__/support/store-factory.ts'; @@ -11,6 +15,7 @@ import { SessionStore } from '../../core/session-store.ts'; import { beginOpenDeviceWait, describeOpenWaitForRefusal, + findSessionDeviceConflict, readOpenWaitAttempt, readOpenWaitBudgetMs, } from '../open-device-contention-wait.ts'; @@ -310,9 +315,180 @@ test('a request the client gave up on stops waiting at its next poll', async () await rejection; }); +// The contention progress names the holder only when that holder is visible to the request +// (#4923). The visible case is the two cwd sessions above; the anonymous case is another tenant's +// leased session. +test('the open-wait progress names a holder the request may see', async () => { + vi.useFakeTimers(); + const messages: string[] = []; + const req = openRequest({ waitMs: 1000 }); + const wait = beginWait({ + req, + sessionName: OPENER_ADDRESS, + sessionStore: storeWithHolder(), + deviceId: IOS_SIMULATOR.id, + })!; + + await waitUntil( + () => + withRequestProgressSink( + (event) => messages.push(event.type === 'command' ? event.message : ''), + () => wait.waitForDeviceOutsideLocks(), + ), + 2_000, + ); + + expect(messages[0]).toContain(`held by session "${HOLDER_ADDRESS}"`); +}); + +test('the open-wait progress names no holder the request may not see', async () => { + vi.useFakeTimers(); + const messages: string[] = []; + const store = makeSessionStore('agent-device-open-wait-'); + store.publish('e2b:agentA', { + name: 'agentA', + sessionScope: { kind: 'tenant', id: 'e2b' }, + lease: { + leaseId: 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', + tenantId: 'e2b', + runId: 'run-a', + backend: 'ios-simulator', + }, + device: IOS_SIMULATOR, + createdAt: 0, + actions: [], + }); + const req: DaemonRequest = { + ...openRequest({ waitMs: 1000 }), + session: 'agentB', + meta: { requestId: 'req-open-wait', tenantId: 'e2b', sessionIsolation: 'tenant' }, + }; + const wait = beginWait({ + req, + sessionName: 'e2b:agentB', + sessionStore: store, + deviceId: IOS_SIMULATOR.id, + })!; + + await waitUntil( + () => + withRequestProgressSink( + (event) => messages.push(event.type === 'command' ? event.message : ''), + () => wait.waitForDeviceOutsideLocks(), + ), + 2_000, + ); + + expect(messages[0]).toContain('held by another session'); + expect(messages[0]).not.toContain('agentA'); +}); + /** Runs `start()` under fake timers and advances the clock until it settles. */ async function waitUntil(start: () => Promise, budgetMs: number): Promise { const running = start(); await vi.advanceTimersByTimeAsync(budgetMs); await running; } + +// The refusal a contended open gets names the holder unless the holder is another proxy client's +// leased or tenant-scoped session (#4923). These cases are the whole table: same workspace, +// another client's leased session on a shared token, and another local workspace's session. +test('the contention refusal names a holder the request may see', () => { + const store = storeWithHolder(); + const conflict = findSessionDeviceConflict({ + req: openRequest({}), + device: IOS_SIMULATOR, + sessionStore: store, + sessionName: OPENER_ADDRESS, + }); + + expect(conflict?.error.message).toBe(`Device is already in use by session "${HOLDER_ADDRESS}".`); + expect(conflict?.error.details?.session).toBe(HOLDER_ADDRESS); +}); + +test('the contention refusal names no session to a caller that may not see it', () => { + const store = makeSessionStore('agent-device-open-wait-'); + store.publish('e2b:agentA', { + name: 'agentA', + sessionScope: { kind: 'tenant', id: 'e2b' }, + lease: { + leaseId: 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', + tenantId: 'e2b', + runId: 'run-a', + backend: 'ios-simulator', + }, + device: IOS_SIMULATOR, + createdAt: 0, + actions: [], + }); + const conflict = findSessionDeviceConflict({ + req: { + ...openRequest({}), + session: 'agentB', + meta: { requestId: 'req-open-wait', tenantId: 'e2b', sessionIsolation: 'tenant' }, + }, + device: IOS_SIMULATOR, + sessionStore: store, + sessionName: 'e2b:agentB', + }); + + expect(conflict?.error.code).toBe('DEVICE_IN_USE'); + expect(conflict?.error.message).toBe('Device is already in use by another session.'); + expect(conflict?.error.details?.session).toBeUndefined(); + expect(String(conflict?.error.details?.hint)).not.toContain('agentA'); +}); + +test('a request carrying the holder lease id still gets the named refusal', () => { + const store = makeSessionStore('agent-device-open-wait-'); + store.publish('e2b:agentA', { + name: 'agentA', + sessionScope: { kind: 'tenant', id: 'e2b' }, + lease: { + leaseId: 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', + tenantId: 'e2b', + runId: 'run-a', + backend: 'ios-simulator', + }, + device: IOS_SIMULATOR, + createdAt: 0, + actions: [], + }); + const conflict = findSessionDeviceConflict({ + req: { + ...openRequest({}), + session: 'agentA', + meta: { + requestId: 'req-open-wait', + tenantId: 'e2b', + sessionIsolation: 'tenant', + leaseId: 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', + }, + }, + device: IOS_SIMULATOR, + sessionStore: store, + // A reopen attempt under a different name still contends with the holder. + sessionName: 'e2b:agentA-reopen', + }); + + expect(conflict?.error.message).toContain('e2b:agentA'); +}); + +// A holder in another local workspace keeps its address: the owner closes it from that folder +// with the named address (#2580). +test('the foreign-workspace conflict names the holder address', () => { + const store = storeWithHolder(); + const conflict = findSessionDeviceConflict({ + req: { ...openRequest({}), meta: { requestId: 'req-open-wait', cwd: '/worktrees/other' } }, + device: IOS_SIMULATOR, + sessionStore: store, + sessionName: OPENER_ADDRESS, + }); + + expect(conflict?.error.details).toMatchObject({ + reason: 'WORKSPACE_SESSION_SCOPE_CONFLICT', + session: HOLDER_ADDRESS, + }); + expect(conflict?.error.message).toBe( + `Device is already in use by workspace session "${HOLDER_ADDRESS}".`, + ); +}); diff --git a/packages/daemon/src/sessions/__tests__/session-routing-reply-visibility.test.ts b/packages/daemon/src/sessions/__tests__/session-routing-reply-visibility.test.ts new file mode 100644 index 0000000000..b1893a4729 --- /dev/null +++ b/packages/daemon/src/sessions/__tests__/session-routing-reply-visibility.test.ts @@ -0,0 +1,210 @@ +import path from 'node:path'; +import { expect, test } from 'vitest'; +import { IOS_SIMULATOR, mkdtempForTestSync } from '@agent-device/test-kit'; +import { makeSessionStore } from '../../__tests__/support/store-factory.ts'; +import { makeIosAppSession } from '../../__tests__/support/session-factories.ts'; +import type { DaemonRequest } from '../../core/daemon-request.ts'; +import { SessionStore } from '../../core/session-store.ts'; +import { claimOwnerVisible, dropInvisibleClaimOwner, mayNameSession } from '../session-routing.ts'; +import type { DaemonResponse } from '@agent-device/kernel/contracts'; + +// A reply names the session a host-global device claim records as its owner unless that owner is +// another proxy client's: a leased or tenant-scoped session the request may not see (#4923). The +// claim's `stateDir` says which daemon wrote it; the store and the naming rule decide the rest. + +const TENANT = 'e2b'; + +function request(overrides: Partial = {}): DaemonRequest { + return { + command: 'open', + token: 'test-token', + session: 'agentB', + positionals: [], + flags: {}, + meta: { + requestId: 'req-claim-visibility', + tenantId: TENANT, + sessionIsolation: 'tenant', + ...overrides, + }, + }; +} + +const LOCAL_REQUEST = request({ tenantId: undefined, sessionIsolation: undefined }); + +function storeWithLeasedSession(): SessionStore { + const store = makeSessionStore('agent-device-reply-visibility-'); + store.publish( + 'e2b:agentA', + makeIosAppSession('e2b:agentA', { + sessionScope: { kind: 'tenant', id: TENANT }, + lease: { + leaseId: 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', + tenantId: TENANT, + runId: 'run-a', + backend: 'ios-simulator', + }, + }), + ); + return store; +} + +function claimConflictResponse(session: string, stateDir: string): DaemonResponse { + return { + ok: false, + error: { + code: 'DEVICE_IN_USE', + message: `apple device sim-1 is owned by session "${session}" in workspace "/work/a".`, + hint: 'Inspect the owner with: agent-device device status --platform ios --udid sim-1', + retriable: false, + details: { + reason: 'DEVICE_CLAIM_LIVE_OWNER', + classification: 'live', + deviceKey: 'local:apple:ios:sim-1', + owner: { session, workspace: '/work/a', stateDir }, + }, + }, + }; +} + +test('a claim naming an invisible leased session loses its owner', () => { + const store = storeWithLeasedSession(); + + const response = dropInvisibleClaimOwner( + request(), + store, + claimConflictResponse('e2b:agentA', store.resolveDaemonStateDir()), + ); + + expect(response.ok).toBe(false); + if (response.ok) return; + expect(response.error.code).toBe('DEVICE_IN_USE'); + expect(response.error.retriable).toBe(false); + expect(response.error.message).toBe('Device is already in use by another session.'); + expect(response.error.details?.owner).toBeUndefined(); + expect(response.error.details?.reason).toBe('DEVICE_CLAIM_LIVE_OWNER'); + expect(response.error.hint).toContain('device status'); +}); + +test('the lease holder keeps the named claim-conflict refusal', () => { + const store = storeWithLeasedSession(); + + const response = dropInvisibleClaimOwner( + request({ leaseId: 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' }), + store, + claimConflictResponse('e2b:agentA', store.resolveDaemonStateDir()), + ); + + expect(response).toMatchObject({ + error: { + message: expect.stringContaining('e2b:agentA'), + details: { owner: { session: 'e2b:agentA' } }, + }, + }); +}); + +test('a claim of this daemon whose session no longer resolves is not named', () => { + const store = storeWithLeasedSession(); + + const response = dropInvisibleClaimOwner( + request({ leaseId: 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' }), + store, + claimConflictResponse('e2b:expired', store.resolveDaemonStateDir()), + ); + + expect(response.ok).toBe(false); + if (response.ok) return; + expect(response.error.message).toBe('Device is already in use by another session.'); + expect(response.error.details?.owner).toBeUndefined(); +}); + +test('a local request keeps the owner of a transient claim of this daemon', () => { + const store = storeWithLeasedSession(); + + const response = dropInvisibleClaimOwner( + LOCAL_REQUEST, + store, + claimConflictResponse('transient:install', store.resolveDaemonStateDir()), + ); + + expect(response.ok).toBe(false); + if (response.ok) return; + expect(response.error.details?.owner).toMatchObject({ session: 'transient:install' }); +}); + +test('a claim another daemon on this host wrote keeps its owner for a local request only', () => { + const store = storeWithLeasedSession(); + const peerStateDir = mkdtempForTestSync('agent-device-reply-visibility-peer-'); + const conflict = claimConflictResponse('default', path.join(peerStateDir, 'daemon')); + + const local = dropInvisibleClaimOwner(LOCAL_REQUEST, store, conflict); + expect(local.ok).toBe(false); + if (local.ok) return; + expect(local.error.message).toContain('default'); + expect(local.error.details?.owner).toMatchObject({ workspace: '/work/a' }); + + const proxied = dropInvisibleClaimOwner(request(), store, conflict); + expect(proxied.ok).toBe(false); + if (proxied.ok) return; + expect(proxied.error.details?.owner).toBeUndefined(); +}); + +test('a refusal without a claim owner passes through', () => { + const store = storeWithLeasedSession(); + const response: DaemonResponse = { + ok: false, + error: { + code: 'DEVICE_IN_USE', + message: 'Device is already in use by session "x".', + details: { session: 'x' }, + }, + }; + + expect(dropInvisibleClaimOwner(request(), store, response)).toBe(response); +}); + +test('only local device recovery names an unlistable local session', () => { + const store = storeWithLeasedSession(); + const own = { session: 'e2b:agentA', workspace: '/w', stateDir: store.resolveDaemonStateDir() }; + + expect(claimOwnerVisible(request(), store, own)).toBe(false); + expect( + claimOwnerVisible(request({ leaseId: 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' }), store, own), + ).toBe(true); + expect( + claimOwnerVisible(request({ leaseId: 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' }), store, { + ...own, + session: 'gone', + }), + ).toBe(false); + const peerClaim = { ...own, stateDir: path.join(own.stateDir, 'peer') }; + expect(claimOwnerVisible(request(), store, peerClaim)).toBe(false); + expect(claimOwnerVisible(LOCAL_REQUEST, store, peerClaim)).toBe(true); + + const foreignWorkspaceSession = { + name: 'default', + sessionScope: { kind: 'cwd' as const, id: 'b'.repeat(16) }, + device: IOS_SIMULATOR, + createdAt: 0, + actions: [], + }; + const cwdRequest = { + ...request({ + cwd: mkdtempForTestSync('agent-device-reply-visibility-cwd-'), + tenantId: undefined, + sessionIsolation: undefined, + }), + session: 'default', + }; + expect(mayNameSession(request(), foreignWorkspaceSession, 'device-recovery')).toBe(false); + expect(mayNameSession(cwdRequest, foreignWorkspaceSession)).toBe(false); + expect(mayNameSession(cwdRequest, foreignWorkspaceSession, 'device-recovery')).toBe(true); + expect(mayNameSession(LOCAL_REQUEST, foreignWorkspaceSession)).toBe(true); + expect( + mayNameSession( + { ...LOCAL_REQUEST, internal: { publicNetworkOnly: true } }, + foreignWorkspaceSession, + ), + ).toBe(false); + expect(mayNameSession(request(), store.get('e2b:agentA')!)).toBe(false); +}); diff --git a/packages/daemon/src/sessions/handlers/__tests__/session-doctor-options.test.ts b/packages/daemon/src/sessions/handlers/__tests__/session-doctor-options.test.ts index 1cad2babe9..406f64a254 100644 --- a/packages/daemon/src/sessions/handlers/__tests__/session-doctor-options.test.ts +++ b/packages/daemon/src/sessions/handlers/__tests__/session-doctor-options.test.ts @@ -2,19 +2,35 @@ import { expect, test } from 'vitest'; import { makeSessionStore } from '../../../__tests__/support/store-factory.ts'; import { makeIosSession } from '../../../__tests__/support/session-factories.ts'; import { sessionChecks } from '../session-doctor-options.ts'; +import type { DaemonRequest } from '../../../core/daemon-request.ts'; // The doctor's close suggestion must carry each session's ADDRESS — the string `close --session` // accepts — and dedupe by address: two cwd-scoped implicit sessions both carry the public name // `default`, so a name compare hid them from each other and the printed // `close --session default` addressed neither (#2031/#1394). +const doctorRequest = { + command: 'doctor', + token: 'test-token', + session: 'default', + positionals: [], + flags: {}, + meta: { sessionExplicit: true }, +} satisfies DaemonRequest; + test('the same-device warning names the other session by its address, not its name', () => { const store = makeSessionStore(); const here = 'cwd:aaaaaaaaaaaaaaaa:default'; const other = 'cwd:bbbbbbbbbbbbbbbb:default'; - store.publish(here, makeIosSession('default')); - store.publish(other, makeIosSession('default')); + store.publish( + here, + makeIosSession('default', { sessionScope: { kind: 'cwd', id: 'a'.repeat(16) } }), + ); + store.publish( + other, + makeIosSession('default', { sessionScope: { kind: 'cwd', id: 'b'.repeat(16) } }), + ); - const [check] = sessionChecks(store, here, store.get(here)); + const [check] = sessionChecks(doctorRequest, store, here, store.get(here)); expect(check?.status).toBe('warn'); expect(check?.summary).toContain(other); @@ -30,10 +46,13 @@ test('the same-device close suggestion shell-quotes a session name with metachar const store = makeSessionStore(); const here = 'cwd:aaaaaaaaaaaaaaaa:default'; const other = 'a;b $(x)'; - store.publish(here, makeIosSession('default')); - store.publish(other, makeIosSession(other)); + store.publish( + here, + makeIosSession('default', { sessionScope: { kind: 'cwd', id: 'a'.repeat(16) } }), + ); + store.publish(other, makeIosSession(other, { sessionScope: { kind: 'named-local' } })); - const [check] = sessionChecks(store, here, store.get(here)); + const [check] = sessionChecks(doctorRequest, store, here, store.get(here)); expect(check?.hint).toContain("agent-device close --session 'a;b $(x)' --platform"); }); @@ -43,9 +62,36 @@ test('a session alone on its device passes with its own address in evidence', () const here = 'cwd:aaaaaaaaaaaaaaaa:default'; store.publish(here, makeIosSession('default')); - const [check] = sessionChecks(store, here, store.get(here)); + const [check] = sessionChecks(doctorRequest, store, here, store.get(here)); expect(check?.status).toBe('pass'); expect(check?.command).toBeUndefined(); expect(check?.evidence).toMatchObject({ session: here }); }); + +// A session held by another client's lease is invisible to a request that does not carry the lease +// id (#4923). The doctor reports it the way it reports nothing: no name in summary, hint or +// evidence. +test('the same-device warning omits a session the request may not see', () => { + const store = makeSessionStore(); + const here = 'cwd:aaaaaaaaaaaaaaaa:default'; + store.publish(here, makeIosSession('default')); + store.publish( + 'e2b:agentB', + makeIosSession('e2b:agentB', { + sessionScope: { kind: 'tenant', id: 'e2b' }, + lease: { + leaseId: 'bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb', + tenantId: 'e2b', + runId: 'run-b', + backend: 'ios-simulator', + }, + }), + ); + + const [check] = sessionChecks(doctorRequest, store, here, store.get(here)); + + expect(check?.status).toBe('pass'); + expect(check?.summary).not.toContain('agentB'); + expect(check?.evidence).toMatchObject({ sameDeviceSessions: [] }); +}); diff --git a/packages/daemon/src/sessions/handlers/session-doctor-options.ts b/packages/daemon/src/sessions/handlers/session-doctor-options.ts index 76c54a72e7..9037f56860 100644 --- a/packages/daemon/src/sessions/handlers/session-doctor-options.ts +++ b/packages/daemon/src/sessions/handlers/session-doctor-options.ts @@ -4,6 +4,7 @@ import { shellQuoteIfNeeded } from '@agent-device/kernel/device-shell'; import type { SessionStore } from '../../core/session-store.ts'; import type { DaemonRequest } from '../../core/daemon-request.ts'; import type { SessionState } from '../../core/session-state.ts'; +import { mayNameSession } from '../session-routing.ts'; import type { DoctorOptions } from './session-doctor-types.ts'; import type { DoctorCheck, DoctorKind } from '@agent-device/contracts/observability'; @@ -88,6 +89,7 @@ export function remoteConnectionChecks( } export function sessionChecks( + req: DaemonRequest, sessionStore: SessionStore, sessionName: string, session: SessionState | undefined, @@ -95,13 +97,17 @@ export function sessionChecks( ): DoctorCheck[] { // Candidates report their ADDRESS — the string `close --session` actually accepts — and the // current session is excluded by address too: two cwd-scoped sessions share the name - // `default`, so a name compare would hide them from each other (#2031/#1394). + // `default`, so a name compare would hide them from each other (#2031/#1394). A session of + // another proxy client is not listed at all: the doctor reports it the way it reports nothing + // (#4923). + const nameableToRequest = (candidate: SessionState) => mayNameSession(req, candidate); const sameDeviceSessions = session ? sessionStore .listRefs() .filter( (candidate) => candidate.address !== sessionName && + nameableToRequest(candidate.session) && candidate.session.device.platform === session.device.platform && candidate.session.device.id === session.device.id, ) diff --git a/packages/daemon/src/sessions/handlers/session-doctor.ts b/packages/daemon/src/sessions/handlers/session-doctor.ts index 2a7276cbf2..c2b2fc5cc4 100644 --- a/packages/daemon/src/sessions/handlers/session-doctor.ts +++ b/packages/daemon/src/sessions/handlers/session-doctor.ts @@ -77,7 +77,7 @@ export async function handleDoctorCommand(params: { evidence: { version: readVersion(), stateDir }, }, ...remoteConnectionChecks(req, { required: options.remote }), - ...sessionChecks(sessionStore, sessionName, session, { remote: options.remote }), + ...sessionChecks(req, sessionStore, sessionName, session, { remote: options.remote }), ); if (options.remote) { diff --git a/packages/daemon/src/sessions/handlers/session-shutdown.ts b/packages/daemon/src/sessions/handlers/session-shutdown.ts index 89d5012f4e..b466c8c28c 100644 --- a/packages/daemon/src/sessions/handlers/session-shutdown.ts +++ b/packages/daemon/src/sessions/handlers/session-shutdown.ts @@ -15,7 +15,7 @@ import { } from '../../core/session-runtime-admission.ts'; import { deviceStatusReportResponse } from './session-device-status-response.ts'; import type { LeaseRegistry } from '../../resources/lease-registry.ts'; -import { createSessionVisibilityPredicate } from '../session-routing.ts'; +import { mayNameSession } from '../session-routing.ts'; import { releaseTargetLease } from '../target-lease-release.ts'; function shutdownUnavailableResponse(fact: RuntimeOperationFact) { @@ -63,7 +63,7 @@ export async function handleShutdownCommand( const deviceSession = params.sessionStore.findByDevice(device.id); if (deviceSession) { - const visible = createSessionVisibilityPredicate(params.req)(deviceSession.session); + const visible = mayNameSession(params.req, deviceSession.session); return errorResponse( 'DEVICE_IN_USE', 'Cannot shut down an active session device directly. Use close --shutdown to end the session and turn off the simulator/emulator.', diff --git a/packages/daemon/src/sessions/open-device-contention-wait.ts b/packages/daemon/src/sessions/open-device-contention-wait.ts index 088ab700ab..999da20635 100644 --- a/packages/daemon/src/sessions/open-device-contention-wait.ts +++ b/packages/daemon/src/sessions/open-device-contention-wait.ts @@ -8,7 +8,7 @@ import type { DaemonRequest } from '../core/daemon-request.ts'; import type { DaemonFailureResponse } from '@agent-device/kernel/contracts'; import type { SessionStore } from '../core/session-store.ts'; import type { SessionRecoveryOptions } from '../core/session-recovery-hints.ts'; -import { isImplicitSessionScopeConflict } from './session-routing.ts'; +import { isImplicitSessionScopeConflict, mayNameSession } from './session-routing.ts'; import { buildDeviceInUseBySessionError, buildForeignWorkspaceSessionConflict, @@ -139,6 +139,7 @@ export function findSessionHoldingDevice( /** * Resolves the device conflict refusal when another session already holds the target device. * Used by both session open and request-execution scope to enforce owner claims consistently. + * The holding session is named only when it is visible to the request (#4923). */ export function findSessionDeviceConflict(params: { req: DaemonRequest; @@ -152,10 +153,16 @@ export function findSessionDeviceConflict(params: { : sessionStore.findByDevice(device.id); if (!inUse) return undefined; const attempt = describeOpenWaitForRefusal(req); - if (isImplicitSessionScopeConflict(req, inUse.session)) { + const canNameHolder = mayNameSession(req, inUse.session, 'device-recovery'); + if (canNameHolder && isImplicitSessionScopeConflict(req, inUse.session)) { return buildForeignWorkspaceSessionConflict(inUse, device, attempt); } - return buildDeviceInUseBySessionError(inUse, device, attempt); + return buildDeviceInUseBySessionError( + inUse, + device, + attempt, + canNameHolder ? 'named' : 'anonymous', + ); } type LockedAttempt = { ran: true; outcome: Outcome } | { ran: false }; @@ -180,9 +187,11 @@ function createOpenDeviceWait(params: { emitRequestProgress({ type: 'command', status: 'progress', - message: `Waiting for ${holding.session.device.name}: held by session "${holding.address}" (${Math.round( - deadline.elapsedMs(), - )}ms of the ${Math.round(budgetMs)}ms wait budget used)`, + message: `Waiting for ${holding.session.device.name}: ${ + mayNameSession(req, holding.session, 'device-recovery') + ? `held by session "${holding.address}"` + : 'held by another session' + } (${Math.round(deadline.elapsedMs())}ms of the ${Math.round(budgetMs)}ms wait budget used)`, }); await sleep(Math.min(DEVICE_CONTENTION_POLL_MS, deadline.remainingMs())); // A client that gave up on the request must not leave the daemon queueing for a device diff --git a/packages/daemon/src/sessions/session-lifecycle/internal/__tests__/session-open-device-in-use.test.ts b/packages/daemon/src/sessions/session-lifecycle/internal/__tests__/session-open-device-in-use.test.ts index 5b049a9f3a..6c8e6dcf2f 100644 --- a/packages/daemon/src/sessions/session-lifecycle/internal/__tests__/session-open-device-in-use.test.ts +++ b/packages/daemon/src/sessions/session-lifecycle/internal/__tests__/session-open-device-in-use.test.ts @@ -26,7 +26,7 @@ const scopedRef: SessionRef = makeStoredSessionRef( ); test('the by-session conflict reports the address, in the message, details and hint', () => { - const response = buildDeviceInUseBySessionError(scopedRef, IOS_SIMULATOR); + const response = buildDeviceInUseBySessionError(scopedRef, IOS_SIMULATOR, {}, 'named'); expect(response.ok).toBe(false); if (response.ok) return; @@ -37,35 +37,47 @@ test('the by-session conflict reports the address, in the message, details and h ); }); -// The other workspace's session used to be reported as "another workspace session" with no -// address at all: the caller was told to wait for a session it could neither name, reach with -// --session, nor close. -test('the foreign-workspace conflict names the owning session address', () => { - const foreignAddress = 'cwd:1d9b7c2f4a6e8b03:default'; - const foreignRef: SessionRef = makeStoredSessionRef( - { - name: 'default', - sessionScope: { kind: 'cwd', id: '1d9b7c2f4a6e8b03' }, - device: IOS_SIMULATOR, - createdAt: 0, - actions: [], - }, - foreignAddress, - ); +// The session of another client on a proxy shared under one token is another client's handle +// (#4923): the refusal keeps the device fields and stays actionable through `session list`, and +// names nothing. +test('the by-session conflict names no session to a request that may not name it', () => { + const response = buildDeviceInUseBySessionError(scopedRef, IOS_SIMULATOR, {}, 'anonymous'); - const response = buildForeignWorkspaceSessionConflict(foreignRef, IOS_SIMULATOR); + expect(response.ok).toBe(false); + if (response.ok) return; + expect(response.error?.code).toBe('DEVICE_IN_USE'); + expect(response.error?.message).toBe('Device is already in use by another session.'); + expect(response.error?.details?.session).toBeUndefined(); + expect(String(response.error?.details?.hint)).not.toContain(SCOPED_ADDRESS); + expect(String(response.error?.details?.hint)).toContain('session list'); + expect(response.error?.details).toMatchObject({ + deviceId: IOS_SIMULATOR.id, + deviceName: IOS_SIMULATOR.name, + }); +}); + +// The foreign-workspace conflict keeps naming its holder: the address is the only handle that +// reaches another workspace's implicit session, and its owner can close it from that folder +// (#2580). +test('the foreign-workspace conflict names the holder address it can be closed with', () => { + const response = buildForeignWorkspaceSessionConflict(scopedRef, IOS_SIMULATOR, { + offersDeviceWait: true, + }); expect(response.ok).toBe(false); if (response.ok) return; expect(response.error?.code).toBe('DEVICE_IN_USE'); - expect(response.error?.message).toContain(foreignAddress); + expect(response.error?.message).toBe( + `Device is already in use by workspace session "${SCOPED_ADDRESS}".`, + ); expect(response.error?.details).toMatchObject({ reason: 'WORKSPACE_SESSION_SCOPE_CONFLICT', - session: foreignAddress, + session: SCOPED_ADDRESS, deviceId: IOS_SIMULATOR.id, }); - const hint = String(response.error?.details?.hint); - expect(hint).toContain(`agent-device close --session ${foreignAddress}`); + expect(String(response.error?.details?.hint)).toContain( + `agent-device close --session ${SCOPED_ADDRESS}`, + ); }); // A caller that already spent a --wait budget is not helped by being told to wait, and is misled @@ -86,8 +98,8 @@ test('a spent wait budget is reported as spent and never re-offered', () => { test('an open that never waited offers the wait instead of claiming one', () => { const hint = String( - buildDeviceInUseBySessionError(scopedRef, IOS_SIMULATOR, { offersDeviceWait: true }).error - ?.details?.hint, + buildDeviceInUseBySessionError(scopedRef, IOS_SIMULATOR, { offersDeviceWait: true }, 'named') + .error?.details?.hint, ); expect(hint).not.toMatch(/Waited/); @@ -98,8 +110,9 @@ test('an open that never waited offers the wait instead of claiming one', () => // owning session, and a hint ending in a flag its command rejects sends it away from both. test('a refusal from a command that cannot wait never offers the flag', () => { const hints = [ - buildDeviceInUseBySessionError(scopedRef, IOS_SIMULATOR), - buildForeignWorkspaceSessionConflict(scopedRef, IOS_SIMULATOR), + buildDeviceInUseBySessionError(scopedRef, IOS_SIMULATOR, {}, 'named'), + buildDeviceInUseBySessionError(scopedRef, IOS_SIMULATOR, {}, 'anonymous'), + buildForeignWorkspaceSessionConflict(scopedRef, IOS_SIMULATOR, {}), ]; for (const response of hints) { diff --git a/packages/daemon/src/sessions/session-lifecycle/internal/inventory.ts b/packages/daemon/src/sessions/session-lifecycle/internal/inventory.ts index 2cc21cfdea..39b67faef6 100644 --- a/packages/daemon/src/sessions/session-lifecycle/internal/inventory.ts +++ b/packages/daemon/src/sessions/session-lifecycle/internal/inventory.ts @@ -50,7 +50,7 @@ import { resolveCommandDevice, selectorTargetsSessionDevice, } from '../../../resources/session-device-resolution.ts'; -import { createSessionVisibilityPredicate } from '../../session-routing.ts'; +import { claimOwnerVisible, createSessionVisibilityPredicate } from '../../session-routing.ts'; import type { BoundDeviceRuntime, RuntimeFacts, @@ -89,7 +89,7 @@ export async function handleSessionInventoryCommands( case 'session_list': return sessionListInventoryResponse(req, sessionStore); case 'devices': - return await devicesInventoryResponse(req, params.host.env); + return await devicesInventoryResponse(req, params.host.env, sessionStore); case 'capabilities': return await capabilitiesInventoryResponse({ req, @@ -160,6 +160,7 @@ function publicSessionInfo({ address, session }: SessionRef, sessionStore: Sessi async function devicesInventoryResponse( req: DaemonRequest, env: HostEnvironment['env'], + sessionStore: SessionStore, ): Promise { try { const claims = await blockingClaims(env); @@ -168,7 +169,7 @@ async function devicesInventoryResponse( data: { devices: (await resolveInventoryDevices(req, env)).map((device) => ({ ...publicDeviceInfo(device), - ...claimedByProjection(device, claims), + ...claimedByProjection(device, claims, req, sessionStore), })), }, }; @@ -194,6 +195,8 @@ async function blockingClaims(env: HostEnvironment['env']): Promise candidate.deviceKey === deviceKey) ?? claims.find((candidate) => isClaimOfHostScopedDevice(identity, candidate)); - return claim ? { claimedBy: { session: claim.session, workspace: claim.workspace } } : {}; + // A claim owned by a session of this daemon that the request may not see is listed without its + // owner: the label would be another client's session handle (#4923). `open` still refuses the + // device, and `device status` stays the host-level view of who holds a device. + if (!claim || !claimOwnerVisible(req, sessionStore, claim)) return {}; + return { claimedBy: { session: claim.session, workspace: claim.workspace } }; } async function resolveInventoryDevices( diff --git a/packages/daemon/src/sessions/session-lifecycle/internal/session-open-execution.ts b/packages/daemon/src/sessions/session-lifecycle/internal/session-open-execution.ts index 9e546f6a69..20f41a8107 100644 --- a/packages/daemon/src/sessions/session-lifecycle/internal/session-open-execution.ts +++ b/packages/daemon/src/sessions/session-lifecycle/internal/session-open-execution.ts @@ -60,7 +60,7 @@ import { type ResolvedOpenRuntimeHintPlan, } from './session-open-prepare.ts'; import { findSessionDeviceConflict } from '../../open-device-contention-wait.ts'; -import { resolvePublicSessionName } from '../../session-routing.ts'; +import { claimOwnerVisible, resolvePublicSessionName } from '../../session-routing.ts'; import { applicationLifecycleExecutionFromRequest } from '../../application-lifecycle-execution.ts'; import { abandonDeviceClaim, @@ -121,9 +121,17 @@ function applyOrdinaryScriptRecordingOpenOutcome(params: { /** * What the caller's `open` output says when a claim was taken over because its device rebooted. A * `macos-app` lease tenant is not told whose claim it was: that belongs to the host (packages/daemon/docs/remote-device-lease-contracts.md). + * Nor is any caller told the owner of a claim that resolves to a session it may not see (#4923). */ -function deviceClaimTakeoverWarning(tookOver: TakenOverDeviceClaim, req: DaemonRequest): string { - if (req.internal?.admittedLease?.backend === 'macos-app') { +function deviceClaimTakeoverWarning( + tookOver: TakenOverDeviceClaim, + req: DaemonRequest, + sessionStore: SessionStore, +): string { + if ( + req.internal?.admittedLease?.backend === 'macos-app' || + !claimOwnerVisible(req, sessionStore, tookOver) + ) { return 'Took the device over: it rebooted after its previous claim was taken, so the previous app was already gone.'; } return ( @@ -394,7 +402,10 @@ export async function completeOpenCommand(params: { launchConfirmation: launchConfirmationReport(outcome), }); if (tookOverDeviceClaim) { - appendResponseWarning(openResult, deviceClaimTakeoverWarning(tookOverDeviceClaim, req)); + appendResponseWarning( + openResult, + deviceClaimTakeoverWarning(tookOverDeviceClaim, req, sessionStore), + ); } if (outcome.launchConfirmation === 'unanswered') { appendResponseWarning( diff --git a/packages/daemon/src/sessions/session-routing.ts b/packages/daemon/src/sessions/session-routing.ts index bacb867b8c..1ce3cc4de6 100644 --- a/packages/daemon/src/sessions/session-routing.ts +++ b/packages/daemon/src/sessions/session-routing.ts @@ -18,6 +18,9 @@ import { type SessionSelectorConflict, } from '../core/session-selector.ts'; import { LEASE_FIELD_NORMALIZERS, resolveLeaseScope } from '../core/lease-context.ts'; +import type { DaemonResponse } from '@agent-device/kernel/contracts'; +import { isDeviceClaimConflictReason } from '@agent-device/contracts/device'; +import { GENERIC_IN_USE_MESSAGE } from '../core/session-recovery-hints.ts'; const DEFAULT_SESSION_NAME = 'default'; const IMPLICIT_SESSION_KEY_PREFIX = 'cwd'; @@ -356,3 +359,101 @@ function findGitWorktreeRoot(startDir: string): string | undefined { current = parent; } } + +/** The ownership fields of a host-global device claim that this visibility rule needs. */ +export type ClaimOwnerRef = Readonly<{ + session: string; + workspace: string; + stateDir: string; +}>; + +/** + * Whether a reply may name `session` to this request. A remote caller (admitted as + * `publicNetworkOnly`, as every proxy client is) or a tenant-scoped one learns only a session it may + * list that is leased or tenant-scoped: on a proxy shared under one token, any other name is another + * client's (#4923). For device recovery, a local caller can also learn the address of an unleased + * local session in another workspace. Its owner uses that address to close it from that folder (#2580). + */ +export function mayNameSession( + req: DaemonRequest, + session: SessionState, + mode: 'listed' | 'device-recovery' = 'listed', +): boolean { + const listed = createSessionVisibilityPredicate(req)(session); + if (!isLocalCaller(req)) { + return listed && (session.lease !== undefined || session.sessionScope?.kind === 'tenant'); + } + return ( + listed || + (mode === 'device-recovery' && + session.lease === undefined && + session.sessionScope?.kind !== 'tenant') + ); +} + +/** A caller on this host: neither admitted from the public network nor scoped to a tenant. */ +function isLocalCaller(req: DaemonRequest): boolean { + return !req.internal?.publicNetworkOnly && resolveSessionScope(req).kind !== 'tenant'; +} + +/** + * Whether a reply may name the session a host-global device claim records as its owner. + * + * A claim of this daemon whose label resolves follows the device recovery naming rule. + * A local caller can also see the owner of a claim from another daemon on this host or a claim + * without a stored session. A remote or tenant-scoped caller can see only listable owners (#4923). + */ +export function claimOwnerVisible( + req: DaemonRequest, + sessionStore: SessionStore, + owner: ClaimOwnerRef, +): boolean { + const localRequest = isLocalCaller(req); + if (!isSameDaemonStateDir(owner.stateDir, sessionStore.resolveDaemonStateDir())) { + return localRequest; + } + const ref = sessionStore.lookup(owner.session); + return ref ? mayNameSession(req, ref.session, 'device-recovery') : localRequest; +} + +/** + * Answers a claim-conflict refusal without its owner when the owner is an unverified or invisible + * session of this daemon. The code, typed reason, classification, device fields, recovery command + * and hint stay; the `owner` detail and the message naming it go. + */ +export function dropInvisibleClaimOwner( + req: DaemonRequest, + sessionStore: SessionStore, + response: DaemonResponse, +): DaemonResponse { + if (response.ok) return response; + const { error } = response; + const details = error.details; + const owner = readClaimOwner(details?.owner); + if ( + !isDeviceClaimConflictReason(details?.reason) || + owner === undefined || + claimOwnerVisible(req, sessionStore, owner) + ) { + return response; + } + const { owner: _namedOwner, ...anonymousDetails } = details ?? {}; + return { + ok: false, + error: { ...error, message: GENERIC_IN_USE_MESSAGE, details: anonymousDetails }, + }; +} + +function isSameDaemonStateDir(claimStateDir: string, daemonStateDir: string): boolean { + return path.resolve(claimStateDir) === path.resolve(daemonStateDir); +} + +function readClaimOwner(owner: unknown): ClaimOwnerRef | undefined { + if (typeof owner !== 'object' || owner === null) return undefined; + const { session, workspace, stateDir } = owner as Record; + return typeof session === 'string' && + typeof workspace === 'string' && + typeof stateDir === 'string' + ? { session, workspace, stateDir } + : undefined; +} diff --git a/src/commands/schema/cli-help.ts b/src/commands/schema/cli-help.ts index 7da78b3bbc..0e2ef66a8a 100644 --- a/src/commands/schema/cli-help.ts +++ b/src/commands/schema/cli-help.ts @@ -327,8 +327,9 @@ Example: Device busy and ownership: DEVICE_IN_USE has two flavors. "already in use by session X" is this daemon's session table: reuse it with --session X, or run close --session X first. "owned by session X in workspace Y" is the host-global device claim another session — from this daemon or another worktree's daemon — or an in-flight command holds; there may be no session to close, and it is never retriable, so run the error's exact recovery command instead of retrying. - Inspect ownership without any daemon: agent-device device status (add --stale to list the claims it hides: dead, PID-reused, missing-state-directory, and daemon-replaced owners, some of which may still run; agent-device device release --stale settles and releases only owners proven unable to release). Its devices list inspects whether a new session can take each claimed device: acquirable true means no claim blocks it, false names the reason in blockedBy (live-owner, owner-pid-reused, owner-process-still-running, owner-liveness-unknown, claim-record-inconsistent, or a resource such as screen-recording-cleanup-pending that still waits for disposal). owner names the claim's owner when its record decodes: the holder that blocks the device, or, when acquirable, the reclaimable dead owner open would settle. It is an inspection, not a promise: status cannot see a reboot and runs no recovery, so open may decide differently, and a daemon's own abandoned claim, which status reports as blocked by that live owner, open through that same daemon may still take. A dead or replaced owner that retains nothing does not block by itself. hiddenStaleClaims counts the claim records this view hides and is not an availability signal, so read acquirable: a hidden owner whose PID was reused or whose state directory is gone, and pending resource cleanup, each still block the device. devices marks rows that are claimed, so pick an unclaimed device instead of contending. - A live foreign owner is released by closing its session from its own workspace or stopping its daemon: agent-device daemon stop --state-dir (the error names the state dir). The device itself can settle a claim: when it rebooted after that claim was taken, its app, runner, and accessibility session were destroyed, so open reconciles the owner's resources, takes the claim, and reports the release in warnings. Never recover by hunting PIDs with ps/kill. boot/install/shutdown take the same claims as open and refuse foreign-claimed devices identically; they do not ask the device about its boot. + Behind a shared proxy token, a holder that this caller cannot list is not named: both flavors answer "already in use by another session" and omit the owner, agent-device session list shows what the caller may close, and only the caller carrying the holder's lease id learns the name. + Inspect ownership without any daemon: agent-device device status (add --stale to list the claims it hides: dead, PID-reused, missing-state-directory, and daemon-replaced owners, some of which may still run; agent-device device release --stale settles and releases only owners proven unable to release). Its devices list inspects whether a new session can take each claimed device: acquirable true means no claim blocks it, false names the reason in blockedBy (live-owner, owner-pid-reused, owner-process-still-running, owner-liveness-unknown, claim-record-inconsistent, or a resource such as screen-recording-cleanup-pending that still waits for disposal). owner names the claim's owner when its record decodes: the holder that blocks the device, or, when acquirable, the reclaimable dead owner open would settle. It is an inspection, not a promise: status cannot see a reboot and runs no recovery, so open may decide differently, and a daemon's own abandoned claim, which status reports as blocked by that live owner, open through that same daemon may still take. A dead or replaced owner that retains nothing does not block by itself. hiddenStaleClaims counts the claim records this view hides and is not an availability signal, so read acquirable: a hidden owner whose PID was reused or whose state directory is gone, and pending resource cleanup, each still block the device. devices marks rows that are claimed, so pick an unclaimed device instead of contending; behind a shared proxy token, a row claimed by a holder this caller cannot list is not marked, and open on it answers DEVICE_IN_USE. + The error shows the owner and its state directory only if you can see the owner. If the error omits the owner, follow its recovery hint. If the error shows a live foreign owner, close its session from its workspace or run agent-device daemon stop --state-dir . The device itself can settle a claim: when it rebooted after that claim was taken, its app, runner, and accessibility session were destroyed, so open reconciles the owner's resources, takes the claim, and reports the release in warnings. Never recover by hunting PIDs with ps/kill. boot/install/shutdown take the same claims as open and refuse foreign-claimed devices identically; they do not ask the device about its boot. Use snapshot, screenshot, logs, network, perf frames, and perf memory for device/app runtime evidence. Use react-devtools when component internals or React rendering performance matter.`, }, diff --git a/website/docs/docs/sessions.md b/website/docs/docs/sessions.md index 4b5faf84d8..33f4c212e1 100644 --- a/website/docs/docs/sessions.md +++ b/website/docs/docs/sessions.md @@ -183,19 +183,25 @@ waits: agent-device open Demo --platform android --wait 60000 ``` -If the wait runs out while the device is still busy, `open` fails with `DEVICE_IN_USE` and names the -session address that holds it; `close --session
` releases it. Each waiting `open` gets its -full wait: if another waiter gets the device first, the rest keep waiting for what is left of their own -budget, so several agents can queue on one device. - -`--wait` waits only for another session. A device claimed by another workspace's -daemon is never waited for; `open` fails at once and names the command that releases it. +If the wait runs out while the device is still busy, `open` fails with `DEVICE_IN_USE`. +If the reply names the holder, its owner can run `close --session
` to release the device. +Each waiting `open` gets its full wait. If another waiter gets the device first, the rest keep +waiting for the time left in their own budgets. + +Behind a shared proxy token, all clients share a tenant. A proxy client can see the holder's address +in a refusal or in wait progress if it can list the holder and the holder has a lease or a tenant +scope. To see the address of a leased holder, the caller must send that holder's lease id. +Open contention and claim conflicts can show the address of an unleased session in another +workspace to a local caller. The owner can use that address to close the session from its workspace. + +`--wait` waits only for another session. If another workspace's daemon holds the claim, +`open` fails at once. Device-mutating commands like `install` and `reinstall` don't wait either: while a session other than yours holds the device, they fail at once with `DEVICE_IN_USE`. Copying the owner's `--session` address doesn't change that — the claim must also record your workspace, so a command run from another checkout is refused even under -the owner's name. The error names the owner when the claim is readable; when it -isn't, `agent-device device status` shows what holds the device. +the owner's name. The error shows the owner and its state directory only if you can see the owner. +If the error omits the owner, follow its recovery hint. ## Release a device another session or workspace holds