Open History to see the last commit
1import {
2 type EnvironmentId,
3 type ServerConfig,
4 type ServerConfigStreamEvent,
5 type ServerLifecycleWelcomePayload,
6 type ServerLifecycleStreamReadyEvent,
7 type ServerSelfUpdateProgressEvent,
8 type ServerSelfUpdateResult,
9 WS_METHODS,
10} from "@t3tools/contracts";
11import * as Cause from "effect/Cause";
12import * as Duration from "effect/Duration";
13import * as Deferred from "effect/Deferred";
14import * as Effect from "effect/Effect";
15import * as Exit from "effect/Exit";
16import * as Fiber from "effect/Fiber";
17import * as Option from "effect/Option";
18import * as Queue from "effect/Queue";
19import * as Ref from "effect/Ref";
20import * as Result from "effect/Result";
21import * as Schema from "effect/Schema";
22import * as Stream from "effect/Stream";
23import * as SubscriptionRef from "effect/SubscriptionRef";
24import { AsyncResult, Atom } from "effect/unstable/reactivity";
25
26import {
27 createAtomCommandScheduler,
28 createEnvironmentRpcCommand,
29 createEnvironmentQueryAtomFamily,
30 createEnvironmentRpcQueryAtomFamily,
31 createEnvironmentRpcSubscriptionAtomFamily,
32 createRuntimeCommand,
33 scheduleAtomCommandEffect,
34} from "./runtime.ts";
35import { EnvironmentRegistry } from "../connection/registry.ts";
36import { EnvironmentSupervisor } from "../connection/supervisor.ts";
37import { safeErrorLogAttributes } from "../errors/safeLog.ts";
38import { EnvironmentCacheStore } from "../platform/persistence.ts";
39import { runCachePersistence } from "./cachePersistence.ts";
40import {
41 isRpcClientError,
42 request,
43 runStream,
44 subscribe,
45 subscribeDynamicWithSession,
46 type EnvironmentRpcInput,
47} from "../rpc/client.ts";
48import type { RpcSession } from "../rpc/session.ts";
49import { followStreamInEnvironment } from "./runtime.ts";
50import {
51 applyServerConfigProjection,
52 type ServerConfigProjection,
53 withoutEnvironmentThemes,
54} from "./serverConfigProjection.ts";
55
56// Exported server state includes this type in its inferred public return type.
57export type { ServerConfigProjection } from "./serverConfigProjection.ts";
58
59export type ServerUpdateStage = "downloading" | "installing" | "resuming";
60
61export type ServerUpdateState =
62 | { readonly status: "idle" }
63 | {
64 readonly status: "running";
65 readonly stage: ServerUpdateStage;
66 readonly fromVersion: string;
67 readonly targetVersion: string;
68 }
69 | {
70 readonly status: "failed";
71 readonly stage: ServerUpdateStage;
72 readonly fromVersion: string;
73 readonly targetVersion: string;
74 readonly message: string;
75 };
76
77export interface ServerUpdateTarget {
78 readonly environmentId: EnvironmentId;
79 readonly input: EnvironmentRpcInput<typeof WS_METHODS.serverUpdateServer>;
80}
81
82const IDLE_SERVER_UPDATE_STATE: ServerUpdateState = { status: "idle" };
83const EMPTY_SERVER_UPDATE_STATE_ATOM = Atom.make<ServerUpdateState>(IDLE_SERVER_UPDATE_STATE).pipe(
84 Atom.withLabel("environment-data:server:update-state:empty"),
85);
86const serverUpdateStateAtom = Atom.family((environmentId: EnvironmentId) =>
87 Atom.make<ServerUpdateState>(IDLE_SERVER_UPDATE_STATE).pipe(
88 Atom.withLabel(`environment-data:server:update-state:${environmentId}`),
89 ),
90);
91
92export class ServerUpdateResumeTimeoutError extends Schema.TaggedError<ServerUpdateResumeTimeoutError>()(
93 "ServerUpdateResumeTimeoutError",
94 {
95 environmentId: Schema.String,
96 targetVersion: Schema.String,
97 },
98) {
99 override get message(): string {
100 return `The server did not resume on t3@${this.targetVersion}.`;
101 }
102}
103
104export class ServerUpdateProgressIncompleteError extends Schema.TaggedError<ServerUpdateProgressIncompleteError>()(
105 "ServerUpdateProgressIncompleteError",
106 {
107 targetVersion: Schema.String,
108 },
109) {
110 override get message(): string {
111 return `The t3@${this.targetVersion} update ended before the server accepted the restart.`;
112 }
113}
114
115export class ServerUpdateTerminalError extends Schema.TaggedError<ServerUpdateTerminalError>()(
116 "ServerUpdateTerminalError",
117 {
118 targetVersion: Schema.String,
119 status: Schema.Literals(["committed", "rolled-back", "failed"]),
120 reason: Schema.optional(Schema.String),
121 },
122) {
123 override get message(): string {
124 return this.reason ?? `The t3@${this.targetVersion} update ${this.status}.`;
125 }
126}
127
128// Covers the 120-second trial deadline and a final restart of the previous
129// version when the trial rolls back.
130const SERVER_UPDATE_RESUME_TIMEOUT = Duration.minutes(4);
131
132export function matchesServerUpdateReadyEvent(
133 result: ServerSelfUpdateResult,
134 event: ServerLifecycleStreamReadyEvent,
135): boolean {
136 return result.updateId === undefined
137 ? event.payload.environment.serverVersion === result.targetVersion
138 : event.payload.updateOutcome?.id === result.updateId;
139}
140
141export function matchesServerUpdateResumeEvent(
142 result: ServerSelfUpdateResult,
143 event: ServerLifecycleStreamReadyEvent,
144): boolean {
145 return (
146 (result.method === "desktop-app" && result.desktopUpdateToken !== undefined) ||
147 matchesServerUpdateReadyEvent(result, event)
148 );
149}
150
151export function validateServerUpdateReadyEvent(
152 result: ServerSelfUpdateResult,
153 event: ServerLifecycleStreamReadyEvent,
154): Effect.Effect<void, ServerUpdateTerminalError> {
155 if (result.updateId === undefined) return Effect.void;
156 const outcome = event.payload.updateOutcome;
157 if (
158 outcome?.id === result.updateId &&
159 outcome.status === "committed" &&
160 outcome.targetVersion === result.targetVersion &&
161 event.payload.environment.serverVersion === result.targetVersion
162 ) {
163 return Effect.void;
164 }
165 return Effect.fail(
166 new ServerUpdateTerminalError({
167 targetVersion: result.targetVersion,
168 status: outcome?.status ?? "failed",
169 reason:
170 outcome?.reason ??
171 "The service launcher resumed without committing the requested server version.",
172 }),
173 );
174}
175
176/**
177 * Keeps reconnect attempts ~1s apart for the whole update restart.
178 *
179 * A restart takes the server down for ~15 seconds, but the supervisor's normal
180 * backoff ladder (1/2/4/8/16s) assumes an unexpected failure and lands attempts
181 * at ~3, 5, 9, 17 and 33 seconds — so a 15-second restart is observed as a
182 * 33-second "Resuming". Nudging on every backoff entry (not just the first)
183 * holds the retry cadence flat until the server answers again. The sleep before
184 * each nudge is the pacer: a connection that fails instantly re-enters backoff
185 * immediately and would otherwise spin a tight retry loop.
186 *
187 * A newly restarted server can also reject the first environment credential.
188 * Authentication blocks need the same paced retry during this known restart;
189 * permission and configuration failures remain blocked.
190 *
191 * Callers fork this as a child of the update command so it is interrupted as
192 * soon as the update settles, whether it succeeds, fails, or times out.
193 */
194export function nudgeReconnectDuringUpdateRestart(input: {
195 readonly stateChanges: Stream.Stream<
196 {
197 readonly phase: string;
198 readonly lastFailure?: { readonly reason: string } | null;
199 },
200 unknown
201 >;
202 readonly retryNow: Effect.Effect<void>;
203 readonly interval?: Duration.Duration;
204}): Effect.Effect<void> {
205 return input.stateChanges.pipe(
206 Stream.filter(
207 (state) =>
208 state.phase === "backoff" ||
209 (state.phase === "blocked" && state.lastFailure?.reason === "authentication"),
210 ),
211 Stream.runForEach(() =>
212 Effect.sleep(input.interval ?? Duration.seconds(1)).pipe(Effect.andThen(input.retryNow)),
213 ),
214 Effect.timeoutOption(SERVER_UPDATE_RESUME_TIMEOUT),
215 Effect.ignore,
216 );
217}
218
219export function waitForNextEnvironmentReconnect<E>(
220 stateChanges: Stream.Stream<{ readonly phase: string }, E>,
221): Effect.Effect<void, E> {
222 return stateChanges.pipe(
223 Stream.dropWhile((state) => state.phase === "connected"),
224 Stream.filter((state) => state.phase === "connected"),
225 Stream.runHead,
226 Effect.asVoid,
227 );
228}
229
230export const runDesktopCommitWithReconnectObserver = Effect.fn(
231 "runDesktopCommitWithReconnectObserver",
232)(function* <EState, ECommit>(
233 stateChanges: Stream.Stream<{ readonly phase: string }, EState>,
234 commit: Effect.Effect<void, ECommit>,
235) {
236 const armed = yield* Deferred.make<void>();
237 const reconnected = yield* Deferred.make<void>();
238 const observer = yield* stateChanges.pipe(
239 Stream.tap(() => Deferred.succeed(armed, undefined)),
240 waitForNextEnvironmentReconnect,
241 Effect.andThen(Deferred.succeed(reconnected, undefined)),
242 Effect.forkChild,
243 );
244 yield* Deferred.await(armed);
245 const commitExit = yield* commit.pipe(Effect.exit);
246 if (Exit.isSuccess(commitExit)) {
247 yield* Fiber.interrupt(observer);
248 return;
249 }
250 if (!isLegacyUpdateHandoffLoss(commitExit.cause)) {
251 yield* Fiber.interrupt(observer);
252 return yield* Effect.failCause(commitExit.cause);
253 }
254 yield* Deferred.await(reconnected).pipe(Effect.timeout(SERVER_UPDATE_RESUME_TIMEOUT));
255 return yield* Effect.failCause(commitExit.cause);
256});
257
258export const waitForDesktopUpdateTarget = Effect.fn("waitForDesktopUpdateTarget")(function* <
259 EReady,
260 ECommit,
261>(
262 targetVersion: string,
263 nextReady: Effect.Effect<ServerLifecycleStreamReadyEvent, EReady>,
264 retryCommit: Effect.Effect<void, ECommit>,
265 maxCommitAttempts = 3,
266): Effect.fn.Return<ServerLifecycleStreamReadyEvent, EReady | ECommit | ServerUpdateTerminalError> {
267 for (let attempt = 1; attempt <= maxCommitAttempts; attempt += 1) {
268 const ready = yield* nextReady;
269 if (ready.payload.environment.serverVersion === targetVersion) return ready;
270 if (attempt === maxCommitAttempts) break;
271 const retryExit = yield* retryCommit.pipe(Effect.exit);
272 if (Exit.isSuccess(retryExit)) break;
273 if (!isLegacyUpdateHandoffLoss(retryExit.cause)) {
274 return yield* Effect.failCause(retryExit.cause);
275 }
276 }
277 return yield* new ServerUpdateTerminalError({
278 targetVersion,
279 status: "failed",
280 reason: "The desktop app resumed without installing the prepared update.",
281 });
282});
283
284export function serverUpdateStateForProgressEvent(
285 fromVersion: string,
286 targetVersion: string,
287 event: ServerSelfUpdateProgressEvent,
288): Extract<ServerUpdateState, { status: "running" }> {
289 return {
290 status: "running",
291 stage: event.type === "complete" ? "resuming" : event.stage,
292 fromVersion,
293 targetVersion,
294 };
295}
296
297export function serverUpdateStateForServerVersion(
298 state: ServerUpdateState,
299 serverVersion: string | null,
300): ServerUpdateState {
301 return state.status === "idle" ||
302 state.status === "running" ||
303 serverVersion === null ||
304 state.fromVersion === serverVersion
305 ? state
306 : IDLE_SERVER_UPDATE_STATE;
307}
308
309function serverUpdateFailureMessage(error: unknown): string {
310 return error instanceof Error ? error.message : "Server update failed.";
311}
312
313function isRpcSocketError(error: unknown): boolean {
314 if (!isRpcClientError(error)) {
315 return false;
316 }
317 switch (error.reason._tag) {
318 case "SocketReadError":
319 case "SocketWriteError":
320 case "SocketCloseError":
321 return true;
322 default:
323 return false;
324 }
325}
326
327export function isLegacyUpdateHandoffLoss(cause: Cause.Cause<unknown>): boolean {
328 if (Cause.hasInterruptsOnly(cause)) {
329 return true;
330 }
331 return (
332 cause.reasons.length > 0 &&
333 cause.reasons.every((reason) => Cause.isFailReason(reason) && isRpcSocketError(reason.error))
334 );
335}
336
337export function resolveServerUpdateProgressResult<E>(
338 targetVersion: string,
339 terminal: Option.Option<ServerSelfUpdateResult>,
340 streamExit: Exit.Exit<void, E>,
341): Effect.Effect<ServerSelfUpdateResult, E | ServerUpdateProgressIncompleteError> {
342 if (
343 Option.isSome(terminal) &&
344 (Exit.isSuccess(streamExit) || isLegacyUpdateHandoffLoss(streamExit.cause))
345 ) {
346 return Effect.succeed(terminal.value);
347 }
348 if (Exit.isFailure(streamExit)) {
349 return Effect.failCause(streamExit.cause);
350 }
351 return Effect.fail(new ServerUpdateProgressIncompleteError({ targetVersion }));
352}
353
354const cachedConfigSnapshotEvent = (config: ServerConfig): ServerConfigStreamEvent => ({
355 version: 1,
356 type: "snapshot",
357 config,
358});
359
360export interface ServerConfigSubscriptionOptions {
361 readonly environmentThemes?: boolean;
362 readonly usageLimitSources?: boolean;
363 readonly usageLimitsCommand?: boolean;
364}
365
366export const makeEnvironmentServerConfigState = Effect.fn("EnvironmentServerConfigState.make")(
367 function* (subscription: ServerConfigSubscriptionOptions) {
368 const supervisor = yield* EnvironmentSupervisor;
369 const cache = yield* EnvironmentCacheStore;
370 const environmentId = supervisor.target.environmentId;
371 const cachedConfig = yield* cache.loadServerConfig(environmentId).pipe(
372 Effect.catch((error) =>
373 Effect.logWarning("Could not load cached server configuration.").pipe(
374 Effect.annotateLogs({
375 environmentId,
376 ...safeErrorLogAttributes(error),
377 }),
378 Effect.as(Option.none<ServerConfig>()),
379 ),
380 ),
381 );
382 const state = yield* SubscriptionRef.make<Option.Option<ServerConfigProjection>>(
383 // Stripped on load as well as on save: a cache written by an earlier
384 // build can still carry published themes.
385 Option.map(cachedConfig, (cached) => ({
386 config: withoutEnvironmentThemes(cached),
387 latestEvent: cachedConfigSnapshotEvent(withoutEnvironmentThemes(cached)),
388 source: "cache" as const,
389 })),
390 );
391 const persistence = yield* Queue.sliding<ServerConfig>(1);
392 const pendingPersistence = yield* Ref.make<Option.Option<ServerConfig>>(Option.none());
393
394 const persist = Effect.fn("EnvironmentServerConfigState.persist")(function* (
395 config: ServerConfig,
396 ) {
397 return yield* cache.saveServerConfig(environmentId, withoutEnvironmentThemes(config)).pipe(
398 Effect.as(true),
399 Effect.catch((error) =>
400 Effect.logWarning("Could not persist cached server configuration.").pipe(
401 Effect.annotateLogs({
402 environmentId,
403 ...safeErrorLogAttributes(error),
404 }),
405 Effect.as(false),
406 ),
407 ),
408 );
409 });
410
411 const persistPending = Effect.fn("EnvironmentServerConfigState.persistPending")(function* (
412 config: ServerConfig,
413 ) {
414 if (!(yield* persist(config))) {
415 return;
416 }
417 yield* Ref.update(pendingPersistence, (pending) =>
418 Option.isSome(pending) && pending.value === config ? Option.none() : pending,
419 );
420 });
421
422 yield* Effect.addFinalizer(() =>
423 Ref.get(pendingPersistence).pipe(
424 Effect.flatMap(
425 Option.match({
426 onNone: () => Effect.void,
427 onSome: (config) => persist(config).pipe(Effect.asVoid),
428 }),
429 ),
430 ),
431 );
432
433 yield* runCachePersistence(persistence, persistPending).pipe(Effect.forkScoped);
434
435 yield* subscribe(WS_METHODS.subscribeServerConfig, {
436 ...(subscription.environmentThemes === true ? { environmentThemes: true } : {}),
437 ...(subscription.usageLimitSources === true ? { usageLimitSources: true } : {}),
438 ...(subscription.usageLimitsCommand === true ? { usageLimitsCommand: true } : {}),
439 }).pipe(
440 Stream.runForEach((event) =>
441 Effect.gen(function* () {
442 const next = applyServerConfigProjection(yield* SubscriptionRef.get(state), event);
443 if (Option.isNone(next)) {
444 return;
445 }
446 yield* Ref.set(pendingPersistence, Option.some(next.value.config));
447 yield* SubscriptionRef.set(state, next);
448 yield* Queue.offer(persistence, next.value.config);
449 }),
450 ),
451 Effect.forkScoped,
452 );
453
454 return state;
455 },
456);
457
458function serverConfigStateChanges(
459 environmentId: EnvironmentId,
460 subscription: ServerConfigSubscriptionOptions,
461) {
462 return followStreamInEnvironment(
463 environmentId,
464 Stream.unwrap(
465 makeEnvironmentServerConfigState(subscription).pipe(
466 Effect.map((state) =>
467 SubscriptionRef.changes(state).pipe(
468 Stream.filterMap((projection) =>
469 Option.match(projection, {
470 onNone: () => Result.failVoid,
471 onSome: (value) => Result.succeed(value),
472 }),
473 ),
474 ),
475 ),
476 ),
477 ),
478 );
479}
480
481export function applyServerWelcomeEvent(
482 current: EnvironmentServerWelcomeState,
483 session: RpcSession,
484 event: {
485 readonly type: "welcome" | "ready" | "legacyThreadMigration";
486 readonly payload: unknown;
487 },
488): EnvironmentServerWelcomeState {
489 return event.type === "welcome" && current.currentSession === session
490 ? {
491 ...current,
492 welcomeSession: session,
493 welcome: event.payload as ServerLifecycleWelcomePayload,
494 }
495 : current;
496}
497
498export interface EnvironmentServerWelcomeState {
499 readonly currentSession: RpcSession | null;
500 readonly welcomeSession: RpcSession | null;
501 readonly welcome: ServerLifecycleWelcomePayload | null;
502}
503
504export function resolveServerWelcomeState(
505 state: EnvironmentServerWelcomeState,
506): ServerLifecycleWelcomePayload | null {
507 return state.currentSession === state.welcomeSession ? state.welcome : null;
508}
509
510export const makeEnvironmentServerWelcomeState = Effect.fn("EnvironmentServerWelcomeState.make")(
511 function* () {
512 const supervisor = yield* EnvironmentSupervisor;
513 const initialSession = Option.getOrNull(yield* SubscriptionRef.get(supervisor.session));
514 const state = yield* SubscriptionRef.make<EnvironmentServerWelcomeState>({
515 currentSession: initialSession,
516 welcomeSession: null,
517 welcome: null,
518 });
519
520 const updateWithCurrentSession = Effect.fn(
521 "EnvironmentServerWelcomeState.updateWithCurrentSession",
522 )(function* (
523 update: (
524 current: EnvironmentServerWelcomeState,
525 currentSession: RpcSession | null,
526 ) => EnvironmentServerWelcomeState,
527 ) {
528 return yield* SubscriptionRef.modifyEffect(state, (current) =>
529 SubscriptionRef.get(supervisor.session).pipe(
530 Effect.map(
531 (latestSession) =>
532 [undefined, update(current, Option.getOrNull(latestSession))] as const,
533 ),
534 ),
535 );
536 });
537
538 yield* SubscriptionRef.changes(supervisor.session).pipe(
539 Stream.runForEach(() =>
540 updateWithCurrentSession((current, currentSession) => ({
541 ...current,
542 currentSession,
543 })),
544 ),
545 Effect.forkScoped,
546 );
547
548 yield* subscribeDynamicWithSession(
549 WS_METHODS.subscribeServerLifecycle,
550 Effect.fn("EnvironmentServerWelcomeState.makeSubscribeInput")(function* (session) {
551 yield* updateWithCurrentSession((current, currentSession) =>
552 currentSession === session
553 ? {
554 ...current,
555 currentSession,
556 welcomeSession: session,
557 welcome: null,
558 }
559 : { ...current, currentSession },
560 );
561 return {};
562 }),
563 ).pipe(
564 Stream.runForEach(([session, event]) =>
565 updateWithCurrentSession((current, currentSession) =>
566 applyServerWelcomeEvent(
567 {
568 ...current,
569 currentSession,
570 },
571 session,
572 event,
573 ),
574 ),
575 ),
576 Effect.forkScoped,
577 );
578
579 return state;
580 },
581);
582
583function serverWelcomeStateChanges(environmentId: EnvironmentId) {
584 return followStreamInEnvironment(
585 environmentId,
586 Stream.unwrap(
587 makeEnvironmentServerWelcomeState().pipe(
588 Effect.map((state) =>
589 SubscriptionRef.changes(state).pipe(Stream.map(resolveServerWelcomeState)),
590 ),
591 ),
592 ),
593 );
594}
595
596export function resolveServerConfigValue(
597 projection: ServerConfigProjection | null,
598 initialConfig: ServerConfig | null,
599): ServerConfig | null {
600 if (
601 projection?.source === "live" &&
602 (initialConfig === null ||
603 projection.config.environment.serverVersion === initialConfig.environment.serverVersion)
604 ) {
605 return projection.config;
606 }
607 return initialConfig ?? projection?.config ?? null;
608}
609
610export function createServerEnvironmentAtoms<R, E>(
611 runtime: Atom.AtomRuntime<EnvironmentRegistry | EnvironmentCacheStore | R, E>,
612 options: {
613 readonly initialConfigValueAtom: (
614 environmentId: EnvironmentId,
615 ) => Atom.Atom<ServerConfig | null>;
616 /**
617 * Whether this surface renders themes the environment publishes. Mobile
618 * keeps its own appearance settings, so it neither asks for the stream nor
619 * receives the payload.
620 */
621 readonly environmentThemes?: boolean;
622 /** Whether this surface renders quota from configured usage-limit sources. */
623 readonly usageLimitSources?: boolean;
624 readonly usageLimitsCommand?: boolean;
625 },
626) {
627 const configScheduler = createAtomCommandScheduler();
628 // Updates stay serial end-to-end, but only their handoff phase occupies the config lane.
629 const updateScheduler = createAtomCommandScheduler();
630 const configConcurrency = {
631 mode: "serial" as const,
632 key: ({ environmentId }: { readonly environmentId: string }) => environmentId,
633 };
634 const configProjectionFamily = Atom.family((environmentId: EnvironmentId) =>
635 runtime
636 .atom(
637 serverConfigStateChanges(environmentId, {
638 ...(options.environmentThemes === true ? { environmentThemes: true } : {}),
639 ...(options.usageLimitSources === true ? { usageLimitSources: true } : {}),
640 ...(options.usageLimitsCommand === true ? { usageLimitsCommand: true } : {}),
641 }),
642 )
643 .pipe(
644 Atom.setIdleTTL(5 * 60_000),
645 Atom.withLabel(`environment-data:server:config-projection:${environmentId}`),
646 ),
647 );
648 const configProjection = (target: {
649 readonly environmentId: EnvironmentId;
650 readonly input: EnvironmentRpcInput<typeof WS_METHODS.subscribeServerConfig>;
651 }) => configProjectionFamily(target.environmentId);
652 const emptyConfigAtom = Atom.make<ServerConfig | null>(null).pipe(
653 Atom.withLabel("environment-data:server:config:empty"),
654 );
655 const configValueAtom = Atom.family((environmentId: EnvironmentId | null) => {
656 if (environmentId === null) {
657 return emptyConfigAtom;
658 }
659 return Atom.make((get): ServerConfig | null => {
660 const projection = Option.getOrNull(
661 AsyncResult.value(get(configProjection({ environmentId, input: {} }))),
662 );
663 return resolveServerConfigValue(
664 projection,
665 get(options.initialConfigValueAtom(environmentId)),
666 );
667 }).pipe(Atom.withLabel(`environment-data:server:config:${environmentId}`));
668 });
669 const updateStateValueAtom = Atom.family((environmentId: EnvironmentId) =>
670 Atom.make((get) =>
671 serverUpdateStateForServerVersion(
672 get(serverUpdateStateAtom(environmentId)),
673 get(configValueAtom(environmentId))?.environment.serverVersion ?? null,
674 ),
675 ).pipe(Atom.withLabel(`environment-data:server:update-state-value:${environmentId}`)),
676 );
677 const updateStateAtom = (environmentId: EnvironmentId | null) =>
678 environmentId === null ? EMPTY_SERVER_UPDATE_STATE_ATOM : updateStateValueAtom(environmentId);
679 const updateServer = createRuntimeCommand<
680 EnvironmentRegistry | EnvironmentCacheStore | R,
681 E,
682 ServerUpdateTarget,
683 ServerSelfUpdateResult,
684 unknown
685 >(runtime, {
686 label: "environment-data:server:update-server",
687 scheduler: updateScheduler,
688 concurrency: configConcurrency,
689 execute: (target, atomRegistry) => {
690 const stateAtom = serverUpdateStateAtom(target.environmentId);
691 let targetVersion = target.input.targetVersion;
692 let fromVersion =
693 atomRegistry.get(configValueAtom(target.environmentId))?.environment.serverVersion ??
694 targetVersion;
695 let currentStage: ServerUpdateStage = "downloading";
696 let desktopCommitLostTransport = false;
697 atomRegistry.set(stateAtom, {
698 status: "running",
699 stage: currentStage,
700 fromVersion,
701 targetVersion,
702 });
703
704 return Effect.gen(function* () {
705 const environmentRegistry = yield* EnvironmentRegistry;
706 const desktopCommitStarting = yield* Deferred.make<void>();
707 const desktopReconnectObserverArmed = yield* Deferred.make<void>();
708 const desktopReconnected = yield* Deferred.make<void>();
709 yield* Deferred.await(desktopCommitStarting).pipe(
710 Effect.andThen(
711 environmentRegistry.stateChanges(target.environmentId).pipe(
712 Stream.tap(() => Deferred.succeed(desktopReconnectObserverArmed, undefined)),
713 Stream.dropWhile((state) => state.phase === "connected"),
714 Stream.filter((state) => state.phase === "connected"),
715 Stream.runHead,
716 ),
717 ),
718 Effect.andThen(Deferred.succeed(desktopReconnected, undefined)),
719 Effect.forkChild,
720 );
721 const result = yield* scheduleAtomCommandEffect(
722 atomRegistry,
723 configScheduler,
724 configConcurrency,
725 target,
726 Effect.gen(function* () {
727 const currentConfig = atomRegistry.get(configValueAtom(target.environmentId));
728 fromVersion = currentConfig?.environment.serverVersion ?? targetVersion;
729 atomRegistry.set(stateAtom, {
730 status: "running",
731 stage: currentStage,
732 fromVersion,
733 targetVersion,
734 });
735
736 const supportsProgress =
737 currentConfig?.environment.capabilities.serverSelfUpdateProgress === true;
738 const updateResult: ServerSelfUpdateResult = supportsProgress
739 ? yield* Effect.gen(function* () {
740 const terminal = yield* Ref.make<Option.Option<ServerSelfUpdateResult>>(
741 Option.none(),
742 );
743 const streamExit = yield* environmentRegistry
744 .runStream(
745 target.environmentId,
746 runStream(WS_METHODS.serverUpdateServerWithProgress, target.input),
747 )
748 .pipe(
749 Stream.runForEach((event) =>
750 Effect.sync(() => {
751 currentStage = event.type === "complete" ? "resuming" : event.stage;
752 atomRegistry.set(
753 stateAtom,
754 serverUpdateStateForProgressEvent(fromVersion, targetVersion, event),
755 );
756 }).pipe(
757 Effect.andThen(
758 event.type === "complete"
759 ? Ref.set(terminal, Option.some(event.result))
760 : Effect.void,
761 ),
762 ),
763 ),
764 Effect.exit,
765 );
766 return yield* resolveServerUpdateProgressResult(
767 targetVersion,
768 yield* Ref.get(terminal),
769 streamExit,
770 );
771 })
772 : yield* Effect.gen(function* () {
773 const selfUpdateMethod = currentConfig?.environment.capabilities.serverSelfUpdate;
774 const exit = yield* environmentRegistry
775 .run(target.environmentId, request(WS_METHODS.serverUpdateServer, target.input))
776 .pipe(Effect.exit);
777 if (Exit.isSuccess(exit)) {
778 return exit.value;
779 }
780 if (
781 (selfUpdateMethod === "boot-service" || selfUpdateMethod === "respawn") &&
782 isLegacyUpdateHandoffLoss(exit.cause)
783 ) {
784 // Older servers can tear down the transport before their
785 // unary acknowledgement arrives. Treat only that transport
786 // loss as a handoff, then prove it by waiting for target ready.
787 return { targetVersion, method: selfUpdateMethod };
788 }
789 return yield* Effect.failCause(exit.cause);
790 });
791
792 if (
793 updateResult.method === "desktop-app" &&
794 updateResult.desktopUpdateToken !== undefined
795 ) {
796 yield* Deferred.succeed(desktopCommitStarting, undefined);
797 yield* Deferred.await(desktopReconnectObserverArmed);
798 const commitExit = yield* environmentRegistry
799 .run(
800 target.environmentId,
801 request(WS_METHODS.serverCommitDesktopUpdate, {
802 requestId: updateResult.desktopUpdateToken,
803 }),
804 )
805 .pipe(Effect.exit);
806 if (Exit.isFailure(commitExit) && !isLegacyUpdateHandoffLoss(commitExit.cause)) {
807 return yield* Effect.failCause(commitExit.cause);
808 }
809 desktopCommitLostTransport = Exit.isFailure(commitExit);
810 }
811
812 targetVersion = updateResult.targetVersion;
813
814 currentStage = "resuming";
815 atomRegistry.set(stateAtom, {
816 status: "running",
817 stage: currentStage,
818 fromVersion,
819 targetVersion,
820 });
821 return updateResult;
822 }),
823 );
824
825 // The update restart is intentional and the server stays unreachable
826 // for the whole restart, so hold the retry cadence flat instead of
827 // letting the supervisor climb its backoff ladder.
828 yield* nudgeReconnectDuringUpdateRestart({
829 stateChanges: environmentRegistry.stateChanges(target.environmentId),
830 retryNow: environmentRegistry.retryNow(target.environmentId),
831 }).pipe(Effect.forkChild);
832
833 if (result.method === "desktop-app" && desktopCommitLostTransport) {
834 yield* Deferred.await(desktopReconnected).pipe(
835 Effect.timeout(SERVER_UPDATE_RESUME_TIMEOUT),
836 );
837 }
838
839 const waitForReady = environmentRegistry
840 .followStream(target.environmentId, subscribe(WS_METHODS.subscribeServerLifecycle, {}))
841 .pipe(
842 Stream.filter(
843 (event): event is ServerLifecycleStreamReadyEvent =>
844 event.type === "ready" && matchesServerUpdateResumeEvent(result, event),
845 ),
846 Stream.runHead,
847 Effect.timeoutOption(SERVER_UPDATE_RESUME_TIMEOUT),
848 Effect.map(Option.flatten),
849 );
850 const nextReady = waitForReady.pipe(
851 Effect.flatMap(
852 Option.match({
853 onNone: () =>
854 new ServerUpdateResumeTimeoutError({
855 environmentId: target.environmentId,
856 targetVersion,
857 }),
858 onSome: Effect.succeed,
859 }),
860 ),
861 );
862 const desktopUpdateToken = result.desktopUpdateToken;
863 const resumed =
864 result.method === "desktop-app" && desktopUpdateToken !== undefined
865 ? yield* waitForDesktopUpdateTarget(
866 result.targetVersion,
867 nextReady,
868 runDesktopCommitWithReconnectObserver(
869 environmentRegistry.stateChanges(target.environmentId),
870 environmentRegistry
871 .run(
872 target.environmentId,
873 request(WS_METHODS.serverCommitDesktopUpdate, {
874 requestId: desktopUpdateToken,
875 }),
876 )
877 .pipe(Effect.asVoid),
878 ),
879 )
880 : yield* nextReady;
881 yield* validateServerUpdateReadyEvent(result, resumed);
882
883 atomRegistry.set(stateAtom, IDLE_SERVER_UPDATE_STATE);
884 return result;
885 }).pipe(
886 Effect.onExit((exit) =>
887 Effect.sync(() => {
888 if (Exit.isSuccess(exit)) {
889 return;
890 }
891 if (Cause.hasInterruptsOnly(exit.cause)) {
892 atomRegistry.set(stateAtom, IDLE_SERVER_UPDATE_STATE);
893 return;
894 }
895 atomRegistry.set(stateAtom, {
896 status: "failed",
897 stage: currentStage,
898 fromVersion,
899 targetVersion,
900 message: serverUpdateFailureMessage(Cause.squash(exit.cause)),
901 });
902 }),
903 ),
904 );
905 },
906 });
907 const settingsValueAtom = Atom.family((environmentId: EnvironmentId) =>
908 Atom.make((get) => get(configValueAtom(environmentId))?.settings ?? null).pipe(
909 Atom.withLabel(`environment-data:server:settings:${environmentId}`),
910 ),
911 );
912 const usagePricesAtom = Atom.family((environmentId: EnvironmentId) =>
913 Atom.make((get) => {
914 const overrides = get(settingsValueAtom(environmentId))?.usagePriceOverrides ?? {};
915 // Only changed prices should trigger another transcript scan. Settings
916 // snapshots can recreate the same mapping in a different property order.
917 return JSON.stringify(
918 Object.keys(overrides)
919 .sort()
920 .map((model) => {
921 const price = overrides[model]!;
922 return [
923 model,
924 price.inputCostPerMillionTokens,
925 price.outputCostPerMillionTokens,
926 price.cacheReadCostPerMillionTokens,
927 price.cacheWriteCostPerMillionTokens,
928 ];
929 }),
930 );
931 }).pipe(Atom.withLabel(`environment-data:server:usage-prices:${environmentId}`)),
932 );
933 const providersValueAtom = Atom.family((environmentId: EnvironmentId) =>
934 Atom.make((get) => get(configValueAtom(environmentId))?.providers ?? null).pipe(
935 Atom.withLabel(`environment-data:server:providers:${environmentId}`),
936 ),
937 );
938 const welcomeStateFamily = Atom.family((environmentId: EnvironmentId) =>
939 runtime
940 .atom(serverWelcomeStateChanges(environmentId), { initialValue: null })
941 .pipe(
942 Atom.setIdleTTL(5 * 60_000),
943 Atom.withLabel(`environment-data:server:welcome-state:${environmentId}`),
944 ),
945 );
946 const welcomeFamily = Atom.family((environmentId: EnvironmentId) =>
947 Atom.make((get) => {
948 const result = get(welcomeStateFamily(environmentId));
949 if (result._tag !== "Success") return result;
950 return result.value === null
951 ? AsyncResult.initial<ServerLifecycleWelcomePayload, never>(result.waiting)
952 : AsyncResult.success(result.value, result);
953 }).pipe(Atom.withLabel(`environment-data:server:welcome:${environmentId}`)),
954 );
955 const welcome = (target: {
956 readonly environmentId: EnvironmentId;
957 readonly input: EnvironmentRpcInput<typeof WS_METHODS.subscribeServerLifecycle>;
958 }) => welcomeFamily(target.environmentId);
959 const updateSettings = createEnvironmentRpcCommand(runtime, {
960 label: "environment-data:server:update-settings",
961 tag: WS_METHODS.serverUpdateSettings,
962 scheduler: configScheduler,
963 concurrency: configConcurrency,
964 });
965
966 return {
967 configValueAtom,
968 updateStateAtom,
969 settingsValueAtom,
970 providersValueAtom,
971 providerAuthState: createEnvironmentRpcSubscriptionAtomFamily(runtime, {
972 label: "environment-data:provider:auth-state",
973 tag: WS_METHODS.providerAuthSubscribe,
974 idleTtlMs: 0,
975 }),
976 startProviderAuth: createEnvironmentRpcCommand(runtime, {
977 label: "environment-data:provider:auth-start",
978 tag: WS_METHODS.providerAuthStart,
979 concurrency: {
980 mode: "singleFlight",
981 key: ({ environmentId, input }) => JSON.stringify([environmentId, input]),
982 },
983 }),
984 completeProviderAuth: createEnvironmentRpcCommand(runtime, {
985 label: "environment-data:provider:auth-complete",
986 tag: WS_METHODS.providerAuthComplete,
987 }),
988 cancelProviderAuth: createEnvironmentRpcCommand(runtime, {
989 label: "environment-data:provider:auth-cancel",
990 tag: WS_METHODS.providerAuthCancel,
991 }),
992 logoutProviderAuth: createEnvironmentRpcCommand(runtime, {
993 label: "environment-data:provider:auth-logout",
994 tag: WS_METHODS.providerAuthLogout,
995 }),
996 providerInstallState: createEnvironmentRpcSubscriptionAtomFamily(runtime, {
997 label: "environment-data:provider:install-state",
998 tag: WS_METHODS.providerInstallSubscribe,
999 idleTtlMs: 0,
1000 }),
1001 startProviderInstall: createEnvironmentRpcCommand(runtime, {
1002 label: "environment-data:provider:install-start",
1003 tag: WS_METHODS.providerInstallStart,
1004 concurrency: {
1005 mode: "singleFlight",
1006 key: ({ environmentId }) => environmentId,
1007 },
1008 }),
1009 cancelProviderInstall: createEnvironmentRpcCommand(runtime, {
1010 label: "environment-data:provider:install-cancel",
1011 tag: WS_METHODS.providerInstallCancel,
1012 }),
1013 removeProviderInstallation: createEnvironmentRpcCommand(runtime, {
1014 label: "environment-data:provider:install-remove",
1015 tag: WS_METHODS.providerInstallRemove,
1016 }),
1017 traceDiagnostics: createEnvironmentRpcQueryAtomFamily(runtime, {
1018 label: "environment-data:server:trace-diagnostics",
1019 tag: WS_METHODS.serverGetTraceDiagnostics,
1020 }),
1021 processDiagnostics: createEnvironmentRpcQueryAtomFamily(runtime, {
1022 label: "environment-data:server:process-diagnostics",
1023 tag: WS_METHODS.serverGetProcessDiagnostics,
1024 }),
1025 hostResources: createEnvironmentQueryAtomFamily(runtime, {
1026 label: "environment-data:server:host-resources",
1027 idleTtlMs: 0,
1028 staleTimeMs: 5_000,
1029 execute: (input: EnvironmentRpcInput<typeof WS_METHODS.serverGetHostResources>) =>
1030 request(WS_METHODS.serverGetHostResources, input).pipe(Effect.timeout("5 seconds")),
1031 }),
1032 processResourceHistory: createEnvironmentRpcQueryAtomFamily(runtime, {
1033 label: "environment-data:server:process-resource-history",
1034 tag: WS_METHODS.serverGetProcessResourceHistory,
1035 }),
1036 /** Live scheduled-task list: snapshot on subscribe, fresh list after every server-side change. */
1037 scheduledTasksLive: createEnvironmentRpcSubscriptionAtomFamily(runtime, {
1038 label: "environment-data:server:scheduled-tasks:live",
1039 tag: WS_METHODS.scheduledTasksSubscribe,
1040 }),
1041 // A cold transcript scan is measured in seconds, so keep the result around
1042 // long enough that switching windows or re-rendering does not rescan.
1043 usageSummary: createEnvironmentRpcQueryAtomFamily(runtime, {
1044 label: "environment-data:server:usage-summary",
1045 tag: WS_METHODS.serverGetUsageSummary,
1046 staleTimeMs: 60_000,
1047 refreshTrigger: ({ environmentId }) => usagePricesAtom(environmentId),
1048 }),
1049 resourceTelemetry: createEnvironmentRpcSubscriptionAtomFamily(runtime, {
1050 label: "environment-data:server:resource-telemetry",
1051 tag: WS_METHODS.subscribeResourceTelemetry,
1052 idleTtlMs: 0,
1053 }),
1054 resourceTelemetryHistory: createEnvironmentRpcQueryAtomFamily(runtime, {
1055 label: "environment-data:server:resource-telemetry-history",
1056 tag: WS_METHODS.serverGetResourceTelemetryHistory,
1057 staleTimeMs: 5_000,
1058 }),
1059 searchAcpRegistry: createEnvironmentRpcQueryAtomFamily(runtime, {
1060 label: "environment-data:server:acp-registry:search",
1061 tag: WS_METHODS.serverSearchAcpRegistry,
1062 // Each submitted search refreshes the server-side registry. Dropping an
1063 // abandoned query immediately also interrupts stale in-flight requests.
1064 staleTimeMs: 0,
1065 idleTtlMs: 0,
1066 }),
1067 configProjection,
1068 welcome,
1069 legacyThreadMigration: createEnvironmentRpcSubscriptionAtomFamily(runtime, {
1070 label: "environment-data:server:legacy-thread-migration",
1071 tag: WS_METHODS.subscribeServerLifecycle,
1072 transform: (stream) =>
1073 stream.pipe(
1074 Stream.filterMap((event) =>
1075 event.type === "legacyThreadMigration"
1076 ? Result.succeed(event.payload)
1077 : Result.failVoid,
1078 ),
1079 ),
1080 }),
1081 consumeResetCredit: createEnvironmentRpcCommand(runtime, {
1082 label: "environment-data:server:consume-reset-credit",
1083 tag: WS_METHODS.providerConsumeResetCredit,
1084 concurrency: {
1085 mode: "singleFlight",
1086 // Both ids are free-form strings; a delimiter could collide.
1087 key: ({ environmentId, input }) => JSON.stringify([environmentId, input]),
1088 },
1089 }),
1090 refreshProviders: createEnvironmentRpcCommand(runtime, {
1091 label: "environment-data:server:refresh-providers",
1092 tag: WS_METHODS.serverRefreshProviders,
1093 concurrency: {
1094 mode: "singleFlight",
1095 key: ({ environmentId, input }) =>
1096 JSON.stringify([
1097 environmentId,
1098 input.instanceId ?? null,
1099 input.cwd ?? null,
1100 input.refreshModels ?? false,
1101 ]),
1102 },
1103 }),
1104 updateProvider: createEnvironmentRpcCommand(runtime, {
1105 label: "environment-data:server:update-provider",
1106 tag: WS_METHODS.serverUpdateProvider,
1107 scheduler: configScheduler,
1108 concurrency: configConcurrency,
1109 }),
1110 updateServer,
1111 upsertKeybinding: createEnvironmentRpcCommand(runtime, {
1112 label: "environment-data:server:upsert-keybinding",
1113 tag: WS_METHODS.serverUpsertKeybinding,
1114 scheduler: configScheduler,
1115 concurrency: configConcurrency,
1116 }),
1117 removeKeybinding: createEnvironmentRpcCommand(runtime, {
1118 label: "environment-data:server:remove-keybinding",
1119 tag: WS_METHODS.serverRemoveKeybinding,
1120 scheduler: configScheduler,
1121 concurrency: configConcurrency,
1122 }),
1123 updateSettings,
1124 // Provider-instance mutations share the settings command and its
1125 // environment-serial scheduler. The named boundary keeps clients on the
1126 // atomic map-entry payload instead of rebuilding a stale whole map.
1127 mutateProviderInstance: updateSettings,
1128 prepareAcpRegistryAgent: createEnvironmentRpcCommand(runtime, {
1129 label: "environment-data:server:acp-registry:prepare",
1130 tag: WS_METHODS.serverPrepareAcpRegistryAgent,
1131 concurrency: {
1132 mode: "singleFlight",
1133 key: ({ environmentId, input }) => `${environmentId}:${input.agentId}`,
1134 },
1135 }),
1136 uninstallAcpRegistryManagedBinary: createEnvironmentRpcCommand(runtime, {
1137 label: "environment-data:server:acp-registry:uninstall-managed-binary",
1138 tag: WS_METHODS.serverUninstallAcpRegistryManagedBinary,
1139 concurrency: {
1140 mode: "singleFlight",
1141 key: ({ environmentId, input }) => `${environmentId}:${input.agentId}`,
1142 },
1143 }),
1144 acceptAcpRegistryUrlAuth: createEnvironmentRpcCommand(runtime, {
1145 label: "environment-data:server:acp-registry:accept-url-auth",
1146 tag: WS_METHODS.serverAcceptAcpRegistryUrlAuth,
1147 concurrency: {
1148 mode: "singleFlight",
1149 key: ({ environmentId, input }) =>
1150 `${environmentId}:${input.instanceId}:${input.elicitationId}`,
1151 },
1152 }),
1153 listAcpRegistrySessions: createEnvironmentRpcCommand(runtime, {
1154 label: "environment-data:server:acp-registry:list-sessions",
1155 tag: WS_METHODS.serverListAcpRegistrySessions,
1156 concurrency: {
1157 mode: "singleFlight",
1158 key: ({ environmentId, input }) =>
1159 `${environmentId}:${input.instanceId}:${input.projectId}:${input.cursor ?? "first"}`,
1160 },
1161 }),
1162 importAcpRegistrySession: createEnvironmentRpcCommand(runtime, {
1163 label: "environment-data:server:acp-registry:import-session",
1164 tag: WS_METHODS.serverImportAcpRegistrySession,
1165 concurrency: {
1166 mode: "singleFlight",
1167 key: ({ environmentId, input }) =>
1168 `${environmentId}:${input.instanceId}:${input.projectId}:${input.sessionId}`,
1169 },
1170 }),
1171 deleteAcpRegistrySession: createEnvironmentRpcCommand(runtime, {
1172 label: "environment-data:server:acp-registry:delete-session",
1173 tag: WS_METHODS.serverDeleteAcpRegistrySession,
1174 concurrency: {
1175 mode: "singleFlight",
1176 key: ({ environmentId, input }) =>
1177 `${environmentId}:${input.instanceId}:${input.projectId}:${input.sessionId}`,
1178 },
1179 }),
1180 listAcpRegistryProviders: createEnvironmentRpcCommand(runtime, {
1181 label: "environment-data:server:acp-registry:list-providers",
1182 tag: WS_METHODS.serverListAcpRegistryProviders,
1183 concurrency: {
1184 mode: "singleFlight",
1185 key: ({ environmentId, input }) =>
1186 `${environmentId}:${input.instanceId}:${input.projectId}`,
1187 },
1188 }),
1189 setAcpRegistryProvider: createEnvironmentRpcCommand(runtime, {
1190 label: "environment-data:server:acp-registry:set-provider",
1191 tag: WS_METHODS.serverSetAcpRegistryProvider,
1192 concurrency: {
1193 mode: "singleFlight",
1194 key: ({ environmentId, input }) =>
1195 `${environmentId}:${input.instanceId}:${input.projectId}:${input.providerId}`,
1196 },
1197 }),
1198 disableAcpRegistryProvider: createEnvironmentRpcCommand(runtime, {
1199 label: "environment-data:server:acp-registry:disable-provider",
1200 tag: WS_METHODS.serverDisableAcpRegistryProvider,
1201 concurrency: {
1202 mode: "singleFlight",
1203 key: ({ environmentId, input }) =>
1204 `${environmentId}:${input.instanceId}:${input.projectId}:${input.providerId}`,
1205 },
1206 }),
1207 logoutAcpRegistry: createEnvironmentRpcCommand(runtime, {
1208 label: "environment-data:server:acp-registry:logout",
1209 tag: WS_METHODS.serverLogoutAcpRegistry,
1210 concurrency: {
1211 mode: "singleFlight",
1212 key: ({ environmentId, input }) => `${environmentId}:${input.instanceId}`,
1213 },
1214 }),
1215 signalProcess: createEnvironmentRpcCommand(runtime, {
1216 label: "environment-data:server:signal-process",
1217 tag: WS_METHODS.serverSignalProcess,
1218 }),
1219 upsertScheduledTask: createEnvironmentRpcCommand(runtime, {
1220 label: "environment-data:server:scheduled-task:upsert",
1221 tag: WS_METHODS.scheduledTasksUpsert,
1222 scheduler: configScheduler,
1223 concurrency: configConcurrency,
1224 }),
1225 setScheduledTaskEnabled: createEnvironmentRpcCommand(runtime, {
1226 label: "environment-data:server:scheduled-task:set-enabled",
1227 tag: WS_METHODS.scheduledTasksSetEnabled,
1228 scheduler: configScheduler,
1229 concurrency: configConcurrency,
1230 }),
1231 deleteScheduledTask: createEnvironmentRpcCommand(runtime, {
1232 label: "environment-data:server:scheduled-task:delete",
1233 tag: WS_METHODS.scheduledTasksDelete,
1234 scheduler: configScheduler,
1235 concurrency: configConcurrency,
1236 }),
1237 // Deliberately not on the config lane: run-now blocks until the run is
1238 // dispatched, and a slow run must not stall settings/keybinding/provider
1239 // mutations (or other scheduled-task edits) queued behind it.
1240 runScheduledTaskNow: createEnvironmentRpcCommand(runtime, {
1241 label: "environment-data:server:scheduled-task:run-now",
1242 tag: WS_METHODS.scheduledTasksRunNow,
1243 }),
1244 refreshUsageRates: createEnvironmentRpcCommand(runtime, {
1245 label: "environment-data:server:refresh-usage-rates",
1246 tag: WS_METHODS.serverRefreshUsageRates,
1247 concurrency: {
1248 mode: "singleFlight",
1249 key: ({ environmentId }) => environmentId,
1250 },
1251 }),
1252 retryResourceTelemetry: createEnvironmentRpcCommand(runtime, {
1253 label: "environment-data:server:retry-resource-telemetry",
1254 tag: WS_METHODS.serverRetryResourceTelemetry,
1255 concurrency: {
1256 mode: "singleFlight",
1257 key: ({ environmentId }) => environmentId,
1258 },
1259 }),
1260 };
1261}