Skip to content

Commit 7519086

Browse files
thymikeeclaude
andcommitted
fix(daemon): keep lease conflicts private, scope replay locks, refuse bad close targets
- A `macos-app` lease tenant sees a busy app as a generic DEVICE_IN_USE with its typed reason, not the other owner's session, workspace, state directory, or host recovery command, and a reboot takeover warning does not name the previous owner. - Only a fresh `open` of an app device takes its host's execution lock. A replay holds its locks for its whole run, so it locks only its app device; its opens still run under the first-open lock keyed by the host. - `close <app>` in an app device session resolves its target through the platform before any teardown (a new close plan use), so another app is refused while the session and its claim stay intact, and any name of the session's own app still closes it. Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent 409b8d5 commit 7519086

12 files changed

Lines changed: 214 additions & 14 deletions

File tree

‎docs/adr/0007-remote-device-leases.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -286,6 +286,7 @@ A session opened under the lease binds the app device of the leased bundle, not
286286
It takes that app device's claim, like any other session.
287287
Sessions on other apps of the Mac do not conflict with it, in this daemon or another.
288288
A session on the same app, or on the whole Mac, conflicts with it.
289+
A tenant sees that conflict as a generic `DEVICE_IN_USE` with its typed reason, never the other owner's session, workspace, state directory, or recovery command.
289290
Thus, one daemon serves several leased apps beside the host's own app sessions.
290291

291292
These rules bind a request that names the lease or runs in its session.

‎docs/adr/0035-macos-app-devices.md‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -15,10 +15,12 @@ Accepted (2026-10-21). Applies to the native macOS app backend (ADR 0031) only.
1515
3. Every per-device rule applies to an app device unchanged: the execution lock, the claim, the
1616
new-session conflict check, and `open --wait`. Two sessions on two apps run in parallel, in one
1717
daemon or in several daemons that share a claims directory. Two sessions on one app conflict.
18-
A request that opens an app device takes its host's execution lock first, in its lock plan, so an
18+
A fresh `open` of an app device takes its host's execution lock first, in its lock plan, so an
1919
`open --wait` looks at the Mac's sessions under a lock a whole-Mac open also takes. The first
2020
opens on one Mac run their session check and publication one at a time in a daemon. Commands of
21-
an open app session take only the app device's lock. A request that already holds a lock on a Mac or one of its apps, itself or through the request it
21+
an open app session take only the app device's lock, and so does a replay or batch for the device
22+
it starts on, since it holds its locks for its whole run. A fresh batch that selects the Mac itself, with no app
23+
target, therefore holds the Mac's lock for its run. A request that already holds a lock on a Mac or one of its apps, itself or through the request it
2224
runs in (a batch step), takes another lock on that Mac only while it is free, and is otherwise
2325
refused with `DEVICE_IN_USE` (`DEVICE_EXECUTION_LOCK_BUSY`) instead of waiting. Waiting could
2426
cross a request that does the same in the other order: batches or replays on two apps that each

‎packages/command-registry/src/__tests__/registry-application-lifecycle-runtime-execution.test.ts‎

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,18 +2,23 @@ import {
22
closeApplicationRuntimePlanUses,
33
closeApplicationRuntimeUse,
44
closeApplicationWithRuntimeHintClearUse,
5+
resolveCloseTargetRuntimeUse,
56
} from '@agent-device/contracts/application-lifecycle-runtime-plan';
67
import { expect, test } from 'vitest';
78
import { commandDescriptors } from '../registry.ts';
89

