Skip to content

Commit b940304

Browse files
committed
fix: narrow client result contracts
1 parent 9dabe5b commit b940304

22 files changed

Lines changed: 468 additions & 52 deletions

‎src/__tests__/client.test.ts‎

Lines changed: 89 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,61 @@
11
import { test } from 'vitest';
22
import assert from 'node:assert/strict';
3-
import { createAgentDeviceClient, type AgentDeviceClientConfig } from '../client/client.ts';
3+
import {
4+
createAgentDeviceClient,
5+
type AgentDeviceClient,
6+
type AgentDeviceClientConfig,
7+
type PrepareCommandResult,
8+
type PushCommandResult,
9+
type TriggerAppEventCommandResult,
10+
type WaitCommandResult,
11+
} from '../client/client.ts';
412
import { runCommand } from '../commands/command-surface.ts';
13+
import type { CommandResult } from '../core/command-descriptor/command-result.ts';
514
import type { DaemonRequest, DaemonResponse, DaemonResponseData } from '../kernel/contracts.ts';
615
import { AppError } from '../kernel/errors.ts';
716

17+
type Equal<A, B> =
18+
(<T>() => T extends A ? 1 : 2) extends <T>() => T extends B ? 1 : 2 ? true : false;
19+
20+
const closedProjectionResponses: Record<string, DaemonResponseData> = {
21+
wait: { waitedMs: 25, text: 'Ready' },
22+
prepare: {
23+
action: 'ios-runner',
24+
platform: 'ios',
25+
deviceId: 'SIM-001',
26+
deviceName: 'iPhone 16',
27+
kind: 'simulator',
28+
durationMs: 30,
29+
runner: { uptimeMs: 42 },
30+
cache: 'exact',
31+
artifact: 'valid',
32+
buildMs: 10,
33+
connectMs: 20,
34+
healthCheckMs: 10,
35+
xctestrunPath: '/tmp/AgentDevice.xctestrun',
36+
timing: {
37+
totalMs: 30,
38+
additiveParts: { buildMs: 10, connectAfterBuildMs: 10, healthCheckMs: 10 },
39+
containment: { connectMs: ['buildMs'], healthCheckMs: [] },
40+
note: 'Use additiveParts.',
41+
},
42+
message: 'Prepared Apple runner: iPhone 16',
43+
},
44+
push: {
45+
platform: 'android',
46+
package: 'com.example.demo',
47+
action: 'com.example.demo.TEST_PUSH',
48+
extrasCount: 1,
49+
message: 'Pushed notification to com.example.demo',
50+
},
51+
'trigger-app-event': {
52+
event: 'screenshot_taken',
53+
eventUrl: 'demo://agent-device/event?name=screenshot_taken',
54+
transport: 'deep-link',
55+
message: 'Triggered app event: screenshot_taken',
56+
},
57+
};
58+
859
function createTransport(
960
handler: (req: Omit<DaemonRequest, 'token'>) => Promise<DaemonResponse> | DaemonResponse,
1061
): {
@@ -35,6 +86,43 @@ function createTransport(
3586
};
3687
}
3788

