The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import type { EnvironmentId } from "@t3tools/contracts"; |
| 2 | import { Atom } from "effect/reactivity"; |
| 3 | |
| 4 | import { environmentCatalog } from "../connection/catalog"; |
| 5 | import { appAtomRegistry } from "../rpc/atomRegistry"; |
| 6 | |
| 7 | export const primaryEnvironmentIdAtom = Atom.make((get) => { |
| 8 | for (const [environmentId, entry] of get(environmentCatalog.catalogValueAtom).entries) { |
| 9 | if (entry.target._tag === "PrimaryConnectionTarget") { |
| 10 | return environmentId; |
| 11 | } |
| 12 | } |
| 13 | return null; |
| 14 | }).pipe(Atom.withLabel("web-primary-environment-id")); |
| 15 | |
| 16 | export const hostEnvironmentIdAtom = Atom.make<string | null>(null).pipe( |
| 17 | Atom.keepAlive, |
| 18 | Atom.withLabel("web-host-environment-id"), |
| 19 | ); |
| 20 | |
| 21 | // This computer's environment: the primary, else a connection to the service sharing the app's T3 home. |
| 22 | export function createLocalEnvironmentIdAtom(input: { |
| 23 | readonly primaryEnvironmentIdAtom: Atom.Atom<EnvironmentId | null>; |
| 24 | readonly hostEnvironmentIdAtom: Atom.Atom<string | null>; |
| 25 | readonly catalogValueAtom: Atom.Atom<{ readonly entries: ReadonlyMap<EnvironmentId, unknown> }>; |
| 26 | }) { |
| 27 | return Atom.make((get) => { |
| 28 | const primaryEnvironmentId = get(input.primaryEnvironmentIdAtom); |
| 29 | if (primaryEnvironmentId !== null) return primaryEnvironmentId; |
| 30 | const hostEnvironmentId = get(input.hostEnvironmentIdAtom); |
| 31 | for (const environmentId of get(input.catalogValueAtom).entries.keys()) { |
| 32 | if (environmentId === hostEnvironmentId) return environmentId; |
| 33 | } |
| 34 | return null; |
| 35 | }).pipe(Atom.withLabel("web-local-environment-id")); |
| 36 | } |
| 37 | |
| 38 | export const localEnvironmentIdAtom = createLocalEnvironmentIdAtom({ |
| 39 | primaryEnvironmentIdAtom, |
| 40 | hostEnvironmentIdAtom, |
| 41 | catalogValueAtom: environmentCatalog.catalogValueAtom, |
| 42 | }); |
| 43 | |
| 44 | export function startHostEnvironmentLookup(): void { |
| 45 | void window.desktopBridge |
| 46 | ?.getHostEnvironmentId?.() |
| 47 | .then((environmentId) => appAtomRegistry.set(hostEnvironmentIdAtom, environmentId)) |
| 48 | .catch(() => {}); |
| 49 | } |