Skip to content

Commit 31005a2

Browse files
committed
fix(batch): stamp the step session flag only when the caller named one (#3674)
The batch runner stamped flags.session on every step so nested invokes route to the parent's resolved address. The wire `session` field already does that; the flag is a provenance carrier, and the new named-session refusal reads it. An unconditional stamp therefore made a sessionless batch look caller-addressed and met SESSION_NOT_FOUND at the daemon — an error no caller of the batch surface asked for, with advice ("omit --session") the surface does not even offer. The stamp now follows the same traced provenance as every other carrier: meta.sessionExplicit or a caller-set step flag. Also from the same review: the named-session disclosure row's driver now pins the producer's own code and typed reason, so a reverted guard cannot satisfy it with the device-selection error it replaced; commands.md states which pre-dispatch refusals answer session_or_device_selector_required even for a named-but-unheld session.
1 parent ddd1817 commit 31005a2

6 files changed

Lines changed: 64 additions & 6 deletions

File tree

‎packages/command-registry/src/__tests__/batch.test.ts‎

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -58,6 +58,47 @@ function batchRequest(commands: string[], responseLevel?: ResponseLevel): BatchR
5858
};
5959
}
6060

61+
// #3674: the daemon refuses a request that names a session it does not hold. A batch step is
62+
// addressed through `session:`, so only a caller who named a session may see one in `flags`:
63+
// stamping every step would hand that refusal to sessionless batches, whose steps are meant to
64+
// resolve their device from the session or the selectors.
65+
test('sessionless batch steps carry no session flag, so they stay sessionless at the daemon', async () => {
66+
const seen: Array<Record<string, unknown> | undefined> = [];
67+
const request: BatchRequest = {
68+
token: 't',
69+
command: 'batch',
70+
positionals: [],
71+
flags: { batchSteps: [{ command: 'snapshot' }] },
72+
};
73+
const response = await runBatch(request, 'cwd:1a2b3c4d5e6f7a8b:default', async (req) => {
74+
seen.push(req.flags as Record<string, unknown> | undefined);
75+
return { ok: true, data: {} };
76+
});
77+
78+
assert.equal(response.ok, true);
79+
assert.equal(seen[0]?.session, undefined);
80+
});
81+
82+
test('a batch whose caller named a session stamps that address onto every step', async () => {
83+
const seen: Array<Record<string, unknown> | undefined> = [];
84+
const request: BatchRequest = {
85+
token: 't',
86+
command: 'batch',
87+
positionals: [],
88+
session: 'e2e-ios-0',
89+
meta: { sessionExplicit: true },
90+
flags: { batchSteps: [{ command: 'snapshot' }, { command: 'get' }] },
91+
};
92+
const response = await runBatch(request, 'e2e-ios-0', async (req) => {
93+
seen.push(req.flags as Record<string, unknown> | undefined);
94+
return { ok: true, data: {} };
95+
});
96+
97+
assert.equal(response.ok, true);
98+
assert.equal(seen[0]?.session, 'e2e-ios-0');
99+
assert.equal(seen[1]?.session, 'e2e-ios-0');
100+
});
101+
61102
// #2997: `testIme` joined INHERITED_PARENT_FLAG_KEYS for the flow command's session
62103
// opens; batch shares that list, so its steps inherit the parent's opt-in the same way.
63104
// Pinning it here keeps the shared-list addition deliberate for both consumers.

