Skip to content

Commit 5b60f30

Browse files
authored
fix(daemon): stop cwd-scoped session resources by store address on close (#2648)
* fix(daemon): stop cwd-scoped session resources by store address on close stopBestEffortSessionResources addressed the app-log, audio-probe, perf-capture and recording records by session.name. For an implicit session that is "default" while the record lives under the store address "cwd:<hash>:default" (SessionRef), so close reported "App-log resource record is missing", left the record open/active and leaked the simctl log stream child; the next logs start on the device then failed with "has not reached a confirmed terminal state". Thread the address the caller already holds into the helper. Adds a regression test that reproduces the missing-record error without the fix. Closes #2647 * style: format teardown call * test(daemon): pin every close teardown step to the store address stopBestEffortSessionResources takes a SessionRef, so the address and the session travel as the pair SessionRef documents and a caller cannot hand it session.name by accident. makeIosSimulatorRecordingSession accepts a separate address and name. One close test per step (recording, app_log, audio_probe, perf_capture) uses name "default" under address "cwd:<hash>:default"; each fails with "<Kind> resource record is missing" if only its own step reverts to session.name. * test(daemon): decoy session under the bare name for the recording close test The recording step no longer re-reads the stored session in the teardown; finishSessionScreenRecording already does that by address and returns when there is no recording, so the duplicate lookup was only a second place to mis-address. The recording test stores a second session with its own live recording under the bare name "default": if the step goes back to session.name, close finishes the decoy's recording instead of the addressed one and the test fails on both counts. * test(daemon): state the recording test's failure mode in the header
1 parent 17eabc8 commit 5b60f30

4 files changed

Lines changed: 296 additions & 21 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,11 @@
22

33
## Unreleased
44

5+
- Fixed (daemon): `close` now stops an active app-log stream (and audio probe / perf capture /
6+
recording) on an implicitly cwd-scoped session. Teardown addressed those resources by
7+
`session.name` (`default`) instead of the store address (`cwd:<hash>:default`), so the record
8+
read as missing, the `log stream` child leaked, and the next `logs start` on that device failed
9+
with "has not reached a confirmed terminal state" (#2647).
510
- Added (limrun): `longpress` on Limrun iOS direct sessions. The interactor refused it as
611
unsupported although the SDK exposes the HID primitives; it now holds one touch as a
712
`performActions` batch of `touchDown`, `wait`, `touchUp`, defaulting to the 800 ms the Android
Lines changed: 268 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,268 @@
1+
import { beforeEach, expect, test, vi } from 'vitest';
2+
import type { AppLogLiveHandle } from '@agent-device/contracts/app-log-runtime';
3+
import type { AudioProbeLiveHandle } from '@agent-device/contracts/audio-probe-runtime';
4+
import type { PerfNativeCaptureLiveHandle } from '@agent-device/contracts/perf-runtime';
5+
import type { DurableResourceEnvelope } from '@agent-device/contracts/durable-resource-envelope';
6+
import {
7+
createDurableResourceEnvelope,
8+
encodeDurableDescriptor,
9+
hostAudioProbeDescriptorCodec,
10+
} from '@agent-device/capture-kit';
11+
import { appLogResourceStore } from '../../../app-log-resource-store.ts';
12+
import { audioProbeResourceStore } from '../../../audio-probe-resource-store.ts';
13+
import { perfCaptureResourceStore } from '../../../perf-capture-resource-store.ts';
14+
import { screenRecordingResourceStore } from '../../../screen-recording-resource-store.ts';
15+
import type { DurableCaptureResourceStore } from '@agent-device/capture-kit/durable-capture';
16+
import {
17+
sessionCloseShutdownFixture,
18+
type SessionState,
19+
} from './session-close-shutdown.fixtures.ts';
20+
import { mkdtempForTestSync } from '../../../../__tests__/test-utils/tmp-dir.ts';
21+
22+
const {
23+
handleSessionCommands,
24+
localRuntimeOwner,
25+
makeIosSimulatorRecordingSession,
26+
makeSession,
27+
makeSessionStore,
28+
noopInvoke,
29+
path,
30+
recordingFinishMock,
31+
resetSessionCloseShutdownMocks,
32+
} = sessionCloseShutdownFixture;
33+
34+
beforeEach(resetSessionCloseShutdownMocks);
35+
36+
// An implicitly cwd-scoped session is *named* `default` but *stored* under `cwd:<hash>:default`
37+
// (`SessionRef`). Each durable-capture record lives in the address's directory, so close teardown
38+
// must address every resource by the store address. If a step goes back to `session.name`:
39+
// - app_log, audio_probe, perf_capture fail with "<Kind> resource record is missing", because
40+
// the record is read from the bare-name directory, which holds none.
41+
// - recording fails on `finish` not being called for the addressed session, because
42+
// `finishSessionScreenRecording` re-reads the store by name and finishes the decoy stored
43+
// under `default` instead.
44+
const ADDRESS = 'cwd:0f803c4542a46e92:default';
45+
const NAME = 'default';
46+
const IOS_SIM: SessionState['device'] = {
47+
platform: 'apple',
48+
appleOs: 'ios',
49+
id: '9105AAA0-3184-40BC-A9FC-46634C90DFFB',
50+
name: 'iPhone 16',
51+
kind: 'simulator',
52+
booted: true,
53+
};
54+
55+
async function closeAtAddress(sessionStore: ReturnType<typeof makeSessionStore>) {
56+
return await handleSessionCommands({
57+
req: { token: 't', session: ADDRESS, command: 'close', positionals: [], flags: {} },
58+
sessionName: ADDRESS,
59+
logPath: path.join(mkdtempForTestSync('daemon'), 'daemon.log'),
60+
sessionStore,
61+
invoke: noopInvoke,
62+
});
63+
}
64+
65+
function expectCompleted<K extends string>(
66+
store: DurableCaptureResourceStore<K>,
67+
resourcePath: string,
68+
): void {
69+
const record = store.read(resourcePath);
70+
expect(record.status).toBe('decoded');
71+
if (record.status === 'decoded') expect(record.envelope.lifecycle).toBe('completed');
72+
}
73+
74+
test('close finishes the recording of a cwd-scoped session by store address', async () => {
75+
const sessionStore = makeSessionStore();
76+
const session = makeIosSimulatorRecordingSession(sessionStore, ADDRESS, { name: NAME });
77+
const finish = recordingFinishMock(session);
78+
sessionStore.set(ADDRESS, session);
79+
const resourcePath = screenRecordingResourceStore.resolvePath(
80+
sessionStore.resolveSessionDir(ADDRESS),
81+
);
82+
// `--session default` addresses a *different* session stored under the bare name. Give it
83+
// its own live recording so a `currentSession` lookup by `session.name` would finish the
84+
// wrong one instead of falling back to `session` and staying green.
85+
const decoy = makeIosSimulatorRecordingSession(sessionStore, NAME, {
86+
device: { ...IOS_SIM, id: 'decoy-udid', name: 'iPhone 15' },
87+
});
88+
const decoyFinish = recordingFinishMock(decoy);
89+
sessionStore.set(NAME, decoy);
90+
const decoyResourcePath = screenRecordingResourceStore.resolvePath(
91+
sessionStore.resolveSessionDir(NAME),
92+
);
93+
94+
const response = await closeAtAddress(sessionStore);
95+
96+
expect(response?.ok).toBe(true);
97+
expect(finish).toHaveBeenCalledOnce();
98+
expectCompleted(screenRecordingResourceStore, resourcePath);
99+
expect(sessionStore.get(ADDRESS)).toBeUndefined();
100+
// The decoy is untouched: not finished, record still open, session still stored.
101+
expect(decoyFinish).not.toHaveBeenCalled();
102+
const decoyRecord = screenRecordingResourceStore.read(decoyResourcePath);
103+
expect(decoyRecord.status).toBe('decoded');
104+
if (decoyRecord.status === 'decoded') expect(decoyRecord.envelope.lifecycle).toBe('open');
105+
expect(sessionStore.get(NAME)).toBeDefined();
106+
});
107+
108+
test('close stops the app log of a cwd-scoped session by store address', async () => {
109+
const sessionStore = makeSessionStore();
110+
const sessionDir = sessionStore.resolveSessionDir(ADDRESS);
111+
const outputPath = path.join(sessionDir, 'app.log');
112+
const forceCleanup = vi.fn(async () => ({ status: 'cleaned' }) as const);
113+
const handle: AppLogLiveHandle = {
114+
inspect: () => ({ backend: 'ios-simulator', state: 'active', startedAt: Date.now() - 1000 }),
115+
finish: async () => ({
116+
status: 'completed' as const,
117+
result: { backend: 'ios-simulator', outputPath, completedAt: Date.now() },
118+
}),
119+
forceCleanup,
120+
[Symbol.asyncDispose]: async () => {},
121+
};
122+
const envelope: DurableResourceEnvelope<'app-log'> = createDurableResourceEnvelope({
123+
resourceKind: 'app-log',
124+
sessionId: ADDRESS,
125+
device: {
126+
id: IOS_SIM.id,
127+
family: 'apple',
128+
appleOs: 'ios',
129+
kind: 'simulator',
130+
target: 'mobile',
131+
},
132+
owner: localRuntimeOwner('apple'),
133+
fence: { token: 'app-log-fence', generation: 1 },
134+
lifecycle: 'open',
135+
descriptor: {
136+
version: 1,
137+
body: {
138+
transport: 'apple-log-stream',
139+
backend: 'ios-simulator',
140+
outputPath,
141+
pidPath: path.join(sessionDir, 'app-log.pid'),
142+
},
143+
},
144+
metadata: { phase: 'active' },
145+
});
146+
sessionStore.set(ADDRESS, {
147+
...makeSession(NAME, IOS_SIM),
148+
appBundleId: 'com.apple.Preferences',
149+
appLog: { handle, envelope },
150+
});
151+
const resourcePath = appLogResourceStore.resolvePath(sessionDir);
152+
appLogResourceStore.write(resourcePath, envelope);
153+
154+
const response = await closeAtAddress(sessionStore);
155+
156+
expect(response?.ok).toBe(true);
157+
expect(forceCleanup).toHaveBeenCalledOnce();
158+
expectCompleted(appLogResourceStore, resourcePath);
159+
expect(sessionStore.get(ADDRESS)).toBeUndefined();
160+
});
161+
162+
test('close finishes the audio probe of a cwd-scoped session by store address', async () => {
163+
const sessionStore = makeSessionStore();
164+
const sessionDir = sessionStore.resolveSessionDir(ADDRESS);
165+
const statusPath = path.join(sessionDir, 'audio-probe.json');
166+
const startedAt = Date.now() - 2000;
167+
const stopped = {
168+
audio: 'probe' as const,
169+
state: 'stopped' as const,
170+
active: false,
171+
heard: false,
172+
source: 'system-audio' as const,
173+
backend: 'macos-screencapturekit',
174+
durationMs: 10000,
175+
elapsedMs: 2000,
176+
bucketMs: 1000,
177+
sampleCount: 2,
178+
sourceCount: 1,
179+
rmsDbfs: [] as number[],
180+
peakDbfs: [] as number[],
181+
};
182+
const finish = vi.fn(async () => ({ status: 'completed' as const, result: stopped }));
183+
const handle: AudioProbeLiveHandle = {
184+
inspect: () => ({
185+
source: 'system-audio' as const,
186+
backend: 'macos-screencapturekit',
187+
sourceCount: 1,
188+
notes: [],
189+
statusPath,
190+
startedAt,
191+
durationMs: 10000,
192+
bucketMs: 1000,
193+
}),
194+
status: async () => stopped,
195+
finish,
196+
forceCleanup: async () => ({ status: 'cleaned' }) as const,
197+
[Symbol.asyncDispose]: async () => {},
198+
};
199+
const envelope = createDurableResourceEnvelope({
200+
resourceKind: 'audio-probe',
201+
sessionId: ADDRESS,
202+
device: { id: IOS_SIM.id, family: 'apple', appleOs: 'ios', kind: 'simulator' },
203+
owner: localRuntimeOwner('apple'),
204+
fence: { token: 'audio-probe-fence', generation: 1 },
205+
lifecycle: 'open',
206+
descriptor: encodeDurableDescriptor(hostAudioProbeDescriptorCodec, {
207+
backend: 'macos-screencapturekit',
208+
source: 'system-audio',
209+
sourceCount: 1,
210+
notes: [],
211+
statusPath,
212+
startedAt,
213+
durationMs: 10000,
214+
bucketMs: 1000,
215+
marker: { pid: 4242, startTime: 'boot+1', command: 'helper' },
216+
}),
217+
});
218+
sessionStore.set(ADDRESS, { ...makeSession(NAME, IOS_SIM), audioProbe: { handle, envelope } });
219+
const resourcePath = audioProbeResourceStore.resolvePath(sessionDir);
220+
audioProbeResourceStore.write(resourcePath, envelope);
221+
222+
const response = await closeAtAddress(sessionStore);
223+
224+
expect(response?.ok).toBe(true);
225+
expect(finish).toHaveBeenCalledOnce();
226+
expectCompleted(audioProbeResourceStore, resourcePath);
227+
expect(sessionStore.get(ADDRESS)).toBeUndefined();
228+
});
229+
230+
test('close stops the perf capture of a cwd-scoped session by store address', async () => {
231+
const sessionStore = makeSessionStore();
232+
const sessionDir = sessionStore.resolveSessionDir(ADDRESS);
233+
const finish = vi.fn(async () => ({
234+
status: 'completed' as const,
235+
result: {
236+
kind: 'xctrace',
237+
mode: 'trace',
238+
state: 'stopped',
239+
outPath: path.join(sessionDir, 'app.trace'),
240+
} as const,
241+
}));
242+
const handle: PerfNativeCaptureLiveHandle = {
243+
inspect: () => ({ kind: 'xctrace', mode: 'trace', state: 'running' }),
244+
setOutputPath: vi.fn(),
245+
finish,
246+
forceCleanup: async () => ({ status: 'cleaned' }) as const,
247+
[Symbol.asyncDispose]: async () => {},
248+
};
249+
const envelope = createDurableResourceEnvelope({
250+
resourceKind: 'perf-capture',
251+
sessionId: ADDRESS,
252+
device: { id: IOS_SIM.id, family: 'apple', appleOs: 'ios', kind: 'simulator' },
253+
owner: localRuntimeOwner('apple'),
254+
fence: { token: 'perf-capture-fence', generation: 1 },
255+
lifecycle: 'open',
256+
descriptor: { version: 1, body: { kind: 'fixture' } },
257+
});
258+
sessionStore.set(ADDRESS, { ...makeSession(NAME, IOS_SIM), perfCapture: { handle, envelope } });
259+
const resourcePath = perfCaptureResourceStore.resolvePath(sessionDir);
260+
perfCaptureResourceStore.write(resourcePath, envelope);
261+
262+
const response = await closeAtAddress(sessionStore);
263+
264+
expect(response?.ok).toBe(true);
265+
expect(finish).toHaveBeenCalledOnce();
266+
expectCompleted(perfCaptureResourceStore, resourcePath);
267+
expect(sessionStore.get(ADDRESS)).toBeUndefined();
268+
});

‎src/daemon/session-lifecycle/internal/__tests__/session-close-shutdown.fixtures.ts‎

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -125,15 +125,22 @@ function makeSession(name: string, device: SessionState['device']): SessionState
125125
};
126126
}
127127

