Repository navigation
Expand file tree
/
Copy pathDeviceService.ts
More file actions
1685 lines (1629 loc) · 66.3 KB
/
Copy pathDeviceService.ts
File metadata and controls
1685 lines (1629 loc) · 66.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import {
type DeviceActionInput,
type DeviceCloseInput,
type DeviceConfigureInput,
type DeviceDetail,
type DeviceDetailInput,
type DeviceError,
DeviceHostId,
DeviceId,
DeviceHostUnavailableError,
DeviceNotFoundError,
DeviceOperationError,
type DeviceOpenInput,
type DevicePlatform,
DevicePlatformUnavailableError,
type DeviceServiceState,
type DeviceSession,
type DeviceShutdownInput,
type DeviceSummary,
type DeviceEasAccount,
DeviceEasAccountError,
type DeviceEasAccountInput,
type DeviceSimlockIdentity,
DeviceSimlockIdentityError,
type DeviceSimlockIdentityInput,
type DeviceHostConfig,
type EasDeviceHostConfig,
type SimlockDeviceHostConfig,
type SshDeviceHostConfig,
type DeviceHostSummary,
LOCAL_DEVICE_HOST_ID,
LOCAL_DEVICE_HOST_LABEL,
type ThreadId,
} from "@t3tools/contracts";
import { SshCommandError } from "@t3tools/ssh/errors";
import * as FileSystem from "effect/FileSystem";
import { resolveNodeExecutable, nodeRuntimeUnavailableMessage } from "@t3tools/shared/nodeRuntime";
import * as Path from "effect/Path";
import { ensureAgentDevice, ensureDeviceHub } from "./DeviceToolchain.ts";
import {
agentDeviceCloseOutcome,
bindAgentDeviceLauncher,
ensureAgentDeviceShim,
pruneAgentDeviceLaunchers,
} from "./AgentDeviceShim.ts";
import * as ServerConfig from "../config.ts";
import {
agentDeviceConfigPath,
agentDeviceSession,
writeAgentDeviceConfig,
} from "./AgentDeviceTarget.ts";
import * as Context from "effect/Context";
import * as Digest from "effect/crypto/Digest";
import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as PubSub from "effect/PubSub";
import * as Schema from "effect/Schema";
import * as Scope from "effect/Scope";
import * as Semaphore from "effect/Semaphore";
import * as Stream from "effect/Stream";
import * as SynchronizedRef from "effect/SynchronizedRef";
import * as HttpClient from "effect/http/HttpClient";
import * as ServerSettings from "../serverSettings.ts";
import { isLocalSshDeviceHost, remoteSshDeviceHosts } from "./localSshDeviceHost.ts";
import { readDeviceDetail, runDeviceAction } from "./DeviceActions.ts";
import * as ProcessRunner from "../processRunner.ts";
import * as SecretResolver from "@t3tools/secret-provider-core/server/SecretResolver";
import * as SecretResolverLayer from "../secrets/SecretResolver.ts";
import { requireSettingsSecret } from "../secrets/settingsSecretValue.ts";
import * as DeviceHost from "./DeviceHost.ts";
import * as SshDeviceHost from "./SshDeviceHost.ts";
import * as EasDeviceHost from "./EasDeviceHost.ts";
import * as SimlockDeviceHost from "./SimlockDeviceHost.ts";
import * as HostProcess from "@t3tools/shared/HostProcess";
import { makeExpoApi } from "./ExpoApi.ts";
import * as Exit from "effect/Exit";
import * as LocalDeviceHost from "./LocalDeviceHost.ts";
export const DEVICE_HUB_ROUTE_PREFIX = "/api/device-hub";
const isSshCommandError = Schema.is(SshCommandError);
const sshProbeFailureMessage = (error: DeviceHost.DeviceHostError): string => {
const windows = SshDeviceHost.isSshWindowsHostError(error.cause) ? error.cause : null;
const cause = windows ? windows.cause : error.cause;
if (
!isSshCommandError(cause) ||
cause.exitCode === null ||
cause.exitCode < 1 ||
(cause.exitCode > 254 && cause.exitCode !== 9009)
)
return "Could not connect to this host over SSH.";
// Only the known bootstrap diagnostic is safe to expose as Node guidance.
if (
cause.exitCode === 1 &&
cause.stderr
.split(/\r?\n/u)
.some((line) => line.trim() === "Node is missing from the non-interactive SSH PATH")
)
return "Connected over SSH, but Node is not on this host's PATH for non-interactive SSH commands.";
if (windows) return windows.message;
return `Connected over SSH, but the device host check failed (exit code ${cause.exitCode}).`;
};
export interface DeviceScreenshot {
readonly device: DeviceSummary;
readonly png: Uint8Array;
}
export interface DeviceReadiness extends DeviceHost.DeviceHostReady {
readonly hostId: DeviceHostId;
}
export interface DeviceAgentReadiness extends DeviceReadiness {
/** Null when each device has its own daemon; see `DeviceOperations.agentEndpoint`. */
readonly agentDevice: DeviceHost.AgentDeviceEndpoint | null;
}
const DeviceHostName = Schema.Struct({ id: DeviceHostId, label: Schema.optional(Schema.String) });
const hostName = (host: typeof DeviceHostName.Type) => host.label ?? `host ${host.id}`;
export class DeviceHostAmbiguousError extends Schema.TaggedError<DeviceHostAmbiguousError>()(
"DeviceHostAmbiguousError",
{ deviceId: DeviceId, hosts: Schema.Array(DeviceHostName) },
) {
override get message(): string {
return `Device ${this.deviceId} is on more than one host: ${this.hosts.map(hostName).join(", ")}.`;
}
}
export class DeviceOnOtherHostError extends Schema.TaggedError<DeviceOnOtherHostError>()(
"DeviceOnOtherHostError",
{ deviceId: DeviceId, host: DeviceHostName, hosts: Schema.Array(DeviceHostName) },
) {
override get message(): string {
return `Device ${this.deviceId} is not on ${hostName(this.host)}. It is on ${this.hosts.map(hostName).join(", ")}.`;
}
}
export class DeviceService extends Context.Service<
DeviceService,
{
readonly testHost: (
config: SshDeviceHostConfig,
) => Effect.Effect<DeviceHostSummary, DeviceError>;
/** Who an Expo credential signs in as and which EAS projects it can run sessions under. */
readonly easAccount: (
input: DeviceEasAccountInput,
) => Effect.Effect<DeviceEasAccount, DeviceEasAccountError>;
/** Who a Simlock agent token is; without a gateway or token, this machine's agent-device's. */
readonly simlockIdentity: (
input: DeviceSimlockIdentityInput,
) => Effect.Effect<DeviceSimlockIdentity, DeviceSimlockIdentityError>;
/**
* The agent-device flags that reach the device: its config and session,
* and the id agent-device selects it by, which can differ from its id here.
*/
readonly agentTarget: (input: {
threadId: ThreadId;
hostId: DeviceHostId;
deviceId: DeviceId;
}) => Effect.Effect<
{
readonly agentDeviceId: string | null;
readonly session: string;
readonly args: ReadonlyArray<string>;
readonly installDirectory?: string | undefined;
},
DeviceError
>;
/**
* The command agents run for one agent-device session; it is removed when the session ends.
* None when the session closed before it could be bound.
*/
readonly agentLauncher: (input: {
readonly threadId: ThreadId;
readonly hostId: DeviceHostId;
readonly deviceId: DeviceId;
readonly targetArgs: ReadonlyArray<string>;
}) => Effect.Effect<Option.Option<string>, DeviceError>;
readonly state: Effect.Effect<DeviceServiceState>;
readonly subscribe: Effect.Effect<PubSub.Subscription<DeviceServiceState>, never, Scope.Scope>;
readonly configure: (
input: DeviceConfigureInput,
) => Effect.Effect<DeviceServiceState, DeviceError>;
readonly list: Effect.Effect<DeviceServiceState, DeviceError>;
readonly updateTool: (tool: "hub" | "agent") => Effect.Effect<DeviceServiceState, DeviceError>;
readonly inspect: Effect.Effect<DeviceServiceState>;
readonly retryHost: (hostId: DeviceHostId) => Effect.Effect<DeviceServiceState, DeviceError>;
readonly open: (
input: DeviceOpenInput,
context?: DeviceHost.DeviceOpenContext,
) => Effect.Effect<DeviceSession, DeviceError>;
readonly close: (input: DeviceCloseInput) => Effect.Effect<void, DeviceError>;
readonly shutdown: (input: DeviceShutdownInput) => Effect.Effect<void, DeviceError>;
readonly detail: (input: DeviceDetailInput) => Effect.Effect<DeviceDetail, DeviceError>;
readonly action: (input: DeviceActionInput) => Effect.Effect<DeviceDetail, DeviceError>;
readonly screenshot: (input: {
readonly hostId?: DeviceHostId | undefined;
readonly deviceId: DeviceId;
}) => Effect.Effect<DeviceScreenshot, DeviceError>;
/**
* The device an id names in the last listing. Ids are unique per host, not across hosts (an
* Android AVD name can exist on two), so a hostId decides, and without one the id has to be
* on a single host.
*/
readonly locateDevice: (input: {
readonly hostId?: DeviceHostId | undefined;
readonly deviceId: DeviceId;
}) => Effect.Effect<
Option.Option<DeviceSummary>,
DeviceHostAmbiguousError | DeviceOnOtherHostError
>;
/** As `locateDevice`, among the devices a thread has open. */
readonly locateSession: (input: {
readonly threadId: ThreadId;
readonly hostId?: DeviceHostId | undefined;
readonly deviceId: DeviceId;
}) => Effect.Effect<
Option.Option<DeviceSession>,
DeviceHostAmbiguousError | DeviceOnOtherHostError
>;
readonly readiness: (hostId?: DeviceHostId) => Effect.Effect<DeviceReadiness, DeviceError>;
readonly readinessIfSupported: (
hostId?: DeviceHostId,
) => Effect.Effect<DeviceReadiness | null, DeviceError>;
readonly agentReadinessIfSupported: (
hostId?: DeviceHostId,
) => Effect.Effect<DeviceAgentReadiness | null, DeviceError>;
readonly currentReadiness: (hostId?: DeviceHostId) => Effect.Effect<DeviceReadiness | null>;
readonly sessionsForThread: (threadId: ThreadId) => Effect.Effect<ReadonlyArray<DeviceSession>>;
}
>()("t3/device/DeviceService") {}
interface ServiceState {
readonly state: DeviceServiceState;
}
export interface AgentDeviceLaunchers {
readonly bind: (input: {
readonly session: string;
readonly targetArgs: ReadonlyArray<string>;
}) => Effect.Effect<string, DeviceError>;
/** Removes every launcher whose session is not in `live`. */
readonly prune: (live: ReadonlySet<string>) => Effect.Effect<void>;
/** Ends the agent-device session behind a launcher, which releases its claim on the device. */
readonly release?: (launcher: string) => Effect.Effect<void>;
}
export const makeWithHosts = Effect.fn("DeviceService.makeWithHosts")(function* (
hosts: ReadonlyMap<DeviceHostId, DeviceHost.DeviceHost["Service"]>,
testHost: DeviceService["Service"]["testHost"] = (host) =>
Effect.fail(
new DeviceHostUnavailableError({
hostId: host.id,
hostLabel: host.label,
reason: "SSH probing is unavailable in this device service.",
}),
),
configureAgent: (
hostId: DeviceHostId,
endpoint: DeviceHost.AgentDaemonEndpoint & { readonly stateDir?: string | undefined },
deviceId?: DeviceId,
) => Effect.Effect<string, DeviceError> = (hostId) =>
Effect.fail(
new DeviceHostUnavailableError({
hostId,
reason: "Agent configuration is unavailable in this device service.",
}),
),
installTool?: (tool: "hub" | "agent") => Effect.Effect<unknown, DeviceError>,
launchers?: AgentDeviceLaunchers,
) {
const settings = yield* ServerSettings.ServerSettingsService;
const digest = yield* Digest.Digest;
const lifecycleLock = yield* Semaphore.make(1);
const readDeviceSettings = settings.getSettings.pipe(
Effect.map((value) => ({
enabled: value.enableDeviceSupport,
agentAccessEnabled: value.enableAgentDeviceAccess,
onboardingCompleted: value.deviceOnboardingCompleted,
})),
Effect.mapError(
(cause) =>
new DeviceOperationError({ operation: "settings", reason: "settings_failed", cause }),
),
);
const initialSettings = yield* readDeviceSettings;
const statePubSub = yield* PubSub.unbounded<DeviceServiceState>();
const initialHosts = yield* Effect.forEach(hosts.values(), (host) => host.summary);
let publishedHosts = new Map(hosts);
const stateRef = yield* SynchronizedRef.make<ServiceState>({
state: {
supportsHostRetry: true,
supportsToolUpdate: installTool !== undefined,
supportsToolInspection: true,
supportsEasHosts: true,
supportsSimlockHosts: true,
hosts: initialHosts,
hostStatus: initialSettings.enabled ? "idle" : "disabled",
hostStatuses: {},
devices: [],
sessions: [],
onboardingCompleted: initialSettings.onboardingCompleted,
agentAccessEnabled: initialSettings.agentAccessEnabled,
hubBasePath: DEVICE_HUB_ROUTE_PREFIX,
revision: 0,
},
});
const launcherLock = yield* Semaphore.make(1);
/** Launchers bound since startup, by agent-device session. */
const boundLaunchers = new Map<string, string>();
/** Launchers on a session the host leases to every thread; the host ends it, not a retiring thread. */
const hostSessionLaunchers = new Set<string>();
// Binding and pruning read sessions under the lock, so neither acts on a session list the other has outdated.
// A retired session's agent-device session ends before its launcher goes, and a reopen of the same
// device waits for the lock, so the close cannot end the reopened session.
const pruneLaunchers = launcherLock.withPermit(
Effect.gen(function* () {
if (!launchers) return;
const { state } = yield* SynchronizedRef.get(stateRef);
const live = new Set(
yield* Effect.forEach(state.sessions, (session) =>
agentDeviceSession(session.threadId, session.hostId, session.deviceId),
).pipe(Effect.provideService(Digest.Digest, digest)),
);
const retired = [...boundLaunchers].filter(([session]) => !live.has(session));
for (const [session] of retired) boundLaunchers.delete(session);
const ending = retired.filter(([session]) => !hostSessionLaunchers.delete(session));
const release = launchers.release;
if (release)
yield* Effect.forEach(ending, ([, launcher]) => release(launcher), {
concurrency: "unbounded",
discard: true,
});
yield* launchers.prune(live);
}),
);
const releaseLaunchers = (sessions: ReadonlyArray<DeviceSession>) =>
launcherLock.withPermit(
Effect.forEach(
sessions,
(session) =>
Effect.gen(function* () {
const name = yield* agentDeviceSession(
session.threadId,
session.hostId,
session.deviceId,
).pipe(Effect.provideService(Digest.Digest, digest));
const launcher = boundLaunchers.get(name);
if (!launcher || hostSessionLaunchers.has(name) || !launchers?.release) return;
yield* launchers.release(launcher);
boundLaunchers.delete(name);
}),
{ discard: true },
),
);
// Uninterruptible so a committed retirement always prunes, even if its caller is cancelled.
const publish = (update: (state: DeviceServiceState) => DeviceServiceState) =>
SynchronizedRef.modifyEffect(stateRef, ({ state }) => {
const next = { ...update(state), revision: state.revision + 1 };
const retired = state.sessions.some((session) => !next.sessions.includes(session));
return PubSub.publish(statePubSub, next).pipe(
Effect.as([{ next, retired }, { state: next }] as const),
);
}).pipe(
Effect.tap(({ retired }) => (retired ? pruneLaunchers : Effect.void)),
Effect.map(({ next }) => next),
Effect.uninterruptible,
);
const resolveHost = Effect.fn("DeviceService.resolveHost")(function* (
hostId: DeviceHostId | undefined,
) {
const id = hostId ?? LOCAL_DEVICE_HOST_ID;
const host = hosts.get(id);
if (!host) {
return yield* new DeviceHostUnavailableError({ hostId: id, reason: "Unknown host." });
}
return host;
});
// Readiness phases replace the shown detail; this restores an incomplete listing's cause once ready.
const discoveryDetails = new Map<DeviceHostId, string>();
const setHostStatus = (
hostId: DeviceHostId,
status: DeviceServiceState["hostStatuses"][string],
) =>
Effect.suspend(() =>
!hosts.has(hostId)
? SynchronizedRef.get(stateRef).pipe(Effect.map(({ state }) => state))
: publish((state) => {
const previous = state.hostStatuses[hostId];
const detail =
status.detail ??
(status.status === "ready" &&
(previous?.incompletePlatforms || previous?.androidDiscoveryIncomplete)
? discoveryDetails.get(hostId)
: undefined);
return {
...state,
...(hostId === LOCAL_DEVICE_HOST_ID
? { hostStatus: status.status, hostStatusDetail: detail }
: {}),
hostStatuses: {
...state.hostStatuses,
[hostId]: {
...(previous?.androidDiscoveryIncomplete
? { androidDiscoveryIncomplete: true }
: {}),
...(previous?.incompletePlatforms
? { incompletePlatforms: previous.incompletePlatforms }
: {}),
...status,
...(detail ? { detail } : {}),
},
},
};
}),
);
const readiness: DeviceService["Service"]["readiness"] = Effect.fn("DeviceService.readiness")(
function* (hostId) {
const host = yield* resolveHost(hostId);
if (!(yield* readDeviceSettings).enabled) {
return yield* new DeviceHostUnavailableError({
hostId: host.id,
hostLabel: host.label,
reason:
"Device support is off. Enable it in the Device panel before installing or starting device tools.",
});
}
const ready = yield* host
.ensureReady((status, detail) =>
setHostStatus(host.id, { status, detail }).pipe(Effect.asVoid),
)
.pipe(
Effect.tapError((error) =>
setHostStatus(host.id, {
status: "failed",
detail:
error._tag === "DeviceHostError" && error.step === "probe"
? sshProbeFailureMessage(error)
: error.message,
}),
),
Effect.mapError(
(error) =>
new DeviceHostUnavailableError({
hostId: host.id,
hostLabel: host.label,
reason:
error._tag === "NodeRuntimeUnavailableError"
? nodeRuntimeUnavailableMessage("Local device support")
: error.step === "probe"
? sshProbeFailureMessage(error)
: `Device support failed during ${error.step}.`,
cause: error,
}),
),
);
if (hosts.get(host.id) !== host)
return yield* new DeviceHostUnavailableError({
hostId: host.id,
hostLabel: host.label,
reason: "Host configuration changed. Retry the operation.",
});
const { state } = yield* SynchronizedRef.get(stateRef);
if (state.hostStatuses[host.id]?.status !== "ready") {
yield* setHostStatus(host.id, { status: "ready" });
}
return { hostId: host.id, ...ready };
},
lifecycleLock.withPermit,
);
const readinessIfSupported: DeviceService["Service"]["readinessIfSupported"] = Effect.fn(
"DeviceService.readinessIfSupported",
)(function* (hostId) {
if (!(yield* readDeviceSettings).enabled) return null;
const host = yield* resolveHost(hostId);
const summary = yield* host.summary;
if (summary.kind === "local" && !summary.platforms.some((platform) => platform.available))
return null;
return yield* readiness(host.id);
});
const agentReadinessIfSupported: DeviceService["Service"]["agentReadinessIfSupported"] =
Effect.fn("DeviceService.agentReadinessIfSupported")(function* (hostId) {
const deviceSettings = yield* readDeviceSettings;
if (!deviceSettings.enabled || !deviceSettings.agentAccessEnabled) return null;
const host = yield* resolveHost(hostId);
const summary = yield* host.summary;
if (summary.kind === "local" && !summary.platforms.some((platform) => platform.available))
return null;
const ready = yield* host
.ensureAgentReady((phase, detail) =>
setHostStatus(host.id, { status: phase, detail }).pipe(Effect.asVoid),
)
.pipe(
Effect.tapError((error) =>
setHostStatus(host.id, {
status: "failed",
detail:
error._tag === "DeviceHostError" && error.step === "probe"
? sshProbeFailureMessage(error)
: error.message,
}),
),
Effect.mapError(
(error) =>
new DeviceHostUnavailableError({
hostId: host.id,
hostLabel: host.label,
reason:
error._tag === "NodeRuntimeUnavailableError"
? nodeRuntimeUnavailableMessage("Local device support")
: error._tag === "DeviceHostTimeoutError"
? `Agent tools did not start within ${error.timeoutMs} ms.`
: error._tag === "AgentDeviceStartError"
? error.message
: error.step === "probe"
? sshProbeFailureMessage(error)
: `Device support failed during ${error.step}.`,
cause: error,
}),
),
);
const hostSummaries = yield* Effect.forEach(hosts.values(), (candidate) => candidate.summary);
yield* publish((state) => ({ ...state, hosts: hostSummaries }));
yield* setHostStatus(host.id, { status: "ready" });
return { hostId: host.id, ...ready };
}, lifecycleLock.withPermit);
const currentReadiness: DeviceService["Service"]["currentReadiness"] = (hostId) =>
resolveHost(hostId).pipe(
Effect.flatMap((host) =>
host.current.pipe(Effect.map((ready) => (ready ? { hostId: host.id, ...ready } : null))),
),
Effect.orElseSucceed(() => null),
);
const fetchDevices = Effect.fn("DeviceService.fetchDevices")(function* (ready: DeviceReadiness) {
const { devices, detail, androidDiscoveryIncomplete, incompletePlatforms } =
yield* ready.devices.list;
return {
devices: devices.map((device): DeviceSummary => ({ ...device, hostId: ready.hostId })),
detail,
androidDiscoveryIncomplete,
incompletePlatforms: incompletePlatforms ?? [],
};
});
const refresh = Effect.fn("DeviceService.refresh")(function* (ready: DeviceReadiness) {
const host = hosts.get(ready.hostId);
// A session opened while the listing ran is on a device the listing could
// not have seen yet; only sessions from before it can be pruned by it.
const sessionKey = (session: DeviceSession) =>
`${session.hostId}\u0000${session.deviceId}\u0000${session.threadId}\u0000${session.openedAt}`;
const before = new Set((yield* SynchronizedRef.get(stateRef)).state.sessions.map(sessionKey));
const { devices, detail, androidDiscoveryIncomplete, incompletePlatforms } =
yield* fetchDevices(ready);
const hostSummaries = yield* Effect.forEach(hosts.values(), (host) => host.summary);
return yield* lifecycleLock.withPermit(
Effect.gen(function* () {
if (!(yield* readDeviceSettings).enabled || !host || hosts.get(ready.hostId) !== host)
return (yield* SynchronizedRef.get(stateRef)).state;
if (detail && (incompletePlatforms.length > 0 || androidDiscoveryIncomplete))
discoveryDetails.set(ready.hostId, detail);
else discoveryDetails.delete(ready.hostId);
return yield* publish((state) => ({
...state,
hosts: hostSummaries,
...(ready.hostId === LOCAL_DEVICE_HOST_ID ? { hostStatusDetail: detail } : {}),
devices: [
...state.devices.filter(
(device) =>
device.hostId !== ready.hostId || incompletePlatforms.includes(device.platform),
),
...devices.filter((device) => !incompletePlatforms.includes(device.platform)),
],
// A host that ends devices itself (EAS stops sessions at their limits)
// leaves sessions on devices it no longer lists with nothing to stream.
// Other hosts can miss a device for one listing, so theirs stay.
sessions: ready.devices.endsDevices
? state.sessions.filter(
(session) =>
session.hostId !== ready.hostId ||
!before.has(sessionKey(session)) ||
devices.some((device) => device.id === session.deviceId),
)
: state.sessions,
hostStatuses: {
...state.hostStatuses,
[ready.hostId]: {
status: "ready",
...(detail ? { detail } : {}),
...(androidDiscoveryIncomplete ? { androidDiscoveryIncomplete } : {}),
...(incompletePlatforms.length > 0 ? { incompletePlatforms } : {}),
},
},
}));
}),
);
});
const list: DeviceService["Service"]["list"] = Effect.gen(function* () {
if (!(yield* readDeviceSettings).enabled) return (yield* SynchronizedRef.get(stateRef)).state;
yield* Effect.forEach(
hosts.values(),
(host) =>
Effect.gen(function* () {
const ready = yield* readinessIfSupported(host.id);
if (ready) yield* refresh(ready);
}).pipe(
Effect.catch((error) =>
setHostStatus(host.id, {
status: "failed",
detail: error._tag === "DeviceHostUnavailableError" ? error.reason : error.message,
}),
),
),
{ concurrency: 4 },
);
return (yield* SynchronizedRef.get(stateRef)).state;
}).pipe(Effect.withSpan("DeviceService.list"));
const inspect = Effect.gen(function* () {
yield* Effect.forEach(
hosts.values(),
(host) =>
Effect.gen(function* () {
const result = yield* (host.inspect ?? host.summary).pipe(Effect.result);
if (hosts.get(host.id) !== host) return;
if (result._tag === "Failure") {
yield* publish((state) => ({
...state,
hosts: state.hosts.map((value) =>
value.id === host.id
? {
...value,
toolInspectionError:
"Cannot check versions. Reconnect the host and check again. Installed tools have not been changed.",
}
: value,
),
}));
return;
}
yield* publish((state) => ({
...state,
hosts: state.hosts.map((value) => (value.id === host.id ? result.success : value)),
}));
}),
{ concurrency: 4 },
);
return (yield* SynchronizedRef.get(stateRef)).state;
});
const retryHost: DeviceService["Service"]["retryHost"] = Effect.fn("DeviceService.retryHost")(
function* (hostId) {
yield* resolveHost(hostId);
if (!(yield* readDeviceSettings).enabled) return (yield* SynchronizedRef.get(stateRef)).state;
yield* Effect.gen(function* () {
const ready =
(yield* agentReadinessIfSupported(hostId)) ?? (yield* readinessIfSupported(hostId));
if (ready) yield* refresh(ready);
}).pipe(
Effect.catch((error) =>
setHostStatus(hostId, {
status: "failed",
detail: error._tag === "DeviceHostUnavailableError" ? error.reason : error.message,
}),
),
);
return (yield* SynchronizedRef.get(stateRef)).state;
},
);
const configure: DeviceService["Service"]["configure"] = Effect.fn("DeviceService.configure")(
function* (input) {
const currentSettings = yield* readDeviceSettings;
const nextEnabled = input.enabled ?? currentSettings.enabled;
const nextAgentAccess = input.agentAccessEnabled ?? currentSettings.agentAccessEnabled;
yield* lifecycleLock.withPermit(
Effect.gen(function* () {
yield* settings
.updateSettings({
...(input.enabled === undefined ? {} : { enableDeviceSupport: input.enabled }),
...(input.agentAccessEnabled === undefined
? {}
: { enableAgentDeviceAccess: input.agentAccessEnabled }),
...(input.onboardingCompleted === undefined
? {}
: { deviceOnboardingCompleted: input.onboardingCompleted }),
})
.pipe(
Effect.mapError(
(cause) =>
new DeviceOperationError({
operation: "configure",
reason: "settings_failed",
cause,
}),
),
);
if (!nextEnabled) {
yield* Effect.forEach(hosts.values(), (host) => host.stop, { discard: true });
} else if (input.agentAccessEnabled === false) {
yield* Effect.forEach(hosts.values(), (host) => host.stopAgent, { discard: true });
}
yield* publish((state) => ({
...state,
hostStatus: nextEnabled ? "idle" : "disabled",
hostStatusDetail: undefined,
hostStatuses: {},
devices: nextEnabled ? state.devices : [],
sessions: nextEnabled ? state.sessions : [],
bootingDevices: nextEnabled ? state.bootingDevices : [],
agentAccessEnabled: nextAgentAccess,
onboardingCompleted: input.onboardingCompleted ?? state.onboardingCompleted,
}));
}),
);
if (nextEnabled && nextAgentAccess && input.agentAccessEnabled === true) {
yield* agentReadinessIfSupported();
}
return yield* list;
},
);
const findDevice = (
state: DeviceServiceState,
hostId: DeviceHostId,
deviceId: DeviceId,
): DeviceSummary | undefined =>
state.devices.find((device) => device.hostId === hostId && device.id === deviceId);
const ensurePlatform = Effect.fn("DeviceService.ensurePlatform")(function* (
host: DeviceHost.DeviceHost["Service"],
platform: DevicePlatform,
) {
const availability = yield* host.platformAvailability(platform);
if (!availability.available) {
return yield* new DevicePlatformUnavailableError({
hostId: host.id,
platform,
reason: availability.reason ?? "Platform toolchain missing.",
});
}
});
const open: DeviceService["Service"]["open"] = Effect.fn("DeviceService.open")(
function* (input, context) {
const host = yield* resolveHost(input.hostId);
yield* ensurePlatform(host, input.platform);
const ready = yield* readiness(host.id);
let state = yield* refresh(ready);
let device = findDevice(state, host.id, input.deviceId);
if (!device) {
return yield* new DeviceNotFoundError({ hostId: host.id, deviceId: input.deviceId });
}
// Hosts that route their own streams never encode emulator video with serve-emu's ffmpeg.
if (device.platform === "android" && !device.physical && !ready.upstream) {
// Resolve the override on the device host the way its hub does.
const encoders = yield* ready.run(ready.nodePath, [
"-e",
`const { spawnSync } = require("node:child_process");
const result = spawnSync(process.env.SERVE_EMU_FFMPEG?.trim() || "ffmpeg", ["-hide_banner", "-encoders"], {
stdio: "inherit", timeout: 10000, killSignal: "SIGKILL",
});
process.exitCode = result.error ? 1 : (result.status ?? 1);`,
]);
if (encoders.code !== 0) {
return yield* new DevicePlatformUnavailableError({
hostId: host.id,
platform: "android",
reason:
"Android emulator video needs working ffmpeg with the libx264 encoder. Install it on the device host's PATH or set SERVE_EMU_FFMPEG there, then retry opening the emulator. After changing PATH or SERVE_EMU_FFMPEG, turn device support off and on for SSH hosts, or restart the local environment server.",
});
}
if (!/^\s*V\S*[ \t]+libx264(?:[ \t]|$)/m.test(`${encoders.stdout}\n${encoders.stderr}`)) {
return yield* new DevicePlatformUnavailableError({
hostId: host.id,
platform: "android",
reason:
"Android emulator video needs the libx264 encoder. Install an ffmpeg build that includes libx264 on the device host, then retry opening the emulator. After changing PATH or SERVE_EMU_FFMPEG, turn device support off and on for SSH hosts, or restart the local environment server.",
});
}
}
if (!device.booted && input.boot !== false) {
const booting = { ...device, threadId: input.threadId };
yield* publish((current) => ({
...current,
bootingDevices: [
...(current.bootingDevices ?? []).filter(
(entry) => entry.hostId !== booting.hostId || entry.id !== booting.id,
),
booting,
],
}));
const bootedId = yield* ready.devices.boot(device, context).pipe(
Effect.ensuring(
publish((current) => ({
...current,
bootingDevices: (current.bootingDevices ?? []).filter(
(entry) => entry.hostId !== booting.hostId || entry.id !== booting.id,
),
})),
),
);
state = yield* refresh(ready);
// Retained entries predate the boot, so only a complete listing confirms the booted device.
device = state.hostStatuses[host.id]?.incompletePlatforms?.includes(device.platform)
? undefined
: (findDevice(state, host.id, bootedId) ?? findDevice(state, host.id, device.id));
if (!device) {
return yield* new DeviceNotFoundError({ hostId: host.id, deviceId: bootedId });
}
} else if (device.booted) {
yield* ready.devices.attach(device);
}
if (hosts.get(host.id) !== host)
return yield* new DeviceHostUnavailableError({
hostId: host.id,
hostLabel: host.label,
reason: "Host configuration changed. Retry the operation.",
});
const openedAt = DateTime.formatIso(yield* DateTime.now);
const session: DeviceSession = {
threadId: input.threadId,
hostId: host.id,
deviceId: device.id,
platform: device.platform,
openedAt,
};
yield* lifecycleLock.withPermit(
Effect.gen(function* () {
if (!(yield* readDeviceSettings).enabled)
return yield* new DeviceHostUnavailableError({
hostId: host.id,
hostLabel: host.label,
reason: "Device support was turned off while the device was opening.",
});
yield* publish((current) => ({
...current,
sessions: [
...current.sessions.filter(
(existing) =>
!(
existing.threadId === session.threadId &&
existing.hostId === session.hostId &&
existing.deviceId === session.deviceId
),
),
session,
],
}));
}),
);
return session;
},
);
const refreshAfterShutdown = (ready: DeviceReadiness) =>
refresh(ready).pipe(
Effect.catch((cause) =>
Effect.logWarning("Device discovery unavailable after shutdown", { cause }),
),
);
const shutdownDevice = Effect.fn("DeviceService.shutdownDevice")(function* (
ready: DeviceReadiness,
deviceId: DeviceId,
platform: DevicePlatform,
) {
yield* ready.devices.shutdown({ id: deviceId, platform });
yield* publish((state) => ({
...state,
devices: state.devices.map((device) =>
device.hostId === ready.hostId && device.id === deviceId
? { ...device, booted: false }
: device,
),
}));
});
const close: DeviceService["Service"]["close"] = Effect.fn("DeviceService.close")(
function* (input) {
// Open publishes under the same lock; an old close must not release a reopened claim.
const closing = yield* lifecycleLock.withPermit(
Effect.gen(function* () {
const { state } = yield* SynchronizedRef.get(stateRef);
const closing = state.sessions.filter(
(session) =>
session.threadId === input.threadId &&
(input.hostId === undefined || session.hostId === input.hostId) &&
(input.deviceId === undefined || session.deviceId === input.deviceId),
);
const ending = input.shutdown
? state.sessions.filter((session) =>
closing.some(
(closed) =>
closed.hostId === session.hostId && closed.deviceId === session.deviceId,
),
)
: closing;
for (const session of ending) {
const host = yield* resolveHost(session.hostId);
const ready = yield* host.current;
// A lost SSH tunnel does not establish that the remote daemon stopped.
if (!ready && (yield* host.summary).kind === "ssh")
return yield* new DeviceHostUnavailableError({
hostId: session.hostId,
hostLabel: host.label,
reason: "Device host is reconnecting. Retry close after it reconnects.",
});
if (ready?.releaseAgentSession) {
const name = yield* agentDeviceSession(
session.threadId,
session.hostId,
session.deviceId,
).pipe(Effect.provideService(Digest.Digest, digest));
yield* ready.releaseAgentSession(name, session.deviceId);
}
}
if (input.shutdown) yield* releaseLaunchers(ending);
if (input.shutdown) {
for (const session of closing) {
const ready = yield* currentReadiness(session.hostId);
if (!ready)
return yield* new DeviceHostUnavailableError({
hostId: session.hostId,
reason: "Device host is not running. Reconnect before retrying close.",
});
yield* shutdownDevice(ready, session.deviceId, session.platform);
}
}
yield* publish((current) => ({
...current,
sessions: current.sessions.filter((session) => !ending.includes(session)),
}));
return closing;
}),
);
if (input.shutdown)
yield* Effect.forEach(
closing,
(session) =>
currentReadiness(session.hostId).pipe(
Effect.flatMap((ready) => (ready ? refreshAfterShutdown(ready) : Effect.void)),
),
{ discard: true },
);
},
);
// Sessions retire before the power-off, while their agent-device sessions can still close the app;
// agent-device keeps a claim whose app close fails.
const shutdown: DeviceService["Service"]["shutdown"] = Effect.fn("DeviceService.shutdown")(
function* (input) {
const host = yield* resolveHost(input.hostId);
yield* publish((current) => ({
...current,
sessions: current.sessions.filter(
(session) => !(session.hostId === host.id && session.deviceId === input.deviceId),
),
}));
const ready = yield* readiness(host.id);
yield* shutdownDevice(ready, input.deviceId, input.platform);
yield* refreshAfterShutdown(ready);
},
);
const screenshot: DeviceService["Service"]["screenshot"] = Effect.fn("DeviceService.screenshot")(
function* (input) {
const { ready, device } = yield* resolveDevice(input.hostId, input.deviceId);
return { device, png: yield* ready.devices.screenshot(device) };
},
);
const resolveDevice = Effect.fn("DeviceService.resolveDevice")(function* (
hostId: DeviceHostId | undefined,
deviceId: DeviceId,
) {
const host = yield* resolveHost(hostId);
const ready = yield* readiness(host.id);
const { state } = yield* SynchronizedRef.get(stateRef);
const device =