Skip to content

Commit a7f2e92

Browse files
committed
fix(daemon): keep an active replay session's daemon alive over the CLI path
A `replay <script>.ad` with no terminal `close` reports its session as still active per ADR 0016's consumption contract, but the real CLI client tears down the daemon that ran it (and its owned ephemeral state dir) regardless — the request's own success response gets overwritten seconds later by an empty `session list`. This happens whenever the client started the daemon itself, independent of whether the state dir was randomly generated or passed explicitly via --state-dir/AGENT_DEVICE_STATE_DIR, matching #1384's live repro. Add `sessionActive` to `ReplayCommandResult`, computed from whether the session survives in the daemon's own store (never by re-parsing the script), and gate the client's one-shot teardown on it — mirroring the existing ADR-0012 repair-divergence keep-alive. A kept-alive owned daemon now also attaches a --state-dir address hint to the response so the caller can reach it. `test` is unaffected: its own per-file runner already closes each session before the suite summary is built. Fixes #1384
1 parent 968db8b commit a7f2e92

8 files changed

Lines changed: 277 additions & 3 deletions

File tree

‎docs/adr/0016-active-session-script-publication.md‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -169,6 +169,13 @@ executing that script, not the artifact being saved.
169169
fragment pinning remain entirely under #1336.
170170
- Secret-bearing authoring remains unsafe until #1348; the initial workflow is limited to journeys that
171171
do not enter secrets. Arbitrary history ranges remain out of scope.
172+
- On consumption (issue #1384), a `replay` whose script has no terminal `close` leaves a live daemon and
173+
app session behind — including the ordinary one-shot `replay` invocation's own owned/ephemeral daemon,
174+
which the client keeps alive and reports a `--state-dir` address hint for instead of tearing down. An
175+
unattended close-less replay (e.g. in CI) therefore leaks a session exactly like one opened
176+
interactively: bounded by ordinary idle-reap or an explicit `close`, never by the one-shot command's own
177+
process lifetime. This is the intended shape of "the caller owns close," not an accident, and recorded
178+
test flows already end with `close` so `test` runs are unaffected.
172179

173180
## Alternatives Considered
174181

‎src/commands/replay/index.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -93,7 +93,7 @@ export const testCommandDefinition = defineExecutableCommand(testCommandMetadata
9393
const replayCliSchema = {
9494
usageOverride: 'replay <path> | replay export <file.ad> [--out <path>]',
9595
helpDescription:
96-
'Replay a recorded session. For Maestro YAML compatibility flows, use replay <flow.yaml> --maestro and keep the target binding such as --platform ios on the replay command.',
96+
'Replay a recorded session. For Maestro YAML compatibility flows, use replay <flow.yaml> --maestro and keep the target binding such as --platform ios on the replay command. A script with no terminal close leaves its session (and daemon) running until you close it or it idle-reaps — no different from a session opened interactively.',
9797
summary: replayCommandDescription,
9898
positionalArgs: ['path'],
9999
allowsExtraPositionals: true,

‎src/contracts/replay.ts‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,14 @@ export type ReplayCommandResult = {
55
replayed: number;
66
healed: number;
77
session: string;
8+
/**
9+
* True iff `session` still exists in the daemon's session store when the
10+
* response is built — i.e. the replayed script had no terminal `close`
11+
* (ADR 0016's consumption contract). The client uses this, not script
12+
* parsing, to decide whether an owned one-shot daemon must stay alive so
13+
* the caller can keep addressing this session.
14+
*/
15+
sessionActive: boolean;
816
artifactPaths: string[];
917
warnings?: string[];
1018
snapshotDiagnostics?: SnapshotDiagnosticsSummary;

‎src/daemon/client/daemon-client-lifecycle.ts‎

Lines changed: 60 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -342,7 +342,19 @@ export async function cleanupDaemonAfterRequest(
342342
// `REPAIR_SESSION_EXPIRED` tombstone on reap), so an abandoned repair still
343343
// cannot leak indefinitely; this only stops the ONE-SHOT-COMMAND teardown
344344
// below from racing ahead of that window.
345-
isHeldRepairDivergence(response)
345+
isHeldRepairDivergence(response) ||
346+
// ADR 0016: a `replay` whose script had no terminal `close` reports its
347+
// session as still active by design (the consumption contract this ADR
348+
// defines) — tearing down its owning daemon here would make that contract
349+
// unaddressable over the real CLI path the instant the response is sent.
350+
// Keyed off the session surviving the run (`sessionActive`), never off
351+
// parsing the script for `close`, so a `--from` resume is covered too.
352+
// Unlike the repair case, this session has no bounded reap of its own: an
353+
// unattended close-less replay leaves a live daemon+app session until
354+
// ordinary idle-reap or an explicit `close` ends it — the same lifetime an
355+
// interactively opened session already has, and exactly what the ADR's
356+
// "caller owns close" contract asks for.
357+
isActiveReplaySessionResponse(req, response)
346358
) {
347359
return response;
348360
}
@@ -476,6 +488,53 @@ function isOneShotReplayCommand(command: string | undefined): boolean {
476488
return command === PUBLIC_COMMANDS.replay || command === PUBLIC_COMMANDS.test;
477489
}
478490

491+
/**
492+
* ADR 0016: true when a successful `replay` response reports its session as
493+
* still active (`ReplayCommandResult.sessionActive`, set by the daemon from
494+
* whether the session survived in its own store — never derived here by
495+
* re-parsing the script). Restricted to `replay` itself, never `test`: a
496+
* `test` run's own per-file runner already closes each session before the
497+
* suite summary is built, and its `ReplaySuiteResult` carries no such field
498+
* anyway, but the explicit command check keeps that carve-out a decision
499+
* rather than an accident of the response shape.
500+
*/
501+
export function isActiveReplaySessionResponse(
502+
req: Omit<DaemonRequest, 'token'>,
503+
response: DaemonResponse | undefined,
504+
): boolean {
505+
if (req.command !== PUBLIC_COMMANDS.replay) return false;
506+
if (!response || !response.ok) return false;
507+
return response.data?.sessionActive === true;
508+
}
509+
510+
/**
511+
* ADR 0016 counterpart to `attachRepairSessionAddressHint`: the owned
512+
* ephemeral daemon this SUCCESSFUL response's session now lives on is kept
513+
* alive by the `isActiveReplaySessionResponse` guard above, but stays at a
514+
* randomly generated `--state-dir` no other invocation knows about. Attached
515+
* to both a structured `hint` field (for `--json` consumers) and appended to
516+
* `message` — the only field the default text renderer surfaces
517+
* (`src/utils/success-text.ts`) — so the hint reaches a caller in either mode.
518+
*/
519+
export function attachActiveSessionAddressHint(
520+
response: Extract<DaemonResponse, { ok: true }>,
521+
stateDir: string,
522+
): Extract<DaemonResponse, { ok: true }> {
523+
const addressHint =
524+
`This session's daemon was kept alive because its script left the session ` +
525+
`active; pass --state-dir ${stateDir} on your next command to reach it.`;
526+
const data = response.data ?? {};
527+
const existingMessage = typeof data.message === 'string' ? data.message : undefined;
528+
return {
529+
...response,
530+
data: {
531+
...data,
532+
hint: addressHint,
533+
message: existingMessage ? `${existingMessage} ${addressHint}` : addressHint,
534+
},
535+
};
536+
}
537+
479538
async function waitForDaemonStartup(
480539
timeoutMs: number,
481540
settings: DaemonClientSettings,

‎src/daemon/client/daemon-client.ts‎

Lines changed: 25 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,9 +8,11 @@ import { createRequestId, emitDiagnostic, withDiagnosticTimer } from '../../util
88
import { INTERNAL_COMMANDS, PUBLIC_COMMANDS } from '../../command-catalog.ts';
99
import { prepareRemoteRequestArtifacts } from '../../remote/daemon-artifacts.ts';
1010
import {
11+
attachActiveSessionAddressHint,
1112
attachRepairSessionAddressHint,
1213
cleanupDaemonAfterRequest,
1314
ensureDaemon,
15+
isActiveReplaySessionResponse,
1416
isHeldRepairDivergence,
1517
resolveClientSettings,
1618
type DaemonClientSettings,
@@ -94,7 +96,11 @@ export async function sendToDaemon(
9496
),
9597
{ requestId, command: req.command },
9698
);
97-
return withRepairSessionAddressHintIfOwned(response, settings);
99+
return withActiveSessionAddressHintIfOwned(
100+
withRepairSessionAddressHintIfOwned(response, settings),
101+
req,
102+
settings,
103+
);
98104
});
99105
}
100106

@@ -153,6 +159,24 @@ function withRepairSessionAddressHintIfOwned(
153159
return attachRepairSessionAddressHint(response, settings.paths.baseDir);
154160
}
155161

162+
/**
163+
* ADR 0016 counterpart to `withRepairSessionAddressHintIfOwned`: the owned
164+
* ephemeral state dir this SUCCESSFUL response's still-active session now
165+
* lives on is otherwise unaddressable by a later invocation — hint it here,
166+
* only when the daemon is actually being kept alive for it
167+
* (`settings.ownedStateDir` means `daemon.startedByClient` is also true).
168+
*/
169+
function withActiveSessionAddressHintIfOwned(
170+
response: DaemonResponse,
171+
req: Omit<DaemonRequest, 'token'>,
172+
settings: DaemonClientSettings,
173+
): DaemonResponse {
174+
if (!response.ok || !settings.ownedStateDir || !isActiveReplaySessionResponse(req, response)) {
175+
return response;
176+
}
177+
return attachActiveSessionAddressHint(response, settings.paths.baseDir);
178+
}
179+
156180
function writeInstallInProgressNotice(command: string | undefined): void {
157181
if (!isInstallLikeCommand(command) || process.stderr.isTTY !== true || process.env.CI) return;
158182
process.stderr.write(

‎src/daemon/handlers/session-replay-maestro-response.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@ export function buildTypedMaestroSuccessResponse(params: {
2828
replayed,
2929
healed: 0,
3030
session: sessionName,
31+
sessionActive: sessionStore.get(sessionName) !== undefined,
3132
artifactPaths: result.artifactPaths,
3233
...(result.warnings ? { warnings: result.warnings } : {}),
3334
...(snapshotDiagnostics ? { snapshotDiagnostics } : {}),

‎src/daemon/handlers/session-replay-runtime.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -383,6 +383,7 @@ function completeReplayRun(params: {
383383
replayed: replayedCount,
384384
healed: 0,
385385
session: sessionName,
386+
sessionActive: completedSession !== undefined,
386387
artifactPaths: [...artifactPaths],
387388
...(snapshotDiagnosticsSummary ? { snapshotDiagnostics: snapshotDiagnosticsSummary } : {}),
388389
message: formatReplaySuccessMessage(replayedCount, Date.now() - startedAt),

‎src/utils/__tests__/daemon-client-lifecycle.test.ts‎

Lines changed: 174 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1081,3 +1081,177 @@ test('continuation: sendToDaemon keeps the daemon alive on a held divergence eve
10811081
if (ownedStateDir) fs.rmSync(ownedStateDir, { recursive: true, force: true });
10821082
}
10831083
});
1084+
1085+
// --- ADR 0016: on consumption, a `replay` whose script had no terminal
1086+
// `close` reports its session as still active (`ReplayCommandResult.
1087+
// sessionActive: true`) by design — the named session stays active and the
1088+
// caller binds subsequent commands to the returned id. Tearing down the
1089+
// owning daemon here (issue #1384) makes that contract unaddressable the
1090+
// instant the response is sent. This mirrors the repair-divergence keep-alive
1091+
// above, but for a SUCCESSFUL response instead of a held divergence, and has
1092+
// no bounded reap of its own (unlike a held repair): an unattended close-less
1093+
// replay leaves a live daemon+app session until ordinary idle-reap or an
1094+
// explicit `close` ends it — the same lifetime an interactively opened
1095+
// session already has. ---
1096+
1097+
function activeReplaySuccessData(
1098+
overrides: Record<string, unknown> = {},
1099+
): Record<string, unknown> {
1100+
return {
1101+
replayed: 1,
1102+
healed: 0,
1103+
session: 'default',
1104+
sessionActive: true,
1105+
artifactPaths: [],
1106+
message: 'Replayed 1 step in 0.1s',
1107+
...overrides,
1108+
};
1109+
}
1110+
1111+
test('sendToDaemon keeps an owned ephemeral daemon alive and hints its --state-dir when a close-less replay leaves the session active', async (t) => {
1112+
if (!(await supportsLoopbackBind())) {
1113+
t.skip('loopback listeners are not permitted in this environment');
1114+
return;
1115+
}
1116+
1117+
const daemon = await startHttpDaemonFixture(activeReplaySuccessData());
1118+
let ownedStateDir = '';
1119+
installSpawnedHttpDaemonAtOwnedStateDir(daemon.port, (dir) => {
1120+
ownedStateDir = dir;
1121+
});
1122+
1123+
try {
1124+
const response = await sendToDaemon({
1125+
session: 'default',
1126+
command: 'replay',
1127+
positionals: ['open-only.ad'],
1128+
flags: { daemonTransport: 'http' },
1129+
meta: { requestId: 'req-active-session-keep-alive' },
1130+
});
1131+
1132+
assert.equal(response.ok, true);
1133+
if (!response.ok) return;
1134+
assert.equal(response.data?.session, 'default');
1135+
assert.equal(response.data?.sessionActive, true);
1136+
assert.ok(ownedStateDir.length > 0);
1137+
assert.match(String(response.data?.hint), /--state-dir/);
1138+
assert.ok(String(response.data?.hint).includes(ownedStateDir));
1139+
assert.match(String(response.data?.message), /--state-dir/);
1140+
1141+
// The daemon was NOT torn down: metadata and the owned state dir itself
1142+
// are still on disk, addressable by a follow-up command's --state-dir.
1143+
const ownedPaths = resolveDaemonPaths(ownedStateDir);
1144+
assert.equal(fs.existsSync(ownedPaths.infoPath), true);
1145+
assert.equal(fs.existsSync(ownedPaths.lockPath), true);
1146+
assert.equal(fs.existsSync(ownedStateDir), true);
1147+
} finally {
1148+
await closeLoopbackServer(daemon.server);
1149+
if (ownedStateDir) fs.rmSync(ownedStateDir, { recursive: true, force: true });
1150+
}
1151+
});
1152+
1153+
test('sendToDaemon tears down an owned ephemeral daemon when replay reports the session was closed (sessionActive: false)', async (t) => {
1154+
if (!(await supportsLoopbackBind())) {
1155+
t.skip('loopback listeners are not permitted in this environment');
1156+
return;
1157+
}
1158+
1159+
const daemon = await startHttpDaemonFixture(activeReplaySuccessData({ sessionActive: false }));
1160+
let ownedStateDir = '';
1161+
installSpawnedHttpDaemonAtOwnedStateDir(daemon.port, (dir) => {
1162+
ownedStateDir = dir;
1163+
});
1164+
1165+
try {
1166+
const response = await sendToDaemon({
1167+
session: 'default',
1168+
command: 'replay',
1169+
positionals: ['closed.ad'],
1170+
flags: { daemonTransport: 'http' },
1171+
meta: { requestId: 'req-closed-session-teardown' },
1172+
});
1173+
1174+
assert.equal(response.ok, true);
1175+
if (!response.ok) return;
1176+
assert.equal(response.data?.hint, undefined);
1177+
assert.ok(ownedStateDir.length > 0);
1178+
assert.equal(fs.existsSync(ownedStateDir), false);
1179+
} finally {
1180+
await closeLoopbackServer(daemon.server);
1181+
if (ownedStateDir) fs.rmSync(ownedStateDir, { recursive: true, force: true });
1182+
}
1183+
});
1184+
1185+
test('issue #1384: sendToDaemon does not stop a client-started daemon at an explicit --state-dir when replay leaves the session active', async (t) => {
1186+
if (!(await supportsLoopbackBind())) {
1187+
t.skip('loopback listeners are not permitted in this environment');
1188+
return;
1189+
}
1190+
1191+
// The literal #1384 repro: an explicit AGENT_DEVICE_STATE_DIR/--state-dir
1192+
// means `ownedStateDir` is false, but this client still STARTS the daemon
1193+
// fresh at that fixed dir (`daemon.startedByClient`) since nothing was
1194+
// running there yet — the teardown branch this guards is reached
1195+
// regardless of `ownedStateDir`.
1196+
const stateDir = makeTempStateDir('agent-device-active-session-explicit-dir-');
1197+
const paths = resolveDaemonPaths(stateDir);
1198+
const daemon = await startHttpDaemonFixture(activeReplaySuccessData());
1199+
installSpawnedHttpDaemon(paths, daemon.port);
1200+
1201+
try {
1202+
const response = await sendToDaemon({
1203+
session: 'default',
1204+
command: 'replay',
1205+
positionals: ['open-only.ad'],
1206+
flags: { stateDir, daemonTransport: 'http' },
1207+
meta: { requestId: 'req-explicit-dir-active-session' },
1208+
});
1209+
1210+
assert.equal(response.ok, true);
1211+
if (!response.ok) return;
1212+
assert.equal(response.data?.sessionActive, true);
1213+
// No address hint here: the caller already knows this state dir — it
1214+
// passed it explicitly — only an OWNED (randomly generated) state dir
1215+
// needs a hint to become addressable again.
1216+
assert.equal(response.data?.hint, undefined);
1217+
assert.equal(fs.existsSync(paths.infoPath), true);
1218+
assert.equal(fs.existsSync(paths.lockPath), true);
1219+
} finally {
1220+
await closeLoopbackServer(daemon.server);
1221+
fs.rmSync(stateDir, { recursive: true, force: true });
1222+
}
1223+
});
1224+
1225+
test('sendToDaemon still tears down a `test` command owned ephemeral daemon even if its response data carried sessionActive:true', async (t) => {
1226+
if (!(await supportsLoopbackBind())) {
1227+
t.skip('loopback listeners are not permitted in this environment');
1228+
return;
1229+
}
1230+
1231+
// `test` never actually sets this field in practice (its own per-file
1232+
// runner always closes each session before the suite summary is built) —
1233+
// this proves the carve-out is an explicit command check, not an accident
1234+
// of the response shape, should a future response ever carry it by mistake.
1235+
const daemon = await startHttpDaemonFixture(activeReplaySuccessData({ total: 1 }));
1236+
let ownedStateDir = '';
1237+
installSpawnedHttpDaemonAtOwnedStateDir(daemon.port, (dir) => {
1238+
ownedStateDir = dir;
1239+
});
1240+
1241+
try {
1242+
const response = await sendToDaemon({
1243+
session: 'default',
1244+
command: 'test',
1245+
positionals: ['suite.ad'],
1246+
flags: { daemonTransport: 'http' },
1247+
meta: { requestId: 'req-test-command-teardown' },
1248+
});
1249+
1250+
assert.equal(response.ok, true);
1251+
assert.ok(ownedStateDir.length > 0);
1252+
assert.equal(fs.existsSync(ownedStateDir), false);
1253+
} finally {
1254+
await closeLoopbackServer(daemon.server);
1255+
if (ownedStateDir) fs.rmSync(ownedStateDir, { recursive: true, force: true });
1256+
}
1257+
});

0 commit comments

Comments
 (0)