Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
22 commits
Select commit Hold shift + click to select a range
fa6c4aa
fix(remote): give each session its own saved-connection file
thymikee Nov 21, 2026
050cf0d
test(daemon-client): publish the startup phase gate atomically
thymikee Nov 21, 2026
1e24b0b
chore(gates): exempt the session file identity export from unused-exp…
thymikee Nov 21, 2026
33d652b
fix(remote): never resolve a session onto another session's record
thymikee Nov 21, 2026
c5cdd7b
fix(remote): keep finding a session's hashed record after the shared …
thymikee Nov 22, 2026
850e14c
fix(remote): resolve a session's saved connection by name and migrate…
thymikee Nov 22, 2026
2e7a7c9
chore(gates): drop the unused-export exemption for the removed sessio…
thymikee Nov 22, 2026
2e784e6
test(remote): ignore the fixture's second hard-link name on case-sens…
thymikee Nov 22, 2026
e0b79c9
docs(commands): name the refusal for an unreadable saved connection a…
thymikee Nov 22, 2026
1f83288
fix(remote): find an empty session's older record and read older reco…
thymikee Nov 22, 2026
8706c92
fix(remote): keep connection status read-only and stop following a no…
thymikee Nov 22, 2026
d888c17
docs(commands): scope the saved-connection refusals to the files they…
thymikee Nov 22, 2026
ea05a48
fix(remote): make the saved-connection readers observation-only and m…
thymikee Nov 22, 2026
426a2db
docs(commands): say that only a save or a removal moves an older save…
thymikee Nov 22, 2026
1846b18
fix(remote): settle the saved connection before disconnect tears it down
thymikee Nov 22, 2026
8f115a5
refactor(cli): split disconnect into claim, teardown and removal steps
thymikee Nov 22, 2026
0bc01ce
fix(remote): remove each invalid record a disconnect passes and fall …
thymikee Nov 22, 2026
716fb68
refactor(remote): merge the claim helpers and drop lookups the name r…
thymikee Nov 22, 2026
4c0e3b9
test(remote): keep one test per saved-connection behavior
thymikee Nov 22, 2026
eb31b81
test(daemon-client): leave the startup gate publish change to its own PR
thymikee Nov 22, 2026
6e4ab95
fix(remote): drive disconnect from its one claim and unlink only a po…
thymikee Nov 22, 2026
ac0b49d
docs(reasons): regenerate error-reasons.md after rebase
thymikee Nov 22, 2026
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
392 changes: 392 additions & 0 deletions packages/remote/src/remote-connection-state-session-identity.test.ts

Large diffs are not rendered by default.

419 changes: 358 additions & 61 deletions packages/remote/src/remote-connection-state.ts

Large diffs are not rendered by default.

10 changes: 6 additions & 4 deletions src/__tests__/cli-config.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1138,7 +1138,7 @@ test('disconnect cleans connection state when remote config file is gone', async
fs.rmSync(root, { recursive: true, force: true });
});