‎packages/command-registry/src/batch.ts‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ import {
66
type DaemonResponse,
77
type ResponseLevel,
88
isNonDefaultResponseLevel,
9+
namesSessionExplicitly,
910
} from '@agent-device/kernel/contracts';
1011
import { AppError, asAppError, type DaemonError } from '@agent-device/kernel/errors';
1112
import { isRecord } from '@agent-device/kernel/record';
@@ -320,7 +321,11 @@ async function runBatchStep(
320321
const isFinalStep = stepNumber === totalSteps;
321322
const stepStartedAt = Date.now();
322323
const stepFlags = buildBatchStepFlags(req.flags, step.flags);
323-
if (stepFlags.session === undefined) {
324+
// The step is already addressed through `session:` below. Stamp the flag only when the caller
325+
// genuinely named a session: an unconditional stamp would make a sessionless batch look
326+
// caller-addressed to the daemon's named-session refusal, which no caller of this surface asked
327+
// for (#3674). A step's own recorded flag always wins, explicit parent or not.
328+
if (stepFlags.session === undefined && namesSessionExplicitly(req)) {
324329
stepFlags.session = sessionName;
325330
}
326331
const response = await invoke(

‎packages/daemon/src/execution/request-dispatch-disclosure.test.ts‎

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,7 @@ vi.mock('../core/device/device-ready.ts', () => ({
3434
ensureDeviceReady: vi.fn(async () => {}),
3535
}));
3636

37-
import { AppError } from '@agent-device/kernel/errors';
37+
import { AppError, PRE_DISPATCH_REFUSAL_REASONS } from '@agent-device/kernel/errors';
3838
import { resolveCommandRecordingEffect } from '@agent-device/command-registry/registry';
3939
import type { AndroidObservationAdapter } from '@agent-device/contracts/android-observation';
4040
import type { DeviceRuntimeGateway, RuntimeFacts } from '@agent-device/contracts/platform-runtime';
@@ -276,14 +276,22 @@ async function sessionOrSelectorRefusedBeforeRouting(): Promise<unknown> {
276276
/**
277277
* The store holds `SESSION` and the request names another address, which is what a run against a
278278
* replaced daemon looks like. The row is about the refusal ordering: `snapshot` would otherwise
279-
* have chosen a device from the host inventory and answered with that.
279+
* have chosen a device from the host inventory and answered with that. `snapshot` declares an
280+
* `observes-app` effect, so the seam stamps `dispatched: no` on any refusal — the driver has to
281+
* pin the producer's own code and reason, or a reverted guard would satisfy the row with the
282+
* device-selection error it replaced.
280283
*/
281284
async function namedSessionRefusedBeforeDeviceSelection(): Promise<unknown> {
282285
const failure = await route(makeSession(SESSION), {
283286
command: 'snapshot',
284287
positionals: [],
285288
session: 'session-never-opened',
286289
meta: { requestId: 'named-session-refusal', sessionExplicit: true },
290+
}).catch((error: unknown) => {
291+
assert.ok(error instanceof AppError);
292+
assert.equal(error.code, 'SESSION_NOT_FOUND');
293+
assert.equal(error.details?.reason, PRE_DISPATCH_REFUSAL_REASONS.namedSessionNotFound);
294+
throw error;
287295
});
288296
assert.fail(`expected the named-session refusal, got ${String(failure)}`);
289297
}

‎packages/daemon/src/sessions/session-lifecycle/internal/__tests__/session-devices-batch-runtime.test.ts‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -356,7 +356,9 @@ test('batch step pins nested requests to the resolved session', async () => {
356356
);
357357

358358
expect(response.ok).toBe(true);
359-
expect(seenSessions).toEqual([{ session: 'resolved-session', flagSession: 'resolved-session' }]);
359+
// The wire address stays pinned to the resolved session. The step flag carries it only when the
360+
// caller named a session (#3674): an unconditional stamp would read as caller-provened.
361+
expect(seenSessions).toEqual([{ session: 'resolved-session', flagSession: undefined }]);
360362
});
361363

362364
test('close clears retained materialized install paths bound to the session', async () => {

‎src/sdk/batch-public.test.ts‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,8 +20,10 @@ test('public batch entrypoint exports daemon-compatible orchestration helpers',
2020

2121
const response = await runBatch(req, 'resolved-session', async (stepReq) => {
2222
seenCommands.push(stepReq.command);
23+
// The wire field pins the resolved address; the step flag names a session only when the
24+
// caller did (#3674).
2325
assert.equal(stepReq.session, 'resolved-session');
24-
assert.equal(stepReq.flags?.session, 'resolved-session');
26+
assert.equal(stepReq.flags?.session, undefined);
2527
if (stepReq.command === 'open') {
2628
assert.equal(stepReq.flags?.platform, 'ios');
2729
assert.equal(stepReq.flags?.udid, 'sim-1');

‎website/docs/docs/commands.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -501,7 +501,7 @@ Read-only commands such as `get`, `snapshot`, and `wait` report `no`, and so do
501501
502502
These refusals carry `dispatched: no` and a typed `error.details.reason`, so branch on the reason, not the message:
503503
504-
- `session_or_device_selector_required`: the request had neither an active session nor a device selector. Open a session or pass `--platform`.
504+
- `session_or_device_selector_required`: the request had neither an active session nor a device selector. Open a session or pass `--platform`. Commands that require a session or a device selector before they read the request's target (`boot`, `clipboard`, `push`, `apps`, and siblings) answer this even when the request named a session the daemon does not hold.
505505
- `named_session_not_found`: the request named a session this daemon does not hold, with no device selector to fall back on. The daemon lost its sessions (replaced or restarted), or the name is wrong; `agent-device session list` shows what it holds.
506506
- `session_app_required`: a per-app setting was requested but the session binds no app and none was named. Run `open <app>`, or name the app on the request for a setting that takes one (`settings clear-app-state com.example.app`).
507507
- `app_not_installed`: the named app resolves to no installed app on the target. Run `apps --all` for the exact bundle id or package, or install the app, then retry.

0 commit comments

Comments
 (0)