Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 19 additions & 4 deletions packages/remote/src/remote-connection-state.ts
Original file line number Diff line number Diff line change
Expand Up @@ -274,6 +274,18 @@ export function readRemoteConnectionState(options: {
stateDir: string;
session: string;
}): RemoteConnectionState | null {
const observed = observeRemoteConnectionState(options);
return observed.kind === 'valid' ? observed.state : null;
}

export function observeRemoteConnectionState(options: {
stateDir: string;
session: string;
}):
| { kind: 'absent' }
| { kind: 'invalid' }
| { kind: 'unknown' }
| { kind: 'valid'; state: RemoteConnectionState } {
const recordsDir = remoteConnectionRecordsDir(options.stateDir);
const canonical = canonicalRemoteConnectionStatePath(recordsDir, options.session);
// The older path is read first. A move links the session's own path before it retires the older
Expand All @@ -295,11 +307,12 @@ export function readRemoteConnectionState(options: {
}
return observedRemoteConnectionState(options.session, canonical, file.record);
}
if (legacyPath !== canonical && legacy.kind === 'unknown') return { kind: 'unknown' };
return legacy.kind === 'owned' &&
legacy.session === options.session &&
isMovableLegacyRecord(recordsDir, legacyPath, legacy)
? observedRemoteConnectionState(options.session, legacyPath, legacy.record)
: null;
: { kind: 'absent' };
}

