From f0af0cd876bf55a670f2049c00e12c9eb2b387cb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Sun, 22 Nov 2026 11:04:34 +0100 Subject: [PATCH 1/9] fix(daemon): answer a busy device without naming another proxy client's session On a proxy shared under one token every client is one tenant, so a leased session belongs to another client, and busy-device answers that carried its address confirmed the session and handed out a handle. A reply may name a holder unless it is another client's: a leased session, or a tenant-scoped session the request does not already see. The open contention refusal, its wait progress, the doctor same-device list, the claimed-device projection, the reboot-takeover warning, and claim- conflict refusals answer generically for that holder; a claim is verified through its state dir. A local session of another workspace keeps its named address: #2580's recovery stands. Closes #4923 --- .../daemon/src/core/session-recovery-hints.ts | 52 +++- .../request-router-open-claim.test.ts | 2 + ...http-server-proxy-reply-visibility.test.ts | 268 ++++++++++++++++++ packages/daemon/src/server/request-router.ts | 19 +- .../open-device-contention-wait.test.ts | 163 ++++++++++- .../reply-session-visibility.test.ts | 172 +++++++++++ .../__tests__/session-doctor-options.test.ts | 55 +++- .../handlers/session-doctor-options.ts | 8 +- .../src/sessions/handlers/session-doctor.ts | 2 +- .../sessions/open-device-contention-wait.ts | 26 +- .../src/sessions/reply-session-visibility.ts | 88 ++++++ .../session-open-device-in-use.test.ts | 63 ++-- .../session-lifecycle/internal/inventory.ts | 14 +- .../internal/session-open-execution.ts | 18 +- src/commands/schema/cli-help.ts | 1 + website/docs/docs/sessions.md | 8 + 16 files changed, 902 insertions(+), 57 deletions(-) create mode 100644 packages/daemon/src/server/http/http-server-proxy-reply-visibility.test.ts create mode 100644 packages/daemon/src/sessions/__tests__/reply-session-visibility.test.ts create mode 100644 packages/daemon/src/sessions/reply-session-visibility.ts 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..61e7a8db53 --- /dev/null +++ b/packages/daemon/src/server/http/http-server-proxy-reply-visibility.test.ts @@ -0,0 +1,268 @@ +// 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 }; + error?: { + data?: { code?: string; message?: string; hint?: string; details?: Record }; + }; +}; + +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, + leaseBackend: 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, + 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, + /** Sends `command` as `session` with the given lease metadata and flags. */ + send: async ( + session: string, + command: string, + params: { meta?: Record; flags?: Record } = {}, + positionals: string[] = [], + ) => { + const response = await fetch(`http://127.0.0.1:${proxyPort}/agent-device/rpc`, { + method: 'POST', + headers: { authorization: `Bearer ${PROXY_TOKEN}`, 'content-type': 'application/json' }, + body: JSON.stringify({ + jsonrpc: '2.0', + id: 1, + method: 'agent_device.command', + params: { + session, + command, + positionals, + flags: params.flags ?? {}, + meta: { + tenantId: TENANT, + sessionIsolation: 'tenant', + sessionExplicit: true, + ...params.meta, + }, + }, + }), + }); + return (await response.json()) as RpcBody; + }, + /** 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); +}); diff --git a/packages/daemon/src/server/request-router.ts b/packages/daemon/src/server/request-router.ts index c5d4aa7e86..c9b157f31a 100644 --- a/packages/daemon/src/server/request-router.ts +++ b/packages/daemon/src/server/request-router.ts @@ -81,6 +81,7 @@ 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 { dropInvisibleClaimOwner } from '../sessions/reply-session-visibility.ts'; import { resolveEffectiveSessionName } from '../sessions/session-routing.ts'; import { sessionIdleExpiredError } from './session-idle-expiry.ts'; import type { IdleSessionTombstone } from '../core/session-idle-tombstone.ts'; @@ -325,7 +326,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 +526,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( + 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..7c9b41c75f 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,165 @@ 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: 'lease-a', tenantId: 'e2b', runId: 'run-a' }, + 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: 'lease-a', tenantId: 'e2b', runId: 'run-a' }, + 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: 'lease-a', tenantId: 'e2b', runId: 'run-a' }, + device: IOS_SIMULATOR, + createdAt: 0, + actions: [], + }); + const conflict = findSessionDeviceConflict({ + req: { + ...openRequest({}), + session: 'agentA', + meta: { + requestId: 'req-open-wait', + tenantId: 'e2b', + sessionIsolation: 'tenant', + leaseId: 'lease-a', + }, + }, + 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__/reply-session-visibility.test.ts b/packages/daemon/src/sessions/__tests__/reply-session-visibility.test.ts new file mode 100644 index 0000000000..309fb05bc7 --- /dev/null +++ b/packages/daemon/src/sessions/__tests__/reply-session-visibility.test.ts @@ -0,0 +1,172 @@ +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 '../reply-session-visibility.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, + }, + }; +} + +function storeWithLeasedSession(): SessionStore { + const store = makeSessionStore('agent-device-reply-visibility-'); + store.publish( + 'e2b:agentA', + makeIosAppSession('e2b:agentA', { + sessionScope: { kind: 'tenant', id: TENANT }, + lease: { leaseId: 'lease-a', tenantId: TENANT, runId: 'run-a' }, + }), + ); + 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: 'lease-a' }), + 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: 'lease-a' }), + 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 claim another daemon on this host wrote keeps its recorded owner', () => { + const store = storeWithLeasedSession(); + const peerStateDir = mkdtempForTestSync('agent-device-reply-visibility-peer-'); + + const response = dropInvisibleClaimOwner( + request(), + store, + claimConflictResponse('default', path.join(peerStateDir, 'daemon')), + ); + + expect(response.ok).toBe(false); + if (response.ok) return; + expect(response.error.message).toContain('default'); + expect(response.error.details?.owner).toMatchObject({ workspace: '/work/a' }); +}); + +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); +}); + +// The naming rule: another proxy client's leased or tenant-scoped session is the only thing a +// local caller may not be told. A local session of another workspace keeps its address (#2580). +test('the naming rule hides only leased and tenant-scoped sessions', () => { + const store = storeWithLeasedSession(); + const own = { session: 'e2b:agentA', workspace: '/w', stateDir: store.resolveDaemonStateDir() }; + + expect(claimOwnerVisible(request(), store, own)).toBe(false); + expect(claimOwnerVisible(request({ leaseId: 'lease-a' }), store, own)).toBe(true); + expect( + claimOwnerVisible(request({ leaseId: 'lease-a' }), store, { ...own, session: 'gone' }), + ).toBe(false); + expect( + claimOwnerVisible(request(), store, { ...own, stateDir: path.join(own.stateDir, 'peer') }), + ).toBe(true); + + const foreignWorkspaceSession = { + name: 'default', + sessionScope: { kind: 'cwd' as const, id: 'b'.repeat(16) }, + device: IOS_SIMULATOR, + createdAt: 0, + actions: [], + }; + expect(mayNameSession(request(), foreignWorkspaceSession)).toBe(true); + 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..96e1180536 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,31 @@ 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: 'lease-b', tenantId: 'e2b', runId: 'run-b' }, + }), + ); + + 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..5ef7cf570a 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 '../reply-session-visibility.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/open-device-contention-wait.ts b/packages/daemon/src/sessions/open-device-contention-wait.ts index 088ab700ab..3c29187198 100644 --- a/packages/daemon/src/sessions/open-device-contention-wait.ts +++ b/packages/daemon/src/sessions/open-device-contention-wait.ts @@ -7,8 +7,10 @@ import type { DeviceInfo } from '@agent-device/kernel/device'; 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 type { SessionState } from '../core/session-state.ts'; +import type { HeldSessionNaming, SessionRecoveryOptions } from '../core/session-recovery-hints.ts'; import { isImplicitSessionScopeConflict } from './session-routing.ts'; +import { mayNameSession } from './reply-session-visibility.ts'; import { buildDeviceInUseBySessionError, buildForeignWorkspaceSessionConflict, @@ -139,6 +141,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; @@ -155,7 +158,17 @@ export function findSessionDeviceConflict(params: { if (isImplicitSessionScopeConflict(req, inUse.session)) { return buildForeignWorkspaceSessionConflict(inUse, device, attempt); } - return buildDeviceInUseBySessionError(inUse, device, attempt); + return buildDeviceInUseBySessionError( + inUse, + device, + attempt, + heldSessionNaming(req, inUse.session), + ); +} + +/** Whether a refusal may name this holding session to this request. */ +function heldSessionNaming(req: DaemonRequest, holder: SessionState): HeldSessionNaming { + return mayNameSession(req, holder) ? 'named' : 'anonymous'; } type LockedAttempt = { ran: true; outcome: Outcome } | { ran: false }; @@ -172,6 +185,7 @@ function createOpenDeviceWait(params: { const holder = () => findSessionHoldingDevice(sessionStore, deviceId, sessionName); const waitForDeviceOutsideLocks = async (): Promise => { + const naming = (holder: SessionState) => mayNameSession(req, holder); for (;;) { const holding = holder(); // Either nobody is on the device and this open goes looking for it under the locks, or the @@ -180,9 +194,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}: ${ + naming(holding.session) + ? `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/reply-session-visibility.ts b/packages/daemon/src/sessions/reply-session-visibility.ts new file mode 100644 index 0000000000..95c901657a --- /dev/null +++ b/packages/daemon/src/sessions/reply-session-visibility.ts @@ -0,0 +1,88 @@ +import path from 'node:path'; +import type { DaemonResponse } from '@agent-device/kernel/contracts'; +import { isDeviceClaimConflictReason } from '@agent-device/contracts/device'; +import type { SessionStore } from '../core/session-store.ts'; +import type { SessionState } from '../core/session-state.ts'; +import type { DaemonRequest } from '../core/daemon-request.ts'; +import { GENERIC_IN_USE_MESSAGE } from '../core/session-recovery-hints.ts'; +import { createSessionVisibilityPredicate } from './session-routing.ts'; + +/** 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. The listing rule decides the common case; + * the exception is #2580's: a local session of another workspace stays unnamed by the listing yet + * must keep its address, because that address is the handle its owner uses to close it from that + * folder. What may never be named is the session of another client on a proxy shared under one + * token — a leased session, or any tenant-scoped session the request does not already see (#4923). + */ +export function mayNameSession(req: DaemonRequest, session: SessionState): boolean { + if (createSessionVisibilityPredicate(req)(session)) return true; + return session.lease === undefined && session.sessionScope?.kind !== 'tenant'; +} + +/** + * Whether a reply may name the session a host-global device claim records as its owner. + * + * The claim names the state dir of the daemon that wrote it. A claim this daemon wrote is verified + * only when its session label still resolves in the store and may be named to the request; an + * expired tenant's unresolvable label gets the generic refusal (#4923). A claim another daemon on + * this host wrote names a session that is not in this store at all, and naming its recorded owner + * and workspace is the documented cross-worktree recovery this refusal exists for, so it stays. + */ +export function claimOwnerVisible( + req: DaemonRequest, + sessionStore: SessionStore, + owner: ClaimOwnerRef, +): boolean { + if (!isSameDaemonStateDir(owner.stateDir, sessionStore.resolveDaemonStateDir())) return true; + const ref = sessionStore.lookup(owner.session); + return ref !== undefined && mayNameSession(req, ref.session); +} + +/** + * 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/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..ee3f6269e3 100644 --- a/packages/daemon/src/sessions/session-lifecycle/internal/inventory.ts +++ b/packages/daemon/src/sessions/session-lifecycle/internal/inventory.ts @@ -51,6 +51,7 @@ import { selectorTargetsSessionDevice, } from '../../../resources/session-device-resolution.ts'; import { createSessionVisibilityPredicate } from '../../session-routing.ts'; +import { claimOwnerVisible } from '../../reply-session-visibility.ts'; import type { BoundDeviceRuntime, RuntimeFacts, @@ -89,7 +90,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 +161,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 +170,7 @@ async function devicesInventoryResponse( data: { devices: (await resolveInventoryDevices(req, env)).map((device) => ({ ...publicDeviceInfo(device), - ...claimedByProjection(device, claims), + ...claimedByProjection(device, claims, req, sessionStore), })), }, }; @@ -194,6 +196,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..86dc1c6f9c 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 @@ -75,6 +75,7 @@ import { import { appendResponseWarning } from './session-open-warnings.ts'; import { buildDeviceClaimConflictError } from '../../../resources/device/device-claim-conflict.ts'; import { deviceClaimRuleForOwner } from '../../../resources/device/device-claim-rule.ts'; +import { claimOwnerVisible } from '../../reply-session-visibility.ts'; import { errorResponse, type DaemonResponse } from '@agent-device/kernel/contracts'; export type SessionOpenResult = @@ -121,9 +122,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 +403,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/src/commands/schema/cli-help.ts b/src/commands/schema/cli-help.ts index 7da78b3bbc..48b7e36bf0 100644 --- a/src/commands/schema/cli-help.ts +++ b/src/commands/schema/cli-help.ts @@ -327,6 +327,7 @@ 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. + Behind a shared proxy token, both flavors answer "already in use by another session" and omit the owner: a session another client leases is not visible to this caller, so agent-device session list is how it finds what it 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. 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. diff --git a/website/docs/docs/sessions.md b/website/docs/docs/sessions.md index 4b5faf84d8..9a65515614 100644 --- a/website/docs/docs/sessions.md +++ b/website/docs/docs/sessions.md @@ -188,6 +188,14 @@ session address that holds it; `close --session
` releases it. Each wai 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. +Behind a shared proxy token, every client is the same tenant and one client cannot see another's +leased session. Refusals about that holder — a session with a lease, or any tenant-scoped session +the caller does not already see — say only that another session holds the device, in the message, +the details, and the wait progress; `session list` shows each caller what it may close. A caller +that carries the holder's lease id is the lease's owner and still gets the name. A session of +another local workspace keeps its named address everywhere: that address is how its owner closes it +from that folder. + `--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. Device-mutating commands like `install` and `reinstall` don't wait either: while a From d796c93ed7eb39bfda31399bd549fa905323310b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Sun, 22 Nov 2026 11:20:42 +0100 Subject: [PATCH 2/9] refactor(daemon): keep the reply naming rule beside the session visibility rule in session-routing --- packages/daemon/src/server/request-router.ts | 6 +- ... session-routing-reply-visibility.test.ts} | 6 +- .../handlers/session-doctor-options.ts | 2 +- .../sessions/open-device-contention-wait.ts | 3 +- .../src/sessions/reply-session-visibility.ts | 88 ------------------- .../session-lifecycle/internal/inventory.ts | 3 +- .../internal/session-open-execution.ts | 3 +- .../daemon/src/sessions/session-routing.ts | 83 +++++++++++++++++ 8 files changed, 92 insertions(+), 102 deletions(-) rename packages/daemon/src/sessions/__tests__/{reply-session-visibility.test.ts => session-routing-reply-visibility.test.ts} (98%) delete mode 100644 packages/daemon/src/sessions/reply-session-visibility.ts diff --git a/packages/daemon/src/server/request-router.ts b/packages/daemon/src/server/request-router.ts index c9b157f31a..d032e2c773 100644 --- a/packages/daemon/src/server/request-router.ts +++ b/packages/daemon/src/server/request-router.ts @@ -81,8 +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 { dropInvisibleClaimOwner } from '../sessions/reply-session-visibility.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 { diff --git a/packages/daemon/src/sessions/__tests__/reply-session-visibility.test.ts b/packages/daemon/src/sessions/__tests__/session-routing-reply-visibility.test.ts similarity index 98% rename from packages/daemon/src/sessions/__tests__/reply-session-visibility.test.ts rename to packages/daemon/src/sessions/__tests__/session-routing-reply-visibility.test.ts index 309fb05bc7..62f5a60ade 100644 --- a/packages/daemon/src/sessions/__tests__/reply-session-visibility.test.ts +++ b/packages/daemon/src/sessions/__tests__/session-routing-reply-visibility.test.ts @@ -5,11 +5,7 @@ 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 '../reply-session-visibility.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 diff --git a/packages/daemon/src/sessions/handlers/session-doctor-options.ts b/packages/daemon/src/sessions/handlers/session-doctor-options.ts index 5ef7cf570a..9037f56860 100644 --- a/packages/daemon/src/sessions/handlers/session-doctor-options.ts +++ b/packages/daemon/src/sessions/handlers/session-doctor-options.ts @@ -4,7 +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 '../reply-session-visibility.ts'; +import { mayNameSession } from '../session-routing.ts'; import type { DoctorOptions } from './session-doctor-types.ts'; import type { DoctorCheck, DoctorKind } from '@agent-device/contracts/observability'; diff --git a/packages/daemon/src/sessions/open-device-contention-wait.ts b/packages/daemon/src/sessions/open-device-contention-wait.ts index 3c29187198..a2e587a9ae 100644 --- a/packages/daemon/src/sessions/open-device-contention-wait.ts +++ b/packages/daemon/src/sessions/open-device-contention-wait.ts @@ -9,8 +9,7 @@ import type { DaemonFailureResponse } from '@agent-device/kernel/contracts'; import type { SessionStore } from '../core/session-store.ts'; import type { SessionState } from '../core/session-state.ts'; import type { HeldSessionNaming, SessionRecoveryOptions } from '../core/session-recovery-hints.ts'; -import { isImplicitSessionScopeConflict } from './session-routing.ts'; -import { mayNameSession } from './reply-session-visibility.ts'; +import { isImplicitSessionScopeConflict, mayNameSession } from './session-routing.ts'; import { buildDeviceInUseBySessionError, buildForeignWorkspaceSessionConflict, diff --git a/packages/daemon/src/sessions/reply-session-visibility.ts b/packages/daemon/src/sessions/reply-session-visibility.ts deleted file mode 100644 index 95c901657a..0000000000 --- a/packages/daemon/src/sessions/reply-session-visibility.ts +++ /dev/null @@ -1,88 +0,0 @@ -import path from 'node:path'; -import type { DaemonResponse } from '@agent-device/kernel/contracts'; -import { isDeviceClaimConflictReason } from '@agent-device/contracts/device'; -import type { SessionStore } from '../core/session-store.ts'; -import type { SessionState } from '../core/session-state.ts'; -import type { DaemonRequest } from '../core/daemon-request.ts'; -import { GENERIC_IN_USE_MESSAGE } from '../core/session-recovery-hints.ts'; -import { createSessionVisibilityPredicate } from './session-routing.ts'; - -/** 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. The listing rule decides the common case; - * the exception is #2580's: a local session of another workspace stays unnamed by the listing yet - * must keep its address, because that address is the handle its owner uses to close it from that - * folder. What may never be named is the session of another client on a proxy shared under one - * token — a leased session, or any tenant-scoped session the request does not already see (#4923). - */ -export function mayNameSession(req: DaemonRequest, session: SessionState): boolean { - if (createSessionVisibilityPredicate(req)(session)) return true; - return session.lease === undefined && session.sessionScope?.kind !== 'tenant'; -} - -/** - * Whether a reply may name the session a host-global device claim records as its owner. - * - * The claim names the state dir of the daemon that wrote it. A claim this daemon wrote is verified - * only when its session label still resolves in the store and may be named to the request; an - * expired tenant's unresolvable label gets the generic refusal (#4923). A claim another daemon on - * this host wrote names a session that is not in this store at all, and naming its recorded owner - * and workspace is the documented cross-worktree recovery this refusal exists for, so it stays. - */ -export function claimOwnerVisible( - req: DaemonRequest, - sessionStore: SessionStore, - owner: ClaimOwnerRef, -): boolean { - if (!isSameDaemonStateDir(owner.stateDir, sessionStore.resolveDaemonStateDir())) return true; - const ref = sessionStore.lookup(owner.session); - return ref !== undefined && mayNameSession(req, ref.session); -} - -/** - * 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/packages/daemon/src/sessions/session-lifecycle/internal/inventory.ts b/packages/daemon/src/sessions/session-lifecycle/internal/inventory.ts index ee3f6269e3..39b67faef6 100644 --- a/packages/daemon/src/sessions/session-lifecycle/internal/inventory.ts +++ b/packages/daemon/src/sessions/session-lifecycle/internal/inventory.ts @@ -50,8 +50,7 @@ import { resolveCommandDevice, selectorTargetsSessionDevice, } from '../../../resources/session-device-resolution.ts'; -import { createSessionVisibilityPredicate } from '../../session-routing.ts'; -import { claimOwnerVisible } from '../../reply-session-visibility.ts'; +import { claimOwnerVisible, createSessionVisibilityPredicate } from '../../session-routing.ts'; import type { BoundDeviceRuntime, RuntimeFacts, 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 86dc1c6f9c..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, @@ -75,7 +75,6 @@ import { import { appendResponseWarning } from './session-open-warnings.ts'; import { buildDeviceClaimConflictError } from '../../../resources/device/device-claim-conflict.ts'; import { deviceClaimRuleForOwner } from '../../../resources/device/device-claim-rule.ts'; -import { claimOwnerVisible } from '../../reply-session-visibility.ts'; import { errorResponse, type DaemonResponse } from '@agent-device/kernel/contracts'; export type SessionOpenResult = diff --git a/packages/daemon/src/sessions/session-routing.ts b/packages/daemon/src/sessions/session-routing.ts index bacb867b8c..5c68c5a59b 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,83 @@ 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. The listing rule decides the common case; + * the exception is #2580's: a local session of another workspace stays unnamed by the listing yet + * must keep its address, because that address is the handle its owner uses to close it from that + * folder. What may never be named is the session of another client on a proxy shared under one + * token — a leased session, or any tenant-scoped session the request does not already see (#4923). + */ +export function mayNameSession(req: DaemonRequest, session: SessionState): boolean { + if (createSessionVisibilityPredicate(req)(session)) return true; + return session.lease === undefined && session.sessionScope?.kind !== 'tenant'; +} + +/** + * Whether a reply may name the session a host-global device claim records as its owner. + * + * The claim names the state dir of the daemon that wrote it. A claim this daemon wrote is verified + * only when its session label still resolves in the store and may be named to the request; an + * expired tenant's unresolvable label gets the generic refusal (#4923). A claim another daemon on + * this host wrote names a session that is not in this store at all, and naming its recorded owner + * and workspace is the documented cross-worktree recovery this refusal exists for, so it stays. + */ +export function claimOwnerVisible( + req: DaemonRequest, + sessionStore: SessionStore, + owner: ClaimOwnerRef, +): boolean { + if (!isSameDaemonStateDir(owner.stateDir, sessionStore.resolveDaemonStateDir())) return true; + const ref = sessionStore.lookup(owner.session); + return ref !== undefined && mayNameSession(req, ref.session); +} + +/** + * 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; +} From d79cc98e28c723b09b370ba4b6efabd8456da8e4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Sun, 22 Nov 2026 11:40:35 +0100 Subject: [PATCH 3/9] fix(daemon): name the owner of a claim that resolves to no session, except to a tenant-scoped request --- .../session-routing-reply-visibility.test.ts | 14 ++++++++++++++ packages/daemon/src/sessions/session-routing.ts | 13 +++++++------ 2 files changed, 21 insertions(+), 6 deletions(-) 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 index 62f5a60ade..69351d4508 100644 --- a/packages/daemon/src/sessions/__tests__/session-routing-reply-visibility.test.ts +++ b/packages/daemon/src/sessions/__tests__/session-routing-reply-visibility.test.ts @@ -111,6 +111,20 @@ test('a claim of this daemon whose session no longer resolves is not named', () 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( + request({ tenantId: undefined, sessionIsolation: undefined }), + 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 recorded owner', () => { const store = storeWithLeasedSession(); const peerStateDir = mkdtempForTestSync('agent-device-reply-visibility-peer-'); diff --git a/packages/daemon/src/sessions/session-routing.ts b/packages/daemon/src/sessions/session-routing.ts index 5c68c5a59b..ebe40864ec 100644 --- a/packages/daemon/src/sessions/session-routing.ts +++ b/packages/daemon/src/sessions/session-routing.ts @@ -382,11 +382,11 @@ export function mayNameSession(req: DaemonRequest, session: SessionState): boole /** * Whether a reply may name the session a host-global device claim records as its owner. * - * The claim names the state dir of the daemon that wrote it. A claim this daemon wrote is verified - * only when its session label still resolves in the store and may be named to the request; an - * expired tenant's unresolvable label gets the generic refusal (#4923). A claim another daemon on - * this host wrote names a session that is not in this store at all, and naming its recorded owner - * and workspace is the documented cross-worktree recovery this refusal exists for, so it stays. + * A claim of another daemon on this host keeps its owner: that is the documented cross-worktree + * recovery. A claim of this daemon whose label resolves follows `mayNameSession`. A label that names + * no stored session, such as a transient command's claim or a claim that outlived its session, is + * named to a local request as before and hidden from a tenant-scoped one: on a proxy shared under + * one token, the tenant prefix does not tell one client's ended session from another's (#4923). */ export function claimOwnerVisible( req: DaemonRequest, @@ -395,7 +395,8 @@ export function claimOwnerVisible( ): boolean { if (!isSameDaemonStateDir(owner.stateDir, sessionStore.resolveDaemonStateDir())) return true; const ref = sessionStore.lookup(owner.session); - return ref !== undefined && mayNameSession(req, ref.session); + if (ref) return mayNameSession(req, ref.session); + return resolveSessionScope(req).kind !== 'tenant'; } /** From b935f1ac2aae5aef436a76ab61e0f9ebb6a28b67 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Sun, 22 Nov 2026 12:15:22 +0100 Subject: [PATCH 4/9] fix(daemon): name no unlistable holder to a tenant-scoped request --- ...http-server-proxy-reply-visibility.test.ts | 26 ++++++++++++ packages/daemon/src/server/request-router.ts | 2 +- .../session-routing-reply-visibility.test.ts | 40 ++++++++++--------- .../src/sessions/handlers/session-shutdown.ts | 4 +- .../sessions/open-device-contention-wait.ts | 3 +- .../daemon/src/sessions/session-routing.ts | 29 ++++++++------ src/commands/schema/cli-help.ts | 4 +- 7 files changed, 70 insertions(+), 38 deletions(-) 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 index 61e7a8db53..15950510d8 100644 --- 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 @@ -266,3 +266,29 @@ test('the peer client gets a claim conflict without the holder session', async ( 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); +}); diff --git a/packages/daemon/src/server/request-router.ts b/packages/daemon/src/server/request-router.ts index d032e2c773..31e9566d09 100644 --- a/packages/daemon/src/server/request-router.ts +++ b/packages/daemon/src/server/request-router.ts @@ -529,7 +529,7 @@ export function createRequestHandler(deps: RequestRouterDeps): DaemonInvokeFn { return redactSensitiveFillResponse( req, dropInvisibleClaimOwner( - req, + childScope?.req ?? req, sessionStore, await finalizeRequestBindingCleanup(childScope, response), ), 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 index 69351d4508..6eb469e5f9 100644 --- a/packages/daemon/src/sessions/__tests__/session-routing-reply-visibility.test.ts +++ b/packages/daemon/src/sessions/__tests__/session-routing-reply-visibility.test.ts @@ -30,6 +30,8 @@ function request(overrides: Partial = {}): DaemonRequest }; } +const LOCAL_REQUEST = request({ tenantId: undefined, sessionIsolation: undefined }); + function storeWithLeasedSession(): SessionStore { const store = makeSessionStore('agent-device-reply-visibility-'); store.publish( @@ -115,7 +117,7 @@ test('a local request keeps the owner of a transient claim of this daemon', () = const store = storeWithLeasedSession(); const response = dropInvisibleClaimOwner( - request({ tenantId: undefined, sessionIsolation: undefined }), + LOCAL_REQUEST, store, claimConflictResponse('transient:install', store.resolveDaemonStateDir()), ); @@ -125,20 +127,21 @@ test('a local request keeps the owner of a transient claim of this daemon', () = expect(response.error.details?.owner).toMatchObject({ session: 'transient:install' }); }); -test('a claim another daemon on this host wrote keeps its recorded owner', () => { +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 response = dropInvisibleClaimOwner( - request(), - store, - claimConflictResponse('default', path.join(peerStateDir, 'daemon')), - ); - - expect(response.ok).toBe(false); - if (response.ok) return; - expect(response.error.message).toContain('default'); - expect(response.error.details?.owner).toMatchObject({ workspace: '/work/a' }); + 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', () => { @@ -157,7 +160,7 @@ test('a refusal without a claim owner passes through', () => { // The naming rule: another proxy client's leased or tenant-scoped session is the only thing a // local caller may not be told. A local session of another workspace keeps its address (#2580). -test('the naming rule hides only leased and tenant-scoped sessions', () => { +test('a tenant-scoped request learns only sessions it may list; a local request keeps #2580', () => { const store = storeWithLeasedSession(); const own = { session: 'e2b:agentA', workspace: '/w', stateDir: store.resolveDaemonStateDir() }; @@ -166,9 +169,9 @@ test('the naming rule hides only leased and tenant-scoped sessions', () => { expect( claimOwnerVisible(request({ leaseId: 'lease-a' }), store, { ...own, session: 'gone' }), ).toBe(false); - expect( - claimOwnerVisible(request(), store, { ...own, stateDir: path.join(own.stateDir, 'peer') }), - ).toBe(true); + 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', @@ -177,6 +180,7 @@ test('the naming rule hides only leased and tenant-scoped sessions', () => { createdAt: 0, actions: [], }; - expect(mayNameSession(request(), foreignWorkspaceSession)).toBe(true); + expect(mayNameSession(request(), foreignWorkspaceSession)).toBe(false); + expect(mayNameSession(LOCAL_REQUEST, foreignWorkspaceSession)).toBe(true); expect(mayNameSession(request(), store.get('e2b:agentA')!)).toBe(false); }); 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 a2e587a9ae..a83344eafe 100644 --- a/packages/daemon/src/sessions/open-device-contention-wait.ts +++ b/packages/daemon/src/sessions/open-device-contention-wait.ts @@ -184,7 +184,6 @@ function createOpenDeviceWait(params: { const holder = () => findSessionHoldingDevice(sessionStore, deviceId, sessionName); const waitForDeviceOutsideLocks = async (): Promise => { - const naming = (holder: SessionState) => mayNameSession(req, holder); for (;;) { const holding = holder(); // Either nobody is on the device and this open goes looking for it under the locks, or the @@ -194,7 +193,7 @@ function createOpenDeviceWait(params: { type: 'command', status: 'progress', message: `Waiting for ${holding.session.device.name}: ${ - naming(holding.session) + mayNameSession(req, holding.session) ? `held by session "${holding.address}"` : 'held by another session' } (${Math.round(deadline.elapsedMs())}ms of the ${Math.round(budgetMs)}ms wait budget used)`, diff --git a/packages/daemon/src/sessions/session-routing.ts b/packages/daemon/src/sessions/session-routing.ts index ebe40864ec..07390acbe8 100644 --- a/packages/daemon/src/sessions/session-routing.ts +++ b/packages/daemon/src/sessions/session-routing.ts @@ -368,35 +368,38 @@ export type ClaimOwnerRef = Readonly<{ }>; /** - * Whether a reply may name `session` to this request. The listing rule decides the common case; - * the exception is #2580's: a local session of another workspace stays unnamed by the listing yet - * must keep its address, because that address is the handle its owner uses to close it from that - * folder. What may never be named is the session of another client on a proxy shared under one - * token — a leased session, or any tenant-scoped session the request does not already see (#4923). + * Whether a reply may name `session` to this request. The listing rule decides. A local request has + * one exception, #2580's: a local session of another workspace stays unnamed by the listing yet keeps + * its address, because that address is the handle its owner uses to close it from that folder. A + * tenant-scoped request, which is how a client reaches a proxy shared under one token, gets no + * exception: it learns only the sessions it may list (#4923). */ export function mayNameSession(req: DaemonRequest, session: SessionState): boolean { if (createSessionVisibilityPredicate(req)(session)) return true; + if (resolveSessionScope(req).kind === 'tenant') return false; return session.lease === undefined && session.sessionScope?.kind !== 'tenant'; } /** * Whether a reply may name the session a host-global device claim records as its owner. * - * A claim of another daemon on this host keeps its owner: that is the documented cross-worktree - * recovery. A claim of this daemon whose label resolves follows `mayNameSession`. A label that names - * no stored session, such as a transient command's claim or a claim that outlived its session, is - * named to a local request as before and hidden from a tenant-scoped one: on a proxy shared under - * one token, the tenant prefix does not tell one client's ended session from another's (#4923). + * A claim of this daemon whose label resolves follows `mayNameSession`. To a local request, a claim + * of another daemon on this host and a label that names no stored session (a transient command's + * claim, or a claim that outlived its session) keep their owner: that is the documented + * cross-worktree recovery. A tenant-scoped request learns neither: on a proxy shared under one token, + * those owners are not sessions it may list (#4923). */ export function claimOwnerVisible( req: DaemonRequest, sessionStore: SessionStore, owner: ClaimOwnerRef, ): boolean { - if (!isSameDaemonStateDir(owner.stateDir, sessionStore.resolveDaemonStateDir())) return true; + const localRequest = resolveSessionScope(req).kind !== 'tenant'; + if (!isSameDaemonStateDir(owner.stateDir, sessionStore.resolveDaemonStateDir())) { + return localRequest; + } const ref = sessionStore.lookup(owner.session); - if (ref) return mayNameSession(req, ref.session); - return resolveSessionScope(req).kind !== 'tenant'; + return ref ? mayNameSession(req, ref.session) : localRequest; } /** diff --git a/src/commands/schema/cli-help.ts b/src/commands/schema/cli-help.ts index 48b7e36bf0..51b5f8c2b1 100644 --- a/src/commands/schema/cli-help.ts +++ b/src/commands/schema/cli-help.ts @@ -327,8 +327,8 @@ 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. - Behind a shared proxy token, both flavors answer "already in use by another session" and omit the owner: a session another client leases is not visible to this caller, so agent-device session list is how it finds what it 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 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. 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. 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.`, From 173d1b6e538708a735853fb42bda8aa7327c9107 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Sun, 22 Nov 2026 13:07:14 +0100 Subject: [PATCH 5/9] fix(daemon): treat every public-network caller as remote when naming a holder --- ...http-server-proxy-reply-visibility.test.ts | 28 ++++++++++++++++++ .../daemon/src/sessions/session-routing.ts | 29 ++++++++++++------- 2 files changed, 46 insertions(+), 11 deletions(-) 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 index 15950510d8..b6254b50ee 100644 --- 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 @@ -292,3 +292,31 @@ test('a proxy client is refused a device held by a local session without learnin 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); +}); diff --git a/packages/daemon/src/sessions/session-routing.ts b/packages/daemon/src/sessions/session-routing.ts index 07390acbe8..2e6820017c 100644 --- a/packages/daemon/src/sessions/session-routing.ts +++ b/packages/daemon/src/sessions/session-routing.ts @@ -368,16 +368,23 @@ export type ClaimOwnerRef = Readonly<{ }>; /** - * Whether a reply may name `session` to this request. The listing rule decides. A local request has - * one exception, #2580's: a local session of another workspace stays unnamed by the listing yet keeps - * its address, because that address is the handle its owner uses to close it from that folder. A - * tenant-scoped request, which is how a client reaches a proxy shared under one token, gets no - * exception: it learns only the sessions it may list (#4923). + * 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). A local request follows the listing rule, with #2580's exception: a local session + * of another workspace keeps its address, the handle its owner uses to close it from that folder. */ export function mayNameSession(req: DaemonRequest, session: SessionState): boolean { - if (createSessionVisibilityPredicate(req)(session)) return true; - if (resolveSessionScope(req).kind === 'tenant') return false; - return session.lease === undefined && session.sessionScope?.kind !== 'tenant'; + const listed = createSessionVisibilityPredicate(req)(session); + if (!isLocalCaller(req)) { + return listed && (session.lease !== undefined || session.sessionScope?.kind === 'tenant'); + } + return listed || (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'; } /** @@ -386,15 +393,15 @@ export function mayNameSession(req: DaemonRequest, session: SessionState): boole * A claim of this daemon whose label resolves follows `mayNameSession`. To a local request, a claim * of another daemon on this host and a label that names no stored session (a transient command's * claim, or a claim that outlived its session) keep their owner: that is the documented - * cross-worktree recovery. A tenant-scoped request learns neither: on a proxy shared under one token, - * those owners are not sessions it may list (#4923). + * cross-worktree recovery. A remote or tenant-scoped request learns neither: on a proxy shared under + * one token, those owners are not sessions it may list (#4923). */ export function claimOwnerVisible( req: DaemonRequest, sessionStore: SessionStore, owner: ClaimOwnerRef, ): boolean { - const localRequest = resolveSessionScope(req).kind !== 'tenant'; + const localRequest = isLocalCaller(req); if (!isSameDaemonStateDir(owner.stateDir, sessionStore.resolveDaemonStateDir())) { return localRequest; } From af917b139f04dd8c1f6d5f1e975c9dc55c5d255c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Sun, 22 Nov 2026 14:13:17 +0100 Subject: [PATCH 6/9] fix(daemon): require listing visibility for shutdown replies --- ...http-server-proxy-reply-visibility.test.ts | 107 +++++++++++++----- .../session-routing-reply-visibility.test.ts | 22 +++- .../sessions/open-device-contention-wait.ts | 4 +- .../daemon/src/sessions/session-routing.ts | 27 +++-- website/docs/docs/sessions.md | 22 ++-- 5 files changed, 128 insertions(+), 54 deletions(-) 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 index b6254b50ee..8f73694356 100644 --- 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 @@ -57,6 +57,24 @@ type RpcBody = { }; }; +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; @@ -114,7 +132,16 @@ async function startProxiedDaemon() { deviceInventoryGateways: createTestDeviceInventoryGateways({ local: async () => [DEVICE], }), - deviceRuntimeGateway: lifecycleDeviceRuntimeGateway, + 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({ @@ -135,36 +162,27 @@ async function startProxiedDaemon() { 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: async ( + send: ( session: string, command: string, params: { meta?: Record; flags?: Record } = {}, positionals: string[] = [], - ) => { - const response = await fetch(`http://127.0.0.1:${proxyPort}/agent-device/rpc`, { - method: 'POST', - headers: { authorization: `Bearer ${PROXY_TOKEN}`, 'content-type': 'application/json' }, - body: JSON.stringify({ - jsonrpc: '2.0', - id: 1, - method: 'agent_device.command', - params: { - session, - command, - positionals, - flags: params.flags ?? {}, - meta: { - tenantId: TENANT, - sessionIsolation: 'tenant', - sessionExplicit: true, - ...params.meta, - }, - }, - }), - }); - return (await response.json()) as RpcBody; - }, + ) => + 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({ @@ -320,3 +338,40 @@ test('a shared-token proxy client without tenant isolation does not learn a loca 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 }, + }); +}); 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 index 6eb469e5f9..984413c723 100644 --- a/packages/daemon/src/sessions/__tests__/session-routing-reply-visibility.test.ts +++ b/packages/daemon/src/sessions/__tests__/session-routing-reply-visibility.test.ts @@ -158,9 +158,7 @@ test('a refusal without a claim owner passes through', () => { expect(dropInvisibleClaimOwner(request(), store, response)).toBe(response); }); -// The naming rule: another proxy client's leased or tenant-scoped session is the only thing a -// local caller may not be told. A local session of another workspace keeps its address (#2580). -test('a tenant-scoped request learns only sessions it may list; a local request keeps #2580', () => { +test('only local device recovery names an unlistable local session', () => { const store = storeWithLeasedSession(); const own = { session: 'e2b:agentA', workspace: '/w', stateDir: store.resolveDaemonStateDir() }; @@ -180,7 +178,23 @@ test('a tenant-scoped request learns only sessions it may list; a local request createdAt: 0, actions: [], }; - expect(mayNameSession(request(), foreignWorkspaceSession)).toBe(false); + 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/open-device-contention-wait.ts b/packages/daemon/src/sessions/open-device-contention-wait.ts index a83344eafe..764eb58e23 100644 --- a/packages/daemon/src/sessions/open-device-contention-wait.ts +++ b/packages/daemon/src/sessions/open-device-contention-wait.ts @@ -167,7 +167,7 @@ export function findSessionDeviceConflict(params: { /** Whether a refusal may name this holding session to this request. */ function heldSessionNaming(req: DaemonRequest, holder: SessionState): HeldSessionNaming { - return mayNameSession(req, holder) ? 'named' : 'anonymous'; + return mayNameSession(req, holder, 'device-recovery') ? 'named' : 'anonymous'; } type LockedAttempt = { ran: true; outcome: Outcome } | { ran: false }; @@ -193,7 +193,7 @@ function createOpenDeviceWait(params: { type: 'command', status: 'progress', message: `Waiting for ${holding.session.device.name}: ${ - mayNameSession(req, holding.session) + 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)`, diff --git a/packages/daemon/src/sessions/session-routing.ts b/packages/daemon/src/sessions/session-routing.ts index 2e6820017c..1ce3cc4de6 100644 --- a/packages/daemon/src/sessions/session-routing.ts +++ b/packages/daemon/src/sessions/session-routing.ts @@ -371,15 +371,24 @@ export type ClaimOwnerRef = Readonly<{ * 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). A local request follows the listing rule, with #2580's exception: a local session - * of another workspace keeps its address, the handle its owner uses to close it from that folder. + * 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): boolean { +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 || (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. */ @@ -390,11 +399,9 @@ function isLocalCaller(req: DaemonRequest): boolean { /** * 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 `mayNameSession`. To a local request, a claim - * of another daemon on this host and a label that names no stored session (a transient command's - * claim, or a claim that outlived its session) keep their owner: that is the documented - * cross-worktree recovery. A remote or tenant-scoped request learns neither: on a proxy shared under - * one token, those owners are not sessions it may list (#4923). + * 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, @@ -406,7 +413,7 @@ export function claimOwnerVisible( return localRequest; } const ref = sessionStore.lookup(owner.session); - return ref ? mayNameSession(req, ref.session) : localRequest; + return ref ? mayNameSession(req, ref.session, 'device-recovery') : localRequest; } /** diff --git a/website/docs/docs/sessions.md b/website/docs/docs/sessions.md index 9a65515614..868de8642c 100644 --- a/website/docs/docs/sessions.md +++ b/website/docs/docs/sessions.md @@ -183,18 +183,16 @@ 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. - -Behind a shared proxy token, every client is the same tenant and one client cannot see another's -leased session. Refusals about that holder — a session with a lease, or any tenant-scoped session -the caller does not already see — say only that another session holds the device, in the message, -the details, and the wait progress; `session list` shows each caller what it may close. A caller -that carries the holder's lease id is the lease's owner and still gets the name. A session of -another local workspace keeps its named address everywhere: that address is how its owner closes it -from that folder. +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. A device claimed by another workspace's daemon is never waited for; `open` fails at once and names the command that releases it. From c33a22fd8a8f4ff944e633b2bc68307fc6f63c83 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Sun, 22 Nov 2026 15:10:06 +0100 Subject: [PATCH 7/9] fix(daemon): gate workspace contention hints on holder visibility --- ...http-server-proxy-reply-visibility.test.ts | 33 ++++++++++++++++++- .../sessions/open-device-contention-wait.ts | 13 +++----- 2 files changed, 36 insertions(+), 10 deletions(-) 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 index 8f73694356..8d0e61aeb0 100644 --- 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 @@ -51,7 +51,7 @@ const PEER_SCOPE = { } as const; type RpcBody = { - result?: { ok?: boolean; data?: Record }; + result?: { ok?: boolean; data?: Record & { lease?: { leaseId: string } } }; error?: { data?: { code?: string; message?: string; hint?: string; details?: Record }; }; @@ -375,3 +375,34 @@ test('implicit shutdown names a cwd-scoped holder only in its own workspace', as 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/sessions/open-device-contention-wait.ts b/packages/daemon/src/sessions/open-device-contention-wait.ts index 764eb58e23..999da20635 100644 --- a/packages/daemon/src/sessions/open-device-contention-wait.ts +++ b/packages/daemon/src/sessions/open-device-contention-wait.ts @@ -7,8 +7,7 @@ import type { DeviceInfo } from '@agent-device/kernel/device'; 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 { SessionState } from '../core/session-state.ts'; -import type { HeldSessionNaming, SessionRecoveryOptions } from '../core/session-recovery-hints.ts'; +import type { SessionRecoveryOptions } from '../core/session-recovery-hints.ts'; import { isImplicitSessionScopeConflict, mayNameSession } from './session-routing.ts'; import { buildDeviceInUseBySessionError, @@ -154,22 +153,18 @@ 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, - heldSessionNaming(req, inUse.session), + canNameHolder ? 'named' : 'anonymous', ); } -/** Whether a refusal may name this holding session to this request. */ -function heldSessionNaming(req: DaemonRequest, holder: SessionState): HeldSessionNaming { - return mayNameSession(req, holder, 'device-recovery') ? 'named' : 'anonymous'; -} - type LockedAttempt = { ran: true; outcome: Outcome } | { ran: false }; function createOpenDeviceWait(params: { From 1ed85f05665b40a168cf8a1a550245a6f42902cf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Sun, 22 Nov 2026 16:13:15 +0100 Subject: [PATCH 8/9] docs: clarify claim owner visibility in device errors --- src/commands/schema/cli-help.ts | 2 +- website/docs/docs/sessions.md | 8 ++++---- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/src/commands/schema/cli-help.ts b/src/commands/schema/cli-help.ts index 51b5f8c2b1..0e2ef66a8a 100644 --- a/src/commands/schema/cli-help.ts +++ b/src/commands/schema/cli-help.ts @@ -329,7 +329,7 @@ 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. 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. - 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. + 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 868de8642c..33f4c212e1 100644 --- a/website/docs/docs/sessions.md +++ b/website/docs/docs/sessions.md @@ -194,14 +194,14 @@ scope. To see the address of a leased holder, the caller must send that holder's 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. A device claimed by another workspace's -daemon is never waited for; `open` fails at once and names the command that releases it. +`--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 From f4550d99c968b69861d5c6513237cac5d63dd5c1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Sun, 22 Nov 2026 17:23:53 +0100 Subject: [PATCH 9/9] test(daemon): give reply-visibility lease fixtures a backend and canonical lease ids after #4942 --- ...http-server-proxy-reply-visibility.test.ts | 2 +- .../open-device-contention-wait.test.ts | 23 +++++++++++++++---- .../session-routing-reply-visibility.test.ts | 20 ++++++++++++---- .../__tests__/session-doctor-options.test.ts | 7 +++++- 4 files changed, 41 insertions(+), 11 deletions(-) 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 index 8d0e61aeb0..20534ca136 100644 --- 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 @@ -112,7 +112,7 @@ async function startProxiedDaemon() { leaseId: holderLease.leaseId, tenantId: TENANT, runId: HOLDER_SCOPE.runId, - leaseBackend: holderLease.backend, + backend: holderLease.backend, leaseProvider: HOLDER_SCOPE.leaseProvider, clientId: HOLDER_SCOPE.clientId, deviceKey: HOLDER_SCOPE.deviceKey, 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 7c9b41c75f..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 @@ -348,7 +348,12 @@ test('the open-wait progress names no holder the request may not see', async () store.publish('e2b:agentA', { name: 'agentA', sessionScope: { kind: 'tenant', id: 'e2b' }, - lease: { leaseId: 'lease-a', tenantId: 'e2b', runId: 'run-a' }, + lease: { + leaseId: 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', + tenantId: 'e2b', + runId: 'run-a', + backend: 'ios-simulator', + }, device: IOS_SIMULATOR, createdAt: 0, actions: [], @@ -406,7 +411,12 @@ test('the contention refusal names no session to a caller that may not see it', store.publish('e2b:agentA', { name: 'agentA', sessionScope: { kind: 'tenant', id: 'e2b' }, - lease: { leaseId: 'lease-a', tenantId: 'e2b', runId: 'run-a' }, + lease: { + leaseId: 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', + tenantId: 'e2b', + runId: 'run-a', + backend: 'ios-simulator', + }, device: IOS_SIMULATOR, createdAt: 0, actions: [], @@ -433,7 +443,12 @@ test('a request carrying the holder lease id still gets the named refusal', () = store.publish('e2b:agentA', { name: 'agentA', sessionScope: { kind: 'tenant', id: 'e2b' }, - lease: { leaseId: 'lease-a', tenantId: 'e2b', runId: 'run-a' }, + lease: { + leaseId: 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', + tenantId: 'e2b', + runId: 'run-a', + backend: 'ios-simulator', + }, device: IOS_SIMULATOR, createdAt: 0, actions: [], @@ -446,7 +461,7 @@ test('a request carrying the holder lease id still gets the named refusal', () = requestId: 'req-open-wait', tenantId: 'e2b', sessionIsolation: 'tenant', - leaseId: 'lease-a', + leaseId: 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', }, }, device: IOS_SIMULATOR, 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 index 984413c723..b1893a4729 100644 --- a/packages/daemon/src/sessions/__tests__/session-routing-reply-visibility.test.ts +++ b/packages/daemon/src/sessions/__tests__/session-routing-reply-visibility.test.ts @@ -38,7 +38,12 @@ function storeWithLeasedSession(): SessionStore { 'e2b:agentA', makeIosAppSession('e2b:agentA', { sessionScope: { kind: 'tenant', id: TENANT }, - lease: { leaseId: 'lease-a', tenantId: TENANT, runId: 'run-a' }, + lease: { + leaseId: 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', + tenantId: TENANT, + runId: 'run-a', + backend: 'ios-simulator', + }, }), ); return store; @@ -85,7 +90,7 @@ test('the lease holder keeps the named claim-conflict refusal', () => { const store = storeWithLeasedSession(); const response = dropInvisibleClaimOwner( - request({ leaseId: 'lease-a' }), + request({ leaseId: 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' }), store, claimConflictResponse('e2b:agentA', store.resolveDaemonStateDir()), ); @@ -102,7 +107,7 @@ test('a claim of this daemon whose session no longer resolves is not named', () const store = storeWithLeasedSession(); const response = dropInvisibleClaimOwner( - request({ leaseId: 'lease-a' }), + request({ leaseId: 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' }), store, claimConflictResponse('e2b:expired', store.resolveDaemonStateDir()), ); @@ -163,9 +168,14 @@ test('only local device recovery names an unlistable local session', () => { const own = { session: 'e2b:agentA', workspace: '/w', stateDir: store.resolveDaemonStateDir() }; expect(claimOwnerVisible(request(), store, own)).toBe(false); - expect(claimOwnerVisible(request({ leaseId: 'lease-a' }), store, own)).toBe(true); expect( - claimOwnerVisible(request({ leaseId: 'lease-a' }), store, { ...own, session: 'gone' }), + 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); 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 96e1180536..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 @@ -80,7 +80,12 @@ test('the same-device warning omits a session the request may not see', () => { 'e2b:agentB', makeIosSession('e2b:agentB', { sessionScope: { kind: 'tenant', id: 'e2b' }, - lease: { leaseId: 'lease-b', tenantId: 'e2b', runId: 'run-b' }, + lease: { + leaseId: 'bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb', + tenantId: 'e2b', + runId: 'run-b', + backend: 'ios-simulator', + }, }), );