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