test('disconnect removes malformed connection state', async () => {
test('disconnect refuses and keeps a connection state file that does not parse', async () => {
const { root, home, project } = makeTempWorkspace();
const stateDir = path.join(root, 'state');
const connectionsDir = path.join(stateDir, 'remote-connections');
Comment thread
thymikee marked this conversation as resolved.
Resolved
Expand All @@ -1153,10 +1153,12 @@ test('disconnect removes malformed connection state', async () => {
env: { HOME: home },
});

assert.equal(disconnected.code, null);
// No session can be shown to own an unparseable file, so it is never removed.
assert.equal(disconnected.code, 1);
assert.equal(disconnected.calls.length, 0);
assert.equal(fs.existsSync(statePath), false);
assert.equal(fs.existsSync(activePath), false);
assert.match(disconnected.stdout, /connection_record_owner_unknown/);
assert.equal(fs.readFileSync(statePath, 'utf8'), '{not json');
assert.equal(fs.existsSync(activePath), true);

fs.rmSync(root, { recursive: true, force: true });
});
Expand Down
107 changes: 107 additions & 0 deletions src/__tests__/cli-disconnect-invalid-default.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
import { test } from 'vitest';
import assert from 'node:assert/strict';
import fs from 'node:fs';
import path from 'node:path';
import { makeTempWorkspace } from '@agent-device/test-kit';
import {
hashRemoteConfigFile,
readRemoteConnectionState,
} from '@agent-device/remote/remote-connection-state';
import { runCliCapture } from './cli-capture.ts';

test('an unnamed disconnect removes an invalid default record before it disconnects the active session', async () => {
const { root, home, project } = makeTempWorkspace();
const stateDir = path.join(root, 'state');
const connectionsDir = path.join(stateDir, 'remote-connections');
fs.mkdirSync(connectionsDir, { recursive: true });
const remoteConfig = path.join(project, 'agent-device.remote.json');
fs.writeFileSync(
remoteConfig,
JSON.stringify({ daemonBaseUrl: 'http://remote-mac.example.test:9124/agent-device' }),
'utf8',
);
const record = (session: string) => ({
version: 1,
session,
remoteConfigPath: remoteConfig,
remoteConfigHash: hashRemoteConfigFile(remoteConfig),
tenant: 'acme',
runId: `run-${session}`,
connectedAt: new Date().toISOString(),
updatedAt: new Date().toISOString(),
});
const defaultPath = path.join(connectionsDir, 'default.json');
const teamPath = path.join(connectionsDir, 'team.json');
const activePath = path.join(connectionsDir, '.active-session.json');
fs.writeFileSync(defaultPath, JSON.stringify({ ...record('default'), updatedAt: null }), 'utf8');
fs.writeFileSync(teamPath, JSON.stringify(record('team')), 'utf8');
fs.writeFileSync(activePath, JSON.stringify({ session: 'team' }), 'utf8');

const disconnected = await runCliCapture(['disconnect', '--state-dir', stateDir, '--json'], {
cwd: project,
env: { HOME: home },
});

assert.equal(disconnected.code, null);
assert.equal(JSON.parse(disconnected.stdout).data.session, 'team');
assert.equal(fs.existsSync(defaultPath), false);
assert.equal(fs.existsSync(teamPath), false);
assert.equal(fs.existsSync(activePath), false);

fs.rmSync(root, { recursive: true, force: true });
});

// A build that sanitized session names wrote the session `.active-session` to exactly the pointer
// path. The unnamed disconnect claims it there, and that claim drives the client and the teardown.
test.each([
{ leaseProvider: undefined, refusal: undefined },
{ leaseProvider: 'proxy', refusal: 'REMOTE_SESSION_REQUIRED' },
])(
'an unnamed disconnect of the older .active-session record at the pointer path (leaseProvider $leaseProvider)',
async ({ leaseProvider, refusal }) => {
const { root, home, project } = makeTempWorkspace();
const stateDir = path.join(root, 'state');
const connectionsDir = path.join(stateDir, 'remote-connections');
fs.mkdirSync(connectionsDir, { recursive: true });
const remoteConfig = path.join(project, 'agent-device.remote.json');
fs.writeFileSync(
remoteConfig,
JSON.stringify({ daemonBaseUrl: 'http://remote-mac.example.test:9124/agent-device' }),
'utf8',
);
const session = '.active-session';
fs.writeFileSync(
path.join(connectionsDir, '.active-session.json'),
JSON.stringify({
version: 1,
session,
remoteConfigPath: remoteConfig,
remoteConfigHash: hashRemoteConfigFile(remoteConfig),
tenant: 'acme',
runId: 'run-legacy',
...(leaseProvider ? { leaseProvider } : {}),
connectedAt: new Date().toISOString(),
updatedAt: new Date().toISOString(),
}),
'utf8',
);

const disconnected = await runCliCapture(['disconnect', '--state-dir', stateDir, '--json'], {
cwd: project,
env: { HOME: home },
});

if (refusal) {
assert.equal(disconnected.code, 1);
assert.equal(JSON.parse(disconnected.stdout).error.details.reason, refusal);
assert.equal(readRemoteConnectionState({ stateDir, session })?.runId, 'run-legacy');
} else {
assert.equal(disconnected.code, null);
assert.equal(JSON.parse(disconnected.stdout).data.session, session);
assert.equal(readRemoteConnectionState({ stateDir, session }), null);
assert.deepEqual(fs.readdirSync(connectionsDir), []);
}

fs.rmSync(root, { recursive: true, force: true });
},
);
17 changes: 8 additions & 9 deletions src/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@ import {
import { resolveCliOptions } from './cli/resolve-cli-options.ts';
import { maybeRunUpgradeNotifier } from './cli/update-check.ts';
import {
claimRemoteConnectionDefaults,
remoteSessionRequiredError,
resolveRemoteConnectionDefaults,
type RemoteConnectionRequestMetadata,
Expand Down Expand Up @@ -654,6 +655,7 @@ async function dispatchCliCommand(
replayTestReporterRuntime,
commandProgress,
leaseDevice: ctx.leaseDevice,
claimedConnection: ctx.connectionDefaults?.claimed,
})
) {
return;
Expand Down Expand Up @@ -778,27 +780,24 @@ function resolveActiveConnectionDefaults(options: {
stateDir: string;
session: string | undefined;
remoteConfig?: string;
}): {
flags: Partial<CliFlags>;
runtime?: SessionRuntimeHints;
connection?: RemoteConnectionRequestMetadata;
} | null {
}) {
if (
options.command === 'connect' ||
options.command === 'connection' ||
!runsOnRemoteConnection(options.command)
) {
return null;
}
const defaults = resolveRemoteConnectionDefaults({
const request = {
stateDir: options.stateDir,
session: options.session,
remoteConfig: options.remoteConfig,
cwd: options.host.cwd,
env: options.host.env,
validateRemoteConfigHash: options.command !== 'disconnect',
});
return defaults;
};
return options.command === 'disconnect'
? claimRemoteConnectionDefaults(request)
: resolveRemoteConnectionDefaults(request);
}

// A command that cannot take a session runs on no remote connection. Reading, authenticating or
Expand Down
154 changes: 154 additions & 0 deletions src/cli/commands/connection-disconnect.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -174,3 +174,157 @@ test('disconnect treats an already-inactive lease as released without a failure
assert.equal(text.trim(), 'Disconnected remote session "adc-release-inactive".');
fs.rmSync(tempRoot, { recursive: true, force: true });
});

test('disconnect refuses a record it cannot remove before it closes the session or releases the lease', async () => {
const { tempRoot, stateDir } = seedReleasableConnection(
'agent-device-disconnect-occupied-session-path-',
'Demo',
);
const recordsDir = path.join(stateDir, 'remote-connections');
const [hashedName] = fs.readdirSync(recordsDir).filter((name) => name.startsWith('~'));
assert.ok(hashedName, 'the new build saves Demo at its hashed path');
const hashedPath = path.join(recordsDir, hashedName);
// An older build connected Demo under a run of its own and saved it at the name it wrote.
const legacyPath = path.join(recordsDir, 'Demo.json');
const legacy = JSON.parse(fs.readFileSync(hashedPath, 'utf8'));
fs.writeFileSync(
legacyPath,
JSON.stringify({ ...legacy, runId: 'run-legacy', leaseId: 'lease-legacy' }),
);
let closed = 0;
let released = 0;

await assert.rejects(
disconnectCommand({
positionals: [],
flags: { json: true, help: false, version: false, stateDir, session: 'Demo' },
client: createTestClient({
closeSession: async () => {
closed += 1;
return { session: 'Demo', identifiers: { session: 'Demo' } };
},
release: async () => {
released += 1;
return { released: true };
},
}),
}),
(error: unknown) =>
error instanceof AppError && error.details?.reason === 'connection_session_mismatch',
);

assert.equal(closed, 0);
assert.equal(released, 0);
assert.equal(JSON.parse(fs.readFileSync(hashedPath, 'utf8')).leaseId, 'lease-1');
assert.equal(JSON.parse(fs.readFileSync(legacyPath, 'utf8')).leaseId, 'lease-legacy');
fs.rmSync(tempRoot, { recursive: true, force: true });
});

test('an unnamed disconnect removes an invalid default record and disconnects the active session', async () => {
const { tempRoot, stateDir, remoteConfigPath } = connectionWorkspace(
'agent-device-disconnect-invalid-default-',
);
fs.writeFileSync(remoteConfigPath, '{}');
seedConnectionState({
stateDir,
state: {
session: 'demo',
remoteConfigPath,
tenant: 'acme',
runId: 'run-demo',
runtime: { platform: 'android', metroPort: 8081 },
},
});
const recordsDir = path.join(stateDir, 'remote-connections');
const defaultPath = path.join(recordsDir, 'default.json');
const demoPath = path.join(recordsDir, 'demo.json');
const activePath = path.join(recordsDir, '.active-session.json');
const valid = JSON.parse(fs.readFileSync(demoPath, 'utf8'));
fs.writeFileSync(defaultPath, JSON.stringify({ ...valid, session: 'default', updatedAt: null }));
const closed: string[] = [];

const text = await withCapturedStdoutAsync(async () => {
await disconnectCommand({
positionals: [],
flags: { json: false, help: false, version: false, stateDir },
client: createTestClient({
closeSession: async (request) => {
closed.push(request?.session ?? '');
return { session: 'demo', identifiers: { session: 'demo' } };
},
}),
});
});

assert.equal(text.trim(), 'Disconnected remote session "demo".');
assert.deepEqual(closed, ['demo']);
assert.equal(fs.existsSync(defaultPath), false);
assert.equal(fs.existsSync(demoPath), false);
assert.equal(fs.existsSync(activePath), false);
fs.rmSync(tempRoot, { recursive: true, force: true });
});

test.each([
{
name: 'its own file',
session: 'demo',
fileName: 'demo.json',
record: { session: 'demo', version: 1, runId: 'run-demo', updatedAt: null },
},
// An older build saved Demo at the name it wrote, and the record holds only its session.
{
name: 'its older pointer-shaped file',
session: 'Demo',
fileName: 'Demo.json',
record: { session: 'Demo' },
},
])(
'disconnect removes a record at $name that names its session but fails validation',
async ({ session, fileName, record }) => {
const { tempRoot, stateDir } = connectionWorkspace('agent-device-disconnect-invalid-record-');
const recordsDir = path.join(stateDir, 'remote-connections');
fs.mkdirSync(recordsDir, { recursive: true });
fs.writeFileSync(path.join(recordsDir, fileName), JSON.stringify(record));
fs.writeFileSync(path.join(recordsDir, '.active-session.json'), JSON.stringify({ session }));

const text = await withCapturedStdoutAsync(async () => {
await disconnectCommand({
positionals: [],
flags: { json: false, help: false, version: false, stateDir, session },
client: createTestClient(),
});
});

assert.equal(text.trim(), `No remote connection for "${session}".`);
assert.deepEqual(fs.readdirSync(recordsDir), []);
fs.rmSync(tempRoot, { recursive: true, force: true });
},
);

// `--session=` names the empty session. Read as an omitted session, it followed the active-session
// pointer and removed the connection the pointer named for another session.
test('disconnect --session= with no empty-session record keeps the record the pointer names', async () => {
const { tempRoot, stateDir, remoteConfigPath } = connectionWorkspace(
'agent-device-connection-empty-session-',
);
fs.writeFileSync(remoteConfigPath, '{}');
seedConnectionState({
stateDir,
state: { session: 'Demo', remoteConfigPath, tenant: 'acme', runId: 'run-Demo' },
});

const stdout = await withCapturedStdoutAsync(async () => {
// Every call this client answers throws: the command may not reach the daemon.
await disconnectCommand({
positionals: [],
flags: { json: true, help: false, version: false, stateDir, session: '' },
client: createTestClient(),
});
});

const payload = JSON.parse(stdout).data;
assert.equal(payload.connected, false);
assert.equal(payload.session, '');
assert.equal(readRemoteConnectionState({ stateDir, session: 'Demo' })?.runId, 'run-Demo');
fs.rmSync(tempRoot, { recursive: true, force: true });
});
52 changes: 52 additions & 0 deletions src/cli/commands/connection-status-read-only.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
import { test } from 'vitest';
import assert from 'node:assert/strict';
import fs from 'node:fs';
import path from 'node:path';
import { withCapturedStdoutAsync } from '@agent-device/test-kit';
import { hashRemoteConfigFile } from '@agent-device/remote/remote-connection-state';
import {
connectionWorkspace,
createTestClient,
} from '../../__tests__/remote-connection.fixtures.ts';
import { connectionCommand } from '../../__tests__/test-utils/host-bound-commands.ts';

// `connection status` only reports the saved connection. A status read that moved an older build's
// record to its session's own file failed where the records directory could not be written.

test('connection status --session Demo over an older Demo.json leaves the records directory unchanged', async () => {
const { tempRoot, stateDir, remoteConfigPath } = connectionWorkspace(
'agent-device-connection-status-read-only-',
);
fs.writeFileSync(remoteConfigPath, '{}');
const recordsDir = path.join(stateDir, 'remote-connections');
fs.mkdirSync(recordsDir, { recursive: true });
const now = new Date().toISOString();
fs.writeFileSync(
path.join(recordsDir, 'Demo.json'),
`${JSON.stringify({
version: 1,
session: 'Demo',
remoteConfigPath,
remoteConfigHash: hashRemoteConfigFile(remoteConfigPath),
tenant: 'acme',
runId: 'run-Demo',
connectedAt: now,
updatedAt: now,
})}\n`,
);

const stdout = await withCapturedStdoutAsync(async () => {
// Every call this client answers throws: status may not reach the daemon.
await connectionCommand({
positionals: ['status'],
flags: { json: true, help: false, version: false, stateDir, session: 'Demo' },
client: createTestClient(),
});
});

const payload = JSON.parse(stdout).data;
assert.equal(payload.session, 'Demo');
assert.equal(payload.runId, 'run-Demo');
assert.deepEqual(fs.readdirSync(recordsDir), ['Demo.json'], 'status moved no file');
fs.rmSync(tempRoot, { recursive: true, force: true });
});
Loading
Loading