Skip to content
Merged
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
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import type { DaemonRequest } from '../../core/daemon-request.ts';
import type { SessionStore } from '../../core/session-store.ts';
import { SessionCoordinator } from '../../core/session-store.ts';
import type { FindSessionAuthority } from '../../core/interaction/internal/types.ts';

/**
* The session authority the dispatcher hands a `find` route for its admitted lifetime, built from the
* store a test published into. A test that calls the find route directly uses this rather than a
* hand-rolled stand-in, so it exercises the same lifetime-bound operations the dispatcher constructs.
* Returns `undefined` for an address with no session, which is what the route sees for one.
*/
export function bindFindSessionForTest(params: {
sessionStore: SessionStore;
sessionName: string;
req: DaemonRequest;
}): FindSessionAuthority | undefined {
const { sessionStore, sessionName, req } = params;
const ref = sessionStore.lookup(sessionName);
if (!ref) return undefined;
return {
captureRef: ref,
mutations: new SessionCoordinator(sessionStore).mutate(req, ref, () => true),
};
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,117 @@
import assert from 'node:assert/strict';
import { test } from 'vitest';
import { clearRequestCanceled, markRequestCanceled } from '@agent-device/host-kit/request';
import { AppError } from '@agent-device/kernel/errors';
import type { DeviceInfo } from '@agent-device/kernel/device';
import type { DaemonRequest } from '../daemon-request.ts';
import { SessionCoordinator } from '../session-store.ts';
import { activateCompleteRefFrame, refFrameState } from '../ref-frame.ts';
import { makeSession } from '../../__tests__/support/session-factories.ts';
import { makeSessionStore } from '../../__tests__/support/store-factory.ts';

const device: DeviceInfo = {
platform: 'android',
id: 'emulator-5554',
name: 'Android',
kind: 'emulator',
};

function request(requestId: string): DaemonRequest {
return {
token: 't',
session: 'agent',
command: 'find',
positionals: ['Save', 'focus'],
flags: {},
meta: { requestId },
};
}

function admittedMutation(requestId: string) {
const store = makeSessionStore();
const coordinator = new SessionCoordinator(store);
const session = makeSession('agent', { device });
const ref = store.publish('agent', session);
const mutations = coordinator.mutate(request(requestId), ref, () => true);
return { store, ref, mutations };
}

test.each(['cancellation', 'replacement'])(
'a revoked mutation authority refuses new work on %s',
(reason) => {
const requestId = `mutation-${reason}`;
const { store, ref, mutations } = admittedMutation(requestId);
const successor = makeSession('agent', { device, appBundleId: 'com.example.successor' });

try {
if (reason === 'cancellation') markRequestCanceled(requestId);
if (reason === 'replacement') {
store.retire(ref);
store.publish('agent', successor);
}

// Observing the successor is refused, and the refusal names the revoked authority's own
// situation rather than the session that now occupies the address.
assert.throws(
() => mutations.requireTargetContext(),
(error) =>
error instanceof AppError &&
error.details?.reason ===
(reason === 'cancellation' ? 'request_canceled' : 'session_lifetime_ended'),
);
// Crossing the side-effect seam is refused rather than silently skipped: a caller must not
// read a no-op on a dead lifetime as its own expiry.
assert.throws(() => mutations.expireRefFrame());
// A completed effect belongs to the admitted lifetime even when the request was canceled.
mutations.recordAction({ command: 'find', positionals: ['Save', 'focus'], flags: {} });
if (reason === 'cancellation') {
assert.deepEqual(
store.requireCurrent(ref).actions.map(({ command }) => command),
['find'],
);
} else {
assert.deepEqual(successor.actions, []);
}
} finally {
clearRequestCanceled(requestId);
}
},
);

test('a stale authority cannot expire the ref frame of the session that replaced its own', () => {
const requestId = 'mutation-stale-frame';
const { store, ref, mutations } = admittedMutation(requestId);

// Close and reopen the same address: the successor has its own active frame to lose.
store.retire(ref);
const successor = makeSession('agent', { device });
store.publish('agent', successor);
activateCompleteRefFrame(successor);

// The stale capability answers with its own ended lifetime and leaves the successor's frame active:
// expiring through an unresolved address is exactly the cross-lifetime damage the seam forbids.
assert.throws(
() => mutations.expireRefFrame(),
(error) => error instanceof AppError,
);
assert.equal(refFrameState(successor), 'active');
});

test('a mutation authority answers with the current facts of the lifetime it was given', () => {
const requestId = 'mutation-live-facts';
const { store, ref, mutations } = admittedMutation(requestId);

// The request's own `open` narrowed the admitted lifetime to an app after admission, so the read
// has to follow that lifetime: this is why find builds its runtime context at dispatch time.
const session = store.requireCurrent(ref);
session.appBundleId = 'com.example.admitted';
assert.equal(mutations.requireTargetContext().appBundleId, 'com.example.admitted');

// Once that lifetime ends, the authority reports its own end rather than the successor's app scope.
store.retire(ref);
store.publish('agent', makeSession('agent', { device, appBundleId: 'com.example.successor' }));
assert.throws(
() => mutations.requireTargetContext(),
(error) => error instanceof AppError && error.details?.reason === 'session_lifetime_ended',
);
});
24 changes: 23 additions & 1 deletion packages/daemon/src/core/interaction/internal/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ import type { BoundGestureExecutor } from '../../gesture-runtime.ts';
import type { BoundTouchExecutor } from '../../touch-runtime.ts';
import type { BoundSnapshotCapture } from '../../snapshot-runtime-binding.ts';
import type { recordTouchVisualizationEvent } from '../../recording-gestures.ts';
import type { SessionStore } from '../../session-store.ts';
import type { AuthorizedMutation, SessionStore } from '../../session-store.ts';
import type {
BindDeviceRuntime,
InspectDeviceRuntimeFacts,
Expand Down Expand Up @@ -62,12 +62,34 @@ export type SettleObservationCaptureInput = {
settleObservationCapture?: BoundSnapshotCapture;
};

/**
* The session authority the dispatcher hands the `find` route, for the one lifetime it admitted.
*/
export type FindSessionAuthority = Readonly<{
/** Lifetime-bound session effects: target-context read, ADR 0014 ref-frame expiry, recording. */
mutations: AuthorizedMutation;
/**
* Retained adapter (#5064 remaining debt): find's own target capture writes its observation
* through the store's snapshot choke point, which is a store-private write no command may hold as
* an operation yet. So that one leg gets the dispatcher's admitted ref instead of resolving the
* address again, and no action branch reads it.
*/
captureRef: SessionRef;
}>;

export type FindRouteInput = {
createCommandSurface: CreateDaemonCommandSurface;
req: DaemonRequest;
sessionName: string;
logPath: string;
/**
* Retained adapter (#5064 remaining debt): the read-only selector-runtime path (`exists`/`wait`/
* `list`/`get text`/`get attrs`) still resolves its session by address. The mutating actions use
* `findSession` and reach no store at all.
*/
sessionStore: SessionStore;
/** The admitted session's authority; absent when the address has no session. */
findSession?: FindSessionAuthority;
invoke: DaemonInvokeFn;
inspectFacts?: InspectDeviceRuntimeFacts;
platformServices: DaemonPlatformServices;
Expand Down
69 changes: 69 additions & 0 deletions packages/daemon/src/core/session-store.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ import type {
SessionState,
} from './session-state.ts';
import { recordActionEntry, type RecordActionEntry } from './session-action-recorder.ts';
import { expireRefFrame } from './ref-frame.ts';
import { isSafeSessionSegment, safeSessionName } from '@agent-device/host-kit/session-paths';
import {
readRepairTombstoneFile,
Expand Down Expand Up @@ -674,6 +675,7 @@ function removeEmptySessionDirectory(directory: string): void {

const sessionAuthority: unique symbol = Symbol();
const openAuthority: unique symbol = Symbol();
const mutationAuthority: unique symbol = Symbol();

export type AuthorizedSession = Readonly<{
[sessionAuthority]: true;
Expand All @@ -695,6 +697,37 @@ export type WithSessionExecutionLock = <T>(
signal?: AbortSignal,
) => Promise<T>;

/**
* What a command may learn about the session it acts on: the neutral facts its guards, runtime
* inputs and refusal wording need. The mutable session record stays behind this projection, so a
* converted caller can neither read nor write a session field it did not declare.
*/
export type SessionTargetContext = Readonly<{
/** Public session name, for refusal wording only. */
name: string;
device: DeviceInfo;
appBundleId?: string;
traceLogPath?: string;
}>;

/**
* The session effects of one admitted lifetime, handed to a mutating command by the dispatcher: the
* target context it reads before it acts, the ADR 0014 ref-frame expiry at its device side-effect
* seam, and its recorded action. They are constructed behind a private brand, so a route the
* dispatcher did not admit holds none of them, and every operation re-checks its own lifetime when
* used. An operation of an ended lifetime resolves only that lifetime and never the address again, so
* a stale capability can neither observe nor change a replacement session.
*/
export type AuthorizedMutation = Readonly<{
[mutationAuthority]: true;
/** The admitted facts, refusing with the ended lifetime's own typed reason. */
requireTargetContext(): SessionTargetContext;
/** Expires the admitted lifetime's ref frame, refusing with that lifetime's own typed reason. */
expireRefFrame(): void;
/** Records the action against the admitted lifetime; a no-op once that lifetime has ended. */
recordAction(entry: RecordActionEntry): void;
}>;

export class SessionCoordinator {
readonly #store: SessionStore;

Expand All @@ -714,6 +747,42 @@ export class SessionCoordinator {
return this.bind(ref, () => active() && !isRequestCanceled(req.meta?.requestId));
}

/**
* Hands the admitted request the session effects a mutating command owns: the target context it
* reads, the ref-frame expiry at its side-effect seam, and its recorded action. The brand is
* constructed here only, so nothing outside the dispatcher can forge one, and every operation
* checks the admitted lifetime again when used. An ended lifetime refuses with its own typed
* reason and never resolves the address again, so a stale capability cannot reach a successor.
*/
mutate(req: DaemonRequest, ref: SessionRef, active: () => boolean): AuthorizedMutation {
const session = this.#store.requireCurrent(ref);
assertRequestHoldsSessionLease(req, session);
const admitted = () => active() && !isRequestCanceled(req.meta?.requestId);
return {
[mutationAuthority]: true,
requireTargetContext: () => {
// Revocation is checked before the read, and the store owns the refusal: an ended lifetime
// reports its own typed reason, exactly as the direct read this operation replaced did.
if (!admitted()) throw createRequestCanceledError();
const current = this.#store.requireCurrent(ref);
return Object.freeze({
name: current.name,
device: current.device,
...(current.appBundleId === undefined ? {} : { appBundleId: current.appBundleId }),
...(current.trace?.outPath === undefined ? {} : { traceLogPath: current.trace.outPath }),
});
},
expireRefFrame: () => {
if (!admitted()) throw createRequestCanceledError();
expireRefFrame(this.#store.requireCurrent(ref));
},
recordAction: (entry) => {
if (!this.#store.resolveCurrent(ref)) return;
this.#store.recordAction(ref, entry);
},
};
}

observeDevice(
req: DaemonRequest,
device: DeviceInfo,
Expand Down
6 changes: 4 additions & 2 deletions packages/daemon/src/core/snapshot-runtime-binding.ts
Original file line number Diff line number Diff line change
Expand Up @@ -120,12 +120,14 @@ export type AdmittedSnapshotCapture =
* side-effect-free facts inspection, refusal before any binding, then exactly one bind on
* the admitted device. `snapshot`/`diff` supply the four-way custom-actions plan and the
* selector family the active-app plan; a new consumer supplies a plan and a command name.
* The session is named, not carried: this path binds a device, and the name is all its refusal
* wording needs.
*/
export async function admitAndBindSnapshotCapture(
params: Readonly<{
command: string;
device: SessionState['device'];
session: SessionState | undefined;
session: Readonly<{ name: string }> | undefined;
plan: SnapshotRuntimePlan | SelectorCaptureRuntimePlan;
inspectFacts?: InspectDeviceRuntimeFacts;
platformServices: DaemonPlatformServices;
Expand Down Expand Up @@ -490,7 +492,7 @@ function selectSnapshotWithoutActiveApp(
type SnapshotPlanUnavailableParams = {
operation: (SnapshotRuntimePlan | SelectorCaptureRuntimePlan)['use']['required'][number];
fact: RuntimeOperationFact;
session: SessionState | undefined;
session: Readonly<{ name: string }> | undefined;
device: SessionState['device'];
command: string;
platformServices: DaemonPlatformServices;
Expand Down
Loading
Loading