The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import { useAtomValue } from "@effect/atom-react"; |
| 2 | import { |
| 3 | allowsPreviewTunnel, |
| 4 | type DesktopPortForward, |
| 5 | type EnvironmentId, |
| 6 | } from "@t3tools/contracts"; |
| 7 | import * as Effect from "effect/Effect"; |
| 8 | import * as Option from "effect/Option"; |
| 9 | import * as Queue from "effect/Queue"; |
| 10 | import * as Schema from "effect/Schema"; |
| 11 | import * as Stream from "effect/Stream"; |
| 12 | import * as AsyncResult from "effect/reactivity/AsyncResult"; |
| 13 | import { Atom } from "effect/reactivity"; |
| 14 | import { msg } from "gt-react"; |
| 15 | |
| 16 | import type { ConnectionTarget } from "@t3tools/client-runtime/connection"; |
| 17 | |
| 18 | import { tunnelsEnvironmentLoopback } from "../browser/browserTargetResolver"; |
| 19 | import { m } from "../i18n/messages"; |
| 20 | import { environmentAtomList } from "./environmentAtomList"; |
| 21 | import { environmentSession } from "./session"; |
| 22 | |
| 23 | const EMPTY_FORWARDS: ReadonlyArray<DesktopPortForward> = []; |
| 24 | |
| 25 | const previewBridge = () => |
| 26 | typeof window === "undefined" ? undefined : window.desktopBridge?.preview; |
| 27 | |
| 28 | /** Ports of other environments the desktop app forwards to this machine; empty elsewhere. */ |
| 29 | const portForwardsAtom = Atom.make( |
| 30 | Stream.callback<ReadonlyArray<DesktopPortForward>>((queue) => |
| 31 | Effect.gen(function* () { |
| 32 | const bridge = previewBridge(); |
| 33 | if (!bridge) return yield* Effect.never; |
| 34 | let changed = false; |
| 35 | yield* Effect.acquireRelease( |
| 36 | Effect.sync(() => |
| 37 | bridge.onPortForwards((forwards) => { |
| 38 | changed = true; |
| 39 | Queue.offerUnsafe(queue, forwards); |
| 40 | }), |
| 41 | ), |
| 42 | (unsubscribe) => Effect.sync(unsubscribe), |
| 43 | ); |
| 44 | const initial = yield* Effect.promise(() => bridge.listPortForwards()); |
| 45 | if (!changed) Queue.offerUnsafe(queue, initial); |
| 46 | return yield* Effect.never; |
| 47 | }), |
| 48 | ), |
| 49 | { initialValue: EMPTY_FORWARDS }, |
| 50 | ).pipe(Atom.keepAlive, Atom.withLabel("desktop:port-forwards")); |
| 51 | |
| 52 | export function usePortForwards(): ReadonlyArray<DesktopPortForward> { |
| 53 | return AsyncResult.getOrElse(useAtomValue(portForwardsAtom), () => EMPTY_FORWARDS); |
| 54 | } |
| 55 | |
| 56 | /** Only the desktop app forwards, and only from environments whose tunnel it may use. */ |
| 57 | export const canForwardPorts = (environment: { |
| 58 | readonly entry: { readonly target: ConnectionTarget }; |
| 59 | readonly serverConfig: Parameters<typeof allowsPreviewTunnel>[0] | null; |
| 60 | }): boolean => |
| 61 | previewBridge() !== undefined && |
| 62 | tunnelsEnvironmentLoopback(environment.entry.target) && |
| 63 | environment.serverConfig !== null && |
| 64 | allowsPreviewTunnel(environment.serverConfig); |
| 65 | |
| 66 | /** |
| 67 | * Whether the environment runs on another machine. A saved route can still lead back to this |
| 68 | * computer (its own Tailscale address, a relay), where a forward would only loop. |
| 69 | */ |
| 70 | export type ForwardLocality = "remote" | "local" | "pending" | "unknown"; |
| 71 | |
| 72 | class PortForwardLocalityError extends Schema.TaggedError<PortForwardLocalityError>()( |
| 73 | "PortForwardLocalityError", |
| 74 | { environmentId: Schema.String, cause: Schema.Defect() }, |
| 75 | ) { |
| 76 | override get message(): string { |
| 77 | return m(msg("Could not tell whether this environment runs on this computer.")); |
| 78 | } |
| 79 | } |
| 80 | |
| 81 | const localityResultAtom = Atom.family((environmentId: EnvironmentId) => |
| 82 | Atom.make((get) => { |
| 83 | // Each established connection probes anew, so a failed probe never outlives a reconnect. |
| 84 | const connection = AsyncResult.getOrElse( |
| 85 | get(environmentSession.transportSessionAtom(environmentId)), |
| 86 | () => Option.none(), |
| 87 | ); |
| 88 | const bridge = previewBridge(); |
| 89 | if (Option.isNone(connection) || bridge === undefined) return Effect.never; |
| 90 | return Effect.tryPromise({ |
| 91 | try: () => bridge.sharesLoopback(environmentId), |
| 92 | catch: (cause) => new PortForwardLocalityError({ environmentId, cause }), |
| 93 | }).pipe(Effect.map((shares): ForwardLocality => (shares ? "local" : "remote"))); |
| 94 | }).pipe( |
| 95 | Atom.setIdleTTL(10 * 60_000), |
| 96 | Atom.withLabel(`desktop:port-forward-locality-probe:${environmentId}`), |
| 97 | ), |
| 98 | ); |
| 99 | |
| 100 | const localityAtom = Atom.family((environmentId: EnvironmentId) => |
| 101 | Atom.make((get): ForwardLocality => { |
| 102 | const result = get(localityResultAtom(environmentId)); |
| 103 | if (AsyncResult.isSuccess(result)) return result.value; |
| 104 | return AsyncResult.isFailure(result) ? "unknown" : "pending"; |
| 105 | }).pipe(Atom.withLabel(`desktop:port-forward-locality:${environmentId}`)), |
| 106 | ); |
| 107 | |
| 108 | const NO_LOCALITY = Atom.make<ForwardLocality>("unknown").pipe( |
| 109 | Atom.withLabel("desktop:port-forward-locality:none"), |
| 110 | ); |
| 111 | |
| 112 | /** Pass `null` for an environment the desktop doesn't tunnel to; that one never probes. */ |
| 113 | export function useForwardLocality(environmentId: EnvironmentId | null): ForwardLocality { |
| 114 | return useAtomValue(environmentId === null ? NO_LOCALITY : localityAtom(environmentId)); |
| 115 | } |
| 116 | |
| 117 | export const forwardLocalitiesAtom = environmentAtomList( |
| 118 | "desktop:port-forward-localities", |
| 119 | localityAtom, |
| 120 | ); |
| 121 | |
| 122 | export const findPortForward = ( |
| 123 | forwards: ReadonlyArray<DesktopPortForward>, |
| 124 | environmentId: EnvironmentId, |
| 125 | remotePort: number, |
| 126 | ) => |
| 127 | forwards.find( |
| 128 | (forward) => forward.environmentId === environmentId && forward.remotePort === remotePort, |
| 129 | ); |
| 130 | |
| 131 | export function forwardPort(environmentId: EnvironmentId, remotePort: number) { |
| 132 | const bridge = previewBridge(); |
| 133 | if (!bridge) return Promise.reject(new Error(m(msg("Port forwarding needs the desktop app.")))); |
| 134 | return bridge.forwardPort(environmentId, remotePort).catch((error: unknown) => { |
| 135 | // Electron flattens main-process errors into "Error invoking remote method '…': Tag: text". |
| 136 | const raw = error instanceof Error ? error.message : String(error); |
| 137 | throw new Error( |
| 138 | raw.includes("LoopbackTunnelSameMachineError") |
| 139 | ? m( |
| 140 | msg("This environment runs on this computer, so localhost:{port} already reaches it.", { |
| 141 | port: remotePort, |
| 142 | }), |
| 143 | ) |
| 144 | : raw.includes("LoopbackTunnelUnavailableError") |
| 145 | ? m(msg("This environment can't be reached right now. Try again once it reconnects.")) |
| 146 | : raw.replace(/^Error invoking remote method '[^']*':\s*(\w+Error:\s*)?/u, ""), |
| 147 | { cause: error }, |
| 148 | ); |
| 149 | }); |
| 150 | } |
| 151 | |
| 152 | export function stopPortForward(environmentId: EnvironmentId, remotePort: number) { |
| 153 | return previewBridge()?.stopPortForward(environmentId, remotePort) ?? Promise.resolve(); |
| 154 | } |
| 155 | |
| 156 | /** `url` with its host and port moved to the forward's end on this machine. */ |
| 157 | export function forwardedUrl(forward: DesktopPortForward, url?: string): string { |
| 158 | const local = new URL(url ?? "http://localhost/"); |
| 159 | local.hostname = "localhost"; |
| 160 | local.port = String(forward.localPort); |
| 161 | return local.toString(); |
| 162 | } |