9-
test('close descriptor declares both native plans, including exact runtime-hint cleanup', () => {
10+
test('close descriptor declares its native plans, including runtime-hint cleanup and the app device target check', () => {
1011
const close = commandDescriptors.find(({ name }) => name === 'close');
1112

1213
expect(close?.platformExecution).toEqual({
1314
kind: 'device-runtime',
1415
uses: closeApplicationRuntimePlanUses,
1516
});
1617
expect(new Set(closeApplicationRuntimePlanUses)).toEqual(
17-
new Set([closeApplicationRuntimeUse, closeApplicationWithRuntimeHintClearUse]),
18+
new Set([
19+
closeApplicationRuntimeUse,
20+
closeApplicationWithRuntimeHintClearUse,
21+
resolveCloseTargetRuntimeUse,
22+
]),
1823
);
1924
});

‎packages/contracts/src/application-lifecycle-runtime-plan.ts‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -89,10 +89,17 @@ export const closeApplicationWithRuntimeHintClearUse = defineUse({
8989
required: ['closeApplication', 'finalizeApplicationClose', 'clearRuntimeHints'],
9090
});
9191

92+
/**
93+
* Close resolves the target of a session on an app device before any teardown, so a target outside
94+
* that app is refused while the session is still intact (ADR 0035).
95+
*/
96+
export const resolveCloseTargetRuntimeUse = defineUse({ required: ['resolveOpenTarget'] });
97+
9298
/** Every close plan is declared at the descriptor: hint cleanup is part of close, never a sibling reach-through. */
9399
export const closeApplicationRuntimePlanUses = Object.freeze([
94100
closeApplicationRuntimeUse,
95101
closeApplicationWithRuntimeHintClearUse,
102+
resolveCloseTargetRuntimeUse,
96103
] as const);
97104

98105
/** Daemon shutdown finalizes durable lifecycle resources without issuing a second close. */

‎packages/daemon/src/resources/__tests__/macos-app-lease.test.ts‎

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -628,3 +628,36 @@ test('a failure under the lease drops its log locators and every host path and t
628628
},
629629
});
630630
});
631+
632+
test('a busy leased app is refused without naming who holds it, whatever host paths it has', () => {
633+
const conflict = {
634+
ok: false as const,
635+
error: {
636+
code: 'DEVICE_IN_USE',
637+
message:
638+
'macos device host:app:com.example.app is owned by session "s" in workspace "/srv/private-project".',
639+
hint: 'Inspect the owner with: agent-device device status --platform macos --udid host:app:com.example.app',
640+
retriable: false,
641+
details: {
642+
reason: 'DEVICE_CLAIM_LIVE_OWNER',
643+
deviceKey: 'local:apple:macos:host:app:com.example.app',
644+
owner: { session: 's', workspace: '/srv/private-project', stateDir: '/srv/daemon-state' },
645+
recovery: { command: 'agent-device device status --platform macos --udid host' },
646+
},
647+
},
648+
};
649+
650+
const redacted = redactMacOsAppLeaseResponse('open', conflict, host);
651+
652+
assert.deepEqual(redacted, {
653+
ok: false,
654+
error: {
655+
code: 'DEVICE_IN_USE',
656+
message: 'The leased app is in use by another session.',
657+
hint: 'Retry once the other session ends.',
658+
details: { reason: 'DEVICE_CLAIM_LIVE_OWNER' },
659+
retriable: false,
660+
},
661+
});
662+
assert.doesNotMatch(JSON.stringify(redacted), /\/srv\/|session "s"|device status/);
663+
});

‎packages/daemon/src/resources/macos-app-lease.ts‎

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -388,10 +388,26 @@ function redactSuccessData(
388388
}
389389

390390
function redactError(error: DaemonError, host: MacOsAppLeaseHost): DaemonError {
391+
if (error.code === 'DEVICE_IN_USE') return tenantDeviceInUse(error);
391392
const { logPath: _logPath, diagnosticsRecord: _diagnosticsRecord, ...rest } = error;
392393
return redactHostText(rest, host);
393394
}
394395

396+
/**
397+
* A busy leased app, without who holds it: the owner's session, workspace, state directory, and
398+
* host recovery command belong to the host, not the tenant. Only the typed reason stays.
399+
*/
400+
function tenantDeviceInUse(error: DaemonError): DaemonError {
401+
const reason = error.details?.reason;
402+
return {
403+
code: 'DEVICE_IN_USE',
404+
message: 'The leased app is in use by another session.',
405+
hint: 'Retry once the other session ends.',
406+
...(typeof reason === 'string' ? { details: { reason } } : {}),
407+
...(error.retriable === undefined ? {} : { retriable: error.retriable }),
408+
};
409+
}
410+
395411
function redactHostText<T>(value: T, host: MacOsAppLeaseHost): T {
396412
if (typeof value === 'string') return redactHostString(value, host) as T;
397413
if (Array.isArray(value)) return value.map((item) => redactHostText(item, host)) as T;

‎packages/daemon/src/server/__tests__/request-router-open.test.ts‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -192,7 +192,7 @@ test('fresh open uses app-aware device selection for advisory locking and dispat
192192
expect(sessionStore.get('session-app-aware')?.device.id).toBe(appDevice.id);
193193
});
194194

