feat(desktop): attach to a running local backend #8115
ClosedPedro-Revez-Silva(GitHub profile, opens in a new tab)wants to merge 6 commits into
main fromrefs/pull/8115/headopened View on GitHubgithub-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:unvouched
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:XXL
- apps/desktop/src/backend/DesktopBackendConfiguration.ts lines 820 to 822OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -653,0 +802,21 @@802+ const failed = {803+ _tag: "PairingFailed",804+ backend: previousBackend,805+ error: new DesktopExistingLocalBackend.ExistingLocalBackendPairingError({806+ baseDir: previousBackend.baseDir,807+ origin: previousBackend.origin,808+ detail: "The previously attached server is no longer available.",809+ }),810+ } as const;811+ return [failed, selection] as const;812+ }813+814+ const backend = Option.getOrThrow(detected);815+ const attachment = yield* DesktopExistingLocalBackend.pairExistingLocalBackend({816+ backend,817+ httpClient,818+ }).pipe(819+ Effect.map((value) => ({ _tag: "Success", value }) as const),820+ Effect.catchTag("ExistingLocalBackendPairingError", (error) =>821+ Effect.succeed({ _tag: "Failure", error } as const),822+ ),apps/desktop/src/backend/DesktopExistingLocalBackend.ts lines 331 to 336OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +316,21 @@316+ origin: input.backend.origin,317+ detail:318+ "The running server does not advertise Desktop attachment credentials. Update and restart that server, then try again.",319+ });320+ }321+322+ const session = yield* bootstrapRemoteBearerSession({323+ httpBaseUrl: input.backend.origin,324+ credential,325+ clientMetadata: {326+ label: "T3 Code Desktop",327+ deviceType: "desktop",328+ },329+ }).pipe(330+ Effect.provideService(HttpClient.HttpClient, input.httpClient),331+ Effect.mapError(332+ (cause) =>333+ new ExistingLocalBackendPairingError({334+ baseDir: input.backend.baseDir,335+ origin: input.backend.origin,336+ detail: cause instanceof Error ? cause.message : "The server rejected the connection.",apps/desktop/src/backend/DesktopBackendManager.ts lines 495 to 497OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -434,0 +477,21 @@477+ );478+ if (!becameReady) {479+ return {480+ code: Option.none(),481+ reason: `Timed out waiting for attached backend readiness at ${options.httpBaseUrl.href}.`,482+ } satisfies BackendProcessExit;483+ }484+485+ while (true) {486+ yield* Effect.sleep(ATTACHED_BACKEND_WATCH_INTERVAL);487+ const stillReady = yield* waitForHttpReady({488+ executablePath: options.executablePath,489+ entryPath: options.entryPath,490+ cwd: options.cwd,491+ httpBaseUrl: options.httpBaseUrl,492+ timeout: options.readinessTimeout ?? DEFAULT_BACKEND_READINESS_TIMEOUT,493+ }).pipe(494+ Effect.as(true),495+ Effect.catchTag("BackendReadinessTimeoutError", (error) =>496+ (options.onReadinessFailure?.(error) ?? Effect.void).pipe(Effect.as(false)),497+ ),
- apps/web/src/environments/primary/desktopAuth.ts line 11OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -1 +1,11 @@1+import { PRIMARY_LOCAL_ENVIRONMENT_ID } from "@t3tools/contracts";2+13 let desktopBearerTokenPromise: Promise<string> | null = null;4+let desktopBearerTokenConfigKey: string | null = null;5+let desktopBearerTokenGeneration = 0;6+7+function readDesktopPrimaryConfigKey(): string {8+ const primary = window.desktopBridge9+ ?.getLocalEnvironmentBootstraps?.()10+ .find((entry) => entry.id === PRIMARY_LOCAL_ENVIRONMENT_ID);11+ return [primary?.httpBaseUrl ?? "", primary?.bootstrapToken ?? ""].join("\u0000");
- apps/desktop/src/backend/DesktopBackendConfiguration.ts lines 903 to 907OutdatedResolvedby Pedro-Revez-Silva(GitHub profile, opens in a new tab)@@ -678,6 +888,20 @@888+ const existingResolution = yield* resolveExistingLocalBackend;889+ if (existingResolution._tag === "PairingFailed") {890+ return yield* existingResolution.error;891+ }892+ if (existingResolution._tag === "ReadyToAttach") {893+ const attachment = existingResolution.attachment;894+ return yield* resolveAttachStartConfig({895+ attachment,896+ }).pipe(Effect.provideService(DesktopEnvironment.DesktopEnvironment, environment));897+ }678898 const shared = yield* sharedInputs;679899 const resourceMonitorPath = yield* resolveResourceMonitorPath().pipe(680900 Effect.provideService(FileSystem.FileSystem, fileSystem),681901 Effect.provideService(DesktopEnvironment.DesktopEnvironment, environment),682902 );683- return yield* resolvePrimaryStartConfig({ ...shared, resourceMonitorPath }).pipe(903+ const t3Home =904+ existingResolution._tag === "Disabled" && existingResolution.reason === "independent-launch"905+ ? path.join(environment.baseDir, "desktop-independent")906+ : environment.baseDir;907+ return yield* resolvePrimaryStartConfig({ ...shared, resourceMonitorPath, t3Home }).pipe(apps/desktop/src/backend/DesktopExistingLocalBackend.ts lines 138 to 144Resolvedby Pedro-Revez-Silva(GitHub profile, opens in a new tab)@@ -0,0 +94,21 @@94+ if (options?.remainderIsValue === true) {95+ return rest.length > 0 ? rest : null;96+ }97+ const space = rest.search(/\s/);98+ const home = space === -1 ? rest : rest.slice(0, space);99+ return home.length > 0 ? home : null;100+};101+102+export const parseSystemdT3Home = (unitText: string): string | null => {103+ let resolvedHome: string | null = null;104+ for (const rawLine of unitText.split(/\r?\n/)) {105+ const line = rawLine.trim();106+ if (!line.startsWith("Environment=")) continue;107+ const raw = line.slice("Environment=".length);108+ const quotedWhole =109+ (raw.startsWith('"') && raw.endsWith('"') && raw.length >= 2) ||110+ (raw.startsWith("'") && raw.endsWith("'") && raw.length >= 2);111+ const home = extractT3HomeAssignment(quotedWhole ? raw.slice(1, -1) : raw, {112+ remainderIsValue: quotedWhole,113+ });114+ if (home !== null && home.length > 0) resolvedHome = home;
- apps/desktop/src/backend/DesktopBackendPool.ts line 156Resolvedby Pedro-Revez-Silva(GitHub profile, opens in a new tab)@@ -105,0 +136,21 @@136+ "No additional backend has been started.",137+ "Try discovery again, explicitly start a separate backend for this launch, or stop reconnecting.",138+ "",139+ input.error.message,140+ ].join("\n"),141+ buttons: ["Try Again", "Start Separate Backend", "Stop Reconnecting"],142+ defaultId: 0,143+ cancelId: 2,144+ noLink: true,145+ })146+ .pipe(147+ Effect.catch((dialogError) =>148+ logBackendPoolWarning("failed to show backend reconnection dialog", {149+ error: dialogError.message,150+ }).pipe(Effect.as({ response: 2 })),151+ ),152+ );153+154+ if (result.response === 1) {155+ yield* input.useIndependentBackendForLaunch;156+ return true;
- apps/desktop/src/backend/DesktopExistingLocalBackend.ts lines 97 to 100OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +80,21 @@80+ try {81+ process.kill(pid, 0);82+ return true;83+ } catch (error) {84+ return error instanceof Error && "code" in error && error.code === "EPERM";85+ }86+};87+88+/**89+ * Pull T3CODE_HOME out of a systemd unit or drop-in snippet. Handles the90+ * common `Environment=T3CODE_HOME=/path` form, quoted values, and multiple91+ * assignments on one line.92+ */93+const extractT3HomeAssignment = (94+ envValue: string,95+ options?: { readonly remainderIsValue?: boolean },96+): string | null => {97+ const marker = "T3CODE_HOME=";98+ const index = envValue.indexOf(marker);99+ if (index === -1) return null;100+ const rest = envValue.slice(index + marker.length);apps/desktop/src/backend/DesktopExistingLocalBackend.ts lines 122 to 126Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +105,21 @@105+ if (character === '"') return value.replaceAll("%%", "%");106+ if (character === "\\" && index + 1 < rest.length) {107+ const escaped = rest[index + 1];108+ if (escaped === "\\" || escaped === '"') {109+ value += escaped;110+ index += 1;111+ continue;112+ }113+ }114+ value += character;115+ }116+ return value.replaceAll("%%", "%");117+ }118+ if (rest.startsWith("'")) {119+ const end = rest.indexOf("'", 1);120+ const value = end === -1 ? rest.slice(1) : rest.slice(1, end);121+ return value.replaceAll("%%", "%");122+ }123+ if (options?.remainderIsValue === true) {124+ return rest.length > 0 ? rest.replaceAll("%%", "%") : null;125+ }
- apps/web/src/components/settings/ConnectionsSettings.tsx lines 2001 to 2013Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -1971,3 +1986,16 @@19711986 }19721987 }, [isTailscaleServePortValid, parsedTailscaleServePort, pendingTailscaleServeEndpoint]);197319881989+ useEffect(() => {1990+ if (!desktopBridge?.getExistingLocalBackendState) {1991+ setExistingLocalBackendState(null);1992+ return;1993+ }1994+ let cancelled = false;1995+ void desktopBridge.getExistingLocalBackendState().then(1996+ (state) => {1997+ if (!cancelled) setExistingLocalBackendState(state);1998+ },1999+ () => {2000+ if (!cancelled) setExistingLocalBackendState(null);2001+ },
- apps/desktop/src/app/DesktopApp.ts lines 33 to 33OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -29,6 +30,4 @@2930 import * as DesktopUpdates from "../updates/DesktopUpdates.ts";3031 import * as DesktopWslBackend from "../wsl/DesktopWslBackend.ts";313232-const DEFAULT_DESKTOP_BACKEND_PORT = 3773;33-const MAX_TCP_PORT = 65_535;34-const DESKTOP_BACKEND_PORT_PROBE_HOSTS = ["127.0.0.1", "0.0.0.0", "::"] as const;33+export { DesktopBackendPortUnavailableError } from "../backend/DesktopBackendPort.ts";apps/server/src/cloud/bootService.ts lines 37 to 41OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -29,9 +34,8 @@2934 type ServiceState,3035 } from "./serviceProtocol.ts";313632-const BOOT_SERVICE_NAME = "t3code";33-export const BOOT_SERVICE_UNIT_FILE = `${BOOT_SERVICE_NAME}.service`;34-// `.service` suffix keeps the label distinct from the desktop app's bundle id35-// (com.t3tools.t3code), so launchd and TCC records never collide.36-export const BOOT_SERVICE_LAUNCHD_LABEL = "com.t3tools.t3code.service";37-export const BOOT_SERVICE_PLIST_FILE = `${BOOT_SERVICE_LAUNCHD_LABEL}.plist`;37+export {38+ BOOT_SERVICE_LAUNCHD_LABEL,39+ BOOT_SERVICE_PLIST_FILE,40+ BOOT_SERVICE_UNIT_FILE,41+} from "@t3tools/shared/bootServiceIdentity";
- apps/web/src/components/settings/ConnectionsSettings.tsx lines 3144 to 3144OutdatedResolvedby Pedro-Revez-Silva(GitHub profile, opens in a new tab)@@ -3062,6 +3131,14 @@30623131 ) : null}30633132 {desktopBridge ? (30643133 <>3065- {renderNetworkAccessRow()}3066- {renderEndpointRows("endpoint-rail")}3067- {renderTailscaleRow()}3134+ {desktopBridge.getExistingLocalBackendState && existingLocalBackendState ? (3135+ <SettingsRow3136+ {...searchableSetting("attach-existing-local-backend")}3137+ description={3138+ !existingLocalBackendState.available3139+ ? "Running-server attachment is disabled in Desktop development so development state stays isolated."3140+ : existingLocalBackendState.attached3141+ ? existingLocalBackendState.origin3142+ ? `Connected to the T3 Code server already running at ${existingLocalBackendState.origin}. Network exposure is managed where that server was launched.`3143+ : "Connected to the T3 Code server already running on this machine. Network exposure is managed where that server was launched."3144+ : "Connect to a T3 Code server already running on this machine instead of starting another one."
- apps/web/src/components/settings/ConnectionsSettings.tsx lines 1776 to 1780OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -1758,6 +1766,15 @@1758- const currentSessionScopes = desktopBridge1759- ? AuthAdministrativeScopes1760- : primarySessionState.data?.authenticated1761- ? (primarySessionState.data.scopes ?? null)1762- : null;1763- const currentAuthPolicy = desktopBridge ? null : (primarySessionState.data?.auth.policy ?? null);1766+ const { isAttached: isAttachedToExistingLocalBackend, canManageDesktopBackend } =1767+ resolveDesktopBackendControlState({1768+ hasDesktopBridge: Boolean(desktopBridge),1769+ supportsExistingBackendState: Boolean(desktopBridge?.getExistingLocalBackendState),1770+ existingBackendState: existingLocalBackendState,1771+ existingBackendStateLoadFailed: existingLocalBackendStateLoadFailed,1772+ });1773+ const authenticatedSessionScopes = primarySessionState.data?.authenticated1774+ ? (primarySessionState.data.scopes ?? null)1775+ : null;1776+ const currentSessionScopes = isAttachedToExistingLocalBackend1777+ ? authenticatedSessionScopes1778+ : desktopBridge1779+ ? AuthAdministrativeScopes1780+ : authenticatedSessionScopes;
t3dotgg(GitHub profile, opens in a new tab) closed this
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 Plus
Run ID:
9349159a-765e-4c5d-9284-813da4a94da7You can disable this status message by setting the
reviews.review_statustofalsein the CodeRabbit configuration file.Use the checkbox below for a quick retry:
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.
❤️ Share