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

server.ts

1,273 lines47.0 KB

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>;
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 }
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 }
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 }
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;
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 );
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 );
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 );
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 );
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 };
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;
308​
309function serverUpdateFailureMessage(error: unknown): string {
310 return error instanceof Error ? error.message : "Server update failed.";
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 }
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 );
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 }));
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;
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 );
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;
497​
498export interface EnvironmentServerWelcomeState {
499 readonly currentSession: RpcSession | null;
500 readonly welcomeSession: RpcSession | null;
501 readonly welcome: ServerLifecycleWelcomePayload | null;
503​
504export function resolveServerWelcomeState(
505 state: EnvironmentServerWelcomeState,
506): ServerLifecycleWelcomePayload | null {
507 return state.currentSession === state.welcomeSession ? state.welcome : null;
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 );
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;
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 usageScanSettingsAtom = Atom.family((environmentId: EnvironmentId) =>
934 Atom.make((get) =>
935 JSON.stringify([
936 get(usagePricesAtom(environmentId)),
937 get(settingsValueAtom(environmentId))?.cursorKeychainUsageEnabled ?? false,
938 ]),
939 ).pipe(Atom.withLabel(`environment-data:server:usage-scan-settings:${environmentId}`)),
940 );
941 const providersValueAtom = Atom.family((environmentId: EnvironmentId) =>
942 Atom.make((get) => get(configValueAtom(environmentId))?.providers ?? null).pipe(
943 Atom.withLabel(`environment-data:server:providers:${environmentId}`),
944 ),
945 );
946 const welcomeStateFamily = Atom.family((environmentId: EnvironmentId) =>
947 runtime
948 .atom(serverWelcomeStateChanges(environmentId), { initialValue: null })
949 .pipe(
950 Atom.setIdleTTL(5 * 60_000),
951 Atom.withLabel(`environment-data:server:welcome-state:${environmentId}`),
952 ),
953 );
954 const welcomeFamily = Atom.family((environmentId: EnvironmentId) =>
955 Atom.make((get) => {
956 const result = get(welcomeStateFamily(environmentId));
957 if (result._tag !== "Success") return result;
958 return result.value === null
959 ? AsyncResult.initial<ServerLifecycleWelcomePayload, never>(result.waiting)
960 : AsyncResult.success(result.value, result);
961 }).pipe(Atom.withLabel(`environment-data:server:welcome:${environmentId}`)),
962 );
963 const welcome = (target: {
964 readonly environmentId: EnvironmentId;
965 readonly input: EnvironmentRpcInput<typeof WS_METHODS.subscribeServerLifecycle>;
966 }) => welcomeFamily(target.environmentId);
967 const updateSettings = createEnvironmentRpcCommand(runtime, {
968 label: "environment-data:server:update-settings",
969 tag: WS_METHODS.serverUpdateSettings,
970 scheduler: configScheduler,
971 concurrency: configConcurrency,
972 });
973​
974 return {
975 configValueAtom,
976 updateStateAtom,
977 settingsValueAtom,
978 providersValueAtom,
979 providerAuthState: createEnvironmentRpcSubscriptionAtomFamily(runtime, {
980 label: "environment-data:provider:auth-state",
981 tag: WS_METHODS.providerAuthSubscribe,
982 idleTtlMs: 0,
983 }),
984 startProviderAuth: createEnvironmentRpcCommand(runtime, {
985 label: "environment-data:provider:auth-start",
986 tag: WS_METHODS.providerAuthStart,
987 concurrency: {
988 mode: "singleFlight",
989 key: ({ environmentId, input }) => JSON.stringify([environmentId, input]),
990 },
991 }),
992 respondProviderAuth: createEnvironmentRpcCommand(runtime, {
993 label: "environment-data:provider:auth-respond",
994 tag: WS_METHODS.providerAuthRespond,
995 }),
996 completeProviderAuth: createEnvironmentRpcCommand(runtime, {
997 label: "environment-data:provider:auth-complete",
998 tag: WS_METHODS.providerAuthComplete,
999 }),
1000 cancelProviderAuth: createEnvironmentRpcCommand(runtime, {
1001 label: "environment-data:provider:auth-cancel",
1002 tag: WS_METHODS.providerAuthCancel,
1003 }),
1004 logoutProviderAuth: createEnvironmentRpcCommand(runtime, {
1005 label: "environment-data:provider:auth-logout",
1006 tag: WS_METHODS.providerAuthLogout,
1007 }),
1008 providerInstallState: createEnvironmentRpcSubscriptionAtomFamily(runtime, {
1009 label: "environment-data:provider:install-state",
1010 tag: WS_METHODS.providerInstallSubscribe,
1011 idleTtlMs: 0,
1012 }),
1013 startProviderInstall: createEnvironmentRpcCommand(runtime, {
1014 label: "environment-data:provider:install-start",
1015 tag: WS_METHODS.providerInstallStart,
1016 concurrency: {
1017 mode: "singleFlight",
1018 key: ({ environmentId }) => environmentId,
1019 },
1020 }),
1021 cancelProviderInstall: createEnvironmentRpcCommand(runtime, {
1022 label: "environment-data:provider:install-cancel",
1023 tag: WS_METHODS.providerInstallCancel,
1024 }),
1025 removeProviderInstallation: createEnvironmentRpcCommand(runtime, {
1026 label: "environment-data:provider:install-remove",
1027 tag: WS_METHODS.providerInstallRemove,
1028 }),
1029 traceDiagnostics: createEnvironmentRpcQueryAtomFamily(runtime, {
1030 label: "environment-data:server:trace-diagnostics",
1031 tag: WS_METHODS.serverGetTraceDiagnostics,
1032 }),
1033 processDiagnostics: createEnvironmentRpcQueryAtomFamily(runtime, {
1034 label: "environment-data:server:process-diagnostics",
1035 tag: WS_METHODS.serverGetProcessDiagnostics,
1036 }),
1037 hostResources: createEnvironmentQueryAtomFamily(runtime, {
1038 label: "environment-data:server:host-resources",
1039 idleTtlMs: 0,
1040 staleTimeMs: 5_000,
1041 execute: (input: EnvironmentRpcInput<typeof WS_METHODS.serverGetHostResources>) =>
1042 request(WS_METHODS.serverGetHostResources, input).pipe(Effect.timeout("5 seconds")),
1043 }),
1044 processResourceHistory: createEnvironmentRpcQueryAtomFamily(runtime, {
1045 label: "environment-data:server:process-resource-history",
1046 tag: WS_METHODS.serverGetProcessResourceHistory,
1047 }),
1048 /** Live scheduled-task list: snapshot on subscribe, fresh list after every server-side change. */
1049 scheduledTasksLive: createEnvironmentRpcSubscriptionAtomFamily(runtime, {
1050 label: "environment-data:server:scheduled-tasks:live",
1051 tag: WS_METHODS.scheduledTasksSubscribe,
1052 }),
1053 // A cold transcript scan is measured in seconds, so keep the result around
1054 // long enough that switching windows or re-rendering does not rescan.
1055 usageSummary: createEnvironmentRpcQueryAtomFamily(runtime, {
1056 label: "environment-data:server:usage-summary",
1057 tag: WS_METHODS.serverGetUsageSummary,
1058 staleTimeMs: 60_000,
1059 refreshTrigger: ({ environmentId }) => usageScanSettingsAtom(environmentId),
1060 }),
1061 resourceTelemetry: createEnvironmentRpcSubscriptionAtomFamily(runtime, {
1062 label: "environment-data:server:resource-telemetry",
1063 tag: WS_METHODS.subscribeResourceTelemetry,
1064 idleTtlMs: 0,
1065 }),
1066 resourceTelemetryHistory: createEnvironmentRpcQueryAtomFamily(runtime, {
1067 label: "environment-data:server:resource-telemetry-history",
1068 tag: WS_METHODS.serverGetResourceTelemetryHistory,
1069 staleTimeMs: 5_000,
1070 }),
1071 searchAcpRegistry: createEnvironmentRpcQueryAtomFamily(runtime, {
1072 label: "environment-data:server:acp-registry:search",
1073 tag: WS_METHODS.serverSearchAcpRegistry,
1074 // Each submitted search refreshes the server-side registry. Dropping an
1075 // abandoned query immediately also interrupts stale in-flight requests.
1076 staleTimeMs: 0,
1077 idleTtlMs: 0,
1078 }),
1079 configProjection,
1080 welcome,
1081 legacyThreadMigration: createEnvironmentRpcSubscriptionAtomFamily(runtime, {
1082 label: "environment-data:server:legacy-thread-migration",
1083 tag: WS_METHODS.subscribeServerLifecycle,
1084 transform: (stream) =>
1085 stream.pipe(
1086 Stream.filterMap((event) =>
1087 event.type === "legacyThreadMigration"
1088 ? Result.succeed(event.payload)
1089 : Result.failVoid,
1090 ),
1091 ),
1092 }),
1093 consumeResetCredit: createEnvironmentRpcCommand(runtime, {
1094 label: "environment-data:server:consume-reset-credit",
1095 tag: WS_METHODS.providerConsumeResetCredit,
1096 concurrency: {
1097 mode: "singleFlight",
1098 // Both ids are free-form strings; a delimiter could collide.
1099 key: ({ environmentId, input }) => JSON.stringify([environmentId, input]),
1100 },
1101 }),
1102 refreshProviders: createEnvironmentRpcCommand(runtime, {
1103 label: "environment-data:server:refresh-providers",
1104 tag: WS_METHODS.serverRefreshProviders,
1105 concurrency: {
1106 mode: "singleFlight",
1107 key: ({ environmentId, input }) =>
1108 JSON.stringify([
1109 environmentId,
1110 input.instanceId ?? null,
1111 input.cwd ?? null,
1112 input.refreshModels ?? false,
1113 ]),
1114 },
1115 }),
1116 updateProvider: createEnvironmentRpcCommand(runtime, {
1117 label: "environment-data:server:update-provider",
1118 tag: WS_METHODS.serverUpdateProvider,
1119 scheduler: configScheduler,
1120 concurrency: configConcurrency,
1121 }),
1122 updateServer,
1123 upsertKeybinding: createEnvironmentRpcCommand(runtime, {
1124 label: "environment-data:server:upsert-keybinding",
1125 tag: WS_METHODS.serverUpsertKeybinding,
1126 scheduler: configScheduler,
1127 concurrency: configConcurrency,
1128 }),
1129 removeKeybinding: createEnvironmentRpcCommand(runtime, {
1130 label: "environment-data:server:remove-keybinding",
1131 tag: WS_METHODS.serverRemoveKeybinding,
1132 scheduler: configScheduler,
1133 concurrency: configConcurrency,
1134 }),
1135 updateSettings,
1136 // Provider-instance mutations share the settings command and its
1137 // environment-serial scheduler. The named boundary keeps clients on the
1138 // atomic map-entry payload instead of rebuilding a stale whole map.
1139 mutateProviderInstance: updateSettings,
1140 prepareAcpRegistryAgent: createEnvironmentRpcCommand(runtime, {
1141 label: "environment-data:server:acp-registry:prepare",
1142 tag: WS_METHODS.serverPrepareAcpRegistryAgent,
1143 concurrency: {
1144 mode: "singleFlight",
1145 key: ({ environmentId, input }) => `${environmentId}:${input.agentId}`,
1146 },
1147 }),
1148 uninstallAcpRegistryManagedBinary: createEnvironmentRpcCommand(runtime, {
1149 label: "environment-data:server:acp-registry:uninstall-managed-binary",
1150 tag: WS_METHODS.serverUninstallAcpRegistryManagedBinary,
1151 concurrency: {
1152 mode: "singleFlight",
1153 key: ({ environmentId, input }) => `${environmentId}:${input.agentId}`,
1154 },
1155 }),
1156 acceptAcpRegistryUrlAuth: createEnvironmentRpcCommand(runtime, {
1157 label: "environment-data:server:acp-registry:accept-url-auth",
1158 tag: WS_METHODS.serverAcceptAcpRegistryUrlAuth,
1159 concurrency: {
1160 mode: "singleFlight",
1161 key: ({ environmentId, input }) =>
1162 `${environmentId}:${input.instanceId}:${input.elicitationId}`,
1163 },
1164 }),
1165 listAcpRegistrySessions: createEnvironmentRpcCommand(runtime, {
1166 label: "environment-data:server:acp-registry:list-sessions",
1167 tag: WS_METHODS.serverListAcpRegistrySessions,
1168 concurrency: {
1169 mode: "singleFlight",
1170 key: ({ environmentId, input }) =>
1171 `${environmentId}:${input.instanceId}:${input.projectId}:${input.cursor ?? "first"}`,
1172 },
1173 }),
1174 importAcpRegistrySession: createEnvironmentRpcCommand(runtime, {
1175 label: "environment-data:server:acp-registry:import-session",
1176 tag: WS_METHODS.serverImportAcpRegistrySession,
1177 concurrency: {
1178 mode: "singleFlight",
1179 key: ({ environmentId, input }) =>
1180 `${environmentId}:${input.instanceId}:${input.projectId}:${input.sessionId}`,
1181 },
1182 }),
1183 deleteAcpRegistrySession: createEnvironmentRpcCommand(runtime, {
1184 label: "environment-data:server:acp-registry:delete-session",
1185 tag: WS_METHODS.serverDeleteAcpRegistrySession,
1186 concurrency: {
1187 mode: "singleFlight",
1188 key: ({ environmentId, input }) =>
1189 `${environmentId}:${input.instanceId}:${input.projectId}:${input.sessionId}`,
1190 },
1191 }),
1192 listAcpRegistryProviders: createEnvironmentRpcCommand(runtime, {
1193 label: "environment-data:server:acp-registry:list-providers",
1194 tag: WS_METHODS.serverListAcpRegistryProviders,
1195 concurrency: {
1196 mode: "singleFlight",
1197 key: ({ environmentId, input }) =>
1198 `${environmentId}:${input.instanceId}:${input.projectId}`,
1199 },
1200 }),
1201 setAcpRegistryProvider: createEnvironmentRpcCommand(runtime, {
1202 label: "environment-data:server:acp-registry:set-provider",
1203 tag: WS_METHODS.serverSetAcpRegistryProvider,
1204 concurrency: {
1205 mode: "singleFlight",
1206 key: ({ environmentId, input }) =>
1207 `${environmentId}:${input.instanceId}:${input.projectId}:${input.providerId}`,
1208 },
1209 }),
1210 disableAcpRegistryProvider: createEnvironmentRpcCommand(runtime, {
1211 label: "environment-data:server:acp-registry:disable-provider",
1212 tag: WS_METHODS.serverDisableAcpRegistryProvider,
1213 concurrency: {
1214 mode: "singleFlight",
1215 key: ({ environmentId, input }) =>
1216 `${environmentId}:${input.instanceId}:${input.projectId}:${input.providerId}`,
1217 },
1218 }),
1219 logoutAcpRegistry: createEnvironmentRpcCommand(runtime, {
1220 label: "environment-data:server:acp-registry:logout",
1221 tag: WS_METHODS.serverLogoutAcpRegistry,
1222 concurrency: {
1223 mode: "singleFlight",
1224 key: ({ environmentId, input }) => `${environmentId}:${input.instanceId}`,
1225 },
1226 }),
1227 signalProcess: createEnvironmentRpcCommand(runtime, {
1228 label: "environment-data:server:signal-process",
1229 tag: WS_METHODS.serverSignalProcess,
1230 }),
1231 upsertScheduledTask: createEnvironmentRpcCommand(runtime, {
1232 label: "environment-data:server:scheduled-task:upsert",
1233 tag: WS_METHODS.scheduledTasksUpsert,
1234 scheduler: configScheduler,
1235 concurrency: configConcurrency,
1236 }),
1237 setScheduledTaskEnabled: createEnvironmentRpcCommand(runtime, {
1238 label: "environment-data:server:scheduled-task:set-enabled",
1239 tag: WS_METHODS.scheduledTasksSetEnabled,
1240 scheduler: configScheduler,
1241 concurrency: configConcurrency,
1242 }),
1243 deleteScheduledTask: createEnvironmentRpcCommand(runtime, {
1244 label: "environment-data:server:scheduled-task:delete",
1245 tag: WS_METHODS.scheduledTasksDelete,
1246 scheduler: configScheduler,
1247 concurrency: configConcurrency,
1248 }),
1249 // Deliberately not on the config lane: run-now blocks until the run is
1250 // dispatched, and a slow run must not stall settings/keybinding/provider
1251 // mutations (or other scheduled-task edits) queued behind it.
1252 runScheduledTaskNow: createEnvironmentRpcCommand(runtime, {
1253 label: "environment-data:server:scheduled-task:run-now",
1254 tag: WS_METHODS.scheduledTasksRunNow,
1255 }),
1256 refreshUsageRates: createEnvironmentRpcCommand(runtime, {
1257 label: "environment-data:server:refresh-usage-rates",
1258 tag: WS_METHODS.serverRefreshUsageRates,
1259 concurrency: {
1260 mode: "singleFlight",
1261 key: ({ environmentId }) => environmentId,
1262 },
1263 }),
1264 retryResourceTelemetry: createEnvironmentRpcCommand(runtime, {
1265 label: "environment-data:server:retry-resource-telemetry",
1266 tag: WS_METHODS.serverRetryResourceTelemetry,
1267 concurrency: {
1268 mode: "singleFlight",
1269 key: ({ environmentId }) => environmentId,
1270 },
1271 }),
1272 };