Open History to see the last commit
1import type { ScopedThreadRef } from "@t3tools/contracts";
2
3import { rootNavigationRef } from "../../lib/rootNavigation";
4import { appAtomRegistry } from "../../state/atom-registry";
5import { environmentThreadShells } from "../../state/threads";
6
7const TIMEOUT_MS = 2_000;
8const POLL_INTERVAL_MS = 40;
9
10/** Resolves true once a thread this client just created, such as a fork, reaches its state. */
11export async function waitForThreadShell(ref: ScopedThreadRef): Promise<boolean> {
12 const atom = environmentThreadShells.threadShellAtom(ref);
13 const read = () => appAtomRegistry.get(atom) !== null;
14 const deadline = Date.now() + TIMEOUT_MS;
15 while (!read() && Date.now() < deadline) {
16 await new Promise<void>((resolve) => {
17 setTimeout(resolve, Math.min(POLL_INTERVAL_MS, deadline - Date.now()));
18 });
19 }
20 return read();
21}
22
23// The detail column reuses a route's key when it switches threads, so the thread ids count too.
24function shownPage() {
25 const route = rootNavigationRef.isReady() ? rootNavigationRef.getCurrentRoute() : undefined;
26 if (!route) return null;
27 const params = route.params as { environmentId?: unknown; threadId?: unknown } | undefined;
28 return JSON.stringify([route.key, route.name, params?.environmentId, params?.threadId]);
29}
30
31/** Notes the page shown now; the returned check tells whether the user is still on it. */
32export function watchShownPage(): () => boolean {
33 const shown = shownPage();
34 return () => shown !== null && shownPage() === shown;
35}