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

remoteOpen.ts

195 lines6.5 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;
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;
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 }
50​
51export function resolveRemoteOpenState(input: {
52 readonly target: ConnectionTarget | null;
53 readonly sshAlias: string | 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 // The desktop app manages its own primary backend, so it is always on this machine even
63 // when its URL is not loopback (wsl-only mode binds the 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.sshAlias !== null && input.sshAlias.length > 0) {
76 return { mode: "remote-links", host: { kind: "ssh-alias", host: input.sshAlias } };
77 }
78 const advertised = input.remoteOpenTargets?.[0];
79 if (advertised !== undefined) {
80 return { mode: "remote-links", host: advertised };
81 }
82 return REMOTE_UNAVAILABLE;
84​
85function remoteOpenStatesEqual(previous: RemoteOpenState, next: RemoteOpenState): boolean {
86 if (previous.mode !== next.mode) return false;
87 if (previous.mode !== "remote-links" || next.mode !== "remote-links") return true;
88 return previous.host.kind === next.host.kind && previous.host.host === next.host.host;
90​
91// The presentation changes with every server config push and reconnect. This
92// keeps the previous resolution while it is equal, so subscribers re-render only
93// when where files open actually changes.
94const remoteOpenResolutionAtom = Atom.family((environmentId: EnvironmentId) =>
95 Atom.make((get): RemoteOpenResolution => {
96 const presentation = get(environmentPresentations.presentationAtom(environmentId));
97 const entry = presentation?.entry ?? null;
98 if (entry === null) {
99 return UNRESOLVED_REMOTE_OPEN;
100 }
101 const profile = Option.getOrNull(entry.profile);
102 const next: RemoteOpenResolution = {
103 state: resolveRemoteOpenState({
104 target: entry.target,
105 sshAlias:
106 profile !== null && profile._tag === "SshConnectionProfile" ? profile.target.alias : null,
107 remoteOpenTargets: presentation?.serverConfig?.remoteOpenTargets,
108 isDesktopRenderer: window.desktopBridge !== undefined,
109 }),
110 isResolved: true,
111 };
112 const previous = Option.getOrNull(get.self<RemoteOpenResolution>());
113 return previous !== null &&
114 previous.isResolved &&
115 remoteOpenStatesEqual(previous.state, next.state)
116 ? previous
117 : next;
118 }).pipe(Atom.withLabel(`remote-open-resolution:${environmentId}`)),
119);
120​
121const UNRESOLVED_REMOTE_OPEN_ATOM = Atom.make(UNRESOLVED_REMOTE_OPEN);
122​
123export function useRemoteOpenResolution(environmentId: EnvironmentId | null): RemoteOpenResolution {
124 return useAtomValue(
125 environmentId === null ? UNRESOLVED_REMOTE_OPEN_ATOM : remoteOpenResolutionAtom(environmentId),
126 );
128​
129export function useRemoteOpenState(environmentId: EnvironmentId | null): RemoteOpenState {
130 return useRemoteOpenResolution(environmentId).state;
132​
133const REMOTE_FALLBACK_EDITORS: ReadonlyArray<EditorId> = ["vscode"];
134​
135let cachedProbedEditors: ReadonlyArray<EditorId> | null = null;
136​
137export function useRemoteCapableEditors(): ReadonlyArray<EditorId> {
138 const [editors, setEditors] = useState<ReadonlyArray<EditorId>>(
139 () => cachedProbedEditors ?? REMOTE_FALLBACK_EDITORS,
140 );
141​
142 useEffect(() => {
143 if (cachedProbedEditors !== null) {
144 return;
145 }
146 const probe = window.desktopBridge?.probeRemoteEditors;
147 if (probe === undefined) {
148 cachedProbedEditors = REMOTE_FALLBACK_EDITORS;
149 return;
150 }
151 let cancelled = false;
152 probe().then(
153 (ids) => {
154 const remoteCapable = ids.filter((id) => REMOTE_CAPABLE_EDITOR_IDS.includes(id));
155 cachedProbedEditors = remoteCapable.length > 0 ? remoteCapable : REMOTE_FALLBACK_EDITORS;
156 if (!cancelled) {
157 setEditors(cachedProbedEditors);
158 }
159 },
160 () => {
161 cachedProbedEditors = REMOTE_FALLBACK_EDITORS;
162 },
163 );
164 return () => {
165 cancelled = true;
166 };
167 }, []);
168​
169 return editors;
171​
172/**
173 * Resolves false when the desktop shell refused the URL (e.g. an older build whose protocol
174 * allowlist predates editor schemes) so callers do not record a successful open that never
175 * happened.
176 */
177export async function openRemoteEditorUrl(url: string): Promise<boolean> {
178 const bridge = window.desktopBridge;
179 if (bridge !== undefined) {
180 try {
181 return await bridge.openExternal(url);
182 } catch {
183 return false;
184 }
185 }
186 window.location.assign(url);
187 return true;
189​
190const REMOTE_OPEN_HINT_KEY = "t3code:remote-open-hint-seen";
191​
192export function useRemoteOpenHint(): readonly [seen: boolean, markSeen: () => void] {
193 const [seen, setSeen] = useLocalStorage(REMOTE_OPEN_HINT_KEY, false, Schema.Boolean);
194 return [seen, () => setSeen(true)] as const;