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

service.ts

677 lines20.7 KB

1import {
2 type AuthSessionRole,
3 type EnvironmentId,
4 type OrchestrationEvent,
5 type OrchestrationReadModel,
6 type ServerConfig,
7 type TerminalEvent,
8 ThreadId,
9} from "@t3tools/contracts";
10import { type QueryClient } from "@tanstack/react-query";
11import { Throttler } from "@tanstack/react-pacer";
12import {
13 createKnownEnvironment,
14 getKnownEnvironmentWsBaseUrl,
15 scopedProjectKey,
16 scopedThreadKey,
17 scopeProjectRef,
18 scopeThreadRef,
19} from "@t3tools/client-runtime";
20​
21import {
22 markPromotedDraftThreadByRef,
23 markPromotedDraftThreadsByRef,
24 useComposerDraftStore,
25} from "~/composerDraftStore";
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 type SavedEnvironmentRecord,
43 useSavedEnvironmentRegistryStore,
44 useSavedEnvironmentRuntimeStore,
45 waitForSavedEnvironmentRegistryHydration,
46} from "./catalog";
47import { createEnvironmentConnection, type EnvironmentConnection } from "./connection";
48import {
49 useStore,
50 selectProjectsAcrossEnvironments,
51 selectThreadByRef,
52 selectThreadsAcrossEnvironments,
53} from "~/store";
54import { useTerminalStateStore } from "~/terminalStateStore";
55import { useUiStateStore } from "~/uiStateStore";
56import { WsTransport } from "../../rpc/wsTransport";
57import { createWsRpcClient, type WsRpcClient } from "../../rpc/wsRpcClient";
58​
59type EnvironmentServiceState = {
60 readonly queryClient: QueryClient;
61 readonly queryInvalidationThrottler: Throttler<() => void>;
62 refCount: number;
63 stop: () => void;
64};
65​
66const environmentConnections = new Map<EnvironmentId, EnvironmentConnection>();
67const environmentConnectionListeners = new Set<() => void>();
68​
69let activeService: EnvironmentServiceState | null = null;
70let needsProviderInvalidation = false;
71​
72function emitEnvironmentConnectionRegistryChange() {
73 for (const listener of environmentConnectionListeners) {
74 listener();
75 }
77​
78function getRuntimeErrorFields(error: unknown) {
79 return {
80 lastError: error instanceof Error ? error.message : String(error),
81 lastErrorAt: new Date().toISOString(),
82 } as const;
84​
85function isoNow(): string {
86 return new Date().toISOString();
88​
89function setRuntimeConnecting(environmentId: EnvironmentId) {
90 useSavedEnvironmentRuntimeStore.getState().patch(environmentId, {
91 connectionState: "connecting",
92 lastError: null,
93 lastErrorAt: null,
94 });
96​
97function setRuntimeConnected(environmentId: EnvironmentId) {
98 const connectedAt = isoNow();
99 useSavedEnvironmentRuntimeStore.getState().patch(environmentId, {
100 connectionState: "connected",
101 authState: "authenticated",
102 connectedAt,
103 disconnectedAt: null,
104 lastError: null,
105 lastErrorAt: null,
106 });
107 useSavedEnvironmentRegistryStore.getState().markConnected(environmentId, connectedAt);
109​
110function setRuntimeDisconnected(environmentId: EnvironmentId, reason?: string | null) {
111 useSavedEnvironmentRuntimeStore.getState().patch(environmentId, {
112 connectionState: "disconnected",
113 disconnectedAt: isoNow(),
114 ...(reason && reason.trim().length > 0
115 ? {
116 lastError: reason,
117 lastErrorAt: isoNow(),
118 }
119 : {}),
120 });
122​
123function setRuntimeError(environmentId: EnvironmentId, error: unknown) {
124 useSavedEnvironmentRuntimeStore.getState().patch(environmentId, {
125 connectionState: "error",
126 ...getRuntimeErrorFields(error),
127 });
129​
130function coalesceOrchestrationUiEvents(
131 events: ReadonlyArray<OrchestrationEvent>,
132): OrchestrationEvent[] {
133 if (events.length < 2) {
134 return [...events];
135 }
136​
137 const coalesced: OrchestrationEvent[] = [];
138 for (const event of events) {
139 const previous = coalesced.at(-1);
140 if (
141 previous?.type === "thread.message-sent" &&
142 event.type === "thread.message-sent" &&
143 previous.payload.threadId === event.payload.threadId &&
144 previous.payload.messageId === event.payload.messageId
145 ) {
146 coalesced[coalesced.length - 1] = {
147 ...event,
148 payload: {
149 ...event.payload,
150 attachments: event.payload.attachments ?? previous.payload.attachments,
151 createdAt: previous.payload.createdAt,
152 text:
153 !event.payload.streaming && event.payload.text.length > 0
154 ? event.payload.text
155 : previous.payload.text + event.payload.text,
156 },
157 };
158 continue;
159 }
160​
161 coalesced.push(event);
162 }
163​
164 return coalesced;
166​
167function reconcileSnapshotDerivedState() {
168 const storeState = useStore.getState();
169 const threads = selectThreadsAcrossEnvironments(storeState);
170 const projects = selectProjectsAcrossEnvironments(storeState);
171​
172 useUiStateStore.getState().syncProjects(
173 projects.map((project) => ({
174 key: scopedProjectKey(scopeProjectRef(project.environmentId, project.id)),
175 cwd: project.cwd,
176 })),
177 );
178 useUiStateStore.getState().syncThreads(
179 threads.map((thread) => ({
180 key: scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)),
181 seedVisitedAt: thread.updatedAt ?? thread.createdAt,
182 })),
183 );
184 markPromotedDraftThreadsByRef(
185 threads.map((thread) => scopeThreadRef(thread.environmentId, thread.id)),
186 );
187​
188 const activeThreadKeys = collectActiveTerminalThreadIds({
189 snapshotThreads: threads.map((thread) => ({
190 key: scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)),
191 deletedAt: null,
192 archivedAt: thread.archivedAt,
193 })),
194 draftThreadKeys: useComposerDraftStore.getState().listDraftThreadKeys(),
195 });
196 useTerminalStateStore.getState().removeOrphanedTerminalStates(activeThreadKeys);
198​
199export function shouldApplyTerminalEvent(input: {
200 serverThreadArchivedAt: string | null | undefined;
201 hasDraftThread: boolean;
202}): boolean {
203 if (input.serverThreadArchivedAt !== undefined) {
204 return input.serverThreadArchivedAt === null;
205 }
206​
207 return input.hasDraftThread;
209​
210function applyRecoveredEventBatch(
211 events: ReadonlyArray<OrchestrationEvent>,
212 environmentId: EnvironmentId,
213) {
214 if (events.length === 0) {
215 return;
216 }
217​
218 const batchEffects = deriveOrchestrationBatchEffects(events);
219 const uiEvents = coalesceOrchestrationUiEvents(events);
220 const needsProjectUiSync = events.some(
221 (event) =>
222 event.type === "project.created" ||
223 event.type === "project.meta-updated" ||
224 event.type === "project.deleted",
225 );
226​
227 if (batchEffects.needsProviderInvalidation) {
228 needsProviderInvalidation = true;
229 void activeService?.queryInvalidationThrottler.maybeExecute();
230 }
231​
232 useStore.getState().applyOrchestrationEvents(uiEvents, environmentId);
233 if (needsProjectUiSync) {
234 const projects = selectProjectsAcrossEnvironments(useStore.getState());
235 useUiStateStore.getState().syncProjects(
236 projects.map((project) => ({
237 key: scopedProjectKey(scopeProjectRef(project.environmentId, project.id)),
238 cwd: project.cwd,
239 })),
240 );
241 }
242​
243 const needsThreadUiSync = events.some(
244 (event) => event.type === "thread.created" || event.type === "thread.deleted",
245 );
246 if (needsThreadUiSync) {
247 const threads = selectThreadsAcrossEnvironments(useStore.getState());
248 useUiStateStore.getState().syncThreads(
249 threads.map((thread) => ({
250 key: scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)),
251 seedVisitedAt: thread.updatedAt ?? thread.createdAt,
252 })),
253 );
254 }
255​
256 const draftStore = useComposerDraftStore.getState();
257 for (const threadId of batchEffects.promoteDraftThreadIds) {
258 markPromotedDraftThreadByRef(scopeThreadRef(environmentId, threadId));
259 }
260 for (const threadId of batchEffects.clearDeletedThreadIds) {
261 draftStore.clearDraftThread(scopeThreadRef(environmentId, threadId));
262 useUiStateStore
263 .getState()
264 .clearThreadUi(scopedThreadKey(scopeThreadRef(environmentId, threadId)));
265 }
266 for (const threadId of batchEffects.removeTerminalStateThreadIds) {
267 useTerminalStateStore.getState().removeTerminalState(scopeThreadRef(environmentId, threadId));
268 }
270​
271function createEnvironmentConnectionHandlers() {
272 return {
273 applyEventBatch: applyRecoveredEventBatch,
274 syncSnapshot: (snapshot: OrchestrationReadModel, environmentId: EnvironmentId) => {
275 useStore.getState().syncServerReadModel(snapshot, environmentId);
276 reconcileSnapshotDerivedState();
277 },
278 applyTerminalEvent: (event: TerminalEvent, environmentId: EnvironmentId) => {
279 const threadRef = scopeThreadRef(environmentId, ThreadId.makeUnsafe(event.threadId));
280 const serverThread = selectThreadByRef(useStore.getState(), threadRef);
281 const hasDraftThread =
282 useComposerDraftStore.getState().getDraftThreadByRef(threadRef) !== null;
283 if (
284 !shouldApplyTerminalEvent({
285 serverThreadArchivedAt: serverThread?.archivedAt,
286 hasDraftThread,
287 })
288 ) {
289 return;
290 }
291 useTerminalStateStore.getState().applyTerminalEvent(threadRef, event);
292 },
293 };
295​
296function createPrimaryEnvironmentClient(
297 knownEnvironment: ReturnType<typeof getPrimaryKnownEnvironment>,
298) {
299 const wsBaseUrl = getKnownEnvironmentWsBaseUrl(knownEnvironment);
300 if (!wsBaseUrl) {
301 throw new Error(
302 `Unable to resolve websocket URL for ${knownEnvironment?.label ?? "primary environment"}.`,
303 );
304 }
305​
306 return createWsRpcClient(new WsTransport(wsBaseUrl));
308​
309function createSavedEnvironmentClient(record: SavedEnvironmentRecord): WsRpcClient {
310 useSavedEnvironmentRuntimeStore.getState().ensure(record.environmentId);
311​
312 return createWsRpcClient(
313 new WsTransport(
314 () =>
315 resolveRemoteWebSocketConnectionUrl({
316 wsBaseUrl: record.wsBaseUrl,
317 httpBaseUrl: record.httpBaseUrl,
318 bearerToken: record.bearerToken,
319 }),
320 {
321 onAttempt: () => {
322 setRuntimeConnecting(record.environmentId);
323 },
324 onOpen: () => {
325 setRuntimeConnected(record.environmentId);
326 },
327 onError: (message: string) => {
328 useSavedEnvironmentRuntimeStore.getState().patch(record.environmentId, {
329 connectionState: "error",
330 lastError: message,
331 lastErrorAt: isoNow(),
332 });
333 },
334 onClose: (details: { readonly code: number; readonly reason: string }) => {
335 setRuntimeDisconnected(record.environmentId, details.reason);
336 },
337 },
338 ),
339 );
341​
342async function refreshSavedEnvironmentMetadata(
343 record: SavedEnvironmentRecord,
344 client: WsRpcClient,
345 roleHint?: AuthSessionRole | null,
346 configHint?: ServerConfig | null,
347): Promise<void> {
348 const [serverConfig, sessionState] = await Promise.all([
349 configHint ? Promise.resolve(configHint) : client.server.getConfig(),
350 fetchRemoteSessionState({
351 httpBaseUrl: record.httpBaseUrl,
352 bearerToken: record.bearerToken,
353 }),
354 ]);
355​
356 useSavedEnvironmentRuntimeStore.getState().patch(record.environmentId, {
357 authState: sessionState.authenticated ? "authenticated" : "requires-auth",
358 descriptor: serverConfig.environment,
359 serverConfig,
360 role: sessionState.authenticated ? (sessionState.role ?? roleHint ?? null) : null,
361 });
363​
364function registerConnection(connection: EnvironmentConnection): EnvironmentConnection {
365 const existing = environmentConnections.get(connection.environmentId);
366 if (existing && existing !== connection) {
367 throw new Error(`Environment ${connection.environmentId} already has an active connection.`);
368 }
369 environmentConnections.set(connection.environmentId, connection);
370 emitEnvironmentConnectionRegistryChange();
371 return connection;
373​
374async function removeConnection(environmentId: EnvironmentId): Promise<boolean> {
375 const connection = environmentConnections.get(environmentId);
376 if (!connection) {
377 return false;
378 }
379​
380 environmentConnections.delete(environmentId);
381 emitEnvironmentConnectionRegistryChange();
382 await connection.dispose();
383 return true;
385​
386function createPrimaryEnvironmentConnection(): EnvironmentConnection {
387 const knownEnvironment = getPrimaryKnownEnvironment();
388 if (!knownEnvironment?.environmentId) {
389 throw new Error("Unable to resolve the primary environment.");
390 }
391​
392 const existing = environmentConnections.get(knownEnvironment.environmentId);
393 if (existing) {
394 return existing;
395 }
396​
397 return registerConnection(
398 createEnvironmentConnection({
399 kind: "primary",
400 knownEnvironment,
401 client: createPrimaryEnvironmentClient(knownEnvironment),
402 ...createEnvironmentConnectionHandlers(),
403 }),
404 );
406​
407async function ensureSavedEnvironmentConnection(
408 record: SavedEnvironmentRecord,
409 options?: {
410 readonly client?: WsRpcClient;
411 readonly role?: AuthSessionRole | null;
412 readonly serverConfig?: ServerConfig | null;
413 },
414): Promise<EnvironmentConnection> {
415 const existing = environmentConnections.get(record.environmentId);
416 if (existing) {
417 return existing;
418 }
419​
420 const client = options?.client ?? createSavedEnvironmentClient(record);
421 const knownEnvironment = createKnownEnvironment({
422 id: record.environmentId,
423 label: record.label,
424 source: "manual",
425 target: {
426 httpBaseUrl: record.httpBaseUrl,
427 wsBaseUrl: record.wsBaseUrl,
428 },
429 });
430 const connection = createEnvironmentConnection({
431 kind: "saved",
432 knownEnvironment: {
433 ...knownEnvironment,
434 environmentId: record.environmentId,
435 },
436 client,
437 refreshMetadata: async () => {
438 await refreshSavedEnvironmentMetadata(record, client);
439 },
440 onConfigSnapshot: (config) => {
441 useSavedEnvironmentRuntimeStore.getState().patch(record.environmentId, {
442 descriptor: config.environment,
443 serverConfig: config,
444 });
445 },
446 onWelcome: (payload) => {
447 useSavedEnvironmentRuntimeStore.getState().patch(record.environmentId, {
448 descriptor: payload.environment,
449 });
450 },
451 ...createEnvironmentConnectionHandlers(),
452 });
453​
454 registerConnection(connection);
455​
456 try {
457 await refreshSavedEnvironmentMetadata(
458 record,
459 client,
460 options?.role ?? null,
461 options?.serverConfig ?? null,
462 );
463 return connection;
464 } catch (error) {
465 setRuntimeError(record.environmentId, error);
466 await removeConnection(record.environmentId).catch(() => false);
467 throw error;
468 }
470​
471async function syncSavedEnvironmentConnections(
472 records: ReadonlyArray<SavedEnvironmentRecord>,
473): Promise<void> {
474 const expectedEnvironmentIds = new Set(records.map((record) => record.environmentId));
475 const staleEnvironmentIds = [...environmentConnections.values()]
476 .filter((connection) => connection.kind === "saved")
477 .map((connection) => connection.environmentId)
478 .filter((environmentId) => !expectedEnvironmentIds.has(environmentId));
479​
480 await Promise.all(
481 staleEnvironmentIds.map((environmentId) => disconnectSavedEnvironment(environmentId)),
482 );
483 await Promise.all(
484 records.map((record) => ensureSavedEnvironmentConnection(record).catch(() => undefined)),
485 );
487​
488function stopActiveService() {
489 activeService?.stop();
490 activeService = null;
492​
493export function subscribeEnvironmentConnections(listener: () => void): () => void {
494 environmentConnectionListeners.add(listener);
495 return () => {
496 environmentConnectionListeners.delete(listener);
497 };
499​
500export function listEnvironmentConnections(): ReadonlyArray<EnvironmentConnection> {
501 return [...environmentConnections.values()];
503​
504export function readEnvironmentConnection(
505 environmentId: EnvironmentId,
506): EnvironmentConnection | null {
507 return environmentConnections.get(environmentId) ?? null;
509​
510export function requireEnvironmentConnection(environmentId: EnvironmentId): EnvironmentConnection {
511 const connection = readEnvironmentConnection(environmentId);
512 if (!connection) {
513 throw new Error(`No websocket client registered for environment ${environmentId}.`);
514 }
515 return connection;
517​
518export function getPrimaryEnvironmentConnection(): EnvironmentConnection {
519 return createPrimaryEnvironmentConnection();
521​
522export async function disconnectSavedEnvironment(environmentId: EnvironmentId): Promise<void> {
523 const connection = environmentConnections.get(environmentId);
524 if (connection?.kind !== "saved") {
525 return;
526 }
527​
528 useSavedEnvironmentRuntimeStore.getState().clear(environmentId);
529 await removeConnection(environmentId).catch(() => false);
531​
532export async function reconnectSavedEnvironment(environmentId: EnvironmentId): Promise<void> {
533 const record = getSavedEnvironmentRecord(environmentId);
534 if (!record) {
535 throw new Error("Saved environment not found.");
536 }
537​
538 const connection = environmentConnections.get(environmentId);
539 if (!connection) {
540 await ensureSavedEnvironmentConnection(record);
541 return;
542 }
543​
544 setRuntimeConnecting(environmentId);
545 try {
546 await connection.reconnect();
547 } catch (error) {
548 setRuntimeError(environmentId, error);
549 throw error;
550 }
552​
553export async function removeSavedEnvironment(environmentId: EnvironmentId): Promise<void> {
554 useSavedEnvironmentRegistryStore.getState().remove(environmentId);
555 await disconnectSavedEnvironment(environmentId);
557​
558export async function addSavedEnvironment(input: {
559 readonly label: string;
560 readonly pairingUrl?: string;
561 readonly host?: string;
562 readonly pairingCode?: string;
563}): Promise<SavedEnvironmentRecord> {
564 const resolvedTarget = resolveRemotePairingTarget({
565 ...(input.pairingUrl !== undefined ? { pairingUrl: input.pairingUrl } : {}),
566 ...(input.host !== undefined ? { host: input.host } : {}),
567 ...(input.pairingCode !== undefined ? { pairingCode: input.pairingCode } : {}),
568 });
569 const descriptor = await fetchRemoteEnvironmentDescriptor({
570 httpBaseUrl: resolvedTarget.httpBaseUrl,
571 });
572 const environmentId = descriptor.environmentId;
573​
574 if (environmentConnections.has(environmentId)) {
575 throw new Error("This environment is already connected.");
576 }
577​
578 const bearerSession = await bootstrapRemoteBearerSession({
579 httpBaseUrl: resolvedTarget.httpBaseUrl,
580 credential: resolvedTarget.credential,
581 });
582​
583 const record: SavedEnvironmentRecord = {
584 environmentId,
585 label: input.label.trim() || descriptor.label,
586 wsBaseUrl: resolvedTarget.wsBaseUrl,
587 httpBaseUrl: resolvedTarget.httpBaseUrl,
588 bearerToken: bearerSession.sessionToken,
589 createdAt: isoNow(),
590 lastConnectedAt: isoNow(),
591 };
592​
593 await ensureSavedEnvironmentConnection(record, {
594 role: bearerSession.role,
595 });
596 useSavedEnvironmentRegistryStore.getState().upsert(record);
597 return record;
599​
600export async function ensureEnvironmentConnectionBootstrapped(
601 environmentId: EnvironmentId,
602): Promise<void> {
603 await environmentConnections.get(environmentId)?.ensureBootstrapped();
605​
606export function startEnvironmentConnectionService(queryClient: QueryClient): () => void {
607 if (activeService?.queryClient === queryClient) {
608 activeService.refCount += 1;
609 return () => {
610 if (!activeService || activeService.queryClient !== queryClient) {
611 return;
612 }
613 activeService.refCount -= 1;
614 if (activeService.refCount === 0) {
615 stopActiveService();
616 }
617 };
618 }
619​
620 stopActiveService();
621 needsProviderInvalidation = false;
622 const queryInvalidationThrottler = new Throttler(
623 () => {
624 if (!needsProviderInvalidation) {
625 return;
626 }
627 needsProviderInvalidation = false;
628 void queryClient.invalidateQueries({ queryKey: providerQueryKeys.all });
629 void queryClient.invalidateQueries({ queryKey: projectQueryKeys.all });
630 },
631 {
632 wait: 100,
633 leading: false,
634 trailing: true,
635 },
636 );
637​
638 createPrimaryEnvironmentConnection();
639​
640 const unsubscribeSavedEnvironments = useSavedEnvironmentRegistryStore.subscribe(() => {
641 if (!hasSavedEnvironmentRegistryHydrated()) {
642 return;
643 }
644 void syncSavedEnvironmentConnections(listSavedEnvironmentRecords());
645 });
646​
647 void waitForSavedEnvironmentRegistryHydration()
648 .then(() => syncSavedEnvironmentConnections(listSavedEnvironmentRecords()))
649 .catch(() => undefined);
650​
651 activeService = {
652 queryClient,
653 queryInvalidationThrottler,
654 refCount: 1,
655 stop: () => {
656 unsubscribeSavedEnvironments();
657 queryInvalidationThrottler.cancel();
658 },
659 };
660​
661 return () => {
662 if (!activeService || activeService.queryClient !== queryClient) {
663 return;
664 }
665 activeService.refCount -= 1;
666 if (activeService.refCount === 0) {
667 stopActiveService();
668 }
669 };
671​
672export async function resetEnvironmentServiceForTests(): Promise<void> {
673 stopActiveService();
674 await Promise.all(
675 [...environmentConnections.keys()].map((environmentId) => removeConnection(environmentId)),
676 );