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