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

service.ts

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