89+
test('client exposes narrowed result types for closed daemon projections', async () => {
90+
const setup = createTransport(async (req) => closedProjectionResponse(req.command));
91+
const client = createAgentDeviceClient(setup.config, { transport: setup.transport });
92+
93+
const waitResult = await client.command.wait({ durationMs: 25 });
94+
const prepareResult = await client.command.prepare({ action: 'ios-runner' });
95+
const pushResult = await client.apps.push({
96+
app: 'com.example.demo',
97+
payload: { extras: { source: 'test' } },
98+
});
99+
const triggerResult = await client.apps.triggerEvent({ event: 'screenshot_taken' });
100+
101+
const waitType: Equal<typeof waitResult, WaitCommandResult> = true;
102+
const prepareType: Equal<typeof prepareResult, PrepareCommandResult> = true;
103+
const pushType: Equal<typeof pushResult, PushCommandResult> = true;
104+
const triggerType: Equal<typeof triggerResult, TriggerAppEventCommandResult> = true;
105+
const clientWaitType: Equal<
106+
Awaited<ReturnType<AgentDeviceClient['command']['wait']>>,
107+
CommandResult<'wait'>
108+
> = true;
109+
110+
assert.deepEqual(
111+
[waitType, prepareType, pushType, triggerType, clientWaitType],
112+
[true, true, true, true, true],
113+
);
114+
assert.deepEqual(waitResult, { waitedMs: 25, text: 'Ready' });
115+
assert.equal(prepareResult.timing.additiveParts.connectAfterBuildMs, 10);
116+
assert.equal(pushResult.platform, 'android');
117+
assert.equal(triggerResult.transport, 'deep-link');
118+
});
119+
120+
function closedProjectionResponse(command: string): DaemonResponse {
121+
const data = closedProjectionResponses[command];
122+
if (!data) throw new Error(`Unexpected command: ${command}`);
123+
return { ok: true, data };
124+
}
125+
38126
test('apps.open resolves session device identifiers from open response', async () => {
39127
const setup = createTransport(async (req) => {
40128
if (req.command === 'open') {

‎src/backend.ts‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import type { AlertAction, AlertInfo } from './alert-contract.ts';
22
import type { AppsFilter } from './contracts/app-inventory.ts';
3+
import type { JsonObject } from './contracts/json.ts';
34
import type { Point, SnapshotNode, SnapshotOptions, SnapshotState } from './kernel/snapshot.ts';
45
import type { NetworkIncludeMode } from './kernel/contracts.ts';
56
import type { DeviceTarget, Platform, PlatformSelector, PublicPlatform } from './kernel/device.ts';
@@ -225,7 +226,7 @@ export type BackendAppState = {
225226
export type BackendPushInput =
226227
| {
227228
kind: 'json';
228-
payload: Record<string, unknown>;
229+
payload: JsonObject;
229230
}
230231
| {
231232
kind: 'file';
@@ -234,7 +235,7 @@ export type BackendPushInput =
234235

235236
export type BackendAppEvent = {
236237
name: string;
237-
payload?: Record<string, unknown>;
238+
payload?: JsonObject;
238239
};
239240

240241
export type BackendDeviceFilter = {

‎src/client/client-types.ts‎

Lines changed: 12 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,7 @@ export type { TargetShutdownResult } from '../target-shutdown-contract.ts';
5151
import type { PerfAction, PerfArea, PerfKind, PerfSubject } from '../contracts/perf.ts';
5252
import type { AlertAction, AlertInfo } from '../alert-contract.ts';
5353
import type { DebugSymbolsOptions, DebugSymbolsResult } from '../contracts/debug-symbols.ts';
54+
import type { JsonObject } from '../contracts/json.ts';
5455
import type {
5556
CloudProviderProfileFields,
5657
RemoteConnectionProfileFields,
@@ -76,6 +77,11 @@ export type {
7677
export type { ClipboardCommandResult } from '../contracts/clipboard.ts';
7778
export type { AppStateCommandResult } from '../contracts/app-state.ts';
7879
export type { KeyboardCommandResult } from '../contracts/keyboard.ts';
80+
export type { WaitCommandResult } from '../contracts/wait.ts';
81+
export type { PrepareCommandResult } from '../contracts/prepare.ts';
82+
export type { PushCommandResult } from '../contracts/push.ts';
83+
export type { TriggerAppEventCommandResult } from '../contracts/app-events.ts';
84+
export type { JsonObject, JsonPrimitive, JsonValue } from '../contracts/json.ts';
7985

8086
export type AgentDeviceDaemonTransport = (
8187
req: Omit<DaemonRequest, 'token'>,
@@ -561,7 +567,7 @@ export type ViewportCommandOptions = DeviceCommandBaseOptions & {
561567
};
562568

563569
export type AgentDeviceCommandClient = {
564-
wait: (options: WaitCommandOptions) => Promise<CommandRequestResult>;
570+
wait: (options: WaitCommandOptions) => Promise<CommandResult<'wait'>>;
565571
alert: (options?: AlertCommandOptions) => Promise<CommandRequestResult>;
566572
appState: (options?: AppStateCommandOptions) => Promise<CommandResult<'appstate'>>;
567573
back: (options?: BackCommandOptions) => Promise<CommandResult<'back'>>;
@@ -577,7 +583,7 @@ export type AgentDeviceCommandClient = {
577583
* JSON prepare results include timing.additiveParts for additive wall-clock phases.
578584
* Top-level buildMs/connectMs/healthCheckMs are diagnostics and may overlap.
579585
*/
580-
prepare: (options: PrepareCommandOptions) => Promise<CommandRequestResult>;
586+
prepare: (options: PrepareCommandOptions) => Promise<CommandResult<'prepare'>>;
581587
viewport: (options: ViewportCommandOptions) => Promise<CommandResult<'viewport'>>;
582588
};
583589

@@ -628,12 +634,12 @@ export type DeviceShutdownOptions = DeviceCommandBaseOptions;
628634

629635
export type AppPushOptions = DeviceCommandBaseOptions & {
630636
app: string;
631-
payload: string | Record<string, unknown>;
637+
payload: string | JsonObject;
632638
};
633639

634640
export type AppTriggerEventOptions = DeviceCommandBaseOptions & {
635641
event: string;
636-
payload?: Record<string, unknown>;
642+
payload?: JsonObject;
637643
};
638644

639645
export type CaptureDiffOptions = DeviceCommandBaseOptions &
@@ -1047,8 +1053,8 @@ export type AgentDeviceClient = {
10471053
list: (options?: AppListOptions) => Promise<string[]>;
10481054
open: (options: AppOpenOptions) => Promise<AppOpenResult>;
10491055
close: (options?: AppCloseOptions) => Promise<AppCloseResult>;
1050-
push: (options: AppPushOptions) => Promise<CommandRequestResult>;
1051-
triggerEvent: (options: AppTriggerEventOptions) => Promise<CommandRequestResult>;
1056+
push: (options: AppPushOptions) => Promise<CommandResult<'push'>>;
1057+
triggerEvent: (options: AppTriggerEventOptions) => Promise<CommandResult<'trigger-app-event'>>;
10521058
};
10531059
materializations: {
10541060
release: (options: MaterializationReleaseOptions) => Promise<MaterializationReleaseResult>;

‎src/client/client.ts‎

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -117,12 +117,13 @@ export function createAgentDeviceClient(
117117

118118
return {
119119
command: {
120-
wait: async (options) => await executeCommand('wait', options),
120+
wait: async (options) => await executeCommand<CommandResult<'wait'>>('wait', options),
121121
alert: async (options = {}) => await executeCommand('alert', options),
122122
...projectedSystemCommands,
123123
reactNative: async (options) => await executeCommand('react-native', options),
124124
doctor: async (options = {}) => await executeCommand('doctor', options),
125-
prepare: async (options) => await executeCommand('prepare', options),
125+
prepare: async (options) =>
126+
await executeCommand<CommandResult<'prepare'>>('prepare', options),
126127
viewport: async (options) =>
127128
await executeCommand<CommandResult<'viewport'>>('viewport', options),
128129
},
@@ -226,8 +227,9 @@ export function createAgentDeviceClient(
226227
identifiers: { session },
227228
};
228229
},
229-
push: async (options) => await executeCommand('push', options),
230-
triggerEvent: async (options) => await executeCommand('trigger-app-event', options),
230+
push: async (options) => await executeCommand<CommandResult<'push'>>('push', options),
231+
triggerEvent: async (options) =>
232+
await executeCommand<CommandResult<'trigger-app-event'>>('trigger-app-event', options),
231233
},
232234
materializations: {
233235
release: async (options: MaterializationReleaseOptions) =>

‎src/commands/__tests__/command-surface-metadata.test.ts‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,16 @@ test('common command input accepts web platform selector', () => {
5454
assert.equal(input.platform, 'web');
5555
});
5656

57+
test('trigger-app-event rejects non-object payloads at command input read time', () => {
58+
const metadata = listCommandMetadata().find((entry) => entry.name === 'trigger-app-event');
59+
if (!metadata) throw new Error('Expected trigger-app-event command metadata');
60+
61+
assert.throws(
62+
() => metadata.readInput({ event: 'screenshot_taken', payload: 'not-json-object' }),
63+
/Expected payload to be an object\./,
64+
);
65+
});
66+
5767
test('command response data transforms reference command input fields', () => {
5868
const metadataByName = new Map<string, ReturnType<typeof listCommandMetadata>[number]>(
5969
listCommandMetadata().map((metadata) => [metadata.name, metadata] as const),

‎src/commands/management/push.ts‎

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,12 @@
11
import { PUBLIC_COMMANDS } from '../../command-catalog.ts';
22
import type { AppPushOptions, AppTriggerEventOptions } from '../../client/client-types.ts';
3+
import type { JsonObject } from '../../contracts/json.ts';
34
import type { CommandSchemaOverride } from '../../utils/cli-command-schema-types.ts';
45
import {
56
jsonSchemaField,
67
looseObjectField,
78
looseObjectSchema,
9+
type CommandField,
810
requiredField,
911
stringField,
1012
stringSchema,
@@ -23,7 +25,7 @@ import { defineFieldCommandMetadata } from '../field-command-contract.ts';
2325
const pushCommandMetadata = defineFieldCommandMetadata('push', 'Deliver a push payload.', {
2426
app: requiredField(stringField()),
2527
payload: requiredField(
26-
jsonSchemaField<string | Record<string, unknown>>({
28+
jsonSchemaField<string | JsonObject>({
2729
oneOf: [stringSchema(), looseObjectSchema()],
2830
}),
2931
),
@@ -34,7 +36,7 @@ const triggerAppEventCommandMetadata = defineFieldCommandMetadata(
3436
'Trigger an app-defined event.',
3537
{
3638
event: requiredField(stringField()),
37-
payload: looseObjectField(),
39+
payload: jsonObjectField(),
3840
},
3941
);
4042

@@ -113,3 +115,7 @@ function pushPositionals(input: AppPushOptions): string[] {
113115
function triggerEventPositionals(input: AppTriggerEventOptions): string[] {
114116
return [input.event, ...(input.payload ? [JSON.stringify(input.payload)] : [])];
115117
}
118+
119+
function jsonObjectField(): CommandField<JsonObject> {
120+
return looseObjectField() as CommandField<JsonObject>;
121+
}

‎src/commands/management/runtime/apps.test.ts‎

Lines changed: 33 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ import type {
66
BackendOpenTarget,
77
BackendPushInput,
88
} from '../../../backend.ts';
9+
import type { JsonObject } from '../../../contracts/json.ts';
910
import { createLocalArtifactAdapter } from '../../../io.ts';
1011
import {
1112
createAgentDevice,
@@ -108,7 +109,7 @@ test('runtime app push rejects local payload paths under restricted policy', asy
108109
assert.equal(pushCalled, false);
109110
});
110111

111-
test('runtime app commands validate JSON payloads', async () => {
112+
test('runtime app commands reject invalid event names', async () => {
112113
const device = createAgentDevice({
113114
backend: createAppsBackend([]),
114115
artifacts: createLocalArtifactAdapter(),
@@ -119,11 +120,16 @@ test('runtime app commands validate JSON payloads', async () => {
119120
() => device.apps.triggerEvent({ name: 'bad event' }),
120121
/Invalid apps\.triggerEvent name/,
121122
);
123+
});
124+
125+
test('runtime app push validates JSON payloads', async () => {
126+
const device = createAppsRuntimeDevice();
127+
122128
await assert.rejects(
123129
() =>
124130
device.apps.push({
125131
app: 'com.example.app',
126-
input: { kind: 'json', payload: [] as unknown as Record<string, unknown> },
132+
input: { kind: 'json', payload: [] as unknown as JsonObject },
127133
}),
128134
/JSON payload must be a JSON object/,
129135
);
@@ -133,7 +139,7 @@ test('runtime app commands validate JSON payloads', async () => {
133139
app: 'com.example.app',
134140
input: {
135141
kind: 'json',
136-
payload: { count: 1n } as unknown as Record<string, unknown>,
142+
payload: { count: 1n } as unknown as JsonObject,
137143
},
138144
}),
139145
/JSON payload must be JSON-serializable/,
@@ -144,7 +150,7 @@ test('runtime app commands validate JSON payloads', async () => {
144150
app: 'com.example.app',
145151
input: {
146152
kind: 'json',
147-
payload: { toJSON: () => undefined } as unknown as Record<string, unknown>,
153+
payload: { toJSON: () => undefined } as unknown as JsonObject,
148154
},
149155
}),
150156
/JSON payload must be JSON-serializable/,
@@ -160,19 +166,32 @@ test('runtime app commands validate JSON payloads', async () => {
160166
}),
161167
/JSON payload exceeds 8192 bytes/,
162168
);
169+
await assert.rejects(
170+
() =>
171+
device.apps.push({
172+
app: 'com.example.app',
173+
input: undefined as unknown as Parameters<typeof device.apps.push>[0]['input'],
174+
}),
175+
/apps\.push requires an input/,
176+
);
177+
});
178+
179+
test('runtime app events validate JSON payloads', async () => {
180+
const device = createAppsRuntimeDevice();
181+
163182
await assert.rejects(
164183
() =>
165184
device.apps.triggerEvent({
166185
name: 'example.ready',
167-
payload: { count: 1n } as unknown as Record<string, unknown>,
186+
payload: { count: 1n } as unknown as JsonObject,
168187
}),
169188
/payload for "example.ready" must be JSON-serializable/,
170189
);
171190
await assert.rejects(
172191
() =>
173192
device.apps.triggerEvent({
174193
name: 'example.ready',
175-
payload: { toJSON: () => undefined } as unknown as Record<string, unknown>,
194+
payload: { toJSON: () => undefined } as unknown as JsonObject,
176195
}),
177196
/payload for "example.ready" must be JSON-serializable/,
178197
);
@@ -184,16 +203,16 @@ test('runtime app commands validate JSON payloads', async () => {
184203
}),
185204
/payload for "example.ready" exceeds 8192 bytes/,
186205
);
187-
await assert.rejects(
188-
() =>
189-
device.apps.push({
190-
app: 'com.example.app',
191-
input: undefined as unknown as Parameters<typeof device.apps.push>[0]['input'],
192-
}),
193-
/apps\.push requires an input/,
194-
);
195206
});
196207

208+
function createAppsRuntimeDevice() {
209+
return createAgentDevice({
210+
backend: createAppsBackend([]),
211+
artifacts: createLocalArtifactAdapter(),
212+
policy: localCommandPolicy(),
213+
});
214+
}
215+
197216
function createAppsBackend(calls: unknown[]): AgentDeviceBackend {
198217
return {
199218
platform: 'ios',

0 commit comments

Comments
 (0)