/**
Expand Down Expand Up @@ -372,10 +385,12 @@ function observedRemoteConnectionState(
session: string,
recordPath: string,
record: Record<string, unknown>,
): RemoteConnectionState | null {
if (isRemoteConnectionState(record)) return normalizeStoredProvider(record);
): { kind: 'invalid' } | { kind: 'valid'; state: RemoteConnectionState } {
if (isRemoteConnectionState(record)) {
return { kind: 'valid', state: normalizeStoredProvider(record) };
}
warnInvalidRecord(session, recordPath);
return null;
return { kind: 'invalid' };
}

function normalizeStoredProvider(record: RemoteConnectionState): RemoteConnectionState {
Expand Down
67 changes: 67 additions & 0 deletions src/__tests__/cli-cloud-limrun-attachment.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -302,3 +302,70 @@ test('disconnect preserves recovery when a startup owns the lock before publishi
expect((await runCliCapture(['disconnect', '--json'], { env })).code).toBeNull();
expect(mock.mock.calls.filter(([, init]) => init.method === 'DELETE')).toHaveLength(1);
});

async function bookLimrunWithDaemon() {
const env = limrunEnv('current');
const location = locationOf(env);
const broker = stubCloudApi();
broker.mockResolvedValueOnce(Response.json(limrunLease('ios'), { status: 201 }));
expect((await runCliCapture(args('ios'), { env })).code).toBeNull();
writeHostedDaemonRegistration(location);
return { env, location };
}

function writeStaleV1Login(env: ReturnType<typeof limrunEnv>): void {
const authDir = path.join(env.AGENT_DEVICE_STATE_DIR, 'auth');
fs.mkdirSync(authDir, { recursive: true, mode: 0o700 });
fs.writeFileSync(
path.join(authDir, 'cli-session.json'),
JSON.stringify({
version: 1,
id: 'stale-login',
cloudBaseUrl: env.AGENT_DEVICE_CLOUD_BASE_URL,
refreshCredential: 'stale-refresh-credential',
createdAt: new Date().toISOString(),
}),
{ mode: 0o600 },
);
}

test.each(['stale-v1-login', 'unbound'] as const)(
'local-only sweep of an expired Limrun booking (%s) removes its attachment without stopping its daemon',
async (mode) => {
const { env, location } = await bookLimrunWithDaemon();
const record = readCloudConnection(location)!;
const { accountBinding: _unbound, ...unbound } = record;
writeCloudConnection(location, {
...(mode === 'unbound' ? unbound : record),
deadlineAt: new Date(0).toISOString(),
});
if (mode === 'stale-v1-login') writeStaleV1Login(env);

await runCliCapture(['connection', 'status', '--session', location.session, '--json'], {
env: mode === 'stale-v1-login' ? { ...env, AGENT_DEVICE_CLOUD_API_KEY: undefined } : env,
});

expect(stop).not.toHaveBeenCalled();
expect(fs.existsSync(cloudAttachmentPath(location))).toBe(false);
},
);

test('forget with a stale v1 login clears a paired Limrun booking locally without stopping its daemon', async () => {
const { env, location } = await bookLimrunWithDaemon();
const daemonDir = hostedPluginDaemonDir(location, readCloudConnection(location)!);
writeStaleV1Login(env);

const forgotten = await runCliCapture(
['disconnect', '--forget', '--session', location.session, '--json'],
{ env: { ...env, AGENT_DEVICE_CLOUD_API_KEY: undefined } },
);

expect(forgotten.code, forgotten.stdout).toBeNull();
expect(JSON.parse(forgotten.stdout).data).toMatchObject({ forgotten: true, released: false });
expect(stop).not.toHaveBeenCalled();
expect(forgotten.stderr).toContain('local daemon may still be running');
expect(forgotten.stderr).toContain(daemonDir);
expect(readCloudConnection(location)).toBeNull();
expect(readRemoteConnectionState(location)).toBeNull();
expect(fs.existsSync(cloudAttachmentPath(location))).toBe(false);
});
241 changes: 241 additions & 0 deletions src/__tests__/cli-cloud-record-recovery.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import path from 'node:path';
import { afterEach, expect, test, vi } from 'vitest';
import { writeCliSession } from '../cli/auth-session.ts';
import {
cloudAttachmentPath,
cloudConnectionDir,
prepareCloudConnection,
readCloudConnection,
Expand All @@ -17,9 +18,11 @@ import {
hostedDevice,
locationOf,
postKey,
proxyFrontDevice,
stubCloudApi,
timeOutAllocation,
timeOutNextCreate,
withLeaseAllocation,
} from './cli-cloud-session.fixtures.ts';

afterEach(() => {
Expand Down Expand Up @@ -286,3 +289,241 @@ test('an inconclusive refusal to end an observed allocation keeps its lease ID',
expect((await runCliCapture(['disconnect', '--json'], { env })).code).toBeNull();
expect(fetchMock.mock.calls.at(-1)?.[0].pathname).toBe(`/v1/sessions/${hostedDevice.id}`);
});

async function bookExpiredUnboundUnfinishedProxyFront(phase: 'pending' | 'closing') {
const env = cloudEnv();
const location = locationOf(env);
const front = withLeaseAllocation();
const broker = stubCloudApi(proxyFrontDevice);
const connected = await runCliCapture(connectArgs, { env, sendToDaemon: front });
expect(connected.code).toBeNull();
const opened = await runCliCapture(
['open', 'com.apple.Preferences', '--session', location.session, '--json'],
{ env, sendToDaemon: front },
);
expect(opened.code).toBeNull();
const { accountBinding: _unbound, ...record } = readCloudConnection(location)!;
writeCloudConnection(location, {
...record,
phase,
hostedLeaseId: 'proposed-lease-id',
deadlineAt: new Date(Date.now() - 1000).toISOString(),
});
broker.mockClear();
return { env, location, front, broker };
}

test.each([
{ phase: 'pending' as const, force: false },
{ phase: 'pending' as const, force: true },
{ phase: 'closing' as const, force: false },
{ phase: 'closing' as const, force: true },
])(
'connect (force=$force) on an expired unbound $phase proxy-front booking refuses another account before any lease teardown',
async ({ phase, force }) => {
const { env, location, front, broker } = await bookExpiredUnboundUnfinishedProxyFront(phase);
broker.mockResolvedValueOnce(Response.json({ error: 'not_found' }, { status: 404 }));

const args = force ? [...connectArgs, '--force'] : connectArgs;
const refused = await runCliCapture(args, {
env: { ...env, AGENT_DEVICE_CLOUD_API_KEY: 'other-account-api-key' },
sendToDaemon: front,
});

expect(refused.code).toBe(1);
expect(JSON.parse(refused.stdout).error.details.reason).toBe(
'cloud_connection_allocation_unconfirmed',
);
expect(refused.calls).toEqual([]);
expect(broker.mock.calls.map(([, init]) => init.method)).toEqual(['GET']);
expect(fs.existsSync(cloudAttachmentPath(location))).toBe(true);
expect(readCloudConnection(location)?.phase).toBe(phase);
expect(readCloudConnection(location)?.accountBinding).toBeUndefined();
},
);

test('connect on an expired unbound unfinished proxy-front booking releases its lease once the owner proves allocation and refuses unpaired state', async () => {
const unpaired = await bookExpiredUnboundUnfinishedProxyFront('pending');
writeCloudConnection(unpaired.location, {
...readCloudConnection(unpaired.location)!,
generation: 'different-generation',
});
const blocked = await runCliCapture(connectArgs, {
env: unpaired.env,
sendToDaemon: unpaired.front,
});
expect(blocked.code).toBe(1);
expect(JSON.parse(blocked.stdout).error.details.reason).toBe('cloud_connection_changed');
expect(blocked.calls).toEqual([]);
expect(unpaired.broker).not.toHaveBeenCalled();

const owned = await bookExpiredUnboundUnfinishedProxyFront('pending');
owned.broker.mockResolvedValueOnce(Response.json({ id: proxyFrontDevice.id, state: 'settled' }));
const replaced = await runCliCapture(connectArgs, {
env: owned.env,
sendToDaemon: owned.front,
});
expect(replaced.code, replaced.stdout).toBeNull();
expect(replaced.calls.map(({ command }) => command)).toContain('lease_release');
expect(owned.broker.mock.calls.map(([, init]) => init.method)).not.toContain('DELETE');
});

test.each<{
label: string;
force: boolean;
overrides?: { phase: 'closing'; rollback: true };
}>([
{ label: 'pending', force: false },
{ label: 'pending', force: true },
{ label: 'closing rollback', force: false, overrides: { phase: 'closing', rollback: true } },
{ label: 'closing rollback', force: true, overrides: { phase: 'closing', rollback: true } },
])(
'connect (force=$force) clears an ID-less legacy $label reservation on canonical not_found and continues',
async ({ force, overrides }) => {
const env = cloudEnv();
const location = locationOf(env);
const reservation = writeLegacyPending(env);
if (overrides) writeCloudConnection(location, { ...reservation, ...overrides });
const broker = stubCloudApi();
broker.mockResolvedValueOnce(Response.json({ error: 'not_found' }, { status: 404 }));

const result = await runCliCapture(force ? [...connectArgs, '--force'] : connectArgs, { env });
expect(result.code, result.stdout).toBeNull();
expect(broker.mock.calls.map(([, init]) => init.method)).toEqual(['GET', 'POST']);
const committed = readCloudConnection(location);
expect(committed?.phase).toBe('committed');
expect(committed?.generation).not.toBe(reservation.generation);
},
);

test.each<{
label: string;
setup?: (location: ReturnType<typeof locationOf>) => void;
response?: () => Response;
}>([
{ label: '500 lookup error', response: () => new Response(null, { status: 500 }) },
{
label: 'non-canonical 404',
response: () => Response.json({ error: 'other' }, { status: 404 }),
},
{
label: 'closing record without rollback',
setup: (location) =>
writeCloudConnection(location, { ...readCloudConnection(location)!, phase: 'closing' }),
},
{
label: 'record with allocation ID',
setup: (location) =>
writeCloudConnection(location, { ...readCloudConnection(location)!, id: hostedDevice.id }),
},
{
label: 'record with hostedLeaseId',
setup: (location) =>
writeCloudConnection(location, {
...readCloudConnection(location)!,
hostedLeaseId: 'proposed-lease-id',
}),
},
{
label: 'reservation with attachment file',
setup: (location) => fs.writeFileSync(cloudAttachmentPath(location), '{}', { mode: 0o600 }),
},
{
label: 'broker allocation ID mismatch',
setup: (location) =>
writeCloudConnection(location, { ...readCloudConnection(location)!, id: hostedDevice.id }),
response: () => Response.json({ id: '00000000-0000-4000-8000-000000000099', state: 'running' }),
},
])(
'connect keeps refusing an unbound pending reservation on $label',
async ({ setup, response }) => {
const env = cloudEnv();
const location = locationOf(env);
const reservation = writeLegacyPending(env);
setup?.(location);
const broker = stubCloudApi();
broker.mockResolvedValueOnce(
response ? response() : Response.json({ error: 'not_found' }, { status: 404 }),
);

const refused = await runCliCapture(connectArgs, { env });
expect(refused.code).toBe(1);
expect(JSON.parse(refused.stdout).error.details.reason).toBe(
'cloud_connection_allocation_unconfirmed',
);
expect(broker.mock.calls.map(([, init]) => init.method)).toEqual(['GET']);
expect(readCloudConnection(location)?.generation).toBe(reservation.generation);
},
);

test('connect ends an active broker allocation found for an ID-less legacy pending reservation', async () => {
const env = cloudEnv();
const location = locationOf(env);
const reservation = writeLegacyPending(env);
const broker = stubCloudApi();
broker.mockResolvedValueOnce(Response.json({ id: hostedDevice.id, state: 'running' }));
broker.mockResolvedValueOnce(new Response(null, { status: 204 }));

const result = await runCliCapture(connectArgs, { env });
expect(result.code, result.stdout).toBeNull();
expect(broker.mock.calls.map(([, init]) => init.method)).toEqual(['GET', 'DELETE', 'POST']);
expect(readCloudConnection(location)?.generation).not.toBe(reservation.generation);
});

test.each([
{ session: 'cloud-qa', force: false },
{ session: 'cloud-qa', force: true },
{ session: 'Cloud-QA', force: false },
])(
'connect (session=$session, force=$force) refuses an ID-less pending reservation beside a legacy-transport saved connection',
async ({ session, force }) => {
const env = { ...cloudEnv(), AGENT_DEVICE_SESSION: session };
const location = locationOf(env);
const reservation = writeLegacyPending(env);
const recordsDir = path.join(location.stateDir, 'remote-connections');
fs.mkdirSync(recordsDir, { recursive: true, mode: 0o700 });
const legacyStatePath = path.join(recordsDir, `${session}.json`);
fs.writeFileSync(
legacyStatePath,
JSON.stringify({
version: 1,
session,
remoteConfigPath: path.join(
location.stateDir,
'remote-connections',
'generated',
'legacy.json',
),
remoteConfigHash: 'hash',
tenant: 'tenant',
runId: 'run-1',
leaseId: 'legacy-lease-id',
cloudSession: {
id: '00000000-0000-4000-8000-000000000077',
baseUrl: env.AGENT_DEVICE_CLOUD_BASE_URL,
vendor: 'limrun',
transport: 'limrun',
deadlineAt: new Date(Date.now() + 60_000).toISOString(),
generation: 'other-generation',
},
connectedAt: new Date().toISOString(),
updatedAt: new Date().toISOString(),
}),
{ mode: 0o600 },
);
const broker = stubCloudApi();
broker.mockResolvedValueOnce(Response.json({ error: 'not_found' }, { status: 404 }));

const args = force
? [...connectArgs, '--session', session, '--force']
: [...connectArgs, '--session', session];
const refused = await runCliCapture(args, { env });
expect(refused.code).toBe(1);
expect(JSON.parse(refused.stdout).error.details.reason).toBe(
'cloud_connection_allocation_unconfirmed',
);
expect(broker.mock.calls.map(([, init]) => init.method)).toEqual(['GET']);
expect(readCloudConnection(location)?.generation).toBe(reservation.generation);
expect(fs.existsSync(legacyStatePath)).toBe(true);
},
);
Loading