195-
test('fresh macOS replay locks the app device it opens first, with its host', async () => {
195+
test('fresh macOS replay locks only the app device it opens first, so other apps open beside it', async () => {
196196
const root = mkdtempForTestSync('agent-device-replay-macos-lock-');
197197
const replayPath = path.join(root, 'flow.ad');
198198
fs.writeFileSync(replayPath, 'context platform=macos\nopen com.example.one\n');
@@ -215,9 +215,10 @@ test('fresh macOS replay locks the app device it opens first, with its host', as
215215
sessionStore: makeSessionStore('agent-device-router-replay-macos-lock-'),
216216
});
217217

218+
// A replay holds these for its whole run; holding the host too would hold every other app's
219+
// fresh open for as long. Its open still runs under the first-open lock keyed by the host.
218220
expect(keys).toEqual([
219221
'session:fresh-macos-replay',
220-
'device:host-macos-local',
221222
'device:host-macos-local:app:com.example.one',
222223
]);
223224
});

‎packages/daemon/src/server/request-binding.ts‎

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -59,10 +59,12 @@ export async function resolveRequestExecutionLockPlan(params: {
5959

6060
const keys = new Set<RequestExecutionLockKey>([sessionExecutionLockKey(sessionName)]);
6161
const device = await resolveFreshSessionDevice(req, sessionStore.host.env);
62-
// A fresh app device open also locks its host (ADR 0035), before its own lock, so an `open --wait`
63-
// looks at the host's sessions under a lock a whole-host open also takes. An open app session's
64-
// commands lock only the app device.
65-
for (const id of device ? hostAndDeviceIds(device) : []) keys.add(deviceExecutionLockKey(id));
62+
// A fresh app device `open` also locks its host (ADR 0035), before its own lock, so an
63+
// `open --wait` looks at the host's sessions under a lock a whole-host open also takes. A replay
64+
// or batch holds its locks for its whole run, so it locks only its device: the first-open lock
65+
// keyed by host still serializes its opens. An open app session's commands lock only the app.
66+
const ids = !device ? [] : req.command === 'open' ? hostAndDeviceIds(device) : [device.id];
67+
for (const id of ids) keys.add(deviceExecutionLockKey(id));
6668
return { keys: orderRequestExecutionLockKeys(keys), deviceId: device?.id };
6769
}
6870

‎packages/daemon/src/sessions/handlers/__tests__/session-device-claims.test.ts‎

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,7 @@ import {
5050
applyRuntimeHintsFixture,
5151
dispatchApplicationLifecycleEffect,
5252
prepareApplicationOpenFixture,
53+
resolveOpenTargetFixture,
5354
} from '../../../__tests__/support/application-lifecycle-runtime-fixture.ts';
5455
import { clearRequestCanceled, markRequestCanceled } from '@agent-device/host-kit/request';
5556
import {
@@ -646,3 +647,60 @@ test('a fresh app device open retains only its own device lock, never its host a
646647
assert.equal(response.ok, true, JSON.stringify(response));
647648
assert.deepEqual(retained, [textEdit.id]);
648649
});
650+
651+
test('closing another app from an app device session is refused before teardown, keeping the session', async () => {
652+
const { store, stateDir } = setup();
653+
const textEdit = hostAppDevice(MACOS_DEVICE, 'com.apple.textedit');
654+
const acquired = await acquireDeviceClaim({
655+
env: process.env,
656+
device: textEdit,
657+
session: 'text-edit',
658+
workspace: process.cwd(),
659+
stateDir,
660+
});
661+
if (acquired.status !== 'acquired') throw new Error('claim seed failed');
662+
store.publish('text-edit', {
663+
name: 'text-edit',
664+
device: textEdit,
665+
deviceClaim: acquired.ownership,
666+
appBundleId: 'com.apple.TextEdit',
667+
appName: 'TextEdit',
668+
surface: 'app',
669+
createdAt: Date.now(),
670+
actions: [],
671+
});
672+
mockDispatch.mockResolvedValue(undefined);
673+
// The platform resolves the target as open does and refuses another app of the Mac.
674+
resolveOpenTargetFixture.mockImplementationOnce(async () => {
675+
throw new AppError('INVALID_ARGS', 'This session drives com.apple.TextEdit.', {
676+
reason: 'app-device-scope',
677+
});
678+
});
679+
680+
const outcome = await handleCloseCommand({
681+
host: createTestHostEnvironment(),
682+
platformServices: daemonPlatformServicesFixture(),
683+
req: {
684+
command: 'close',
685+
token: 'test',
686+
session: 'text-edit',
687+
positionals: ['Calculator'],
688+
flags: {},
689+
},
690+
sessionName: 'text-edit',
691+
logPath: path.join(stateDir, 'daemon.log'),
692+
sessionStore: store,
693+
leaseRegistry: new LeaseRegistry(),
694+
}).catch((error: unknown) => error);
695+
696+
assert.equal((outcome as AppError).details?.reason, 'app-device-scope');
697+
assert.ok(
698+
resolveOpenTargetFixture.mock.calls.some(([, , input]) => input.target === 'Calculator'),
699+
);
700+
assert.equal(mockDispatch.mock.calls.length, 0);
701+
assert.equal(store.get('text-edit')?.device.id, textEdit.id);
702+
assert.deepEqual(
703+
inspectDeviceClaims({}, process.env).map((entry) => entry.claim?.session),
704+
['text-edit'],
705+
);
706+
});

‎packages/daemon/src/sessions/session-lifecycle/internal/session-close.ts‎

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,8 @@ import {
4242
import { closeCleanupError, runSessionCloseTeardown } from './session-close-lifecycle-teardown.ts';
4343
import type { PlatformResourceCleanup } from '../../../core/platform-resource-cleanup.ts';
4444
import { errorResponse } from '@agent-device/kernel/contracts';
45+
import { resolveCloseTargetRuntimeUse } from '@agent-device/contracts/application-lifecycle-runtime-plan';
46+
import { admitRuntimeUse } from '../../../core/runtime-admission.ts';
4547

4648
export type SessionCloseCommandInput = Readonly<{
4749
host: HostEnvironment;
@@ -200,6 +202,37 @@ function assertTerminalRecordingCloseAllowed(req: DaemonRequest, session: Sessio
200202
);
201203
}
202204

205+
/**
206+
* A session on an app device closes only its own app (ADR 0035). The platform resolves the target
207+
* before any teardown, the way open does, and refuses another app, so the session and its
208+
* resources stay intact; the platform close refuses it too.
209+
*/
210+
async function refuseCloseOutsideAppDevice(params: {
211+
session: SessionState;
212+
app: string | undefined;
213+
inspectFacts?: InspectDeviceRuntimeFacts;
214+
bindDevice?: BindDeviceRuntime;
215+
platformServices: DaemonPlatformServices;
216+
}): Promise<DaemonResponse | undefined> {
217+
const { session, app } = params;
218+
if (!session.device.hostApp || !app) return undefined;
219+
const admitted = await admitRuntimeUse({
220+
command: 'close',
221+
device: session.device,
222+
use: resolveCloseTargetRuntimeUse,
223+
inspectFacts: params.inspectFacts,
224+
bindDevice: params.bindDevice,
225+
platformServices: params.platformServices,
226+
});
227+
if (admitted.type === 'response') return admitted.response;
228+
await admitted.runtime.operations.resolveOpenTarget({
229+
target: app,
230+
surface: 'app',
231+
foreground: false,
232+
});
233+
return undefined;
234+
}
235+
203236
export async function handleSessionCloseCommands(
204237
params: SessionCloseCommandInput,
205238
): Promise<DaemonResponse> {
@@ -219,6 +252,14 @@ export async function handleSessionCloseCommands(
219252
let session = sessionStore.requireCurrent(ref);
220253
assertTerminalRecordingCloseAllowed(req, session);
221254
const app = req.positionals?.[0];
255+
const outsideAppDevice = await refuseCloseOutsideAppDevice({
256+
session,
257+
app,
258+
inspectFacts: params.inspectFacts,
259+
bindDevice: params.bindDevice,
260+
platformServices: params.platformServices,
261+
});
262+
if (outsideAppDevice) return outsideAppDevice;
222263
if (req.internal?.closeAppOnly === true && !app) {
223264
return errorResponse('INVALID_ARGS', 'App-only close requires an app target');
224265
}

0 commit comments

Comments
 (0)