Skip to content

Commit e180d9f

Browse files
committed
refactor: bind session references to stable lifetime entries
1 parent 64f40ac commit e180d9f

12 files changed

Lines changed: 243 additions & 57 deletions
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,13 @@
11
import path from 'node:path';
22
import { SessionStore } from '../../daemon/session-store.ts';
33
import { mkdtempForTestSync } from './tmp-dir.ts';
4+
import type { SessionRef, SessionState } from '../../daemon/session-state.ts';
45

56
export function makeSessionStore(prefix = 'agent-device-test-'): SessionStore {
67
const tempRoot = mkdtempForTestSync(prefix);
78
return new SessionStore(path.join(tempRoot, 'sessions'));
89
}
10+
11+
export function makeStoredSessionRef(session: SessionState, address = session.name): SessionRef {
12+
return makeSessionStore().publish(address, session);
13+
}

‎src/daemon/__tests__/request-lock-identity-policy.test.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import { makeStoredSessionRef } from '../../__tests__/test-utils/store-factory.ts';
12
import { test } from 'vitest';
23
import assert from 'node:assert/strict';
34
import { AppError } from '@agent-device/kernel/errors';
@@ -175,7 +176,7 @@ const ROWS: Row[] = [
175176

176177
/** Every row's session is explicitly named, so it is stored under — and addressed by — its name. */
177178
function ref(session: SessionState | undefined): SessionRef | undefined {
178-
return session ? { address: session.name, session } : undefined;
179+
return session ? makeStoredSessionRef(session) : undefined;
179180
}
180181

181182
for (const row of ROWS) {

‎src/daemon/__tests__/request-lock-policy.test.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import { makeStoredSessionRef } from '../../__tests__/test-utils/store-factory.ts';
12
import { test } from 'vitest';
23
import assert from 'node:assert/strict';
34
import { applyRequestLockPolicy } from '../request-lock-policy.ts';
@@ -34,7 +35,7 @@ const ANDROID_SESSION: SessionState = {
3435

3536
/** Both fixtures are explicitly named, so each is stored under — and addressed by — its name. */
3637
function ref(session: SessionState): SessionRef {
37-
return { address: session.name, session };
38+
return makeStoredSessionRef(session);
3839
}
3940

4041
test('allows compatible fresh-session selectors under request lock policy', () => {

‎src/daemon/__tests__/session-selector.test.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import { makeStoredSessionRef } from '../../__tests__/test-utils/store-factory.ts';
12
import { test } from 'vitest';
23
import assert from 'node:assert/strict';
34
import { assertSessionSelectorMatches } from '../session-selector.ts';
@@ -23,7 +24,7 @@ function makeSession(overrides?: Partial<SessionState>): SessionState {
2324

2425
/** These sessions are explicitly named, so each is stored under — and addressed by — its name. */
2526
function ref(session: SessionState): SessionRef {
26-
return { address: session.name, session };
27+
return makeStoredSessionRef(session);
2728
}
2829

2930
test('accepts matching platform and serial selectors', () => {
Lines changed: 118 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,118 @@
1+
import assert from 'node:assert/strict';
2+
import { test } from 'vitest';
3+
import { AppError } from '@agent-device/kernel/errors';
4+
import { makeSession } from '../../__tests__/test-utils/session-factories.ts';
5+
import { makeSessionStore } from '../../__tests__/test-utils/store-factory.ts';
6+
7+
const ADDRESS = 'cwd:worktree:default';
8+
9+
function ended(error: unknown): boolean {
10+
return error instanceof AppError && error.details?.reason === 'session_lifetime_ended';
11+
}
12+
13+
test('refs capture records while resolving rebuilds from the same lifetime', () => {
14+
const store = makeSessionStore();
15+
const session = makeSession('default');
16+
const initial = store.publish(ADDRESS, session);
17+
const lookup = store.lookup(ADDRESS)!;
18+
const listed = store.listRefs()[0]!;
19+
const byDevice = store.findByDevice(session.device.id)!;
20+
for (const ref of [lookup, listed, byDevice]) {
21+
assert.notEqual(ref, initial);
22+
assert.equal(ref.lifetime, initial.lifetime);
23+
assert.equal(ref.session, session);
24+
assert.equal(Object.isFrozen(ref), true);
25+
}
26+
const rebuilt = store.update(initial, { appName: 'Reopened' });
27+
assert.equal(initial.session, session);
28+
assert.equal(initial.session.appName, undefined);
29+
for (const ref of [initial, lookup, listed, byDevice]) {
30+
assert.equal(store.resolveCurrent(ref), rebuilt);
31+
}
32+
assert.equal(store.lookup(ADDRESS)?.session, rebuilt);
33+
assert.equal(store.get('default'), undefined);
34+
});
35+
36+
test('updates derive from the latest matching record and preserve intervening fields', () => {
37+
const store = makeSessionStore();
38+
const ref = store.publish(ADDRESS, makeSession('default', { createdAt: 10 }));
39+
store.update(ref, { appBundleId: 'com.example.updated' });
40+
store.update(ref, (current) => ({
41+
appName: current.appBundleId,
42+
createdAt: current.createdAt + 1,
43+
}));
44+
assert.equal(store.get(ADDRESS)?.appBundleId, 'com.example.updated');
45+
assert.equal(store.get(ADDRESS)?.appName, 'com.example.updated');
46+
assert.equal(store.get(ADDRESS)?.createdAt, 11);
47+
assert.equal(store.get(ADDRESS)?.actions, ref.session.actions);
48+
});
49+
50+
test('address reuse with the same record still starts a different lifetime', () => {
51+
const store = makeSessionStore();
52+
const session = makeSession('default');
53+
const old = store.publish(ADDRESS, session);
54+
assert.equal(store.retire(old), true);
55+
const successor = store.publish(ADDRESS, session);
56+
store.setRuntimeHints(ADDRESS, { metroPort: 8082 });
57+
assert.notEqual(successor.lifetime, old.lifetime);
58+
assert.equal(store.resolveCurrent(old), undefined);
59+
assert.throws(() => store.requireCurrent(old), ended);
60+
assert.throws(() => store.update(old, { appName: 'Stale' }), ended);
61+
assert.equal(store.retire(old), false);
62+
assert.equal(store.get(ADDRESS), session);
63+
assert.equal(store.getRuntimeHints(ADDRESS)?.metroPort, 8082);
64+
assert.equal(store.retire(successor), true);
65+
assert.equal(store.getRuntimeHints(ADDRESS), undefined);
66+
});
67+
68+
test('retired updates cannot run their derivation or resurrect a record', () => {
69+
const store = makeSessionStore();
70+
const ref = store.publish(ADDRESS, makeSession('default'));
71+
store.retire(ref);
72+
let ran = false;
73+
assert.throws(
74+
() =>
75+
store.update(ref, () => {
76+
ran = true;
77+
return { appName: 'Late' };
78+
}),
79+
ended,
80+
);
81+
assert.equal(ran, false);
82+
assert.equal(store.lookup(ADDRESS), undefined);
83+
});
84+
85+
test('an occupied address cannot be published again', () => {
86+
const store = makeSessionStore();
87+
const ref = store.publish(ADDRESS, makeSession('default'));
88+
assert.throws(
89+
() => store.publish(ADDRESS, makeSession('default')),
90+
(error) => error instanceof AppError && error.details?.reason === 'session_address_occupied',
91+
);
92+
assert.equal(store.requireCurrent(ref), ref.session);
93+
});
94+
95+
test('shutdown closes draft admission while allowing the current lifetime to settle', () => {
96+
const store = makeSessionStore();
97+
const ref = store.publish(ADDRESS, makeSession('default'));
98+
store.closeAdmission();
99+
assert.throws(
100+
() => store.publish('late-draft', makeSession('late-draft')),
101+
(error) => error instanceof AppError && error.details?.reason === 'daemon_shutting_down',
102+
);
103+
store.update(ref, { appName: 'Settled' });
104+
assert.equal(store.requireCurrent(ref).appName, 'Settled');
105+
assert.equal(store.retire(ref), true);
106+
assert.equal(store.lookup('late-draft'), undefined);
107+
});
108+
109+
test('a ref from another store has no authority over the same address', () => {
110+
const source = makeSessionStore();
111+
const target = makeSessionStore();
112+
const foreign = source.publish(ADDRESS, makeSession('default'));
113+
const local = target.publish(ADDRESS, foreign.session);
114+
assert.equal(target.resolveCurrent(foreign), undefined);
115+
assert.throws(() => target.update(foreign, { appName: 'Foreign' }), ended);
116+
assert.equal(target.retire(foreign), false);
117+
assert.equal(target.requireCurrent(local), foreign.session);
118+
});

‎src/daemon/server/daemon-runtime.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -748,6 +748,7 @@ export async function startDaemonRuntime(
748748
sessionIdleExpiry.cancel();
749749
if (shuttingDown) return;
750750
shuttingDown = true;
751+
sessionStore.closeAdmission();
751752
stopMetadataLossWatch();
752753
if (shutdownOptions.cause) {
753754
await emitFatalDiagnostic(shutdownOptions.cause);

‎src/daemon/session-lifecycle/internal/__tests__/session-open-device-in-use.test.ts‎

Lines changed: 9 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import { makeStoredSessionRef } from '../../../../__tests__/test-utils/store-factory.ts';
12
import { test, expect } from 'vitest';
23
import {
34
buildDeviceInUseBySessionError,
@@ -13,16 +14,16 @@ import { IOS_SIMULATOR } from '../../../../__tests__/test-utils/device-fixtures.
1314

1415
const SCOPED_ADDRESS = 'cwd:8bea844ab16aa9b3:default';
1516

16-
const scopedRef: SessionRef = {
17-
address: SCOPED_ADDRESS,
18-
session: {
17+
const scopedRef: SessionRef = makeStoredSessionRef(
18+
{
1919
name: 'default',
2020
sessionScope: { kind: 'cwd', id: '8bea844ab16aa9b3' },
2121
device: IOS_SIMULATOR,
2222
createdAt: 0,
2323
actions: [],
2424
},
25-
};
25+
SCOPED_ADDRESS,
26+
);
2627

2728
test('the by-session conflict reports the address, in the message, details and hint', () => {
2829
const response = buildDeviceInUseBySessionError(scopedRef, IOS_SIMULATOR);
@@ -41,16 +42,16 @@ test('the by-session conflict reports the address, in the message, details and h
4142
// --session, nor close.
4243
test('the foreign-workspace conflict names the owning session address', () => {
4344
const foreignAddress = 'cwd:1d9b7c2f4a6e8b03:default';
44-
const foreignRef: SessionRef = {
45-
address: foreignAddress,
46-
session: {
45+
const foreignRef: SessionRef = makeStoredSessionRef(
46+
{
4747
name: 'default',
4848
sessionScope: { kind: 'cwd', id: '1d9b7c2f4a6e8b03' },
4949
device: IOS_SIMULATOR,
5050
createdAt: 0,
5151
actions: [],
5252
},
53-
};
53+
foreignAddress,
54+
);
5455

5556
const response = buildForeignWorkspaceSessionConflict(foreignRef, IOS_SIMULATOR);
5657

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

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -37,8 +37,7 @@ export type SessionCloseTeardownResult = Readonly<{
3737
/** Runs owned resources, native close, native hint cleanup, and final lifecycle disposal. */
3838
export async function runSessionCloseTeardown(params: {
3939
req: DaemonRequest;
40-
session: SessionState;
41-
sessionName: string;
40+
ref: SessionRef;
4241
logPath: string;
4342
sessionStore: SessionStore;
4443
lifecycle: CloseRuntime | CloseRuntimeWithRuntimeHintClear;
@@ -56,8 +55,7 @@ export async function runSessionCloseTeardown(params: {
5655
}): Promise<SessionCloseTeardownResult> {
5756
const {
5857
req,
59-
session,
60-
sessionName,
58+
ref,
6159
logPath,
6260
sessionStore,
6361
lifecycle,
@@ -67,6 +65,8 @@ export async function runSessionCloseTeardown(params: {
6765
dispatchTargetedPlatformClose,
6866
finalizeOrdinaryCloseScript,
6967
} = params;
68+
const { address: sessionName } = ref;
69+
const session = sessionStore.requireCurrent(ref);
7070
const attemptCleanup = async <Result>(
7171
step: string,
7272
run: () => Promise<Result>,
@@ -86,7 +86,7 @@ export async function runSessionCloseTeardown(params: {
8686
});
8787
const configuredRuntimeHints = sessionStore.getRuntimeHints(sessionName);
8888
await stopBestEffortSessionResources(
89-
{ address: sessionName, session },
89+
ref,
9090
sessionStore,
9191
attemptCleanup,
9292
params.platformResourceCleanup,

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

Lines changed: 9 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ import { emitDiagnostic } from '@agent-device/host-kit/diagnostics';
22
import { AppError, normalizeError } from '@agent-device/kernel/errors';
33
import type { LeaseLifecycleProvider, TargetShutdownResult } from '@agent-device/contracts/device';
44
import type { DaemonRequest, DaemonResponse } from '../../daemon-request.ts';
5-
import type { SessionState } from '../../session-state.ts';
5+
import type { SessionRef, SessionState } from '../../session-state.ts';
66
import { SessionStore } from '../../session-store.ts';
77
import { successText, withSuccessText } from '@agent-device/kernel/success-text';
88
import { resolveCommandDevice } from '../../session-device-resolution.ts';
@@ -193,15 +193,16 @@ export async function handleSessionCloseCommands(
193193
params: SessionCloseCommandInput,
194194
): Promise<DaemonResponse> {
195195
const { req, sessionName, logPath, sessionStore, leaseRegistry, leaseLifecycleProvider } = params;
196-
const session = sessionStore.get(sessionName);
197-
if (!session) {
196+
const ref = sessionStore.lookup(sessionName);
197+
if (!ref) {
198198
return await closeWithoutSession({
199199
req,
200200
logPath,
201201
inspectFacts: params.inspectFacts,
202202
bindDevice: params.bindDevice,
203203
});
204204
}
205+
const session = ref.session;
205206
assertTerminalRecordingCloseAllowed(req, session);
206207
const app = req.positionals?.[0];
207208
if (req.internal?.closeAppOnly === true && !app) {
@@ -246,8 +247,7 @@ export async function handleSessionCloseCommands(
246247
if ('response' in repair) return repair.response;
247248
const closed = await runCloseTeardownAndRelease({
248249
req,
249-
session,
250-
sessionName,
250+
ref,
251251
logPath,
252252
sessionStore,
253253
leaseRegistry,
@@ -281,8 +281,7 @@ type SessionCloseFinalization =
281281
// lease release keeps the session retryable instead (`{kind:'response'}`).
282282
async function runCloseTeardownAndRelease(params: {
283283
req: DaemonRequest;
284-
session: SessionState;
285-
sessionName: string;
284+
ref: SessionRef;
286285
logPath: string;
287286
sessionStore: SessionStore;
288287
leaseRegistry: LeaseRegistry;
@@ -294,20 +293,19 @@ async function runCloseTeardownAndRelease(params: {
294293
}): Promise<SessionCloseFinalization> {
295294
const {
296295
req,
297-
session,
298-
sessionName,
296+
ref,
299297
logPath,
300298
sessionStore,
301299
leaseRegistry,
302300
leaseLifecycleProvider,
303301
lifecycle,
304302
clearRuntimeHints,
305303
} = params;
304+
const { address: sessionName, session } = ref;
306305
const cleanupFailures: SessionCleanupFailure[] = [];
307306
const { platformCloseError, saveScriptError, shutdownResult } = await runSessionCloseTeardown({
308307
req,
309-
session,
310-
sessionName,
308+
ref,
311309
logPath,
312310
sessionStore,
313311
lifecycle,

‎src/daemon/session-recovery-hints.test.ts‎

Lines changed: 7 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import { makeStoredSessionRef } from '../__tests__/test-utils/store-factory.ts';
12
import { test, expect } from 'vitest';
23
import { buildSessionRecoveryHint } from './session-recovery-hints.ts';
34
import type { SessionRef, SessionState } from './session-state.ts';
@@ -12,17 +13,17 @@ import { IOS_SIMULATOR } from '../__tests__/test-utils/device-fixtures.ts';
1213
const SCOPED_ADDRESS = 'cwd:8bea844ab16aa9b3:default';
1314

1415
function scopedRef(overrides: Partial<SessionState> = {}): SessionRef {
15-
return {
16-
address: SCOPED_ADDRESS,
17-
session: {
16+
return makeStoredSessionRef(
17+
{
1818
name: 'default',
1919
sessionScope: { kind: 'cwd', id: '8bea844ab16aa9b3' },
2020
device: IOS_SIMULATOR,
2121
createdAt: Date.now(),
2222
actions: [],
2323
...overrides,
2424
},
25-
};
25+
SCOPED_ADDRESS,
26+
);
2627
}
2728

2829
test('device-in-use recovery names the address --session accepts, not the public name', () => {
@@ -55,10 +56,7 @@ test('a recording session recovery uses the address for both close and record st
5556

5657
test('an explicitly named session addresses itself unchanged', () => {
5758
const hint = buildSessionRecoveryHint(
58-
{
59-
address: 'checkout',
60-
session: { ...scopedRef().session, name: 'checkout', sessionScope: undefined },
61-
},
59+
makeStoredSessionRef({ ...scopedRef().session, name: 'checkout', sessionScope: undefined }),
6260
'device-in-use',
6361
);
6462

@@ -81,10 +79,7 @@ test('a device or target conflict does not offer a platform session it cannot an
8179

8280
test('selector-conflict recovery offers no platform session to a hand-named session', () => {
8381
const hint = buildSessionRecoveryHint(
84-
{
85-
address: 'checkout',
86-
session: { ...scopedRef().session, name: 'checkout', sessionScope: undefined },
87-
},
82+
makeStoredSessionRef({ ...scopedRef().session, name: 'checkout', sessionScope: undefined }),
8883
'selector-conflict',
8984
);
9085

0 commit comments

Comments
 (0)