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

service.ts

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