The best way to control Claude Code, Codex and more from any computer or phone

main
ts 258 lines 9.96 KB
Raw
1 import { msg } from "gt-i18n";
2 import { MarkedText, translatableMessage } from "../errors/translatable.ts";
3 import {
4 ORCHESTRATION_PROTOCOL_VERSION,
5 type EnvironmentId,
6 type ExecutionEnvironmentDescriptor,
7 type ServerSelfUpdateInput,
8 type ServerSelfUpdateResult,
9 WS_METHODS,
10 } from "@t3tools/contracts";
11 import * as Duration from "effect/Duration";
12 import * as Effect from "effect/Effect";
13 import * as Layer from "effect/Layer";
14 import * as Option from "effect/Option";
15 import * as Ref from "effect/Ref";
16 import * as Schedule from "effect/Schedule";
17 import * as Schema from "effect/Schema";
18 import * as Stream from "effect/Stream";
19 import * as SubscriptionRef from "effect/SubscriptionRef";
20 import * as HttpClient from "effect/http/HttpClient";
21 import * as RpcClient from "effect/rpc/RpcClient";
22 import * as RpcSerialization from "effect/rpc/RpcSerialization";
23 import * as Socket from "effect/socket/Socket";
24
25 import { fetchRemoteEnvironmentDescriptor } from "../environment/descriptor.ts";
26 import { makeWsRpcProtocolClient, PING_TIMEOUT } from "../rpc/protocol.ts";
27 import {
28 isLegacyUpdateHandoffLoss,
29 localizeServerSelfUpdateError,
30 resolveServerUpdateProgressResult,
31 } from "../state/server.ts";
32 import * as RelayEnvironmentDiscovery from "../relay/discovery.ts";
33 import * as ConnectionResolver from "./resolver.ts";
34 import * as EnvironmentRegistry from "./registry.ts";
35 import {
36 connectionRoutes,
37 hasRelayRoute,
38 routeEntry,
39 routeHttpBaseUrl,
40 usableRoutes,
41 } from "./routes.ts";
42
43 // A v1 host restarting into v2 runs migrations before its descriptor answers again.
44 const OUTDATED_HOST_RESTART_TIMEOUT = Duration.minutes(4);
45 const SOCKET_OPEN_TIMEOUT = "15 seconds";
46
47 export class OutdatedHostUpdateError extends Schema.TaggedError<OutdatedHostUpdateError>()(
48 "OutdatedHostUpdateError",
49 {
50 environmentId: Schema.String,
51 message: Schema.String,
52 i18nMessage: Schema.optionalKey(MarkedText),
53 },
54 ) {}
55
56 export type OutdatedHostUpdateStage = "downloading" | "installing" | "resuming";
57
58 const reachOutdatedHost = Effect.fn("clientRuntime.connection.reachOutdatedHost")(function* (
59 environmentId: EnvironmentId,
60 ) {
61 const registry = yield* EnvironmentRegistry.EnvironmentRegistry;
62 const resolver = yield* ConnectionResolver.ConnectionResolver;
63 const entry = (yield* SubscriptionRef.get(registry.entries)).get(environmentId);
64 if (entry === undefined) {
65 return yield* new EnvironmentRegistry.EnvironmentNotRegisteredError({ environmentId });
66 }
67 const { prepared, descriptor } = yield* Effect.firstSuccessOf(
68 usableRoutes(entry).map((route) => resolver.prepareForUpdate(routeEntry(entry, route))),
69 );
70 return { entry, prepared, descriptor };
71 });
72
73 // The normal session cannot read config from a host behind the protocol gate.
74 export const describeOutdatedHost = (environmentId: EnvironmentId) =>
75 reachOutdatedHost(environmentId).pipe(Effect.map(({ descriptor }) => descriptor));
76
77 /**
78 * The normal session refuses to open against such a host, so this opens a bare
79 * socket and calls only the self-update RPCs, whose wire shape has not changed
80 * across protocol versions.
81 */
82 export const updateOutdatedHost = Effect.fn("clientRuntime.connection.updateOutdatedHost")(
83 function* (
84 environmentId: EnvironmentId,
85 input: ServerSelfUpdateInput,
86 onStage: (stage: OutdatedHostUpdateStage) => Effect.Effect<void>,
87 ) {
88 const registry = yield* EnvironmentRegistry.EnvironmentRegistry;
89 const webSocketConstructor = yield* Socket.WebSocketConstructor;
90 const httpClient = yield* HttpClient.HttpClient;
91 const { entry, prepared, descriptor } = yield* reachOutdatedHost(environmentId);
92 // Discovery still holds the old relay descriptor and would re-block the
93 // environment from it, so replace that before clearing the block.
94 const switchBackOn = Effect.gen(function* () {
95 if (hasRelayRoute(entry)) {
96 const discovery = yield* RelayEnvironmentDiscovery.RelayEnvironmentDiscovery;
97 yield* discovery.refresh;
98 }
99 yield* registry.setCompatibility(environmentId, null);
100 yield* registry.setEnabled(environmentId, true);
101 });
102
103 // A host updated by hand is already compatible, and a bare socket would be
104 // rejected with 426, so there is nothing to update.
105 if (isCompatibleDescriptor(descriptor)) {
106 yield* switchBackOn;
107 return { targetVersion: descriptor.serverVersion };
108 }
109
110 const capabilities = descriptor.capabilities;
111 if (
112 capabilities.serverSelfUpdate === undefined ||
113 (capabilities.serverSelfUpdate === "desktop-managed" &&
114 capabilities.desktopAppUpdate !== true)
115 ) {
116 return yield* new OutdatedHostUpdateError({
117 environmentId,
118 ...translatableMessage(
119 msg("Update T3 Code on {host} manually; it cannot update itself.", {
120 host: descriptor.label,
121 }),
122 ),
123 });
124 }
125
126 const result = yield* Effect.scoped(
127 Effect.gen(function* () {
128 const protocolContext = yield* Layer.build(
129 Layer.effect(
130 RpcClient.Protocol,
131 RpcClient.makeProtocolSocket({
132 pingTimeout: PING_TIMEOUT,
133 retryTransientErrors: false,
134 retryPolicy: Schedule.recurs(0),
135 }),
136 ).pipe(
137 Layer.provide(
138 Layer.mergeAll(
139 Socket.layerWebSocket(prepared.socketUrl, {
140 openTimeout: SOCKET_OPEN_TIMEOUT,
141 }).pipe(
142 Layer.provide(Layer.succeed(Socket.WebSocketConstructor, webSocketConstructor)),
143 ),
144 RpcSerialization.layerJson,
145 ),
146 ),
147 ),
148 );
149 const client = yield* makeWsRpcProtocolClient.pipe(Effect.provide(protocolContext));
150
151 const updateResult: ServerSelfUpdateResult =
152 capabilities.serverSelfUpdateProgress === true
153 ? yield* Effect.gen(function* () {
154 const terminal = yield* Ref.make(Option.none<ServerSelfUpdateResult>());
155 let receivedProgress = false;
156 const streamExit = yield* client[WS_METHODS.serverUpdateServerWithProgress](
157 input,
158 ).pipe(
159 Stream.runForEach((event) =>
160 event.type === "complete"
161 ? Ref.set(terminal, Option.some(event.result))
162 : Effect.sync(() => {
163 receivedProgress = true;
164 }).pipe(Effect.andThen(onStage(event.stage))),
165 ),
166 Effect.exit,
167 );
168 const selfUpdateMethod = capabilities.serverSelfUpdate;
169 // Desktop preparation needs its terminal commit token.
170 const accepted =
171 receivedProgress &&
172 (selfUpdateMethod === "boot-service" || selfUpdateMethod === "respawn")
173 ? { targetVersion: input.targetVersion, method: selfUpdateMethod }
174 : undefined;
175 return yield* resolveServerUpdateProgressResult(
176 input.targetVersion,
177 yield* Ref.get(terminal),
178 streamExit,
179 accepted,
180 );
181 })
182 : yield* client[WS_METHODS.serverUpdateServer](input).pipe(
183 // Older servers can drop the socket before acknowledging the restart.
184 Effect.catchCauseIf(
185 (cause) =>
186 (capabilities.serverSelfUpdate === "boot-service" ||
187 capabilities.serverSelfUpdate === "respawn") &&
188 isLegacyUpdateHandoffLoss(cause),
189 () =>
190 Effect.succeed({
191 targetVersion: input.targetVersion,
192 method: capabilities.serverSelfUpdate as "boot-service" | "respawn",
193 } satisfies ServerSelfUpdateResult),
194 ),
195 );
196
197 if (
198 updateResult.method === "desktop-app" &&
199 updateResult.desktopUpdateToken !== undefined
200 ) {
201 // The commit relaunches the desktop app, so a dropped socket is success.
202 yield* client[WS_METHODS.serverCommitDesktopUpdate]({
203 requestId: updateResult.desktopUpdateToken,
204 }).pipe(
205 Effect.catchCauseIf(
206 (cause) => isLegacyUpdateHandoffLoss(cause),
207 () => Effect.void,
208 ),
209 );
210 }
211 return updateResult;
212 }),
213 ).pipe(Effect.mapError(localizeServerSelfUpdateError));
214
215 yield* onStage("resuming");
216 const pollUrls = [
217 prepared.httpBaseUrl,
218 ...connectionRoutes(entry).flatMap((route) => routeHttpBaseUrl(route) ?? []),
219 ].filter((url, index, all) => all.indexOf(url) === index);
220 const resumed = yield* Effect.firstSuccessOf(
221 pollUrls.map((httpBaseUrl) =>
222 fetchRemoteEnvironmentDescriptor({ httpBaseUrl }).pipe(
223 Effect.filterOrFail(
224 (descriptor) =>
225 descriptor.environmentId === environmentId && isCompatibleDescriptor(descriptor),
226 () => "not-ready" as const,
227 ),
228 ),
229 ),
230 ).pipe(
231 Effect.provideService(HttpClient.HttpClient, httpClient),
232 Effect.option,
233 Effect.repeat({
234 schedule: Schedule.spaced(Duration.seconds(1)),
235 until: (current) => Option.exists(current, isCompatibleDescriptor),
236 }),
237 Effect.timeoutOption(OUTDATED_HOST_RESTART_TIMEOUT),
238 Effect.map(Option.flatten),
239 );
240 if (Option.isNone(resumed)) {
241 return yield* new OutdatedHostUpdateError({
242 environmentId,
243 ...translatableMessage(
244 msg("{host} did not come back on a compatible T3 Code version.", {
245 host: descriptor.label,
246 }),
247 ),
248 });
249 }
250
251 yield* switchBackOn;
252 return { ...result, targetVersion: resumed.value.serverVersion };
253 },
254 );
255
256 function isCompatibleDescriptor(descriptor: ExecutionEnvironmentDescriptor): boolean {
257 return (descriptor.orchestrationProtocolVersion ?? 1) === ORCHESTRATION_PROTOCOL_VERSION;
258 }