Open History to see the last commit
1import {
2 connectionRoutes,
3 type ConnectionRoute,
4 type ConnectionTarget,
5} from "@t3tools/client-runtime/connection";
6import {
7 REMOTE_CAPABLE_EDITOR_IDS,
8 type EditorId,
9 type EnvironmentId,
10 type RemoteOpenTarget,
11} from "@t3tools/contracts";
12import * as Option from "effect/Option";
13import * as Schema from "effect/Schema";
14import { Atom } from "effect/reactivity";
15import { useAtomValue } from "@effect/atom-react";
16
17import { browserClientOs, type BrowserIdentity } from "~/connection/clientMetadata";
18import { isDesktopLocalConnectionTarget } from "~/connection/desktopLocal";
19import { isLoopbackHostname } from "~/environments/primary/target";
20import { useLocalStorage } from "~/hooks/useLocalStorage";
21import { environmentPresentations } from "~/state/presentation";
22import { hostEnvironmentIdAtom } from "~/state/primaryEnvironment";
23
24export interface RemoteOpenHost {
25 readonly kind: "ssh-alias" | RemoteOpenTarget["kind"];
26 readonly host: string;
27 readonly username?: string;
28}
29
30export type RemoteOpenState =
31 | { readonly mode: "local-exec" }
32 | { readonly mode: "remote-links"; readonly host: RemoteOpenHost }
33 | { readonly mode: "remote-unavailable" };
34
35export type RemoteOpenMode = RemoteOpenState["mode"];
36
37export interface RemoteOpenResolution {
38 readonly state: RemoteOpenState;
39 readonly isResolved: boolean;
40}
41
42const LOCAL_EXEC: RemoteOpenState = { mode: "local-exec" };
43const REMOTE_UNAVAILABLE: RemoteOpenState = { mode: "remote-unavailable" };
44const UNRESOLVED_REMOTE_OPEN: RemoteOpenResolution = {
45 state: LOCAL_EXEC,
46 isResolved: false,
47};
48
49function parseHostname(url: string): string | null {
50 try {
51 return new URL(url).hostname;
52 } catch {
53 return null;
54 }
55}
56
57function firstSshTarget(routes: ReadonlyArray<ConnectionRoute>) {
58 for (const route of routes) {
59 const profile = Option.getOrNull(route.profile);
60 if (profile?._tag === "SshConnectionProfile" && profile.target.alias.length > 0) {
61 return profile.target;
62 }
63 }
64 return null;
65}
66
67export function resolveRemoteOpenState(input: {
68 readonly target: ConnectionTarget | null;
69 /** The environment's saved routes, preferred route first. */
70 readonly routes: ReadonlyArray<ConnectionRoute>;
71 readonly remoteOpenTargets: ReadonlyArray<RemoteOpenTarget> | undefined;
72 readonly isDesktopRenderer: boolean;
73 readonly hostEnvironmentId: string | null;
74}): RemoteOpenState {
75 const { target } = input;
76 if (target === null || target.environmentId === input.hostEnvironmentId) {
77 return LOCAL_EXEC;
78 }
79 if (target._tag === "PrimaryConnectionTarget") {
80 // Desktop owns its primary even at a non-loopback WSL2 NAT address.
81 if (input.isDesktopRenderer) {
82 return LOCAL_EXEC;
83 }
84 const hostname = parseHostname(target.httpBaseUrl);
85 if (hostname !== null && isLoopbackHostname(hostname)) {
86 return LOCAL_EXEC;
87 }
88 } else if (isDesktopLocalConnectionTarget(target)) {
89 return LOCAL_EXEC;
90 }
91
92 const sshTarget = firstSshTarget(input.routes);
93 if (sshTarget !== null) {
94 const { alias } = sshTarget;
95 const userSeparator = alias.lastIndexOf("@");
96 const host = userSeparator === -1 ? alias : alias.slice(userSeparator + 1);
97 const username =
98 sshTarget.username?.trim() || (userSeparator === -1 ? null : alias.slice(0, userSeparator));
99 return {
100 mode: "remote-links",
101 host: {
102 kind: "ssh-alias",
103 host,
104 ...(username === null ? {} : { username }),
105 },
106 };
107 }
108 const advertised = input.remoteOpenTargets?.[0];
109 if (advertised !== undefined) {
110 return { mode: "remote-links", host: advertised };
111 }
112 return REMOTE_UNAVAILABLE;
113}
114
115function remoteOpenStatesEqual(previous: RemoteOpenState, next: RemoteOpenState): boolean {
116 if (previous.mode !== next.mode) return false;
117 if (previous.mode !== "remote-links" || next.mode !== "remote-links") return true;
118 return (
119 previous.host.kind === next.host.kind &&
120 previous.host.host === next.host.host &&
121 previous.host.username === next.host.username
122 );
123}
124
125// Config pushes recreate presentations; preserve equal resolutions to avoid re-rendering file links.
126const remoteOpenResolutionAtom = Atom.family((environmentId: EnvironmentId) =>
127 Atom.make((get): RemoteOpenResolution => {
128 const presentation = get(environmentPresentations.presentationAtom(environmentId));
129 const entry = presentation?.entry ?? null;
130 if (entry === null) {
131 return UNRESOLVED_REMOTE_OPEN;
132 }
133 const next: RemoteOpenResolution = {
134 state: resolveRemoteOpenState({
135 target: entry.target,
136 routes: connectionRoutes(entry),
137 remoteOpenTargets: presentation?.serverConfig?.remoteOpenTargets,
138 isDesktopRenderer: window.desktopBridge !== undefined,
139 hostEnvironmentId: get(hostEnvironmentIdAtom),
140 }),
141 isResolved: true,
142 };
143 const previous = Option.getOrNull(get.self<RemoteOpenResolution>());
144 return previous !== null &&
145 previous.isResolved &&
146 remoteOpenStatesEqual(previous.state, next.state)
147 ? previous
148 : next;
149 }).pipe(Atom.withLabel(`remote-open-resolution:${environmentId}`)),
150);
151
152const UNRESOLVED_REMOTE_OPEN_ATOM = Atom.make(UNRESOLVED_REMOTE_OPEN);
153
154export function useRemoteOpenResolution(environmentId: EnvironmentId | null): RemoteOpenResolution {
155 return useAtomValue(
156 environmentId === null ? UNRESOLVED_REMOTE_OPEN_ATOM : remoteOpenResolutionAtom(environmentId),
157 );
158}
159
160export function useRemoteOpenState(environmentId: EnvironmentId | null): RemoteOpenState {
161 return useRemoteOpenResolution(environmentId).state;
162}
163
164const REMOTE_FALLBACK_EDITORS: ReadonlyArray<EditorId> = ["vscode"];
165
166// Phone and tablet browsers have no desktop editor to receive a vscode:// remote link.
167export function remoteFallbackEditors(identity: BrowserIdentity): ReadonlyArray<EditorId> {
168 const os = browserClientOs(identity);
169 return os === "iOS" || os === "Android" ? [] : REMOTE_FALLBACK_EDITORS;
170}
171
172// Probed once per page: installed editors rarely change, and the probe spawns processes.
173const remoteCapableEditorsAtom = Atom.make((get): ReadonlyArray<EditorId> => {
174 const probe = window.desktopBridge?.probeRemoteEditors;
175 probe?.().then(
176 (ids) => {
177 const remoteCapable = ids.filter((id) => REMOTE_CAPABLE_EDITOR_IDS.includes(id));
178 if (remoteCapable.length > 0) get.setSelf(remoteCapable);
179 },
180 () => undefined,
181 );
182 return remoteFallbackEditors(navigator);
183}).pipe(Atom.keepAlive, Atom.withLabel("remote-capable-editors"));
184
185export function useRemoteCapableEditors(): ReadonlyArray<EditorId> {
186 return useAtomValue(remoteCapableEditorsAtom);
187}
188
189/** Resolves false when the desktop refuses the URL, including unsupported editor schemes. */
190export async function openRemoteEditorUrl(url: string): Promise<boolean> {
191 const bridge = window.desktopBridge;
192 if (bridge !== undefined) {
193 try {
194 return await bridge.openExternal(url);
195 } catch {
196 return false;
197 }
198 }
199 window.location.assign(url);
200 return true;
201}
202
203const REMOTE_OPEN_HINT_KEY = "t3code:remote-open-hint-seen";
204
205export function useRemoteOpenHint(): readonly [seen: boolean, markSeen: () => void] {
206 const [seen, setSeen] = useLocalStorage(REMOTE_OPEN_HINT_KEY, false, Schema.Boolean);
207 return [seen, () => setSeen(true)] as const;
208}