Skip to content

Commit c269880

Browse files
refactor(macos): keep the new-session open under the complexity gate
1 parent d6a8793 commit c269880

2 files changed

Lines changed: 99 additions & 74 deletions

File tree

‎src/daemon/session-lifecycle/internal/__tests__/session-open-execution-runtime.test.ts‎

Lines changed: 35 additions & 45 deletions
Original file line numberDiff line numberDiff line change
@@ -75,7 +75,6 @@ import {
7575
} from '../../../../platform-runtime-runtime-hints.ts';
7676
import { resolveAndroidPackageForOpen } from '@agent-device/platform-android/mechanics';
7777
import { resolveIosApp } from '@agent-device/platform-apple/app-resolution';
78-
import { clearDeviceClaim } from '../../../device/device-claims.ts';
7978
import { dispatchApplicationLifecycleEffect } from '../../../__tests__/application-lifecycle-runtime-fixture.ts';
8079
import {
8180
makeAndroidEmulator,
@@ -656,51 +655,42 @@ for (const transition of ['rebuild', 'retire'] as const) {
656655
test('native macOS app sessions claim their app, so another app opens beside them', async () => {
657656
vi.stubEnv('AGENT_DEVICE_MACOS_APP_BACKEND', 'native');
658657
vi.mocked(resolveIosApp).mockImplementation(async (_device, app) => app);
658+
mockResolveTargetDevice.mockResolvedValue({
659+
platform: 'apple',
660+
appleOs: 'macos',
661+
id: 'host-macos-local',
662+
name: 'Host Mac',
663+
kind: 'device',
664+
target: 'desktop',
665+
booted: true,
666+
});
659667
const sessionStore = makeSessionStore();
660-
try {
661-
mockResolveTargetDevice.mockResolvedValue({
662-
platform: 'apple',
663-
appleOs: 'macos',
664-
id: 'host-macos-local',
665-
name: 'Host Mac',
666-
kind: 'device',
667-
target: 'desktop',
668-
booted: true,
668+
const open = async (session: string, app: string) =>
669+
await handleSessionCommands({
670+
req: {
671+
token: 't',
672+
session,
673+
command: 'open',
674+
positionals: [app],
675+
flags: { platform: 'macos' },
676+
},
677+
sessionName: session,
678+
logPath: path.join(mkdtempForTestSync('agent-device-macos-app-claim-'), 'daemon.log'),
679+
sessionStore,
680+
invoke: noopInvoke,
669681
});
670-
const open = async (session: string, app: string) =>
671-
await handleSessionCommands({
672-
req: {
673-
token: 't',
674-
session,
675-
command: 'open',
676-
positionals: [app],
677-
flags: { platform: 'macos' },
678-
},
679-
sessionName: session,
680-
logPath: path.join(mkdtempForTestSync('agent-device-macos-app-claim-'), 'daemon.log'),
681-
sessionStore,
682-
invoke: noopInvoke,
683-
});
682+
const refusedFor = { ok: false, error: { details: { reason: 'app-claim-scope' } } };
684683

685-
expect((await open('one', 'com.example.one'))?.ok).toBe(true);
686-
expect((await open('two', 'com.example.two'))?.ok).toBe(true);
687-
const sameApp = await open('three', 'com.example.one');
688-
expect(sameApp?.ok).toBe(false);
689-
if (sameApp?.ok !== false) return;
690-
expect(sameApp.error.code).toBe('DEVICE_IN_USE');
691-
692-
const otherAppInSession = await open('one', 'com.example.two');
693-
expect(otherAppInSession?.ok).toBe(false);
694-
if (otherAppInSession?.ok !== false) return;
695-
expect(otherAppInSession.error.details?.reason).toBe('app-claim-scope');
696-
const linkInSession = await open('one', 'demo://route');
697-
expect(linkInSession?.ok).toBe(false);
698-
if (linkInSession?.ok !== false) return;
699-
expect(linkInSession.error.details?.reason).toBe('app-claim-scope');
700-
expect((await open('one', 'com.example.one'))?.ok).toBe(true);
701-
} finally {
702-
for (const ref of sessionStore.listRefs()) await clearDeviceClaim(ref.session.deviceClaim);
703-
vi.unstubAllEnvs();
704-
vi.mocked(resolveIosApp).mockImplementation(async () => 'com.example.demo');
705-
}
684+
expect(await open('one', 'com.example.one')).toMatchObject({ ok: true });
685+
expect(await open('two', 'com.example.two')).toMatchObject({ ok: true });
686+
expect(await open('three', 'com.example.one')).toMatchObject({
687+
ok: false,
688+
error: { code: 'DEVICE_IN_USE' },
689+
});
690+
expect(await open('one', 'com.example.two')).toMatchObject(refusedFor);
691+
expect(await open('one', 'demo://route')).toMatchObject(refusedFor);
692+
expect(await open('one', 'com.example.one')).toMatchObject({ ok: true });
693+
694+
vi.unstubAllEnvs();
695+
vi.mocked(resolveIosApp).mockImplementation(async () => 'com.example.demo');
706696
});

‎src/daemon/session-lifecycle/internal/session-open-execution.ts‎

Lines changed: 64 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -497,8 +497,24 @@ export function reopenOutsideAppClaim(params: {
497497
);
498498
}
499499

500-
function sameBundleId(resolved: string | undefined, claimed: string): boolean {
501-
return resolved !== undefined && resolved.toLowerCase() === claimed.toLowerCase();
500+
function appClaimKeyFor(device: DeviceInfo, app: DeviceClaimApp | undefined): string | undefined {
501+
return app
502+
? appScopedDeviceKey(canonicalLocalDeviceKey(deviceClaimIdentity(device)), app.bundleId)
503+
: undefined;
504+
}
505+
506+
/** The claim was taken for the app resolved before preparation; the open must launch that app. */
507+
function openedOutsideAppClaim(
508+
app: DeviceClaimApp | undefined,
509+
resolved: string | undefined,
510+
openTarget: string | undefined,
511+
): DaemonResponse | undefined {
512+
if (!app || resolved?.toLowerCase() === app.bundleId.toLowerCase()) return undefined;
513+
return errorResponse(
514+
'COMMAND_FAILED',
515+
`${openTarget ?? 'The app'} resolved to ${resolved ?? 'no app'} after its claim was taken for ${app.bundleId}.`,
516+
{ reason: 'app-claim-scope', hint: 'Run the same open again.' },
517+
);
502518
}
503519

504520
async function acquireDeviceClaimForOwner(params: {
@@ -548,6 +564,43 @@ async function acquireDeviceClaimForOwner(params: {
548564
}
549565
}
550566

567+
/** Takes the claim a new session needs: its app's, or the whole device's. */
568+
async function claimNewSessionDevice(params: {
569+
req: DaemonRequest;
570+
device: DeviceInfo;
571+
surface: SessionSurface;
572+
openTarget: string | undefined;
573+
lifecycle: OpenApplicationRuntime;
574+
sessionName: string;
575+
sessionStore: SessionStore;
576+
reconcileOrphanedDeviceClaim: DeviceClaimReconciler;
577+
}): Promise<
578+
| { response: DaemonResponse }
579+
| {
580+
app: DeviceClaimApp | undefined;
581+
deviceClaim: DeviceClaimSessionOwnership | undefined;
582+
tookOverDeviceClaim: TakenOverDeviceClaim | undefined;
583+
}
584+
> {
585+
const { req, device, lifecycle, sessionStore } = params;
586+
const app = await resolveAppClaim(params);
587+
const conflict = findNewSessionDeviceConflict({
588+
req,
589+
device,
590+
sessionStore,
591+
appClaimKey: appClaimKeyFor(device, app),
592+
});
593+
if (conflict) return { response: conflict };
594+
const ownerClaim = await acquireDeviceClaimForOwner({ ...params, owner: lifecycle.owner, app });
595+
if (ownerClaim.status === 'conflict') {
596+
return { response: buildDeviceClaimConflictError(device, ownerClaim.conflict) };
597+
}
598+
if (ownerClaim.status === 'refused') return { response: ownerClaim.response };
599+
return ownerClaim.status === 'acquired'
600+
? { app, deviceClaim: ownerClaim.ownership, tookOverDeviceClaim: ownerClaim.tookOver }
601+
: { app, deviceClaim: undefined, tookOverDeviceClaim: undefined };
602+
}
603+
551604
export async function openNewSessionWithDeviceClaim(params: {
552605
req: DaemonRequest;
553606
sessionName: string;
@@ -579,30 +632,18 @@ export async function openNewSessionWithDeviceClaim(params: {
579632
selection,
580633
} = params;
581634
requireOpenSessionAdmission(sessionStore, sessionName, undefined);
582-
const app = await resolveAppClaim({ req, device, surface, openTarget, lifecycle });
583-
const appClaimKey = app
584-
? appScopedDeviceKey(canonicalLocalDeviceKey(deviceClaimIdentity(device)), app.bundleId)
585-
: undefined;
586-
const conflict = findNewSessionDeviceConflict({ req, device, sessionStore, appClaimKey });
587-
if (conflict) return { type: 'response', response: conflict };
588-
589-
const ownerClaim = await acquireDeviceClaimForOwner({
635+
const claimed = await claimNewSessionDevice({
590636
req,
591637
device,
592-
owner: lifecycle.owner,
638+
surface,
639+
openTarget,
640+
lifecycle,
593641
sessionName,
594642
sessionStore,
595643
reconcileOrphanedDeviceClaim,
596-
app,
597644
});
598-
if (ownerClaim.status === 'conflict')
599-
return {
600-
type: 'response',
601-
response: buildDeviceClaimConflictError(device, ownerClaim.conflict),
602-
};
603-
if (ownerClaim.status === 'refused') return { type: 'response', response: ownerClaim.response };
604-
const deviceClaim = ownerClaim.status === 'acquired' ? ownerClaim.ownership : undefined;
605-
const tookOverDeviceClaim = ownerClaim.status === 'acquired' ? ownerClaim.tookOver : undefined;
645+
if ('response' in claimed) return { type: 'response', response: claimed.response };
646+
const { app, deviceClaim, tookOverDeviceClaim } = claimed;
606647
const effects: NewSessionOpenEffects = { mayHaveStarted: false };
607648
const rollbackClaim = async () =>
608649
await rollbackNewSessionClaim({
@@ -627,16 +668,10 @@ export async function openNewSessionWithDeviceClaim(params: {
627668
await rollbackClaim();
628669
return { type: 'response', response: details.response };
629670
}
630-
if (app && !sameBundleId(details.details.appBundleId, app.bundleId)) {
671+
const outsideClaim = openedOutsideAppClaim(app, details.details.appBundleId, openTarget);
672+
if (outsideClaim) {
631673
await rollbackClaim();
632-
return {
633-
type: 'response',
634-
response: errorResponse(
635-
'COMMAND_FAILED',
636-
`${openTarget ?? 'The app'} resolved to ${details.details.appBundleId ?? 'no app'} after its claim was taken for ${app.bundleId}.`,
637-
{ reason: 'app-claim-scope', hint: 'Run the same open again.' },
638-
),
639-
};
674+
return { type: 'response', response: outsideClaim };
640675
}
641676
// Preparation can boot the device or warm caches, but it cannot establish session ownership.
642677
// Stamping here is what covers a boot preparation caused for this very open; from

0 commit comments

Comments
 (0)