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

remoteOpen.ts

213 lines7.0 KB

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";
12import { useEffect, useState } from "react";
13​
14import { isDesktopLocalConnectionTarget } from "~/connection/desktopLocal";
15import { isLoopbackHostname } from "~/environments/primary/target";
16import { useLocalStorage } from "~/hooks/useLocalStorage";
17import { environmentPresentations } from "~/state/presentation";
18​
19export interface RemoteOpenHost {
20 readonly kind: "ssh-alias" | RemoteOpenTarget["kind"];
21 readonly host: string;
22 readonly username?: string;
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;
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 }
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}): RemoteOpenState {
58 const { target } = input;
59 if (target === null) {
60 return LOCAL_EXEC;
61 }
62 if (target._tag === "PrimaryConnectionTarget") {
63 // The desktop app manages its own primary backend, so it is always on this machine even
64 // when its URL is not loopback (wsl-only mode binds the 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;
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 );
108​
109// The presentation changes with every server config push and reconnect. This
110// keeps the previous resolution while it is equal, so subscribers re-render only
111// when where files open actually changes.
112const remoteOpenResolutionAtom = Atom.family((environmentId: EnvironmentId) =>
113 Atom.make((get): RemoteOpenResolution => {
114 const presentation = get(environmentPresentations.presentationAtom(environmentId));
115 const entry = presentation?.entry ?? null;
116 if (entry === null) {
117 return UNRESOLVED_REMOTE_OPEN;
118 }
119 const profile = Option.getOrNull(entry.profile);
120 const next: RemoteOpenResolution = {
121 state: resolveRemoteOpenState({
122 target: entry.target,
123 sshTarget:
124 profile !== null && profile._tag === "SshConnectionProfile" ? profile.target : null,
125 remoteOpenTargets: presentation?.serverConfig?.remoteOpenTargets,
126 isDesktopRenderer: window.desktopBridge !== undefined,
127 }),
128 isResolved: true,
129 };
130 const previous = Option.getOrNull(get.self<RemoteOpenResolution>());
131 return previous !== null &&
132 previous.isResolved &&
133 remoteOpenStatesEqual(previous.state, next.state)
134 ? previous
135 : next;
136 }).pipe(Atom.withLabel(`remote-open-resolution:${environmentId}`)),
137);
138​
139const UNRESOLVED_REMOTE_OPEN_ATOM = Atom.make(UNRESOLVED_REMOTE_OPEN);
140​
141export function useRemoteOpenResolution(environmentId: EnvironmentId | null): RemoteOpenResolution {
142 return useAtomValue(
143 environmentId === null ? UNRESOLVED_REMOTE_OPEN_ATOM : remoteOpenResolutionAtom(environmentId),
144 );
146​
147export function useRemoteOpenState(environmentId: EnvironmentId | null): RemoteOpenState {
148 return useRemoteOpenResolution(environmentId).state;
150​
151const REMOTE_FALLBACK_EDITORS: ReadonlyArray<EditorId> = ["vscode"];
152​
153let cachedProbedEditors: ReadonlyArray<EditorId> | null = null;
154​
155export function useRemoteCapableEditors(): ReadonlyArray<EditorId> {
156 const [editors, setEditors] = useState<ReadonlyArray<EditorId>>(
157 () => cachedProbedEditors ?? REMOTE_FALLBACK_EDITORS,
158 );
159​
160 useEffect(() => {
161 if (cachedProbedEditors !== null) {
162 return;
163 }
164 const probe = window.desktopBridge?.probeRemoteEditors;
165 if (probe === undefined) {
166 cachedProbedEditors = REMOTE_FALLBACK_EDITORS;
167 return;
168 }
169 let cancelled = false;
170 probe().then(
171 (ids) => {
172 const remoteCapable = ids.filter((id) => REMOTE_CAPABLE_EDITOR_IDS.includes(id));
173 cachedProbedEditors = remoteCapable.length > 0 ? remoteCapable : REMOTE_FALLBACK_EDITORS;
174 if (!cancelled) {
175 setEditors(cachedProbedEditors);
176 }
177 },
178 () => {
179 cachedProbedEditors = REMOTE_FALLBACK_EDITORS;
180 },
181 );
182 return () => {
183 cancelled = true;
184 };
185 }, []);
186​
187 return editors;
189​
190/**
191 * Resolves false when the desktop shell refused the URL (e.g. an older build whose protocol
192 * allowlist predates editor schemes) so callers do not record a successful open that never
193 * happened.
194 */
195export async function openRemoteEditorUrl(url: string): Promise<boolean> {
196 const bridge = window.desktopBridge;
197 if (bridge !== undefined) {
198 try {
199 return await bridge.openExternal(url);
200 } catch {
201 return false;
202 }
203 }
204 window.location.assign(url);
205 return true;
207​
208const REMOTE_OPEN_HINT_KEY = "t3code:remote-open-hint-seen";
209​
210export function useRemoteOpenHint(): readonly [seen: boolean, markSeen: () => void] {
211 const [seen, setSeen] = useLocalStorage(REMOTE_OPEN_HINT_KEY, false, Schema.Boolean);
212 return [seen, () => setSeen(true)] as const;