Skip to content

Commit f21b001

Browse files
thymikeeclaude
andcommitted
feat(client): daemonLifecycle attach mode and ensureDaemon()
An attach client connects to the daemon registered in its state directory and never starts, replaces or kills one, including after a request times out; it fails with daemon-not-running or daemon-incompatible. ensureDaemon() starts a missing daemon and replaces an incompatible one only through the daemon's own quiesce answer, refusing with daemon-busy while it holds work and never replacing a daemon that predates the capability. managed stays the default and unchanged. Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
1 parent ad93822 commit f21b001

30 files changed

Lines changed: 1708 additions & 77 deletions

‎CHANGELOG.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
## Unreleased
44

5+
- Add `ensureDaemon({ stateDir })` and the client config `daemonLifecycle: 'attach' | 'managed'`. An `attach` client connects to the daemon registered in the state directory and never starts, replaces or kills one, including after a request times out. It fails with `details.reason: 'daemon-not-running'` (the hint points at `ensureDaemon()`) or `'daemon-incompatible'` (both identities in `details`, the hint names `agent-device daemon stop`). `ensureDaemon()` starts a missing daemon and replaces an incompatible one that answers only through an authenticated quiesce request the daemon answers itself (a resumable upload still streaming and a human-control hold that names no lease are not counted, so a replacement can end them): it refuses with `daemon-busy` while any request is in flight or any session, repair session or live lease exists, and a daemon from a release before this one is never replaced. A registered daemon that answers nothing is retired, as is one that times out on the quiesce request and then fails repeated liveness probes; neither can be asked. A remote `daemonBaseUrl` connection never starts or retires a local daemon in either mode. `managed` stays the default and behaves as before until 0.22.
56
- Add `uninstall <app>` and `client.apps.uninstall({ app })` to remove an installed app on adb-backed Android targets, iOS simulators, and CoreDevice iOS devices. Both report `wasInstalled`. A package name or bundle id that is not installed succeeds with `wasInstalled: false`. Other targets, Appium and Limrun sessions included, refuse it before anything runs.
67
- Add `settings mobile-data on|off` for adb-backed Android targets. It switches mobile data through `svc data` and reports the `mobileData` state stored in the global `mobile_data` row; multi-SIM read-back is not covered yet. Every other target refuses it before anything runs, and `--app` is refused because the switch is device-wide.
78
- On iOS, a `fill` that runs under a degraded XCTest snapshot channel now aims at a point, including ref, selector and replay fills. When the runner identifies no text input under that point, it refuses with `NO_TEXT_INPUT_AT_POINT` (`error.details.reason: no_text_input_at_point`, `dispatched: no`) before dispatching its focus tap, and no field changes; when the input lookup itself cannot answer, it refuses with `TEXT_INPUT_PROBE_UNAVAILABLE` (`error.details.reason: text_input_probe_unavailable`). Previously such a fill cleared and typed through the app-level first responder, so it could rewrite a field the caller never named, or report a clear failure after emptying it. A ref or selector fill whose rect centre misses the real field (an outer container, a non-input node) now needs a point inside the input's own rect.

‎packages/contracts/src/client-connection.ts‎

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

