Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

remoteOpen.ts

189 lines6.4 KB

1/**
2 * Remote open-in-editor: when this client is not on the environment's
3 * machine, "Open" must hand the OS a `vscode://vscode-remote/ssh-remote+…`
4 * deep link (local editor connects over SSH) instead of exec'ing an editor
5 * on the environment host.
6 *
7 * Host precedence: a desktop-SSH environment's real `~/.ssh/config` alias
8 * beats server-advertised names; among advertised names the tailnet MagicDNS
9 * name beats mDNS `<hostname>.local` (server sends them in that order).
10 */
11import type { ConnectionTarget } from "@t3tools/client-runtime/connection";
12import {
13 REMOTE_CAPABLE_EDITOR_IDS,
14 type EditorId,
15 type EnvironmentId,
16 type RemoteOpenTarget,
17} from "@t3tools/contracts";
18import * as Option from "effect/Option";
19import * as Schema from "effect/Schema";
20import { useEffect, useMemo, useState } from "react";
21​
22import { isDesktopLocalConnectionTarget } from "~/connection/desktopLocal";
23import { isLoopbackHostname } from "~/environments/primary/target";
24import { useLocalStorage } from "~/hooks/useLocalStorage";
25import { useEnvironmentPresentation } from "~/state/presentation";
26​
27export interface RemoteOpenHost {
28 readonly kind: "ssh-alias" | RemoteOpenTarget["kind"];
29 readonly host: string;
31​
32export type RemoteOpenState =
33 | { readonly mode: "local-exec" }
34 | { readonly mode: "remote-links"; readonly host: RemoteOpenHost }
35 | { readonly mode: "remote-unavailable" };
36​
37export type RemoteOpenMode = RemoteOpenState["mode"];
38​
39const LOCAL_EXEC: RemoteOpenState = { mode: "local-exec" };
40const REMOTE_UNAVAILABLE: RemoteOpenState = { mode: "remote-unavailable" };
41​
42function parseHostname(url: string): string | null {
43 try {
44 return new URL(url).hostname;
45 } catch {
46 return null;
47 }
49​
50export function resolveRemoteOpenState(input: {
51 readonly target: ConnectionTarget | null;
52 /** Real ssh alias for desktop-SSH environments; null elsewhere. */
53 readonly sshAlias: string | null;
54 /** Server-advertised hosts; undefined on servers that predate the feature. */
55 readonly remoteOpenTargets: ReadonlyArray<RemoteOpenTarget> | undefined;
56 /** True when running inside the desktop app's renderer. */
57 readonly isDesktopRenderer: boolean;
58}): RemoteOpenState {
59 const { target } = input;
60 // No catalog entry: keep today's exec behavior rather than guessing.
61 if (target === null) {
62 return LOCAL_EXEC;
63 }
64 if (target._tag === "PrimaryConnectionTarget") {
65 // The desktop app manages its own primary backend, so it is always on
66 // this machine even when its URL is not loopback (wsl-only mode binds
67 // the WSL2 NAT address). In a browser, a loopback primary means the
68 // browser runs on the serving machine; a tailnet/LAN URL means remote.
69 if (input.isDesktopRenderer) {
70 return LOCAL_EXEC;
71 }
72 const hostname = parseHostname(target.httpBaseUrl);
73 if (hostname !== null && isLoopbackHostname(hostname)) {
74 return LOCAL_EXEC;
75 }
76 } else if (isDesktopLocalConnectionTarget(target)) {
77 return LOCAL_EXEC;
78 }
79​
80 if (input.sshAlias !== null && input.sshAlias.length > 0) {
81 return { mode: "remote-links", host: { kind: "ssh-alias", host: input.sshAlias } };
82 }
83 const advertised = input.remoteOpenTargets?.[0];
84 if (advertised !== undefined) {
85 return { mode: "remote-links", host: advertised };
86 }
87 return REMOTE_UNAVAILABLE;
89​
90export function useRemoteOpenState(environmentId: EnvironmentId | null): RemoteOpenState {
91 const { presentation } = useEnvironmentPresentation(environmentId);
92​
93 return useMemo(() => {
94 if (presentation === null) {
95 return LOCAL_EXEC;
96 }
97 const profile = Option.getOrNull(presentation.entry.profile);
98 const sshAlias =
99 profile !== null && profile._tag === "SshConnectionProfile" ? profile.target.alias : null;
100 return resolveRemoteOpenState({
101 target: presentation.entry.target,
102 sshAlias,
103 remoteOpenTargets: presentation.serverConfig?.remoteOpenTargets,
104 isDesktopRenderer: window.desktopBridge !== undefined,
105 });
106 }, [presentation]);
108​
109/**
110 * Editors offered in remote-link mode. The desktop app probes the machine the
111 * renderer runs on; a browser cannot, so it offers VS Code only.
112 */
113const REMOTE_FALLBACK_EDITORS: ReadonlyArray<EditorId> = ["vscode"];
114​
115let cachedProbedEditors: ReadonlyArray<EditorId> | null = null;
116​
117export function __resetRemoteEditorProbeForTests(): void {
118 cachedProbedEditors = null;
120​
121export function useRemoteCapableEditors(): ReadonlyArray<EditorId> {
122 const [editors, setEditors] = useState<ReadonlyArray<EditorId>>(
123 () => cachedProbedEditors ?? REMOTE_FALLBACK_EDITORS,
124 );
125​
126 useEffect(() => {
127 if (cachedProbedEditors !== null) {
128 return;
129 }
130 const probe = window.desktopBridge?.probeRemoteEditors;
131 if (probe === undefined) {
132 cachedProbedEditors = REMOTE_FALLBACK_EDITORS;
133 return;
134 }
135 let cancelled = false;
136 probe().then(
137 (ids) => {
138 const remoteCapable = ids.filter((id) => REMOTE_CAPABLE_EDITOR_IDS.includes(id));
139 cachedProbedEditors = remoteCapable.length > 0 ? remoteCapable : REMOTE_FALLBACK_EDITORS;
140 if (!cancelled) {
141 setEditors(cachedProbedEditors);
142 }
143 },
144 () => {
145 cachedProbedEditors = REMOTE_FALLBACK_EDITORS;
146 },
147 );
148 return () => {
149 cancelled = true;
150 };
151 }, []);
152​
153 return editors;
155​
156/**
157 * Fire a remote editor deep link. In desktop, route through the Electron
158 * shell so the OS handler opens without navigating the renderer; in a
159 * browser, assign the location — unlike window.open this does not leave a
160 * blank tab behind.
161 *
162 * Resolves false when the desktop shell refused the URL (e.g. an older
163 * build whose protocol allowlist predates editor schemes) so callers do not
164 * record a successful open that never happened.
165 */
166export async function openRemoteEditorUrl(url: string): Promise<boolean> {
167 const bridge = window.desktopBridge;
168 if (bridge !== undefined) {
169 try {
170 return await bridge.openExternal(url);
171 } catch {
172 return false;
173 }
174 }
175 window.location.assign(url);
176 return true;
178​
179/**
180 * One-time "you need SSH keys on that machine" hint, shown in the picker menu
181 * until the first remote open fires (we cannot observe SSH success from here,
182 * so first click is the dismiss signal).
183 */
184const REMOTE_OPEN_HINT_KEY = "t3code:remote-open-hint-seen";
185​
186export function useRemoteOpenHint(): readonly [seen: boolean, markSeen: () => void] {
187 const [seen, setSeen] = useLocalStorage(REMOTE_OPEN_HINT_KEY, false, Schema.Boolean);
188 return [seen, () => setSeen(true)] as const;