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

service.ts

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