33
import type {
44
DaemonLockPolicy,
5+
DaemonServerMode,
6+
DaemonTransportPreference,
57
DaemonRequest,
68
DaemonResponse,
79
LeaseBackend,
@@ -15,8 +17,58 @@ import type {
1517
RemoteConnectionProfileFields,
1618
} from './remote-config-fields.ts';
1719

20+
/**
21+
* Who owns the daemon on a client's state directory.
22+
*
23+
* - `managed`: the client starts a missing daemon and replaces an incompatible one itself, and may
24+
* retire a hung one after a timeout. This is the default until 0.22.
25+
* - `attach`: the client only connects to the daemon registered in the state directory. It never
26+
* starts, replaces or kills one. A missing daemon fails with `details.reason: 'daemon-not-running'`
27+
* and an incompatible one with `'daemon-incompatible'`; `ensureDaemon()` is the explicit way to
28+
* start or replace one.
29+
*
30+
* Independent of `daemonTransport`, `daemonServerMode` and `daemonBaseUrl`: a remote connection
31+
* never starts or retires a local daemon in either mode.
32+
*/
33+
export type DaemonLifecycle = 'attach' | 'managed';
34+
35+
/** What a client can learn about a daemon without talking to it: how it identifies itself on disk. */
36+
export type DaemonIdentity = {
37+
pid: number;
38+
version?: string;
39+
/** `installed` for a published package, `checkout` for a source tree. */
40+
codeOrigin?: 'installed' | 'checkout';
41+
codeSignature?: string;
42+
processStartTime?: string;
43+
};
44+
45+
export type EnsureDaemonOptions = {
46+
/** The state directory the daemon owns; defaults to `AGENT_DEVICE_STATE_DIR`, then the user default. */
47+
stateDir?: string;
48+
daemonTransport?: DaemonTransportPreference;
49+
daemonServerMode?: DaemonServerMode;
50+
/**
51+
* Called when this call started a daemon, before `ensureDaemon` returns. `missing` means no
52+
* usable daemon was registered; `incompatible` means a daemon this client cannot use was
53+
* replaced after it agreed to leave. `previous` is the daemon that was replaced, when there was
54+
* one: a `missing` start with a `previous` replaced a registered daemon that answered nothing,
55+
* either unreachable or hung and force-retired.
56+
*/
57+
onStart?: (reason: 'missing' | 'incompatible', previous?: DaemonIdentity) => void;
58+
};
59+
60+
/** A reachable local daemon. It carries no credentials. */
61+
export type DaemonConnection = {
62+
stateDir: string;
63+
daemon: DaemonIdentity;
64+
/** True when this call started the daemon. */
65+
started: boolean;
66+
};
67+
1868
export type AgentDeviceDaemonTransportContext = {
1969
authToken?: string;
70+
/** How this request treats the local daemon; `managed` when omitted. */
71+
daemonLifecycle?: DaemonLifecycle;
2072
/**
2173
* Cancels this one in-flight request. A built-in transport that sees an abort destroys the
2274
* request's connection, which makes the daemon mark the request canceled; the promise rejects
@@ -33,6 +85,8 @@ export type AgentDeviceDaemonTransport = (
3385

3486
export type AgentDeviceClientConfig = RemoteConnectionProfileFields &
3587
CloudProviderProfileFields & {
88+
/** See `DaemonLifecycle`. */
89+
daemonLifecycle?: DaemonLifecycle;
3690
session?: string;
3791
lockPolicy?: DaemonLockPolicy;
3892
lockPlatform?: PlatformSelector;

‎packages/contracts/src/facades/client.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,11 @@ export type {
3434
AgentDeviceIdentifiers,
3535
AgentDeviceRequestOverrides,
3636
AgentDeviceSelectionOptions,
37+
DaemonConnection,
38+
DaemonIdentity,
39+
DaemonLifecycle,
3740
DeviceCommandBaseOptions,
41+
EnsureDaemonOptions,
3842
} from '../client-connection.ts';
3943
export type {
4044
AgentDeviceCapabilitiesResult,
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
import assert from 'node:assert/strict';
2+
import { test } from 'vitest';
3+
import { readDaemonQuiesceCensus, readDaemonQuiesceFence } from './daemon-resolution.ts';
4+
5+
test('a census is read only when every count is a non-negative integer', () => {
6+
const census = {
7+
startingUp: false,
8+
inFlightRequests: 1,
9+
sessions: 0,
10+
repairSessions: 2,
11+
leases: 3,
12+
};
13+
assert.deepEqual(readDaemonQuiesceCensus({ reason: 'daemon-busy', ...census }), census);
14+
15+
for (const malformed of [-1, 1.5, '1', Number.NaN, Number.POSITIVE_INFINITY, null]) {
16+
assert.equal(readDaemonQuiesceCensus({ ...census, leases: malformed }), undefined);
17+
}
18+
assert.equal(readDaemonQuiesceCensus({ sessions: 1 }), undefined);
19+
// Only a daemon that is starting up says so; an older one omits the field.
20+
assert.equal(readDaemonQuiesceCensus({ ...census, startingUp: true })?.startingUp, true);
21+
const { startingUp: _omitted, ...withoutStartingUp } = census;
22+
assert.equal(readDaemonQuiesceCensus(withoutStartingUp)?.startingUp, false);
23+
assert.equal(readDaemonQuiesceCensus({ ...census, startingUp: 'yes' }), undefined);
24+
assert.equal(readDaemonQuiesceCensus(undefined), undefined);
25+
});
26+
27+
test('a fence names an integer pid and a start time or null, nothing else', () => {
28+
assert.deepEqual(readDaemonQuiesceFence({ pid: 7, processStartTime: 'Fri' }), {
29+
pid: 7,
30+
processStartTime: 'Fri',
31+
});
32+
assert.deepEqual(readDaemonQuiesceFence({ pid: 7, processStartTime: null }), {
33+
pid: 7,
34+
processStartTime: null,
35+
});
36+
assert.equal(readDaemonQuiesceFence({ pid: 7 }), undefined);
37+
assert.equal(readDaemonQuiesceFence({ pid: 7.5, processStartTime: null }), undefined);
38+
assert.equal(readDaemonQuiesceFence('7'), undefined);
39+
});

‎packages/daemon-contracts/src/daemon-resolution.ts‎

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import { expandUserHomePath, resolveUserPath } from '@agent-device/host-kit/file
55
import { findProjectRoot, isSourceCheckoutProjectRoot } from '@agent-device/host-kit/version';
66
import { type EnvMap } from '@agent-device/kernel/source-value';
77

8+
import type { DaemonWireRequest } from '@agent-device/contracts/command';
89
import type { DaemonServerMode, DaemonTransportPreference } from '@agent-device/kernel/contracts';
910
export type { DaemonServerMode, DaemonTransportPreference };
1011

@@ -134,6 +135,22 @@ export type DaemonQuiesceCensus = Readonly<{
134135
leases: number;
135136
}>;
136137

138+
export function buildDaemonQuiesceRequest(params: {
139+
token: string;
140+
fence: DaemonQuiesceFence;
141+
requestId: string;
142+
}): DaemonWireRequest {
143+
const { token, fence, requestId } = params;
144+
return {
145+
token,
146+
session: 'default',
147+
command: DAEMON_QUIESCE_COMMAND,
148+
positionals: [],
149+
input: { pid: fence.pid, processStartTime: fence.processStartTime },
150+
meta: { requestId },
151+
};
152+
}
153+
137154
export function readDaemonQuiesceFence(input: unknown): DaemonQuiesceFence | undefined {
138155
if (typeof input !== 'object' || input === null) return undefined;
139156
const { pid, processStartTime } = input as Record<string, unknown>;
@@ -146,3 +163,23 @@ export function readDaemonCapabilities(value: unknown): readonly DaemonCapabilit
146163
if (!Array.isArray(value)) return [];
147164
return DAEMON_CAPABILITIES.filter((capability) => value.includes(capability));
148165
}
166+
167+
export function readDaemonQuiesceCensus(details: unknown): DaemonQuiesceCensus | undefined {
168+
if (typeof details !== 'object' || details === null) return undefined;
169+
const { startingUp, inFlightRequests, sessions, repairSessions, leases } = details as Record<
170+
string,
171+
unknown
172+
>;
173+
if (startingUp !== undefined && typeof startingUp !== 'boolean') return undefined;
174+
const counts = [inFlightRequests, sessions, repairSessions, leases];
175+
if (!counts.every((count) => Number.isSafeInteger(count) && (count as number) >= 0)) {
176+
return undefined;
177+
}
178+
return {
179+
startingUp: startingUp === true,
180+
inFlightRequests: inFlightRequests as number,
181+
sessions: sessions as number,
182+
repairSessions: repairSessions as number,
183+
leases: leases as number,
184+
};
185+
}

‎packages/daemon/src/server/http/daemon-runtime-quiesce.test.ts‎

Lines changed: 1 addition & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -3,28 +3,12 @@ import net from 'node:net';
33
import { afterEach, expect, test, vi } from 'vitest';
44
import { mkdtempForTestSync } from '@agent-device/test-kit';
55
import {
6-
DAEMON_QUIESCE_COMMAND,
6+
buildDaemonQuiesceRequest,
77
resolveDaemonPaths,
8-
type DaemonQuiesceFence,
98
} from '@agent-device/daemon-contracts/daemon-resolution';
109
import { readCurrentOwnerIdentity } from '@agent-device/host-kit/process';
1110
import type { DaemonResponse } from '@agent-device/kernel/contracts';
1211

13-
function buildDaemonQuiesceRequest(params: {
14-
token: string;
15-
fence: DaemonQuiesceFence;
16-
requestId: string;
17-
}) {
18-
return {
19-
token: params.token,
20-
session: 'default',
21-
command: DAEMON_QUIESCE_COMMAND,
22-
positionals: [],
23-
input: { pid: params.fence.pid, processStartTime: params.fence.processStartTime },
24-
meta: { requestId: params.requestId },
25-
};
26-
}
27-
2812
// A quiesce is the daemon's own answer to "may I leave?", so these tests boot the real runtime and
2913
// ask over its real socket: the census, the closing of admission and the drain are one flow.
3014
const probe = vi.hoisted(() => ({
Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
import { test } from 'vitest';
2+
import assert from 'node:assert/strict';
3+
import type {
4+
AgentDeviceDaemonTransport,
5+
AgentDeviceDaemonTransportContext,
6+
DaemonLifecycle,
7+
} from '@agent-device/contracts/client';
8+
import { createAgentDeviceClient } from '../agent-device-client.ts';
9+
10+
// `daemonLifecycle` is a client choice that only the transport can act on, so the client's job is to
11+
// hand it over exactly and to refuse a value it does not know.
12+
13+
function recordingTransport() {
14+
const contexts: Array<AgentDeviceDaemonTransportContext | undefined> = [];
15+
const transport: AgentDeviceDaemonTransport = async (_request, context) => {
16+
contexts.push(context);
17+
return { ok: true, data: { devices: [] } };
18+
};
19+
return { contexts, transport };
20+
}
21+
22+
test('the configured daemon lifecycle reaches the transport', async () => {
23+
const { contexts, transport } = recordingTransport();
24+
const attached = createAgentDeviceClient({ daemonLifecycle: 'attach' }, { transport });
25+
const plain = createAgentDeviceClient({}, { transport });
26+
27+
const managed = createAgentDeviceClient({ daemonLifecycle: 'managed' }, { transport });
28+
29+
await attached.devices.list();
30+
await managed.devices.list();
31+
await plain.devices.list();
32+
33+
assert.deepEqual(
34+
contexts.map((context) => context?.daemonLifecycle),
35+
['attach', 'managed', undefined],
36+
);
37+
});
38+
39+
test('an unknown daemon lifecycle is refused instead of becoming managed', () => {
40+
const { transport } = recordingTransport();
41+
const mistyped = 'Attach' as DaemonLifecycle;
42+
43+
assert.throws(
44+
() => createAgentDeviceClient({ daemonLifecycle: mistyped }, { transport }),
45+
(error: { code?: string }) => error.code === 'INVALID_ARGS',
46+
);
47+
});

‎src/__tests__/daemon-registration-owner.test.ts‎

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,10 @@ import {
2727
spawnRegisteredDaemonFixture,
2828
finishRegisteredDaemonFixture,
2929
} from './test-utils/registered-daemon-fixture.ts';
30-
import { ensureDaemon, resolveClientSettings } from '../daemon-client/daemon-client-lifecycle.ts';
30+
import {
31+
ensureManagedDaemon,
32+
resolveClientSettings,
33+
} from '../daemon-client/daemon-client-lifecycle.ts';
3134
import { inspectProcessLock } from '@agent-device/host-kit/file';
3235
import { AppError } from '@agent-device/kernel/errors';
3336
import { sleep } from '@agent-device/host-kit/retry';
@@ -791,7 +794,7 @@ test('cutover refuses an already-running legacy daemon before signaling or chang
791794
assert.ok(disposition, 'a new daemon must refuse an occupied legacy file');
792795
assert.equal(disposition.exitCode, DAEMON_STARTUP_EXIT_CODES.unproven);
793796
await assert.rejects(
794-
ensureDaemon(
797+
ensureManagedDaemon(
795798
resolveClientSettings({
796799
session: 'default',
797800
command: 'devices',

‎src/agent-device-client.ts‎

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ import type {
1616
CaptureScreenshotResult,
1717
CaptureSnapshotOptions,
1818
CaptureSnapshotResult,
19+
DaemonLifecycle,
1920
DragOptions,
2021
FlingOptions,
2122
MaterializationReleaseOptions,
@@ -84,6 +85,8 @@ export function createAgentDeviceClient(
8485
deps: { transport?: AgentDeviceDaemonTransport } = {},
8586
): AgentDeviceClient {
8687
const transport = deps.transport ?? sendToDaemon;
88+
// A typo in a JSON or JS config must not fall through to the default and manage a daemon.
89+
readDaemonLifecycle(config.daemonLifecycle);
8790

8891
// A non-default responseLevel (digest/full) makes the daemon return a leveled
8992
// shape; the per-command client normalizers assume the default shape, so the
@@ -120,7 +123,11 @@ export function createAgentDeviceClient(
120123
// mark the request canceled.
121124
const response = await cancellation.guard(
122125
async () =>
123-
await transport(request, { authToken: merged.daemonAuthToken, signal: merged.signal }),
126+
await transport(request, {
127+
authToken: merged.daemonAuthToken,
128+
signal: merged.signal,
129+
daemonLifecycle: merged.daemonLifecycle,
130+
}),
124131
);
125132
if (!response.ok) {
126133
throwDaemonError(response.error);
@@ -585,6 +592,13 @@ function optionalSnapshotResponseFields(
585592
};
586593
}
587594

595+
function readDaemonLifecycle(value: unknown): DaemonLifecycle | undefined {
596+
if (value === undefined || value === 'attach' || value === 'managed') return value;
597+
throw new AppError('INVALID_ARGS', "daemonLifecycle must be 'attach' or 'managed'.", {
598+
daemonLifecycle: value,
599+
});
600+
}
601+
588602
function mergeClientOptions(
589603
config: AgentDeviceClientConfig,
590604
options: InternalRequestOptions,

0 commit comments

Comments
 (0)