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

service.ts

1,082 lines33.4 KB

1import {
2 type AuthSessionRole,
3 type EnvironmentId,
4 type OrchestrationEvent,
5 type OrchestrationShellSnapshot,
6 type OrchestrationShellStreamEvent,
7 type ServerConfig,
8 type TerminalEvent,
9 ThreadId,
10} from "@t3tools/contracts";
11import { type QueryClient } from "@tanstack/react-query";
12import { Throttler } from "@tanstack/react-pacer";
13import {
14 createKnownEnvironment,
15 getKnownEnvironmentWsBaseUrl,
16 scopedProjectKey,
17 scopedThreadKey,
18 scopeProjectRef,
19 scopeThreadRef,
20} from "@t3tools/client-runtime";
21​
22import {
23 markPromotedDraftThreadByRef,
24 markPromotedDraftThreadsByRef,
25 useComposerDraftStore,
26} from "~/composerDraftStore";
27import { ensureLocalApi } from "~/localApi";
28import { collectActiveTerminalThreadIds } from "~/lib/terminalStateCleanup";
29import { deriveOrchestrationBatchEffects } from "~/orchestrationEventEffects";
30import { projectQueryKeys } from "~/lib/projectReactQuery";
31import { providerQueryKeys } from "~/lib/providerReactQuery";
32import { getPrimaryKnownEnvironment } from "../primary";
33import {
34 bootstrapRemoteBearerSession,
35 fetchRemoteEnvironmentDescriptor,
36 fetchRemoteSessionState,
37 resolveRemoteWebSocketConnectionUrl,
38} from "../remote/api";
39import { resolveRemotePairingTarget } from "../remote/target";
40import {
41 getSavedEnvironmentRecord,
42 hasSavedEnvironmentRegistryHydrated,
43 listSavedEnvironmentRecords,
44 persistSavedEnvironmentRecord,
45 readSavedEnvironmentBearerToken,
46 removeSavedEnvironmentBearerToken,
47 type SavedEnvironmentRecord,
48 useSavedEnvironmentRegistryStore,
49 useSavedEnvironmentRuntimeStore,
50 waitForSavedEnvironmentRegistryHydration,
51 writeSavedEnvironmentBearerToken,
52} from "./catalog";
53import { createEnvironmentConnection, type EnvironmentConnection } from "./connection";
54import {
55 useStore,
56 selectProjectsAcrossEnvironments,
57 selectSidebarThreadSummaryByRef,
58 selectThreadByRef,
59 selectThreadsAcrossEnvironments,
60} from "~/store";
61import { useTerminalStateStore } from "~/terminalStateStore";
62import { useUiStateStore } from "~/uiStateStore";
63import { WsTransport } from "../../rpc/wsTransport";
64import { createWsRpcClient, type WsRpcClient } from "../../rpc/wsRpcClient";
65​
66type EnvironmentServiceState = {
67 readonly queryClient: QueryClient;
68 readonly queryInvalidationThrottler: Throttler<() => void>;
69 refCount: number;
70 stop: () => void;
71};
72​
73type ThreadDetailSubscriptionEntry = {
74 readonly environmentId: EnvironmentId;
75 readonly threadId: ThreadId;
76 unsubscribe: () => void;
77 unsubscribeConnectionListener: (() => void) | null;
78 refCount: number;
79 lastAccessedAt: number;
80 evictionTimeoutId: ReturnType<typeof setTimeout> | null;
81};
82​
83const environmentConnections = new Map<EnvironmentId, EnvironmentConnection>();
84const environmentConnectionListeners = new Set<() => void>();
85const threadDetailSubscriptions = new Map<string, ThreadDetailSubscriptionEntry>();
86​
87let activeService: EnvironmentServiceState | null = null;
88let needsProviderInvalidation = false;
89​
90// Thread detail subscription cache policy:
91// - Active consumers keep a subscription retained via refCount.
92// - Released subscriptions stay warm for a longer idle TTL to avoid churn
93// while moving around the UI.
94// - Threads with active work or pending user action are sticky and are never
95// evicted while they remain non-idle.
96// - Capacity eviction only targets idle cached subscriptions.
97const THREAD_DETAIL_SUBSCRIPTION_IDLE_EVICTION_MS = 15 * 60 * 1000;
98const MAX_CACHED_THREAD_DETAIL_SUBSCRIPTIONS = 32;
99const NOOP = () => undefined;
100​
101function getThreadDetailSubscriptionKey(environmentId: EnvironmentId, threadId: ThreadId): string {
102 return scopedThreadKey(scopeThreadRef(environmentId, threadId));
104​
105function clearThreadDetailSubscriptionEviction(
106 entry: ThreadDetailSubscriptionEntry,
107): ThreadDetailSubscriptionEntry {
108 if (entry.evictionTimeoutId !== null) {
109 clearTimeout(entry.evictionTimeoutId);
110 entry.evictionTimeoutId = null;
111 }
112 return entry;
114​
115function isNonIdleThreadDetailSubscription(entry: ThreadDetailSubscriptionEntry): boolean {
116 const threadRef = scopeThreadRef(entry.environmentId, entry.threadId);
117 const state = useStore.getState();
118 const sidebarThread = selectSidebarThreadSummaryByRef(state, threadRef);
119​
120 // Prefer shell/sidebar state first because it carries the coarse thread
121 // readiness flags used throughout the UI (pending approvals/input/plan).
122 if (sidebarThread) {
123 if (
124 sidebarThread.hasPendingApprovals ||
125 sidebarThread.hasPendingUserInput ||
126 sidebarThread.hasActionableProposedPlan
127 ) {
128 return true;
129 }
130​
131 const orchestrationStatus = sidebarThread.session?.orchestrationStatus;
132 if (
133 orchestrationStatus &&
134 orchestrationStatus !== "idle" &&
135 orchestrationStatus !== "stopped"
136 ) {
137 return true;
138 }
139​
140 if (sidebarThread.latestTurn?.state === "running") {
141 return true;
142 }
143 }
144​
145 const thread = selectThreadByRef(state, threadRef);
146 if (!thread) {
147 return false;
148 }
149​
150 const orchestrationStatus = thread.session?.orchestrationStatus;
151 return (
152 Boolean(
153 orchestrationStatus && orchestrationStatus !== "idle" && orchestrationStatus !== "stopped",
154 ) ||
155 thread.latestTurn?.state === "running" ||
156 thread.pendingSourceProposedPlan !== undefined
157 );
159​
160function shouldEvictThreadDetailSubscription(entry: ThreadDetailSubscriptionEntry): boolean {
161 return entry.refCount === 0 && !isNonIdleThreadDetailSubscription(entry);
163​
164function attachThreadDetailSubscription(entry: ThreadDetailSubscriptionEntry): boolean {
165 if (entry.unsubscribeConnectionListener !== null) {
166 entry.unsubscribeConnectionListener();
167 entry.unsubscribeConnectionListener = null;
168 }
169 if (entry.unsubscribe !== NOOP) {
170 return true;
171 }
172​
173 const connection = readEnvironmentConnection(entry.environmentId);
174 if (!connection) {
175 return false;
176 }
177​
178 entry.unsubscribe = connection.client.orchestration.subscribeThread(
179 { threadId: entry.threadId },
180 (item) => {
181 if (item.kind === "snapshot") {
182 useStore.getState().syncServerThreadDetail(item.snapshot.thread, entry.environmentId);
183 return;
184 }
185 applyEnvironmentThreadDetailEvent(item.event, entry.environmentId);
186 },
187 );
188 return true;
190​
191function watchThreadDetailSubscriptionConnection(entry: ThreadDetailSubscriptionEntry): void {
192 if (entry.unsubscribeConnectionListener !== null) {
193 return;
194 }
195​
196 entry.unsubscribeConnectionListener = subscribeEnvironmentConnections(() => {
197 if (attachThreadDetailSubscription(entry)) {
198 entry.lastAccessedAt = Date.now();
199 }
200 });
201 attachThreadDetailSubscription(entry);
203​
204function disposeThreadDetailSubscriptionByKey(key: string): boolean {
205 const entry = threadDetailSubscriptions.get(key);
206 if (!entry) {
207 return false;
208 }
209​
210 clearThreadDetailSubscriptionEviction(entry);
211 entry.unsubscribeConnectionListener?.();
212 entry.unsubscribeConnectionListener = null;
213 threadDetailSubscriptions.delete(key);
214 entry.unsubscribe();
215 entry.unsubscribe = NOOP;
216 return true;
218​
219function disposeThreadDetailSubscriptionsForEnvironment(environmentId: EnvironmentId): void {
220 for (const [key, entry] of threadDetailSubscriptions) {
221 if (entry.environmentId === environmentId) {
222 disposeThreadDetailSubscriptionByKey(key);
223 }
224 }
226​
227function reconcileThreadDetailSubscriptionsForEnvironment(
228 environmentId: EnvironmentId,
229 threadIds: ReadonlyArray<ThreadId>,
230): void {
231 const activeThreadIds = new Set(threadIds);
232 for (const [key, entry] of threadDetailSubscriptions) {
233 if (entry.environmentId === environmentId && !activeThreadIds.has(entry.threadId)) {
234 disposeThreadDetailSubscriptionByKey(key);
235 }
236 }
238​
239function scheduleThreadDetailSubscriptionEviction(entry: ThreadDetailSubscriptionEntry): void {
240 clearThreadDetailSubscriptionEviction(entry);
241 if (!shouldEvictThreadDetailSubscription(entry)) {
242 return;
243 }
244​
245 entry.evictionTimeoutId = setTimeout(() => {
246 const currentEntry = threadDetailSubscriptions.get(
247 getThreadDetailSubscriptionKey(entry.environmentId, entry.threadId),
248 );
249 if (!currentEntry) {
250 return;
251 }
252​
253 currentEntry.evictionTimeoutId = null;
254 if (!shouldEvictThreadDetailSubscription(currentEntry)) {
255 return;
256 }
257 disposeThreadDetailSubscriptionByKey(
258 getThreadDetailSubscriptionKey(entry.environmentId, entry.threadId),
259 );
260 }, THREAD_DETAIL_SUBSCRIPTION_IDLE_EVICTION_MS);
262​
263function evictIdleThreadDetailSubscriptionsToCapacity(): void {
264 if (threadDetailSubscriptions.size <= MAX_CACHED_THREAD_DETAIL_SUBSCRIPTIONS) {
265 return;
266 }
267​
268 const idleEntries = [...threadDetailSubscriptions.entries()]
269 .filter(([, entry]) => shouldEvictThreadDetailSubscription(entry))
270 .toSorted(([, left], [, right]) => left.lastAccessedAt - right.lastAccessedAt);
271​
272 for (const [key] of idleEntries) {
273 if (threadDetailSubscriptions.size <= MAX_CACHED_THREAD_DETAIL_SUBSCRIPTIONS) {
274 return;
275 }
276 disposeThreadDetailSubscriptionByKey(key);
277 }
279​
280function reconcileThreadDetailSubscriptionEvictionState(
281 entry: ThreadDetailSubscriptionEntry,
282): void {
283 clearThreadDetailSubscriptionEviction(entry);
284 if (!shouldEvictThreadDetailSubscription(entry)) {
285 return;
286 }
287​
288 scheduleThreadDetailSubscriptionEviction(entry);
290​
291function reconcileThreadDetailSubscriptionEvictionForThread(
292 environmentId: EnvironmentId,
293 threadId: ThreadId,
294): void {
295 const entry = threadDetailSubscriptions.get(
296 getThreadDetailSubscriptionKey(environmentId, threadId),
297 );
298 if (!entry) {
299 return;
300 }
301​
302 reconcileThreadDetailSubscriptionEvictionState(entry);
304​
305function reconcileThreadDetailSubscriptionEvictionForEnvironment(
306 environmentId: EnvironmentId,
307): void {
308 for (const entry of threadDetailSubscriptions.values()) {
309 if (entry.environmentId === environmentId) {
310 reconcileThreadDetailSubscriptionEvictionState(entry);
311 }
312 }
313 evictIdleThreadDetailSubscriptionsToCapacity();
315​
316export function retainThreadDetailSubscription(
317 environmentId: EnvironmentId,
318 threadId: ThreadId,
319): () => void {
320 const key = getThreadDetailSubscriptionKey(environmentId, threadId);
321 const existing = threadDetailSubscriptions.get(key);
322 if (existing) {
323 clearThreadDetailSubscriptionEviction(existing);
324 existing.refCount += 1;
325 existing.lastAccessedAt = Date.now();
326 if (!attachThreadDetailSubscription(existing)) {
327 watchThreadDetailSubscriptionConnection(existing);
328 }
329 let released = false;
330 return () => {
331 if (released) {
332 return;
333 }
334 released = true;
335 existing.refCount = Math.max(0, existing.refCount - 1);
336 existing.lastAccessedAt = Date.now();
337 if (existing.refCount === 0) {
338 reconcileThreadDetailSubscriptionEvictionState(existing);
339 evictIdleThreadDetailSubscriptionsToCapacity();
340 }
341 };
342 }
343​
344 const entry: ThreadDetailSubscriptionEntry = {
345 environmentId,
346 threadId,
347 unsubscribe: NOOP,
348 unsubscribeConnectionListener: null,
349 refCount: 1,
350 lastAccessedAt: Date.now(),
351 evictionTimeoutId: null,
352 };
353 threadDetailSubscriptions.set(key, entry);
354 if (!attachThreadDetailSubscription(entry)) {
355 watchThreadDetailSubscriptionConnection(entry);
356 }
357 evictIdleThreadDetailSubscriptionsToCapacity();
358​
359 let released = false;
360 return () => {
361 if (released) {
362 return;
363 }
364 released = true;
365 entry.refCount = Math.max(0, entry.refCount - 1);
366 entry.lastAccessedAt = Date.now();
367 if (entry.refCount === 0) {
368 reconcileThreadDetailSubscriptionEvictionState(entry);
369 evictIdleThreadDetailSubscriptionsToCapacity();
370 }
371 };
373​
374function emitEnvironmentConnectionRegistryChange() {
375 for (const listener of environmentConnectionListeners) {
376 listener();
377 }
379​
380function getRuntimeErrorFields(error: unknown) {
381 return {
382 lastError: error instanceof Error ? error.message : String(error),
383 lastErrorAt: new Date().toISOString(),
384 } as const;
386​
387function isoNow(): string {
388 return new Date().toISOString();
390​
391function setRuntimeConnecting(environmentId: EnvironmentId) {
392 useSavedEnvironmentRuntimeStore.getState().patch(environmentId, {
393 connectionState: "connecting",
394 lastError: null,
395 lastErrorAt: null,
396 });
398​
399function setRuntimeConnected(environmentId: EnvironmentId) {
400 const connectedAt = isoNow();
401 useSavedEnvironmentRuntimeStore.getState().patch(environmentId, {
402 connectionState: "connected",
403 authState: "authenticated",
404 connectedAt,
405 disconnectedAt: null,
406 lastError: null,
407 lastErrorAt: null,
408 });
409 useSavedEnvironmentRegistryStore.getState().markConnected(environmentId, connectedAt);
411​
412function setRuntimeDisconnected(environmentId: EnvironmentId, reason?: string | null) {
413 useSavedEnvironmentRuntimeStore.getState().patch(environmentId, {
414 connectionState: "disconnected",
415 disconnectedAt: isoNow(),
416 ...(reason && reason.trim().length > 0
417 ? {
418 lastError: reason,
419 lastErrorAt: isoNow(),
420 }
421 : {}),
422 });
424​
425function setRuntimeError(environmentId: EnvironmentId, error: unknown) {
426 useSavedEnvironmentRuntimeStore.getState().patch(environmentId, {
427 connectionState: "error",
428 ...getRuntimeErrorFields(error),
429 });
431​
432function coalesceOrchestrationUiEvents(
433 events: ReadonlyArray<OrchestrationEvent>,
434): OrchestrationEvent[] {
435 if (events.length < 2) {
436 return [...events];
437 }
438​
439 const coalesced: OrchestrationEvent[] = [];
440 for (const event of events) {
441 const previous = coalesced.at(-1);
442 if (
443 previous?.type === "thread.message-sent" &&
444 event.type === "thread.message-sent" &&
445 previous.payload.threadId === event.payload.threadId &&
446 previous.payload.messageId === event.payload.messageId
447 ) {
448 coalesced[coalesced.length - 1] = {
449 ...event,
450 payload: {
451 ...event.payload,
452 attachments: event.payload.attachments ?? previous.payload.attachments,
453 createdAt: previous.payload.createdAt,
454 text:
455 !event.payload.streaming && event.payload.text.length > 0
456 ? event.payload.text
457 : previous.payload.text + event.payload.text,
458 },
459 };
460 continue;
461 }
462​
463 coalesced.push(event);
464 }
465​
466 return coalesced;
468​
469function syncProjectUiFromStore() {
470 const projects = selectProjectsAcrossEnvironments(useStore.getState());
471 useUiStateStore.getState().syncProjects(
472 projects.map((project) => ({
473 key: scopedProjectKey(scopeProjectRef(project.environmentId, project.id)),
474 cwd: project.cwd,
475 })),
476 );
478​
479function syncThreadUiFromStore() {
480 const threads = selectThreadsAcrossEnvironments(useStore.getState());
481 useUiStateStore.getState().syncThreads(
482 threads.map((thread) => ({
483 key: scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)),
484 seedVisitedAt: thread.updatedAt ?? thread.createdAt,
485 })),
486 );
487 markPromotedDraftThreadsByRef(
488 threads.map((thread) => scopeThreadRef(thread.environmentId, thread.id)),
489 );
491​
492function reconcileSnapshotDerivedState() {
493 syncProjectUiFromStore();
494 syncThreadUiFromStore();
495​
496 const threads = selectThreadsAcrossEnvironments(useStore.getState());
497 const activeThreadKeys = collectActiveTerminalThreadIds({
498 snapshotThreads: threads.map((thread) => ({
499 key: scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)),
500 deletedAt: null,
501 archivedAt: thread.archivedAt,
502 })),
503 draftThreadKeys: useComposerDraftStore.getState().listDraftThreadKeys(),
504 });
505 useTerminalStateStore.getState().removeOrphanedTerminalStates(activeThreadKeys);
507​
508export function shouldApplyTerminalEvent(input: {
509 serverThreadArchivedAt: string | null | undefined;
510 hasDraftThread: boolean;
511}): boolean {
512 if (input.serverThreadArchivedAt !== undefined) {
513 return input.serverThreadArchivedAt === null;
514 }
515​
516 return input.hasDraftThread;
518​
519function applyRecoveredEventBatch(
520 events: ReadonlyArray<OrchestrationEvent>,
521 environmentId: EnvironmentId,
522) {
523 if (events.length === 0) {
524 return;
525 }
526​
527 const batchEffects = deriveOrchestrationBatchEffects(events);
528 const uiEvents = coalesceOrchestrationUiEvents(events);
529 const needsProjectUiSync = events.some(
530 (event) =>
531 event.type === "project.created" ||
532 event.type === "project.meta-updated" ||
533 event.type === "project.deleted",
534 );
535​
536 if (batchEffects.needsProviderInvalidation) {
537 needsProviderInvalidation = true;
538 void activeService?.queryInvalidationThrottler.maybeExecute();
539 }
540​
541 useStore.getState().applyOrchestrationEvents(uiEvents, environmentId);
542 if (needsProjectUiSync) {
543 const projects = selectProjectsAcrossEnvironments(useStore.getState());
544 useUiStateStore.getState().syncProjects(
545 projects.map((project) => ({
546 key: scopedProjectKey(scopeProjectRef(project.environmentId, project.id)),
547 cwd: project.cwd,
548 })),
549 );
550 }
551​
552 const needsThreadUiSync = events.some(
553 (event) => event.type === "thread.created" || event.type === "thread.deleted",
554 );
555 if (needsThreadUiSync) {
556 const threads = selectThreadsAcrossEnvironments(useStore.getState());
557 useUiStateStore.getState().syncThreads(
558 threads.map((thread) => ({
559 key: scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)),
560 seedVisitedAt: thread.updatedAt ?? thread.createdAt,
561 })),
562 );
563 }
564​
565 const draftStore = useComposerDraftStore.getState();
566 for (const threadId of batchEffects.promoteDraftThreadIds) {
567 markPromotedDraftThreadByRef(scopeThreadRef(environmentId, threadId));
568 }
569 for (const threadId of batchEffects.clearDeletedThreadIds) {
570 draftStore.clearDraftThread(scopeThreadRef(environmentId, threadId));
571 useUiStateStore
572 .getState()
573 .clearThreadUi(scopedThreadKey(scopeThreadRef(environmentId, threadId)));
574 }
575 for (const threadId of batchEffects.removeTerminalStateThreadIds) {
576 useTerminalStateStore.getState().removeTerminalState(scopeThreadRef(environmentId, threadId));
577 }
578​
579 reconcileThreadDetailSubscriptionEvictionForEnvironment(environmentId);
581​
582export function applyEnvironmentThreadDetailEvent(
583 event: OrchestrationEvent,
584 environmentId: EnvironmentId,
585) {
586 applyRecoveredEventBatch([event], environmentId);
588​
589function applyShellEvent(event: OrchestrationShellStreamEvent, environmentId: EnvironmentId) {
590 const threadId =
591 event.kind === "thread-upserted"
592 ? event.thread.id
593 : event.kind === "thread-removed"
594 ? event.threadId
595 : null;
596 const threadRef = threadId ? scopeThreadRef(environmentId, threadId) : null;
597 const previousThread = threadRef ? selectThreadByRef(useStore.getState(), threadRef) : undefined;
598​
599 useStore.getState().applyShellEvent(event, environmentId);
600​
601 switch (event.kind) {
602 case "project-upserted":
603 case "project-removed":
604 syncProjectUiFromStore();
605 return;
606 case "thread-upserted":
607 syncThreadUiFromStore();
608 if (!previousThread && threadRef) {
609 markPromotedDraftThreadByRef(threadRef);
610 }
611 if (previousThread?.archivedAt === null && event.thread.archivedAt !== null && threadRef) {
612 useTerminalStateStore.getState().removeTerminalState(threadRef);
613 }
614 reconcileThreadDetailSubscriptionEvictionForThread(environmentId, event.thread.id);
615 evictIdleThreadDetailSubscriptionsToCapacity();
616 return;
617 case "thread-removed":
618 if (threadRef) {
619 disposeThreadDetailSubscriptionByKey(scopedThreadKey(threadRef));
620 useComposerDraftStore.getState().clearDraftThread(threadRef);
621 useUiStateStore.getState().clearThreadUi(scopedThreadKey(threadRef));
622 useTerminalStateStore.getState().removeTerminalState(threadRef);
623 }
624 syncThreadUiFromStore();
625 return;
626 }
628​
629function createEnvironmentConnectionHandlers() {
630 return {
631 applyShellEvent,
632 syncShellSnapshot: (snapshot: OrchestrationShellSnapshot, environmentId: EnvironmentId) => {
633 useStore.getState().syncServerShellSnapshot(snapshot, environmentId);
634 reconcileThreadDetailSubscriptionsForEnvironment(
635 environmentId,
636 snapshot.threads.map((thread) => thread.id),
637 );
638 reconcileThreadDetailSubscriptionEvictionForEnvironment(environmentId);
639 reconcileSnapshotDerivedState();
640 },
641 applyTerminalEvent: (event: TerminalEvent, environmentId: EnvironmentId) => {
642 const threadRef = scopeThreadRef(environmentId, ThreadId.make(event.threadId));
643 const serverThread = selectThreadByRef(useStore.getState(), threadRef);
644 const hasDraftThread =
645 useComposerDraftStore.getState().getDraftThreadByRef(threadRef) !== null;
646 if (
647 !shouldApplyTerminalEvent({
648 serverThreadArchivedAt: serverThread?.archivedAt,
649 hasDraftThread,
650 })
651 ) {
652 return;
653 }
654 useTerminalStateStore.getState().applyTerminalEvent(threadRef, event);
655 },
656 };
658​
659function createPrimaryEnvironmentClient(
660 knownEnvironment: ReturnType<typeof getPrimaryKnownEnvironment>,
661) {
662 const wsBaseUrl = getKnownEnvironmentWsBaseUrl(knownEnvironment);
663 if (!wsBaseUrl) {
664 throw new Error(
665 `Unable to resolve websocket URL for ${knownEnvironment?.label ?? "primary environment"}.`,
666 );
667 }
668​
669 return createWsRpcClient(new WsTransport(wsBaseUrl));
671​
672function createSavedEnvironmentClient(
673 record: SavedEnvironmentRecord,
674 bearerToken: string,
675): WsRpcClient {
676 useSavedEnvironmentRuntimeStore.getState().ensure(record.environmentId);
677​
678 return createWsRpcClient(
679 new WsTransport(
680 () =>
681 resolveRemoteWebSocketConnectionUrl({
682 wsBaseUrl: record.wsBaseUrl,
683 httpBaseUrl: record.httpBaseUrl,
684 bearerToken,
685 }),
686 {
687 onAttempt: () => {
688 setRuntimeConnecting(record.environmentId);
689 },
690 onOpen: () => {
691 setRuntimeConnected(record.environmentId);
692 },
693 onError: (message: string) => {
694 useSavedEnvironmentRuntimeStore.getState().patch(record.environmentId, {
695 connectionState: "error",
696 lastError: message,
697 lastErrorAt: isoNow(),
698 });
699 },
700 onClose: (details: { readonly code: number; readonly reason: string }) => {
701 setRuntimeDisconnected(record.environmentId, details.reason);
702 },
703 },
704 ),
705 );
707​
708async function refreshSavedEnvironmentMetadata(
709 record: SavedEnvironmentRecord,
710 bearerToken: string,
711 client: WsRpcClient,
712 roleHint?: AuthSessionRole | null,
713 configHint?: ServerConfig | null,
714): Promise<void> {
715 const [serverConfig, sessionState] = await Promise.all([
716 configHint ? Promise.resolve(configHint) : client.server.getConfig(),
717 fetchRemoteSessionState({
718 httpBaseUrl: record.httpBaseUrl,
719 bearerToken,
720 }),
721 ]);
722​
723 useSavedEnvironmentRuntimeStore.getState().patch(record.environmentId, {
724 authState: sessionState.authenticated ? "authenticated" : "requires-auth",
725 descriptor: serverConfig.environment,
726 serverConfig,
727 role: sessionState.authenticated ? (sessionState.role ?? roleHint ?? null) : null,
728 });
730​
731function registerConnection(connection: EnvironmentConnection): EnvironmentConnection {
732 const existing = environmentConnections.get(connection.environmentId);
733 if (existing && existing !== connection) {
734 throw new Error(`Environment ${connection.environmentId} already has an active connection.`);
735 }
736 environmentConnections.set(connection.environmentId, connection);
737 emitEnvironmentConnectionRegistryChange();
738 return connection;
740​
741async function removeConnection(environmentId: EnvironmentId): Promise<boolean> {
742 const connection = environmentConnections.get(environmentId);
743 if (!connection) {
744 return false;
745 }
746​
747 disposeThreadDetailSubscriptionsForEnvironment(environmentId);
748 environmentConnections.delete(environmentId);
749 emitEnvironmentConnectionRegistryChange();
750 await connection.dispose();
751 return true;
753​
754function createPrimaryEnvironmentConnection(): EnvironmentConnection {
755 const knownEnvironment = getPrimaryKnownEnvironment();
756 if (!knownEnvironment?.environmentId) {
757 throw new Error("Unable to resolve the primary environment.");
758 }
759​
760 const existing = environmentConnections.get(knownEnvironment.environmentId);
761 if (existing) {
762 return existing;
763 }
764​
765 return registerConnection(
766 createEnvironmentConnection({
767 kind: "primary",
768 knownEnvironment,
769 client: createPrimaryEnvironmentClient(knownEnvironment),
770 ...createEnvironmentConnectionHandlers(),
771 }),
772 );
774​
775async function ensureSavedEnvironmentConnection(
776 record: SavedEnvironmentRecord,
777 options?: {
778 readonly client?: WsRpcClient;
779 readonly bearerToken?: string;
780 readonly role?: AuthSessionRole | null;
781 readonly serverConfig?: ServerConfig | null;
782 },
783): Promise<EnvironmentConnection> {
784 const existing = environmentConnections.get(record.environmentId);
785 if (existing) {
786 return existing;
787 }
788​
789 const bearerToken =
790 options?.bearerToken ?? (await readSavedEnvironmentBearerToken(record.environmentId));
791 if (!bearerToken) {
792 useSavedEnvironmentRuntimeStore.getState().patch(record.environmentId, {
793 authState: "requires-auth",
794 role: null,
795 connectionState: "disconnected",
796 lastError: "Saved environment is missing its saved credential. Pair it again.",
797 lastErrorAt: isoNow(),
798 });
799 throw new Error("Saved environment is missing its saved credential.");
800 }
801​
802 const client = options?.client ?? createSavedEnvironmentClient(record, bearerToken);
803 const knownEnvironment = createKnownEnvironment({
804 id: record.environmentId,
805 label: record.label,
806 source: "manual",
807 target: {
808 httpBaseUrl: record.httpBaseUrl,
809 wsBaseUrl: record.wsBaseUrl,
810 },
811 });
812 const connection = createEnvironmentConnection({
813 kind: "saved",
814 knownEnvironment: {
815 ...knownEnvironment,
816 environmentId: record.environmentId,
817 },
818 client,
819 refreshMetadata: async () => {
820 await refreshSavedEnvironmentMetadata(record, bearerToken, client);
821 },
822 onConfigSnapshot: (config) => {
823 useSavedEnvironmentRuntimeStore.getState().patch(record.environmentId, {
824 descriptor: config.environment,
825 serverConfig: config,
826 });
827 },
828 onWelcome: (payload) => {
829 useSavedEnvironmentRuntimeStore.getState().patch(record.environmentId, {
830 descriptor: payload.environment,
831 });
832 },
833 ...createEnvironmentConnectionHandlers(),
834 });
835​
836 registerConnection(connection);
837​
838 try {
839 await refreshSavedEnvironmentMetadata(
840 record,
841 bearerToken,
842 client,
843 options?.role ?? null,
844 options?.serverConfig ?? null,
845 );
846 return connection;
847 } catch (error) {
848 setRuntimeError(record.environmentId, error);
849 await removeConnection(record.environmentId).catch(() => false);
850 throw error;
851 }
853​
854async function syncSavedEnvironmentConnections(
855 records: ReadonlyArray<SavedEnvironmentRecord>,
856): Promise<void> {
857 const expectedEnvironmentIds = new Set(records.map((record) => record.environmentId));
858 const staleEnvironmentIds = [...environmentConnections.values()]
859 .filter((connection) => connection.kind === "saved")
860 .map((connection) => connection.environmentId)
861 .filter((environmentId) => !expectedEnvironmentIds.has(environmentId));
862​
863 await Promise.all(
864 staleEnvironmentIds.map((environmentId) => disconnectSavedEnvironment(environmentId)),
865 );
866 await Promise.all(
867 records.map((record) => ensureSavedEnvironmentConnection(record).catch(() => undefined)),
868 );
870​
871function stopActiveService() {
872 activeService?.stop();
873 activeService = null;
875​
876export function subscribeEnvironmentConnections(listener: () => void): () => void {
877 environmentConnectionListeners.add(listener);
878 return () => {
879 environmentConnectionListeners.delete(listener);
880 };
882​
883export function listEnvironmentConnections(): ReadonlyArray<EnvironmentConnection> {
884 return [...environmentConnections.values()];
886​
887export function readEnvironmentConnection(
888 environmentId: EnvironmentId,
889): EnvironmentConnection | null {
890 return environmentConnections.get(environmentId) ?? null;
892​
893export function requireEnvironmentConnection(environmentId: EnvironmentId): EnvironmentConnection {
894 const connection = readEnvironmentConnection(environmentId);
895 if (!connection) {
896 throw new Error(`No websocket client registered for environment ${environmentId}.`);
897 }
898 return connection;
900​
901export function getPrimaryEnvironmentConnection(): EnvironmentConnection {
902 return createPrimaryEnvironmentConnection();
904​
905export async function disconnectSavedEnvironment(environmentId: EnvironmentId): Promise<void> {
906 const connection = environmentConnections.get(environmentId);
907 if (connection?.kind !== "saved") {
908 return;
909 }
910​
911 useSavedEnvironmentRuntimeStore.getState().clear(environmentId);
912 await removeConnection(environmentId).catch(() => false);
914​
915export async function reconnectSavedEnvironment(environmentId: EnvironmentId): Promise<void> {
916 const record = getSavedEnvironmentRecord(environmentId);
917 if (!record) {
918 throw new Error("Saved environment not found.");
919 }
920​
921 const connection = environmentConnections.get(environmentId);
922 if (!connection) {
923 await ensureSavedEnvironmentConnection(record);
924 return;
925 }
926​
927 setRuntimeConnecting(environmentId);
928 try {
929 await connection.reconnect();
930 } catch (error) {
931 setRuntimeError(environmentId, error);
932 throw error;
933 }
935​
936export async function removeSavedEnvironment(environmentId: EnvironmentId): Promise<void> {
937 useSavedEnvironmentRegistryStore.getState().remove(environmentId);
938 await removeSavedEnvironmentBearerToken(environmentId);
939 await disconnectSavedEnvironment(environmentId);
941​
942export async function addSavedEnvironment(input: {
943 readonly label: string;
944 readonly pairingUrl?: string;
945 readonly host?: string;
946 readonly pairingCode?: string;
947}): Promise<SavedEnvironmentRecord> {
948 const resolvedTarget = resolveRemotePairingTarget({
949 ...(input.pairingUrl !== undefined ? { pairingUrl: input.pairingUrl } : {}),
950 ...(input.host !== undefined ? { host: input.host } : {}),
951 ...(input.pairingCode !== undefined ? { pairingCode: input.pairingCode } : {}),
952 });
953 const descriptor = await fetchRemoteEnvironmentDescriptor({
954 httpBaseUrl: resolvedTarget.httpBaseUrl,
955 });
956 const environmentId = descriptor.environmentId;
957​
958 if (environmentConnections.has(environmentId)) {
959 throw new Error("This environment is already connected.");
960 }
961​
962 const bearerSession = await bootstrapRemoteBearerSession({
963 httpBaseUrl: resolvedTarget.httpBaseUrl,
964 credential: resolvedTarget.credential,
965 });
966​
967 const record: SavedEnvironmentRecord = {
968 environmentId,
969 label: input.label.trim() || descriptor.label,
970 wsBaseUrl: resolvedTarget.wsBaseUrl,
971 httpBaseUrl: resolvedTarget.httpBaseUrl,
972 createdAt: isoNow(),
973 lastConnectedAt: isoNow(),
974 };
975​
976 await persistSavedEnvironmentRecord(record);
977 const didPersistBearerToken = await writeSavedEnvironmentBearerToken(
978 environmentId,
979 bearerSession.sessionToken,
980 );
981 if (!didPersistBearerToken) {
982 await ensureLocalApi().persistence.setSavedEnvironmentRegistry(
983 listSavedEnvironmentRecords().map((entry) => ({
984 environmentId: entry.environmentId,
985 label: entry.label,
986 httpBaseUrl: entry.httpBaseUrl,
987 wsBaseUrl: entry.wsBaseUrl,
988 createdAt: entry.createdAt,
989 lastConnectedAt: entry.lastConnectedAt,
990 })),
991 );
992 throw new Error("Unable to persist saved environment credentials.");
993 }
994 await ensureSavedEnvironmentConnection(record, {
995 bearerToken: bearerSession.sessionToken,
996 role: bearerSession.role,
997 });
998 useSavedEnvironmentRegistryStore.getState().upsert(record);
999 return record;
1001​
1002export async function ensureEnvironmentConnectionBootstrapped(
1003 environmentId: EnvironmentId,
1004): Promise<void> {
1005 await environmentConnections.get(environmentId)?.ensureBootstrapped();
1007​
1008export function startEnvironmentConnectionService(queryClient: QueryClient): () => void {
1009 if (activeService?.queryClient === queryClient) {
1010 activeService.refCount += 1;
1011 return () => {
1012 if (!activeService || activeService.queryClient !== queryClient) {
1013 return;
1015 activeService.refCount -= 1;
1016 if (activeService.refCount === 0) {
1017 stopActiveService();
1019 };
1021​
1022 stopActiveService();
1023 needsProviderInvalidation = false;
1024 const queryInvalidationThrottler = new Throttler(
1025 () => {
1026 if (!needsProviderInvalidation) {
1027 return;
1029 needsProviderInvalidation = false;
1030 void queryClient.invalidateQueries({ queryKey: providerQueryKeys.all });
1031 void queryClient.invalidateQueries({ queryKey: projectQueryKeys.all });
1032 },
1034 wait: 100,
1035 leading: false,
1036 trailing: true,
1037 },
1038 );
1039​
1040 createPrimaryEnvironmentConnection();
1041​
1042 const unsubscribeSavedEnvironments = useSavedEnvironmentRegistryStore.subscribe(() => {
1043 if (!hasSavedEnvironmentRegistryHydrated()) {
1044 return;
1046 void syncSavedEnvironmentConnections(listSavedEnvironmentRecords());
1047 });
1048​
1049 void waitForSavedEnvironmentRegistryHydration()
1050 .then(() => syncSavedEnvironmentConnections(listSavedEnvironmentRecords()))
1051 .catch(() => undefined);
1052​
1053 activeService = {
1054 queryClient,
1055 queryInvalidationThrottler,
1056 refCount: 1,
1057 stop: () => {
1058 unsubscribeSavedEnvironments();
1059 queryInvalidationThrottler.cancel();
1060 },
1061 };
1062​
1063 return () => {
1064 if (!activeService || activeService.queryClient !== queryClient) {
1065 return;
1067 activeService.refCount -= 1;
1068 if (activeService.refCount === 0) {
1069 stopActiveService();
1071 };
1073​
1074export async function resetEnvironmentServiceForTests(): Promise<void> {
1075 stopActiveService();
1076 for (const key of Array.from(threadDetailSubscriptions.keys())) {
1077 disposeThreadDetailSubscriptionByKey(key);
1079 await Promise.all(
1080 [...environmentConnections.keys()].map((environmentId) => removeConnection(environmentId)),
1081 );