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

remoteOpen.ts

206 lines6.7 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 // Desktop owns its primary even at a non-loopback WSL2 NAT address.
64 if (input.isDesktopRenderer) {
65 return LOCAL_EXEC;
66 }
67 const hostname = parseHostname(target.httpBaseUrl);
68 if (hostname !== null && isLoopbackHostname(hostname)) {
69 return LOCAL_EXEC;
70 }
71 } else if (isDesktopLocalConnectionTarget(target)) {
72 return LOCAL_EXEC;
73 }
74​
75 if (input.sshTarget !== null && input.sshTarget.alias.length > 0) {
76 const { alias } = input.sshTarget;
77 const userSeparator = alias.lastIndexOf("@");
78 const host = userSeparator === -1 ? alias : alias.slice(userSeparator + 1);
79 const username =
80 input.sshTarget.username?.trim() ||
81 (userSeparator === -1 ? null : alias.slice(0, userSeparator));
82 return {
83 mode: "remote-links",
84 host: {
85 kind: "ssh-alias",
86 host,
87 ...(username === null ? {} : { username }),
88 },
89 };
90 }
91 const advertised = input.remoteOpenTargets?.[0];
92 if (advertised !== undefined) {
93 return { mode: "remote-links", host: advertised };
94 }
95 return REMOTE_UNAVAILABLE;
97​
98function remoteOpenStatesEqual(previous: RemoteOpenState, next: RemoteOpenState): boolean {
99 if (previous.mode !== next.mode) return false;
100 if (previous.mode !== "remote-links" || next.mode !== "remote-links") return true;
101 return (
102 previous.host.kind === next.host.kind &&
103 previous.host.host === next.host.host &&
104 previous.host.username === next.host.username
105 );
107​
108// Config pushes recreate presentations; preserve equal resolutions to avoid re-rendering file links.
109const remoteOpenResolutionAtom = Atom.family((environmentId: EnvironmentId) =>
110 Atom.make((get): RemoteOpenResolution => {
111 const presentation = get(environmentPresentations.presentationAtom(environmentId));
112 const entry = presentation?.entry ?? null;
113 if (entry === null) {
114 return UNRESOLVED_REMOTE_OPEN;
115 }
116 const profile = Option.getOrNull(entry.profile);
117 const next: RemoteOpenResolution = {
118 state: resolveRemoteOpenState({
119 target: entry.target,
120 sshTarget:
121 profile !== null && profile._tag === "SshConnectionProfile" ? profile.target : null,
122 remoteOpenTargets: presentation?.serverConfig?.remoteOpenTargets,
123 isDesktopRenderer: window.desktopBridge !== undefined,
124 }),
125 isResolved: true,
126 };
127 const previous = Option.getOrNull(get.self<RemoteOpenResolution>());
128 return previous !== null &&
129 previous.isResolved &&
130 remoteOpenStatesEqual(previous.state, next.state)
131 ? previous
132 : next;
133 }).pipe(Atom.withLabel(`remote-open-resolution:${environmentId}`)),
134);
135​
136const UNRESOLVED_REMOTE_OPEN_ATOM = Atom.make(UNRESOLVED_REMOTE_OPEN);
137​
138export function useRemoteOpenResolution(environmentId: EnvironmentId | null): RemoteOpenResolution {
139 return useAtomValue(
140 environmentId === null ? UNRESOLVED_REMOTE_OPEN_ATOM : remoteOpenResolutionAtom(environmentId),
141 );
143​
144export function useRemoteOpenState(environmentId: EnvironmentId | null): RemoteOpenState {
145 return useRemoteOpenResolution(environmentId).state;
147​
148const REMOTE_FALLBACK_EDITORS: ReadonlyArray<EditorId> = ["vscode"];
149​
150let cachedProbedEditors: ReadonlyArray<EditorId> | null = null;
151​
152export function useRemoteCapableEditors(): ReadonlyArray<EditorId> {
153 const [editors, setEditors] = useState<ReadonlyArray<EditorId>>(
154 () => cachedProbedEditors ?? REMOTE_FALLBACK_EDITORS,
155 );
156​
157 useEffect(() => {
158 if (cachedProbedEditors !== null) {
159 return;
160 }
161 const probe = window.desktopBridge?.probeRemoteEditors;
162 if (probe === undefined) {
163 cachedProbedEditors = REMOTE_FALLBACK_EDITORS;
164 return;
165 }
166 let cancelled = false;
167 probe().then(
168 (ids) => {
169 const remoteCapable = ids.filter((id) => REMOTE_CAPABLE_EDITOR_IDS.includes(id));
170 cachedProbedEditors = remoteCapable.length > 0 ? remoteCapable : REMOTE_FALLBACK_EDITORS;
171 if (!cancelled) {
172 setEditors(cachedProbedEditors);
173 }
174 },
175 () => {
176 cachedProbedEditors = REMOTE_FALLBACK_EDITORS;
177 },
178 );
179 return () => {
180 cancelled = true;
181 };
182 }, []);
183​
184 return editors;
186​
187/** Resolves false when the desktop refuses the URL, including unsupported editor schemes. */
188export async function openRemoteEditorUrl(url: string): Promise<boolean> {
189 const bridge = window.desktopBridge;
190 if (bridge !== undefined) {
191 try {
192 return await bridge.openExternal(url);
193 } catch {
194 return false;
195 }
196 }
197 window.location.assign(url);
198 return true;
200​
201const REMOTE_OPEN_HINT_KEY = "t3code:remote-open-hint-seen";
202​
203export function useRemoteOpenHint(): readonly [seen: boolean, markSeen: () => void] {
204 const [seen, setSeen] = useLocalStorage(REMOTE_OPEN_HINT_KEY, false, Schema.Boolean);
205 return [seen, () => setSeen(true)] as const;