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