Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

handlers.ts

378 lines16.7 KB

1import {
2 type DeviceError,
3 type DeviceHostId,
4 type DeviceHostSummary,
5 type DeviceId,
6 type DevicePlatform,
7 type DeviceSummary,
8 DeviceToolUnavailableError,
9 LOCAL_DEVICE_HOST_ID,
10} from "@t3tools/contracts";
11import * as Effect from "effect/Effect";
12import * as Option from "effect/Option";
13import * as DeviceService from "../../../device/DeviceService.ts";
14import { threadWorkspaceRoot } from "../../../project/threadWorkspaceRoot.ts";
15import * as McpInvocationContext from "../../McpInvocationContext.ts";
16import * as McpToolAccess from "../../McpToolAccess.ts";
17import { DeviceScreenshotToolkit, DeviceStandardToolkit, DeviceToolkit } from "./tools.ts";
18​
19function agentDeviceTargetArgs(device: DeviceSummary): ReadonlyArray<string> {
20 return device.platform === "ios"
21 ? ["--platform", "ios", "--udid", device.id]
22 : ["--platform", "android", "--serial", device.id];
24​
25const shellWord = (value: string) =>
26 /^[a-zA-Z0-9_./:-]+$/.test(value) ? value : "'" + value.replaceAll("'", "'\"'\"'") + "'";
27​
28/** `targetArgs` are the flags the command still needs; a bound launcher needs none. */
29export function agentDeviceQuickStart(
30 device: DeviceSummary,
31 targetArgs = agentDeviceTargetArgs(device),
32 command = "agent-device",
33 host?:
34 | { readonly kind: "eas" }
35 | { readonly kind: "simlock"; readonly installDirectory?: string },
36): string {
37 const executable = shellWord(command);
38 const target = targetArgs.map(shellWord).join(" ");
39 const run = (args: string) => [executable, args, target].filter(Boolean).join(" ");
40 const platformNotes =
41 host?.kind === "simlock"
42 ? [
43 "This device is leased from a Simlock pool (alpha in T3 Code). The lease returns it to the pool, wiped, when it ends, so call device_close with shutdown: true when you are done. It starts with no apps installed.",
44 host.installDirectory
45 ? `agent-device accepts install for this lease only when run from ${host.installDirectory}.`
46 : "",
47 ]
48 .filter(Boolean)
49 .join(" ")
50 : host?.kind === "eas"
51 ? "This is an EAS Simulator session in the cloud. It bills the Expo account per minute until it stops, so call device_close with shutdown: true when you are done. It starts with no apps installed: install-from-source <url> installs a build from a URL (iOS needs a .tar.gz containing a .app), and install uploads one from this machine."
52 : device.platform === "ios"
53 ? "First use builds an XCTest runner and can take a couple of minutes; later commands are fast."
54 : "The Android snapshot helper installs itself on first use.";
55 return [
56 `The user is watching ${device.name} (${device.version}) in the Device panel.`,
57 target === ""
58 ? `Drive it with ${executable}. It is bound to this device and session, so it needs no --platform, --udid, --serial, --config or --session flags. Use this exact path; login shells may reset PATH.`
59 : `Drive it with ${executable}. Use this exact path; login shells may reset PATH. Always pass ${target}.`,
60 // Screenshots and input need the session agent-device's open starts, and an iOS snapshot also
61 // needs its app. device_open does not run open itself: on iOS that can start a minutes-long
62 // XCTest runner build.
63 "Every app launch, deep link, tap, text entry, alert, setting, screenshot and recording on this device goes through it. Run open <bundle-or-package-id> (apps lists them) before snapshots, CLI screenshots or input; it starts the session they need. Use device_screenshot just to look.",
64 ` ${run("open <bundle-or-package-id> --relaunch")} # restarts the app; Expo dev clients connect to their Metro, --metro-port <port> picks it`,
65 ` ${run("open <bundle-or-package-id> <deep-link-url>")}`,
66 ` ${run("snapshot -i")} # accessibility tree with @eN refs`,
67 ` ${run("press @e3 --settle")}`,
68 ` ${run('fill @e5 "text" --settle')}`,
69 ` ${run("alert accept")}`,
70 ` ${run("settings appearance dark")} # also text-size, permission grant <name>`,
71 ` ${run("screenshot /tmp/shot.png")} # ${device.platform === "ios" ? "iOS saves 1x points; add --pixel-density <n> (3 on most iPhones) for device resolution, " : ""}or call device_screenshot to look`,
72 ` ${run("record start --scope device /tmp/run.mp4")} # then record stop`,
73 ` ${run("install <app> <path-to-.app-or-.apk>")}`,
74 `Prefer snapshot refs over coordinates. Run ${executable} help <command> for flags and ${executable} help workflow for guides.`,
75 "Do not use simctl, idb, adb or ssh for those actions. They stay fine for builds, installs, code sync, Metro, port forwards, logs, test runners and what this command cannot do; come back to it for every UI action and screenshot so the user can watch.",
76 "Each device_open returns its own command; opening another device does not retarget this one.",
77 ...(target === ""
78 ? [
79 "The command is removed when the device closes or T3 Code restarts. If it is missing, call device_open again.",
80 ]
81 : []),
82 platformNotes,
83 ].join("\n");
85​
86const requireDeviceAccess = McpInvocationContext.requireThreadMcpCapability("device").pipe(
87 Effect.mapError(
88 () =>
89 new DeviceToolUnavailableError({
90 reason:
91 "Agent device access is turned off for this environment. Ask the user to turn on Agent device access in Settings > Integrations > Devices; it applies when the agent session next starts, such as in a new thread.",
92 }),
93 ),
94);
95​
96export const resolveHostId = Effect.fn("handlers.resolveHostId")(function* (
97 hosts: ReadonlyArray<DeviceHostSummary>,
98 hostId: string | undefined,
99): Effect.fn.Return<DeviceHostId | undefined, DeviceToolUnavailableError> {
100 if (!hostId) return undefined;
101 const exact = hosts.find((host) => host.id === hostId);
102 if (exact) return exact.id;
103 const labelMatches = hosts.filter((host) => host.label.toLowerCase() === hostId.toLowerCase());
104 if (labelMatches.length === 1) return labelMatches[0]!.id;
105 const candidates = labelMatches.length > 1 ? labelMatches : hosts;
106 const listed = [
107 ...candidates.slice(0, 10).map((host) => `${host.label.slice(0, 64)} (${host.id})`),
108 ...(candidates.length > 10 ? [`${candidates.length - 10} more`] : []),
109 ].join(", ");
110 const selector = hostId.slice(0, 128);
111 return yield* new DeviceToolUnavailableError({
112 reason:
113 labelMatches.length > 1
114 ? `Several device hosts are named ${selector}; pass one id: ${listed}.`
115 : `No device host ${selector}. Known hosts: ${listed || "none"}.`,
116 });
117});
118​
119const hostName = (host: { readonly id: DeviceHostId; readonly label?: string | undefined }) =>
120 host.label === undefined ? `hostId ${host.id}` : `'${host.label}' (hostId ${host.id})`;
121​
122const mapLocateErrors = <A, R>(
123 effect: Effect.Effect<
124 A,
125 DeviceService.DeviceHostAmbiguousError | DeviceService.DeviceOnOtherHostError,
126 R
127 >,
128) =>
129 effect.pipe(
130 Effect.catchTags({
131 DeviceHostAmbiguousError: (error) =>
132 Effect.fail(
133 new DeviceToolUnavailableError({
134 reason: `Device ${error.deviceId} is on more than one host: ${error.hosts.map(hostName).join(", ")}. Pass hostId.`,
135 }),
136 ),
137 DeviceOnOtherHostError: (error) =>
138 Effect.fail(
139 new DeviceToolUnavailableError({
140 reason: `Device ${error.deviceId} is not on ${hostName(error.host)}. It is on ${error.hosts.map(hostName).join(", ")}; pass that hostId.`,
141 }),
142 ),
143 }),
144 );
145​
146const pickDevice = Effect.fn("handlers.pickDevice")(function* (
147 state: {
148 readonly hosts: ReadonlyArray<DeviceHostSummary>;
149 readonly devices: ReadonlyArray<DeviceSummary>;
150 },
151 input: {
152 readonly deviceId?: DeviceId | undefined;
153 readonly platform?: DevicePlatform | undefined;
154 readonly hostId?: DeviceHostId | undefined;
155 },
156): Effect.fn.Return<DeviceSummary, DeviceToolUnavailableError, DeviceService.DeviceService> {
157 if (input.deviceId !== undefined) {
158 const { deviceId, hostId } = input;
159 const devices = yield* DeviceService.DeviceService;
160 const located = yield* devices.locateDevice({ deviceId, hostId }).pipe(mapLocateErrors);
161 if (Option.isSome(located)) return located.value;
162 return yield* new DeviceToolUnavailableError({
163 reason: `No device ${deviceId} on ${hostId === undefined ? "any host" : hostName(state.hosts.find((host) => host.id === hostId) ?? { id: hostId })}. Call device_list for current ids.`,
164 });
165 }
166 const hostId = input.hostId ?? LOCAL_DEVICE_HOST_ID;
167 const candidates = state.devices.filter(
168 (device) =>
169 device.hostId === hostId &&
170 (input.platform === undefined || device.platform === input.platform),
171 );
172 if (candidates.length === 0) {
173 return yield* new DeviceToolUnavailableError({
174 reason:
175 input.platform === undefined
176 ? "No simulators or emulators were found. Call device_list to see why."
177 : `No ${input.platform} devices were found on host ${hostId}. Call device_list to see why.`,
178 });
179 }
180 const platforms = new Set(candidates.map((device) => device.platform));
181 if (input.platform === undefined && platforms.size > 1) {
182 return yield* new DeviceToolUnavailableError({
183 reason: "Both iOS and Android devices are available; pass platform or deviceId.",
184 });
185 }
186 return candidates.find((device) => device.booted) ?? candidates[0]!;
187});
188​
189const toolError = (error: DeviceError | DeviceToolUnavailableError) => error;
190​
191const handlers = {
192 device_list: McpToolAccess.readsAsCaller((input) =>
193 Effect.gen(function* () {
194 const scope = yield* requireDeviceAccess;
195 const devices = yield* DeviceService.DeviceService;
196 const state = yield* devices.list;
197 if (state.hostStatus === "disabled") {
198 return yield* new DeviceToolUnavailableError({
199 reason:
200 "Device support is off. Ask the user to enable it in the Device panel before installing or starting device tools.",
201 });
202 }
203 const hostId = yield* resolveHostId(state.hosts, input?.hostId);
204 const open = state.sessions
205 .filter((session) => session.threadId === scope.thread.threadId)
206 .map((session) => ({ hostId: session.hostId, deviceId: session.deviceId }));
207 return {
208 hostStatuses: Object.fromEntries(
209 Object.entries(state.hostStatuses).filter(([id]) => !hostId || id === hostId),
210 ),
211 hosts: hostId ? state.hosts.filter((host) => host.id === hostId) : state.hosts,
212 devices: hostId
213 ? state.devices.filter((device) => device.hostId === hostId)
214 : state.devices,
215 open,
216 };
217 }).pipe(Effect.mapError(toolError)),
218 ),
219 device_open: McpToolAccess.actsAsCaller((input) =>
220 Effect.gen(function* () {
221 const scope = yield* requireDeviceAccess;
222 const devices = yield* DeviceService.DeviceService;
223 const state = yield* devices.list;
224 if (state.hostStatus === "disabled") {
225 return yield* new DeviceToolUnavailableError({
226 reason:
227 "Device support is off. Ask the user to enable it in the Device panel before installing or starting device tools.",
228 });
229 }
230 const hostId = yield* resolveHostId(state.hosts, input.hostId);
231 const target = yield* pickDevice(state, { ...input, hostId });
232 // Resolve consent and agent connectivity before booting or registering a session.
233 if (!(yield* devices.agentReadinessIfSupported(target.hostId))) {
234 return yield* new DeviceToolUnavailableError({
235 reason:
236 "Agent device access requires enabled device support, agent access, and an available simulator platform on this host.",
237 });
238 }
239 const session = yield* devices.open(
240 {
241 threadId: scope.thread.threadId,
242 hostId: target.hostId,
243 deviceId: target.id,
244 platform: target.platform,
245 },
246 { workspaceRoot: yield* threadWorkspaceRoot(scope.thread.threadId) },
247 );
248 const after = yield* devices.state;
249 const device =
250 after.devices.find(
251 (candidate) => candidate.hostId === session.hostId && candidate.id === session.deviceId,
252 ) ?? target;
253 // Target the opened device: an EAS device and its agent-device daemon
254 // exist only once its session runs, and Android ids change on boot.
255 const opened = {
256 threadId: scope.thread.threadId,
257 hostId: session.hostId,
258 deviceId: session.deviceId,
259 };
260 const agent = yield* devices.agentTarget(opened);
261 const hostKind = after.hosts.find((host) => host.id === device.hostId)?.kind;
262 const targetArgs = [
263 ...(agent.agentDeviceId === null
264 ? []
265 : agentDeviceTargetArgs({ ...device, id: agent.agentDeviceId })),
266 ...agent.args,
267 ];
268 const launcher = yield* devices.agentLauncher({ ...opened, targetArgs });
269 if (Option.isNone(launcher)) {
270 return yield* new DeviceToolUnavailableError({
271 reason:
272 "The device was closed while device_open was preparing it. Call device_open again only if you still need it.",
273 });
274 }
275 const command = launcher.value;
276 return {
277 device,
278 agentDevice: { command, targetArgs, session: agent.session },
279 quickStart: agentDeviceQuickStart(
280 device,
281 [],
282 command,
283 hostKind === "simlock"
284 ? {
285 kind: "simlock",
286 ...(agent.installDirectory ? { installDirectory: agent.installDirectory } : {}),
287 }
288 : hostKind === "eas"
289 ? { kind: "eas" }
290 : undefined,
291 ),
292 };
293 }).pipe(Effect.mapError(toolError)),
294 ),
295 device_screenshot: McpToolAccess.readsAsCaller((input) =>
296 Effect.gen(function* () {
297 const scope = yield* requireDeviceAccess;
298 const devices = yield* DeviceService.DeviceService;
299 const threadId = scope.thread.threadId;
300 const hostId =
301 input.hostId === undefined
302 ? undefined
303 : yield* resolveHostId((yield* devices.state).hosts, input.hostId);
304 const target =
305 input.deviceId === undefined
306 ? (yield* devices.sessionsForThread(threadId)).findLast(
307 (session) => hostId === undefined || session.hostId === hostId,
308 )
309 : Option.getOrUndefined(
310 yield* devices
311 .locateSession({ threadId, deviceId: input.deviceId, hostId })
312 .pipe(mapLocateErrors),
313 );
314 if (!target) {
315 return yield* new DeviceToolUnavailableError({
316 reason:
317 input.deviceId === undefined
318 ? "No device is open in this thread. Call device_open first."
319 : `Device ${input.deviceId} is not open in this thread. Call device_open first.`,
320 });
321 }
322 const shot = yield* devices.screenshot(target);
323 return {
324 device: shot.device,
325 screenshot: {
326 mimeType: "image/png" as const,
327 data: Buffer.from(shot.png).toString("base64"),
328 ...pngDimensions(shot.png),
329 },
330 };
331 }).pipe(Effect.mapError(toolError)),
332 ),
333 device_close: McpToolAccess.actsAsCaller((input) =>
334 Effect.gen(function* () {
335 const scope = yield* requireDeviceAccess;
336 const devices = yield* DeviceService.DeviceService;
337 const deviceId = input.deviceId;
338 const inputHostId =
339 input.hostId === undefined
340 ? undefined
341 : yield* resolveHostId((yield* devices.state).hosts, input.hostId);
342 const open =
343 deviceId === undefined
344 ? Option.none()
345 : yield* devices
346 .locateSession({ threadId: scope.thread.threadId, deviceId, hostId: inputHostId })
347 .pipe(mapLocateErrors);
348 const hostId = Option.isSome(open) ? open.value.hostId : inputHostId;
349 yield* devices.close({
350 threadId: scope.thread.threadId,
351 ...(hostId === undefined ? {} : { hostId }),
352 ...(deviceId === undefined ? {} : { deviceId }),
353 ...(input.shutdown === undefined ? {} : { shutdown: input.shutdown }),
354 });
355 return {};
356 }).pipe(Effect.mapError(toolError)),
357 ),
358} satisfies McpToolAccess.Handlers<typeof DeviceToolkit.tools>;
359​
360export function pngDimensions(png: Uint8Array): { width: number; height: number } {
361 if (png.length < 24) return { width: 0, height: 0 };
362 const view = new DataView(png.buffer, png.byteOffset, png.byteLength);
363 const isPng =
364 view.getUint32(0) === 0x89504e47 &&
365 view.getUint32(4) === 0x0d0a1a0a &&
366 view.getUint32(12) === 0x49484452;
367 return isPng
368 ? { width: view.getUint32(16), height: view.getUint32(20) }
369 : { width: 0, height: 0 };
371​
372const { device_screenshot, ...standardHandlers } = handlers;
373​
374export const layerStandard = McpToolAccess.toLayer(DeviceStandardToolkit, standardHandlers);
375​
376export const layerScreenshot = McpToolAccess.toLayer(DeviceScreenshotToolkit, {
377 device_screenshot,
378});