feat: Hosted Frontend, Tailscale Integration & SSH Lancher #2361
Mergedjuliusmarmingemerged 76 commits into
main fromrefs/pull/2361/headmerged by juliusmarminge View on GitHubgithub-actions[bot](GitHub profile, opens in a new tab) added labelssize:XL
github-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:trusted
- apps/web/src/components/settings/ConnectionsSettings.tsx line 619OutdatedResolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -278,6 +286,13 @@278286 () => resolveCurrentOriginPairingUrl(pairingLink.credential),279287 [pairingLink.credential],280288 );289+ const hostedPairingUrl = useMemo(290+ () =>291+ endpointUrl != null && endpointUrl !== ""292+ ? resolveHostedPairingUrl(endpointUrl, pairingLink.credential)293+ : null,294+ [endpointUrl, pairingLink.credential],295+ );281296 const shareablePairingUrl =282297 endpointUrl != null && endpointUrl !== ""283- ? resolveDesktopPairingUrl(endpointUrl, pairingLink.credential)298+ ? (hostedPairingUrl ?? resolveDesktopPairingUrl(endpointUrl, pairingLink.credential))
- apps/web/src/environments/runtime/service.ts lines 788 to 789OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -785,3 +785,5 @@785785 );786786 }787787788+function maybeCreatePrimaryEnvironmentConnection(): EnvironmentConnection | null {789+ return getPrimaryKnownEnvironment() ? createPrimaryEnvironmentConnection() : null;
- apps/web/src/routes/__root.tsx line 83OutdatedResolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -68,0 +74,21 @@74+75+ try {76+ const [, authGateState] = await Promise.all([77+ ensurePrimaryEnvironmentReady(),78+ resolveInitialServerAuthGateState(),79+ ]);80+ return {81+ authGateState,82+ };83+ } catch (error) {84+ if (location.pathname === "/pair") {85+ throw error;86+ }87+88+ await waitForSavedEnvironmentRegistryHydration();89+ return {90+ authGateState: {91+ status: "hosted-static",92+ } as const,93+ };94+ }
- @@ -128,4 +151,7 @@128151 return cachedApi;129152 }130153131- cachedApi = createLocalApi(getPrimaryEnvironmentConnection().client);154+ const primaryEnvironment = getPrimaryKnownEnvironment();155+ cachedApi = primaryEnvironment156+ ? createLocalApi(getPrimaryEnvironmentConnection().client)157+ : createBrowserLocalApi();
- apps/web/src/components/auth/PairingRouteSurface.tsx line 249OutdatedResolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -161,0 +229,21 @@229+ {request ? (230+ <div className="mt-5 rounded-lg border border-border/70 bg-background/55 px-3 py-3 text-xs leading-relaxed text-muted-foreground">231+ Host: <span className="font-mono text-foreground/80">{request.host}</span>232+ </div>233+ ) : null}234+235+ {status === "error" ? (236+ <div className="mt-5 rounded-lg border border-destructive/30 bg-destructive/6 px-3 py-2 text-sm text-destructive">237+ Verify the backend is reachable from this browser, supports CORS for hosted clients, and238+ is served over HTTPS when opening this page from HTTPS.239+ </div>240+ ) : null}241+242+ <div className="mt-6 flex flex-wrap gap-2">243+ <Button244+ disabled={status === "pairing"}245+ size="sm"246+ onClick={() => void submitHostedPairingRequest()}247+ >248+ {status === "pairing" ? "Pairing..." : "Try again"}249+ </Button>
github-actions[bot](GitHub profile, opens in a new tab) removed labelssize:XL
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:XXL
juliusmarminge changed the title
- apps/desktop/src/sshScripts/remote-pick-port.cjs lines 6 to 6OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +1,6 @@1+const fs = require("node:fs");2+const net = require("node:net");3+const filePath = process.argv[2];4+const defaultPort = Number.parseInt(process.argv[3] ?? "", 10);5+const scanWindow = Number.parseInt(process.argv[4] ?? "", 10);6+const raw = fs.existsSync(filePath) ? fs.readFileSync(filePath, "utf8").trim() : "";apps/desktop/src/sshEnvironment.ts lines 1022 to 1030OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +1010,21 @@1010+ new Error(1011+ normalizeSshErrorMessage(1012+ stderr,1013+ `SSH tunnel exited unexpectedly for ${resolvedTarget.alias} (exit ${code ?? "unknown"}).`,1014+ ),1015+ ),1016+ );1017+ });1018+ waitForHttpReady(httpBaseUrl, { timeoutMs: SSH_READY_TIMEOUT_MS })1019+ .then(() => resolve())1020+ .catch((error: unknown) => reject(error));1021+ });1022+ this.tunnels.set(key, tunnelEntry);1023+ try {1024+ await tunnelReady;1025+ return tunnelEntry;1026+ } catch (error) {1027+ await stopTunnel(tunnelEntry).catch(() => undefined);1028+ this.deleteTunnelIfCurrent(tunnelEntry);1029+ throw error;1030+ }apps/desktop/src/sshEnvironment.ts lines 475 to 477OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +457,21 @@457+ return [458+ "-o",459+ `BatchMode=${input?.batchMode ?? "no"}`,460+ "-o",461+ "ConnectTimeout=10",462+ ...(target.port !== null ? ["-p", String(target.port)] : []),463+ ];464+}465+466+function normalizeSshErrorMessage(stderr: string, fallbackMessage: string): string {467+ const cleaned = stderr.trim();468+ return cleaned.length > 0 ? cleaned : fallbackMessage;469+}470+471+function isSshAuthFailure(error: unknown): boolean {472+ const message = error instanceof Error ? error.message : String(error);473+ const normalized = message.toLowerCase();474+ return (475+ /permission denied \((?:publickey|password|keyboard-interactive|hostbased|gssapi-with-mic)[^)]+\)/u.test(476+ normalized,477+ ) ||apps/desktop/src/sshEnvironment.ts lines 133 to 136Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +1026,21 @@1026+ } catch (error) {1027+ await stopTunnel(tunnelEntry).catch(() => undefined);1028+ this.deleteTunnelIfCurrent(tunnelEntry);1029+ throw error;1030+ }1031+ });1032+ })();1033+ this.pendingTunnelEntries.set(key, nextEntry);1034+ return await nextEntry.finally(() => {1035+ if (this.pendingTunnelEntries.get(key) === nextEntry) {1036+ this.pendingTunnelEntries.delete(key);1037+ }1038+ });1039+ }1040+1041+ async dispose(): Promise<void> {1042+ const entries = [...this.tunnels.values()];1043+ this.tunnels.clear();1044+ this.pendingTunnelEntries.clear();1045+ await Promise.all(entries.map((entry) => stopTunnel(entry).catch(() => undefined)));1046+ }
- apps/web/src/components/desktop/SshPasswordPromptDialog.tsx line 98OutdatedResolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -0,0 +78,21 @@78+ <DialogPopup className="max-w-md" showCloseButton={false}>79+ <DialogHeader>80+ <DialogTitle>SSH Password Required</DialogTitle>81+ <DialogDescription>82+ T3 needs your SSH password to connect to{" "}83+ {target ? <code>{target}</code> : "the remote host"}. The password is passed to the84+ local SSH process for this connection attempt and is not saved by T3 Code.85+ </DialogDescription>86+ </DialogHeader>87+ <DialogPanel className="space-y-3" scrollFade={false}>88+ <div className="space-y-2">89+ <p className="text-sm font-medium text-foreground">{currentRequest?.prompt}</p>90+ <Input91+ ref={inputRef}92+ autoComplete="current-password"93+ name="ssh-password"94+ type="password"95+ value={password}96+ onChange={(event) => setPassword(event.target.value)}97+ />98+ </div>apps/desktop/src/serverExposure.ts line 185Resolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -80,0 +150,21 @@150+ reachability: "lan",151+ status: "available",152+ isDefault: true,153+ description: "Reachable from devices on the same network.",154+ }),155+ );156+ }157+158+ for (const customEndpointUrl of input.customHttpsEndpointUrls ?? []) {159+ endpoints.push(160+ createManualEndpoint({161+ id: `manual:${customEndpointUrl}`,162+ label: "Custom HTTPS",163+ httpBaseUrl: customEndpointUrl,164+ reachability: "public",165+ hostedHttpsCompatibility: "compatible",166+ status: "unknown",167+ description: "User-configured HTTPS endpoint for this desktop backend.",168+ }),169+ );170+ }
- apps/desktop/src/desktopSettings.ts lines 44 to 52Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -35,3 +41,9 @@3541 };3642 }374344+export function setDesktopTailscaleServePreference(45+ settings: DesktopSettings,46+ input: { readonly enabled: boolean; readonly port?: number },47+): DesktopSettings {48+ const port = normalizeTailscaleServePort(input.port);49+ return settings.tailscaleServeEnabled === input.enabled && settings.tailscaleServePort === port
- apps/web/src/components/auth/PairingRouteSurface.tsx line 226Resolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -161,0 +184,21 @@184+ label: request.label,185+ host: request.host,186+ pairingCode: request.token,187+ });188+ setStatus("paired");189+ setMessage(`${record.label} is saved in this browser.`);190+ } catch (error) {191+ setStatus("error");192+ setMessage(errorMessageFromUnknown(error));193+ }194+ }, []);195+196+ useEffect(() => {197+ if (submitAttemptedRef.current) {198+ return;199+ }200+ submitAttemptedRef.current = true;201+202+ stripPairingTokenFromUrl();203+ void submitHostedPairingRequest();204+ }, [submitHostedPairingRequest]);apps/web/src/components/desktop/SshPasswordPromptDialog.tsx line 131Resolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -0,0 +45,21 @@45+ inputRef.current?.select();46+ });47+ return () => {48+ window.cancelAnimationFrame(frame);49+ };50+ }, [currentRequest]);51+52+ const respond = async (nextPassword: string | null) => {53+ if (!currentRequest) {54+ return;55+ }56+57+ const requestId = currentRequest.requestId;58+ setQueue((currentQueue) => currentQueue.slice(1));59+ setPassword("");60+ try {61+ await window.desktopBridge?.resolveSshPasswordPrompt(requestId, nextPassword);62+ } catch (error) {63+ console.error("Failed to resolve SSH password prompt.", error);64+ }65+ };@@ -361,3 +402,12 @@361402 return getDesktopServerExposureState();362403 }363404405+async function applyDesktopTailscaleServeEnabled(input: {406+ readonly enabled: boolean;407+ readonly port?: number;408+}): Promise<DesktopServerExposureState> {409+ desktopSettings = setDesktopTailscaleServePreference(desktopSettings, input);410+ writeDesktopSettings(DESKTOP_SETTINGS_PATH, desktopSettings);411+ relaunchDesktopApp(input.enabled ? "tailscale-serve-enabled" : "tailscale-serve-disabled");412+ return getDesktopServerExposureState();413+}
- apps/web/src/components/auth/PairingRouteSurface.tsx line 273Resolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -161,0 +241,21 @@241+ Host: <span className="font-mono text-foreground/80">{request.host}</span>242+ </div>243+ ) : null}244+245+ {status === "error" ? (246+ <div className="mt-5 rounded-lg border border-destructive/30 bg-destructive/6 px-3 py-2 text-sm text-destructive">247+ Verify the backend is reachable from this browser, supports CORS for hosted clients, and248+ is served over HTTPS when opening this page from HTTPS.249+ </div>250+ ) : null}251+252+ <div className="mt-6 flex flex-wrap gap-2">253+ {status === "pairing" ? (254+ <Button disabled size="sm">255+ Pairing...256+ </Button>257+ ) : !tokenSubmittedRef.current ? (258+ <Button size="sm" onClick={() => void submitHostedPairingRequest()}>259+ Try again260+ </Button>261+ ) : null}apps/desktop/src/serverExposure.ts line 58Resolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -21,3 +49,6 @@2149 const isUsableLanIpv4Address = (address: string): boolean =>2250 !address.startsWith("127.") && !address.startsWith("169.254.");235152+function isHttpsEndpointUrl(value: string): boolean {53+ return new URL(value).protocol === "https:";54+}
- apps/web/src/components/auth/PairingRouteSurface.tsx lines 265 to 279Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -161,0 +247,21 @@247+ Verify the backend is reachable from this browser, supports CORS for hosted clients, and248+ is served over HTTPS when opening this page from HTTPS.249+ </div>250+ ) : null}251+252+ <div className="mt-6 flex flex-wrap gap-2">253+ {status === "pairing" ? (254+ <Button disabled size="sm">255+ Pairing...256+ </Button>257+ ) : !tokenSubmittedRef.current ? (258+ <Button size="sm" onClick={() => void submitHostedPairingRequest()}>259+ Try again260+ </Button>261+ ) : null}262+ {status === "paired" ? (263+ <Button size="sm" variant="outline" onClick={() => (window.location.href = "/")}>264+ Open app265+ </Button>266+ ) : null}267+ </div>
- apps/desktop/src/serverExposure.ts line 184Resolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -80,0 +163,21 @@163+ );164+ }165+166+ for (const customEndpointUrl of input.customHttpsEndpointUrls ?? []) {167+ try {168+ endpoints.push(169+ createManualEndpoint({170+ id: `manual:${customEndpointUrl}`,171+ label: "Custom HTTPS",172+ httpBaseUrl: customEndpointUrl,173+ reachability: "public",174+ ...(isHttpsEndpointUrl(customEndpointUrl)175+ ? ({ hostedHttpsCompatibility: "compatible" } as const)176+ : {}),177+ status: "unknown",178+ description: "User-configured HTTPS endpoint for this desktop backend.",179+ }),180+ );181+ } catch {182+ // Ignore malformed user-configured endpoints without dropping valid endpoints.183+ }
- @@ -308,0 +312,21 @@312+ ensureTailscaleServe({313+ localPort: config.port,314+ servePort: config.tailscaleServePort,315+ localHost: "127.0.0.1",316+ }).pipe(317+ Effect.tap(() =>318+ Effect.logInfo("Tailscale Serve configured", {319+ localPort: config.port,320+ servePort: config.tailscaleServePort,321+ }),322+ ),323+ Effect.catch((cause) =>324+ Effect.logWarning("Failed to configure Tailscale Serve", {325+ cause,326+ localPort: config.port,327+ servePort: config.tailscaleServePort,328+ }),329+ ),330+ ),331+ )332+ : Layer.empty;
- packages/ssh/src/config.ts lines 9 to 12Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +7,21 @@7+ DesktopDiscoveredSshHost,8+ DesktopSshEnvironmentTarget,9+ DesktopUpdateChannel,10+} from "@t3tools/contracts";11+12+import { Data, Effect } from "effect";13+14+export const DEFAULT_REMOTE_PORT = 3773;15+16+const NO_HOSTS = [] as const;17+const PUBLISHABLE_T3_VERSION_PATTERN = /^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/u;18+19+export class SshHostDiscoveryError extends Data.TaggedError("SshHostDiscoveryError")<{20+ readonly message: string;21+ readonly cause: unknown;22+}> {}23+24+function stripInlineComment(line: string): string {25+ const hashIndex = line.indexOf("#");26+ return (hashIndex >= 0 ? line.slice(0, hashIndex) : line).trim();27+}
- apps/web/src/components/auth/PairingRouteSurface.tsx line 225Resolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -161,0 +194,21 @@194+ pairingCode: request.token,195+ });196+ setStatus("paired");197+ setMessage(`${record.label} is saved in this browser.`);198+ } catch (error) {199+ tokenSubmittedRef.current = false;200+ setStatus("error");201+ setMessage(202+ `${errorMessageFromUnknown(error)} If the backend accepted this one-time token, request a new pairing link before retrying.`,203+ );204+ }205+ }, []);206+207+ useEffect(() => {208+ if (submitAttemptedRef.current) {209+ return;210+ }211+ submitAttemptedRef.current = true;212+213+ stripPairingTokenFromUrl();214+ void submitHostedPairingRequest();
- apps/desktop/src/sshScripts/askpass-windows.cmd line 2OutdatedResolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -0,0 +1,2 @@1+@echo off2+powershell -NoProfile -ExecutionPolicy Bypass -File "%~dp0ssh-askpass.ps1" %*
- apps/desktop/src/sshEnvironment.ts lines 133 to 136Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +113,21 @@113+ }114+115+ async discoverHosts(): Promise<readonly DesktopDiscoveredSshHost[]> {116+ return await discoverDesktopSshHosts();117+ }118+119+ async ensureEnvironment(120+ target: DesktopSshEnvironmentTarget,121+ options?: { readonly issuePairingToken?: boolean },122+ ) {123+ return await this.runtime.runPromise(124+ Effect.service(SshEnvironmentManager).pipe(125+ Effect.flatMap((manager) => manager.ensureEnvironment(target, options)),126+ ),127+ );128+ }129+130+ async dispose(): Promise<void> {131+ await this.runtime.runPromise(Scope.close(this.scope, Exit.void));132+ await this.runtime.dispose();133+ }
- @@ -110,3 +120,9 @@110120 const DESKTOP_SCHEME = "t3";111121 const ROOT_DIR = Path.resolve(__dirname, "../../..");112122 const isDevelopment = Boolean(process.env.VITE_DEV_SERVER_URL);123+// Dev-only SSH launcher override. Set this to an absolute path on the SSH host124+// for a built server entry, for example:125+// "/Users/julius/Development/Work/codething-mvp/apps/server/dist/bin.mjs"126+const DEV_REMOTE_T3_SERVER_ENTRY_PATH =127+ process.env.T3CODE_DEV_REMOTE_T3_SERVER_ENTRY_PATH?.trim() ??128+ "/Users/julius/Developer/t3code/apps/server/dist/bin.mjs";
- apps/desktop/src/sshEnvironment.ts line 363Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +324,21 @@324+ const pending = this.pendingPrompts.get(rawRequestId);325+ if (!pending) {326+ throw new Error("SSH password prompt expired. Try connecting again.");327+ }328+329+ clearTimeout(pending.timeout);330+ this.pendingPrompts.delete(rawRequestId);331+ pending.resolve(rawPassword);332+ },333+ );334+ }335+336+ cancelPendingPasswordPrompts(reason: string): void {337+ for (const [requestId, pending] of this.pendingPrompts) {338+ clearTimeout(pending.timeout);339+ this.pendingPrompts.delete(requestId);340+ pending.reject(new Error(reason));341+ }342+ }343+344+ async dispose(): Promise<void> {
- packages/ssh/src/tunnel.ts lines 1353 to 1365Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +1263,21 @@1263+ ),1264+ );1265+ tunnels.set(input.key, tunnelEntry);1266+ const spawnerService = yield* ChildProcessSpawner.ChildProcessSpawner;1267+ const fileSystemService = yield* FileSystem.FileSystem;1268+ const pathService = yield* Path.Path;1269+ yield* Scope.addFinalizer(1270+ entryScope,1271+ Effect.gen(function* () {1272+ if (tunnels.get(tunnelEntry.key) !== tunnelEntry) {1273+ return;1274+ }1275+ yield* Effect.logDebug("ssh.environment.tunnel.finalizer.start", {1276+ ...sshTargetLogFields(tunnelEntry.target),1277+ key: tunnelEntry.key,1278+ localPort: tunnelEntry.localPort,1279+ remotePort: tunnelEntry.remotePort,1280+ });1281+ tunnels.delete(tunnelEntry.key);1282+ const authSecret = authSecrets.get(tunnelEntry.key) ?? null;1283+ yield* Effect.all(
- apps/web/src/components/chat/ChatComposer.tsx line 1992OutdatedResolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -1970,6 +1978,15 @@19701978 ? "Type your own answer, or leave this blank to use the selected option"19711979 : showPlanFollowUpPrompt && activeProposedPlan19721980 ? "Add feedback to refine the plan, or leave this blank to implement it"1973- : phase === "disconnected"1974- ? "Ask for follow-up changes or attach images"1975- : "Ask anything, @tag files/folders, or use / to show available commands"1981+ : environmentUnavailable1982+ ? `${environmentUnavailable.label} is ${1983+ environmentUnavailable.connectionState === "connecting"1984+ ? "connecting"1985+ : "disconnected"1986+ }`1987+ : phase === "disconnected"1988+ ? "Ask for follow-up changes or attach images"1989+ : "Ask anything, @tag files/folders, or use / to show available commands"1990+ }1991+ disabled={1992+ isConnecting || isComposerApprovalState || environmentUnavailable !== null
- apps/web/src/components/ChatView.tsx line 2563Resolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -2354,3 +2421,10 @@23542421 const localApi = readLocalApi();23552422 if (!api || !localApi || !activeThread || isRevertingCheckpoint) return;235624232424+ if (activeEnvironmentUnavailable && activeEnvironmentUnavailableLabel) {2425+ setThreadError(2426+ activeThread.id,2427+ `Reconnect ${activeEnvironmentUnavailableLabel} before reverting checkpoints.`,2428+ );2429+ return;2430+ }
- packages/shared/src/keybindings.ts lines 52 to 56Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +36,21 @@36+ key: `mod+${index + 1}`,37+ command,38+ })),39+ ...MODEL_PICKER_JUMP_KEYBINDING_COMMANDS.map((command, index) => ({40+ key: `mod+${index + 1}`,41+ command,42+ when: "modelPickerOpen",43+ })),44+];45+46+function normalizeKeyToken(token: string): string {47+ if (token === "space") return " ";48+ if (token === "esc") return "escape";49+ return token;50+}51+52+export function parseKeybindingShortcut(value: string): KeybindingShortcut | null {53+ const rawTokens = value54+ .toLowerCase()55+ .split("+")56+ .map((token) => token.trim());
- @@ -15,4 +15,4 @@1515 injectedDesktopAppBranding?.stageLabel ?? (import.meta.env.DEV ? "Dev" : "Alpha");1616 export const APP_DISPLAY_NAME =1717 injectedDesktopAppBranding?.displayName ?? `${APP_BASE_NAME} (${APP_STAGE_LABEL})`;18-export const APP_VERSION = import.meta.env.APP_VERSION || "0.0.0";18+export const APP_VERSION = "0.0.20"; // import.meta.env.APP_VERSION || "0.0.0";
- packages/ssh/src/tunnel.ts lines 497 to 499Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +423,21 @@423+ WAIT_COUNT=0424+ while kill -0 "$REMOTE_PID" 2>/dev/null && [ "$WAIT_COUNT" -lt 20 ]; do425+ WAIT_COUNT=$((WAIT_COUNT + 1))426+ sleep 0.1427+ done428+fi429+rm -f "$PID_FILE" "$PORT_FILE"430+printf '{"stopped":true}\\n'431+`;432+433+const REMOTE_LOG_TAIL_SCRIPT = `set -eu434+STATE_DIR="$HOME/.t3/ssh-launch/@@T3_STATE_KEY@@"435+LOG_FILE="$STATE_DIR/server.log"436+if [ -f "$LOG_FILE" ]; then437+ tail -n 80 "$LOG_FILE" 2>/dev/null || true438+fi439+`;440+441+export function buildRemoteT3RunnerScript(input?: RemoteT3RunnerOptions): string {442+ const packageSpec = input?.packageSpec?.trim() || "t3@latest";443+ const nodeScriptPath = input?.nodeScriptPath?.trim() || "";packages/ssh/src/command.ts lines 110 to 111Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +91,21 @@91+ ];92+}93+94+export function getLastNonEmptyOutputLine(stdout: string): string | null {95+ return (96+ stdout97+ .trim()98+ .split(/\r?\n/u)99+ .map((entry) => entry.trim())100+ .findLast((entry) => entry.length > 0) ?? null101+ );102+}103+104+export const collectProcessOutput = <E>(105+ stream: Stream.Stream<Uint8Array, E>,106+): Effect.Effect<string, E> =>107+ stream.pipe(108+ Stream.decodeText(),109+ Stream.runFold(110+ () => "",111+ (acc, chunk) => acc + chunk,apps/web/src/components/settings/ConnectionsSettings.tsx lines 186 to 223Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -137,0 +193,21 @@193+ const updateHeightAfterPaint = () => {194+ updateHeight();195+ firstFrameId = window.requestAnimationFrame(() => {196+ updateHeight();197+ secondFrameId = window.requestAnimationFrame(updateHeight);198+ });199+ };200+201+ updateHeightAfterPaint();202+ const resizeObserver = new ResizeObserver(updateHeightAfterPaint);203+ resizeObserver.observe(element);204+ return () => {205+ resizeObserver.disconnect();206+ if (firstFrameId !== null) {207+ window.cancelAnimationFrame(firstFrameId);208+ }209+ if (secondFrameId !== null) {210+ window.cancelAnimationFrame(secondFrameId);211+ }212+ };213+ }, []);
- apps/web/src/components/auth/PairingRouteSurface.tsx line 167OutdatedResolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -159,3 +161,7 @@159161 );160162 }161163164+export function HostedPairingRouteSurface() {165+ const hostedPairingRequestRef = useRef(readHostedPairingRequest());166+ const [status, setStatus] = useState<"pairing" | "paired" | "error">("pairing");167+ const [message, setMessage] = useState("Connecting to this backend.");
- apps/web/src/components/ChatView.tsx line 943Resolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -857,0 +918,21 @@918+ try {919+ await reconnectSavedEnvironment(environmentId);920+ toastManager.add({921+ type: "success",922+ title: "Environment reconnected",923+ description: `${label} is ready.`,924+ });925+ } catch (error) {926+ toastManager.add(927+ stackedThreadToast({928+ type: "error",929+ title: "Could not reconnect environment",930+ description: error instanceof Error ? error.message : "Failed to reconnect.",931+ }),932+ );933+ } finally {934+ setReconnectingEnvironmentId(null);935+ }936+ },937+ [],938+ );apps/web/src/components/auth/PairingRouteSurface.tsx line 205Resolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -161,0 +181,21 @@181+ setStatus("error");182+ setMessage("This pairing link is missing its backend host or token.");183+ return;184+ }185+186+ if (tokenSubmittedRef.current) {187+ setStatus("error");188+ setMessage("This one-time pairing token was already submitted. Request a new pairing link.");189+ return;190+ }191+192+ setStatus("pairing");193+ setMessage("Connecting to this backend.");194+ tokenSubmittedRef.current = true;195+196+ try {197+ const record = await addSavedEnvironment({198+ label: request.label,199+ host: request.host,200+ pairingCode: request.token,201+ });
- @@ -0,0 +35,21 @@35+ ...THREAD_JUMP_KEYBINDING_COMMANDS.map((command, index) => ({36+ key: `mod+${index + 1}`,37+ command,38+ })),39+ ...MODEL_PICKER_JUMP_KEYBINDING_COMMANDS.map((command, index) => ({40+ key: `mod+${index + 1}`,41+ command,42+ when: "modelPickerOpen",43+ })),44+];45+46+function normalizeKeyToken(token: string): string {47+ if (token === "space") return " ";48+ if (token === "esc") return "escape";49+ return token;50+}51+52+export function parseKeybindingShortcut(value: string): KeybindingShortcut | null {53+ const rawTokens = value54+ .toLowerCase()55+ .split("+")
- packages/ssh/src/tunnel.ts line 434Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +411,21 @@411+ REMOTE_MANAGED=""412+ fi413+else414+ REMOTE_PID=""415+ REMOTE_PORT=""416+ REMOTE_MANAGED=""417+fi418+if [ -z "$REMOTE_PID" ] && [ -z "$REMOTE_PORT" ]; then419+ DEFAULT_REMOTE_PORT="$(resolve_default_runtime_port 2>/dev/null || true)"420+ if [ -n "$DEFAULT_REMOTE_PORT" ]; then421+ REMOTE_PORT="$DEFAULT_REMOTE_PORT"422+ if wait_ready "@@T3_REUSE_READY_TIMEOUT_MS@@"; then423+ printf '%s\\n' "$REMOTE_PORT" >"$PORT_FILE"424+ printf '%s\\n' "$DEFAULT_SERVER_HOME" >"$BASE_DIR_FILE"425+ printf 'external\\n' >"$MANAGED_FILE"426+ else427+ REMOTE_PORT=""428+ fi429+ fi430+fi431+if [ -z "$REMOTE_PID" ] || [ -z "$REMOTE_PORT" ]; then
- apps/desktop/src/sshEnvironment.ts line 211Resolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -0,0 +189,21 @@189+ listener: (event: unknown, ...args: readonly unknown[]) => unknown | Promise<unknown>,190+ ): void;191+}192+193+export interface DesktopSshEnvironmentBridgeOptions {194+ readonly getMainWindow: () => DesktopSshBridgeWindow | null;195+ readonly resolveCliPackageSpec?: () => string;196+ readonly resolveCliRunner?: () => RemoteT3RunnerOptions;197+ readonly passwordPromptTimeoutMs?: number;198+}199+200+interface PendingSshPasswordPrompt {201+ readonly resolve: (password: string | null) => void;202+ readonly reject: (error: Error) => void;203+ readonly timeout: ReturnType<typeof setTimeout>;204+}205+206+function isSshPasswordPromptCancellation(error: unknown): error is SshPasswordPromptError {207+ return (208+ error instanceof SshPasswordPromptError && error.message.toLowerCase().includes("cancelled")209+ );
- apps/web/src/components/auth/PairingRouteSurface.tsx line 273Resolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -161,0 +248,21 @@248+ Host: <span className="font-mono text-foreground/80">{request.host}</span>249+ </div>250+ ) : null}251+252+ {status === "error" ? (253+ <div className="mt-5 rounded-lg border border-destructive/30 bg-destructive/6 px-3 py-2 text-sm text-destructive">254+ Verify the backend is reachable from this browser, supports CORS for hosted clients, and255+ is served over HTTPS when opening this page from HTTPS.256+ </div>257+ ) : null}258+259+ <div className="mt-6 flex flex-wrap gap-2">260+ {status === "pairing" ? (261+ <Button disabled size="sm">262+ Pairing...263+ </Button>264+ ) : !tokenSubmittedRef.current ? (265+ <Button size="sm" onClick={() => void submitHostedPairingRequest()}>266+ Try again267+ </Button>268+ ) : null}
- apps/desktop/src/main.ts lines 152 to 157OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -106,7 +138,20 @@138+ "desktop:set-tailscale-serve-enabled";139+const GET_ADVERTISED_ENDPOINTS_CHANNEL = "desktop:get-advertised-endpoints";140+const BASE_DIR =141+ process.env.T3CODE_HOME?.trim() || Path.join(OS.homedir(), ".t3");106142 const STATE_DIR = Path.join(BASE_DIR, "userdata");107143 const DESKTOP_SETTINGS_PATH = Path.join(STATE_DIR, "desktop-settings.json");108144 const CLIENT_SETTINGS_PATH = Path.join(STATE_DIR, "client-settings.json");109-const SAVED_ENVIRONMENT_REGISTRY_PATH = Path.join(STATE_DIR, "saved-environments.json");145+const SAVED_ENVIRONMENT_REGISTRY_PATH = Path.join(146+ STATE_DIR,147+ "saved-environments.json",148+);110149 const DESKTOP_SCHEME = "t3";111150 const ROOT_DIR = Path.resolve(__dirname, "../../..");112151 const isDevelopment = Boolean(process.env.VITE_DEV_SERVER_URL);152+// Dev-only SSH launcher override. Set this to an absolute path on the SSH host153+// for a built server entry, for example:154+// "/Users/julius/Development/Work/codething-mvp/apps/server/dist/bin.mjs"155+const DEV_REMOTE_T3_SERVER_ENTRY_PATH =156+ "/Users/julius/Developer/t3code/apps/server/dist/bin.mjs";157+process.env.T3CODE_DEV_REMOTE_T3_SERVER_ENTRY_PATH?.trim() ?? "";
- apps/desktop/src/main.ts lines 126 to 127OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -110,3 +120,8 @@110120 const DESKTOP_SCHEME = "t3";111121 const ROOT_DIR = Path.resolve(__dirname, "../../..");112122 const isDevelopment = Boolean(process.env.VITE_DEV_SERVER_URL);123+// Dev-only SSH launcher override. Set this to an absolute path on the SSH host124+// for a built server entry, for example:125+// "/Users/julius/Development/Work/codething-mvp/apps/server/dist/bin.mjs"126+const DEV_REMOTE_T3_SERVER_ENTRY_PATH = "/Users/julius/Developer/t3code/apps/server/dist/bin.mjs";127+process.env.T3CODE_DEV_REMOTE_T3_SERVER_ENTRY_PATH?.trim() ?? "";
- packages/ssh/src/tunnel.ts line 1554Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +1571,21 @@1571+ remotePort: entry.remotePort,1572+ ...(entry.remoteServerKind ? { remoteServerKind: entry.remoteServerKind } : {}),1573+ ...(pairingResult?.diagnostics ? { pairingDiagnostics: pairingResult.diagnostics } : {}),1574+ };1575+ });1576+1577+ const disconnectEnvironment = Effect.fn("ssh/tunnel.disconnectEnvironment")(function* (1578+ target: DesktopSshEnvironmentTarget,1579+ ): Effect.fn.Return<void, SshEnvironmentEffectError, SshEnvironmentEffectContext> {1580+ yield* Effect.logInfo("ssh.environment.disconnect.start", sshTargetLogFields(target));1581+ const baseResolved = yield* resolveSshTarget(target.alias || target.hostname);1582+ const resolvedTarget: DesktopSshEnvironmentTarget = {1583+ ...baseResolved,1584+ ...(target.username !== null ? { username: target.username } : {}),1585+ ...(target.port !== null ? { port: target.port } : {}),1586+ };1587+ const key = targetConnectionKey(resolvedTarget);1588+ const entry = tunnels.get(key) ?? null;1589+ yield* Effect.logDebug("ssh.environment.disconnect.targetResolved", {1590+ ...sshTargetLogFields(resolvedTarget),1591+ key,apps/web/src/environments/runtime/service.ts lines 719 to 736OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -493,0 +716,21 @@716+ const bearerSession = await bootstrapDesktopSshBearerSession(717+ prepared.record.httpBaseUrl,718+ prepared.pairingToken,719+ ).catch((error) => {720+ const detail = [721+ `local ${prepared.record.httpBaseUrl}`,722+ `remote port ${prepared.remotePort ?? "unknown"}`,723+ prepared.remoteServerKind ? `remote server ${prepared.remoteServerKind}` : null,724+ prepared.pairingDiagnostics ? `pairing db ${prepared.pairingDiagnostics.dbPath}` : null,725+ prepared.pairingDiagnostics726+ ? `pairing runtime ${prepared.pairingDiagnostics.runtimePath}`727+ : null,728+ prepared.pairingDiagnostics729+ ? `pairing devUrl ${prepared.pairingDiagnostics.devUrl ?? "none"}`730+ : null,731+ ]732+ .filter(Boolean)733+ .join(", ");734+ const message = error instanceof Error ? error.message : String(error);735+ throw new Error(`${message} (${detail})`);736+ });
- packages/ssh/src/tunnel.ts lines 394 to 402Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +391,21 @@391+ if (origin.protocol !== "http:" || !["127.0.0.1", "localhost"].includes(origin.hostname)) {392+ process.exit(1);393+ }394+ process.kill(pid, 0);395+ process.stdout.write(String(port));396+} catch {397+ process.exit(1);398+}399+NODE400+}401+REMOTE_PID="$(cat "$PID_FILE" 2>/dev/null || true)"402+REMOTE_PORT="$(cat "$PORT_FILE" 2>/dev/null || true)"403+REMOTE_MANAGED="$(cat "$MANAGED_FILE" 2>/dev/null || true)"404+DEFAULT_REMOTE_PORT="$(resolve_default_runtime_port 2>/dev/null || true)"405+if [ -n "$DEFAULT_REMOTE_PORT" ]; then406+ REMOTE_PORT="$DEFAULT_REMOTE_PORT"407+ if wait_ready "@@T3_REUSE_READY_TIMEOUT_MS@@"; then408+ printf '%s\\n' "$REMOTE_PORT" >"$PORT_FILE"409+ printf 'external\\n' >"$MANAGED_FILE"410+ REMOTE_PID=""411+ REMOTE_MANAGED="external"
- packages/ssh/src/tunnel.ts lines 1408 to 1453Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +1418,21 @@1418+ return entry;1419+ }1420+ yield* Effect.logWarning("ssh.environment.tunnel.existing.stale", {1421+ ...sshTargetLogFields(resolvedTarget),1422+ key,1423+ localPort: entry.localPort,1424+ remotePort: entry.remotePort,1425+ cause: readinessExit.cause,1426+ });1427+ yield* closeTunnelEntry(entry);1428+ entry = null;1429+ }1430+1431+ const pending = pendingTunnelEntries.get(key);1432+ if (pending) {1433+ yield* Effect.logDebug("ssh.environment.tunnel.pending.await", {1434+ ...sshTargetLogFields(resolvedTarget),1435+ key,1436+ });1437+ return yield* Deferred.await(pending);1438+ }
- apps/web/src/environments/runtime/service.ts line 731Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -493,0 +689,21 @@689+ useSavedEnvironmentRegistryStore.getState().upsert(nextRecord);690+ }691+692+ return {693+ record: nextRecord,694+ pairingToken: bootstrap.pairingToken,695+ remotePort: bootstrap.remotePort ?? null,696+ remoteServerKind: bootstrap.remoteServerKind ?? null,697+ };698+}699+700+async function issueDesktopSshBearerSession(record: SavedEnvironmentRecord): Promise<{701+ readonly record: SavedEnvironmentRecord;702+ readonly bearerToken: string;703+ readonly role: AuthSessionRole | null;704+}> {705+ const registrySnapshot = snapshotSavedEnvironmentRegistry([record.environmentId]);706+ const prepared = await prepareSavedEnvironmentRecordForConnection(record, {707+ issuePairingToken: true,708+ });709+ if (!prepared.pairingToken) {
- patches/effect@4.0.0-beta.59.patch line 154Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +134,21 @@134+ });135+- yield* middleware(message => options.onFromClient({136++ yield* onStart.pipe(Effect.andThen(middleware(message => options.onFromClient({137+ message,138+ context,139+ discard: false140+141+ sampled: span.sampled142+ } : {}),143+ headers: Headers.merge(fiber.getRef(CurrentHeaders), headers)144+- }).pipe(span ? Effect.withParentSpan(span, {145++ }))).pipe(span ? Effect.withParentSpan(span, {146+ captureStackTrace: false147+ }) : identity, Effect.catchCause(error => Queue.failCause(queue, error)), Effect.interruptible, Effect.forkIn(scope, {148+ startImmediately: true149+150+ });151+ };152+ };153+- const sendInterrupt = (requestId, interruptors, context) => Effect.callback(resume => {154++ const sendInterrupt = (requestId, interruptors, context, tag) => (Option.isSome(hooks) && hooks.value.onRequestInterrupt ? hooks.value.onRequestInterrupt({
- apps/web/src/rpc/wsTransport.ts lines 250 to 250OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -224,4 +247,4 @@224247 Layer.mergeAll(225248 createWsRpcProtocolLayer(this.url, {226249 ...this.lifecycleHandlers,227- isActive: () => !this.disposed && this.activeSessionId === sessionId,250+ isActive: () => this.activeSessionId === sessionId,
Sign in to join this conversation.



Important
Review skipped#
Auto reviews are disabled on this repository. Please check the settings in the CodeRabbit UI or the
.coderabbit.yamlfile in this repository. To trigger a single review, invoke the@coderabbitai reviewcommand.⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro
Run ID:
352672e0-c017-487c-8367-80125cfaf3fdYou can disable this status message by setting the
reviews.review_statustofalsein the CodeRabbit configuration file.Use the checkbox below for a quick retry:
✨ Finishing Touches
🧪 Generate unit tests (beta)
Comment `@coderabbitai help` to get the list of available commands and usage tips.