128+
/**
129+
* `address` is the store key the record lives under; `options.name` is the session's own name.
130+
* They differ for an implicitly cwd-scoped session (`default` under `cwd:<hash>:default`, see
131+
* `SessionRef`), and default to the same string otherwise.
132+
*/
128133
function makeIosSimulatorRecordingSession(
129134
sessionStore: SessionStore,
130-
name: string,
135+
address: string,
131136
options: {
137+
name?: string;
132138
recorderExitCode?: number;
133139
cleanupConfirmed?: boolean;
134140
device?: SessionState['device'];
135141
} = {},
136142
): SessionState {
143+
const name = options.name ?? address;
137144
const session = makeSession(
138145
name,
139146
options.device ?? {
@@ -195,7 +202,7 @@ function makeIosSimulatorRecordingSession(
195202
};
196203
const envelope = createDurableResourceEnvelope({
197204
resourceKind: 'screen-recording',
198-
sessionId: name,
205+
sessionId: address,
199206
device: { id: session.device.id, family: 'apple', appleOs: 'ios', kind: 'simulator' },
200207
owner: localRuntimeOwner('apple'),
201208
fence: { token: name + '-fence', generation: 1 },
@@ -208,7 +215,7 @@ function makeIosSimulatorRecordingSession(
208215
envelope,
209216
};
210217
screenRecordingResourceStore.write(
211-
screenRecordingResourceStore.resolvePath(sessionStore.resolveSessionDir(name)),
218+
screenRecordingResourceStore.resolvePath(sessionStore.resolveSessionDir(address)),
212219
envelope,
213220
);
214221
return session;

‎src/daemon/session-lifecycle/internal/session-close-lifecycle-teardown.ts‎

Lines changed: 13 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import type { CloseApplicationFinalizationResult } from '@agent-device/contracts/application-lifecycle-runtime';
22
import type { TargetShutdownResult } from '@agent-device/contracts/device';
33
import type { DaemonRequest } from '../../daemon-request.ts';
4-
import type { SessionState } from '../../session-state.ts';
4+
import type { SessionRef, SessionState } from '../../session-state.ts';
55
import { SessionStore } from '../../session-store.ts';
66
import { cleanupRetainedMaterializedPathsForSession } from '../../materialized-path-registry.ts';
77
import {
@@ -86,7 +86,7 @@ export async function runSessionCloseTeardown(params: {
8686
});
8787
const configuredRuntimeHints = sessionStore.getRuntimeHints(sessionName);
8888
await stopBestEffortSessionResources(
89-
session,
89+
{ address: sessionName, session },
9090
sessionStore,
9191
attemptCleanup,
9292
params.platformResourceCleanup,
@@ -129,30 +129,25 @@ export async function runSessionCloseTeardown(params: {
129129
type CleanupRunner = (step: string, run: () => Promise<void>) => Promise<void>;
130130

131131
async function stopBestEffortSessionResources(
132-
session: SessionState,
132+
ref: SessionRef,
133133
sessionStore: SessionStore,
134134
attemptCleanup: CleanupRunner,
135135
platformCleanup: PlatformResourceCleanup,
136136
): Promise<void> {
137-
// Recording overlay finalization needs the Apple runner.
138-
const currentSession = sessionStore.get(session.name) ?? session;
139-
if (currentSession.screenRecording) {
140-
await attemptCleanup('recording', () =>
141-
finishSessionScreenRecording({
142-
session: currentSession,
143-
sessionName: session.name,
144-
sessionStore,
145-
}),
146-
);
147-
}
148-
await attemptCleanup('app_log', () =>
149-
stopSessionAppLog({ session, sessionName: session.name, sessionStore }),
137+
const { address: sessionName, session } = ref;
138+
// Recording overlay finalization needs the Apple runner, so it runs first.
139+
// `finishSessionScreenRecording` re-reads the stored session by address and
140+
// returns when there is no recording; a second lookup here would only be a
141+
// place to mis-address it.
142+
await attemptCleanup('recording', () =>
143+
finishSessionScreenRecording({ session, sessionName, sessionStore }),
150144
);
145+
await attemptCleanup('app_log', () => stopSessionAppLog({ session, sessionName, sessionStore }));
151146
await attemptCleanup('audio_probe', () =>
152-
finishSessionAudioProbe({ session, sessionName: session.name, sessionStore }),
147+
finishSessionAudioProbe({ session, sessionName, sessionStore }),
153148
);
154149
await attemptCleanup('perf_capture', () =>
155-
stopSessionPerfCapture({ session, sessionName: session.name, sessionStore }),
150+
stopSessionPerfCapture({ session, sessionName, sessionStore }),
156151
);
157152
await attemptCleanup('platform_snapshot_helper', () =>
158153
stopSessionSnapshotHelper(session, platformCleanup),

0 commit comments

Comments
 (0)