Discover local t3 serve instances for explicit pairing #4474
Closedcolonelpanic8(GitHub profile, opens in a new tab)wants to merge 17 commits into
main fromrefs/pull/4474/headopened View on GitHubgithub-actions[bot](GitHub profile, opens in a new tab) added labelssize:XXL
github-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:unvouched
- apps/web/src/environments/primary/target.ts line 300Resolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -292,3 +297,4 @@292297 resolveWindowOriginPrimaryTarget()293298 );294299 }300+
- apps/server/src/localServerAdvertisement.ts line 133OutdatedResolvedby colonelpanic8(GitHub profile, opens in a new tab)@@ -0,0 +113,21 @@113+ if (Exit.isFailure(publishExit)) {114+ yield* Effect.logWarning("Local T3 Code server discovery is unavailable.", {115+ recordPath,116+ cause: publishExit.cause,117+ });118+ return;119+ }120+121+ yield* Effect.addFinalizer(() =>122+ Effect.gen(function* () {123+ yield* discoveryState.deactivate;124+ yield* fileSystem.remove(recordPath, { force: true }).pipe(Effect.ignore);125+ yield* fileSystem.remove(tempPath, { force: true }).pipe(Effect.ignore);126+ }),127+ );128+ yield* discoveryState.activate({129+ instanceId,130+ httpBaseUrl,131+ platform,132+ xdgRuntimeDirectory,133+ });
- packages/contracts/src/localServerDiscovery.ts line 38OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +18,21 @@18+export const LocalServerAdvertisement = Schema.Struct({19+ version: LocalServerAdvertisementVersion,20+ instanceId: TrimmedNonEmptyString,21+ pid: PositiveInt,22+ startedAt: TrimmedNonEmptyString,23+ httpBaseUrl: TrimmedNonEmptyString,24+ environmentId: EnvironmentId,25+ label: TrimmedNonEmptyString,26+});27+export type LocalServerAdvertisement = typeof LocalServerAdvertisement.Type;28+29+/**30+ * Proof that the caller can create a file inside the server owner's private31+ * runtime directory, which on a 0700 XDG_RUNTIME_DIR means the caller is the32+ * same local user. `challengePath` must resolve inside the challenge directory33+ * and be a 0600 regular file owned by the server's uid whose contents equal34+ * `nonce`.35+ */36+export const LocalServerPairingChallenge = Schema.Struct({37+ instanceId: TrimmedNonEmptyString,38+ challengePath: TrimmedNonEmptyString,
- apps/desktop/src/app/DesktopLocalServerDiscovery.ts line 331Resolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -0,0 +298,21 @@298+ xdgRuntimeDirectory: hostEnvironment.XDG_RUNTIME_DIR,299+ uid: process.getuid?.(),300+ probeEnvironment: (httpBaseUrl) =>301+ fetchRemoteEnvironmentDescriptor({302+ httpBaseUrl,303+ timeoutMs: 2_000,304+ }).pipe(305+ Effect.provideService(HttpClient.HttpClient, httpClient),306+ Effect.orElseSucceed(() => null),307+ ),308+ postPairingChallenge: ({ httpBaseUrl, challenge }) =>309+ Effect.gen(function* () {310+ const url = new URL(LOCAL_SERVER_PAIRING_PATH, httpBaseUrl);311+ const request = HttpClientRequest.bodyJsonUnsafe(312+ HttpClientRequest.post(url.toString()),313+ challenge,314+ );315+ const response = yield* httpClient316+ .execute(request)317+ .pipe(Effect.flatMap(HttpClientResponse.filterStatusOk));318+ return yield* decodePairingResult(yield* response.json);apps/desktop/src/ipc/methods/backendMode.ts line 58OutdatedResolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -0,0 +38,21 @@38+ channel: IpcChannels.SET_BACKEND_MODE_CHANNEL,39+ payload: DesktopBackendModeSchema,40+ result: DesktopBackendModeStateSchema,41+ handler: Effect.fn("desktop.ipc.backendMode.set")(function* (mode) {42+ const launchMode = yield* DesktopBackendMode.DesktopBackendMode;43+ const lifecycle = yield* DesktopLifecycle.DesktopLifecycle;44+ const settings = yield* DesktopAppSettings.DesktopAppSettings;45+ const change = yield* settings.setBackendMode(mode);46+ const launchState = yield* launchMode.get;47+ const state = {48+ ...launchState,49+ configuredMode: change.settings.backendMode,50+ };51+ if (52+ change.changed &&53+ launchState.cliOverride === null &&54+ launchState.effectiveMode !== change.settings.backendMode55+ ) {56+ yield* lifecycle.relaunch(`backendMode=${mode}`);57+ }58+ return state;apps/desktop/src/ipc/methods/backendMode.ts line 60Resolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -0,0 +37,21 @@37+export const setBackendMode = DesktopIpc.makeIpcMethod({38+ channel: IpcChannels.SET_BACKEND_MODE_CHANNEL,39+ payload: DesktopBackendModeSchema,40+ result: DesktopBackendModeStateSchema,41+ handler: Effect.fn("desktop.ipc.backendMode.set")(function* (mode) {42+ const launchMode = yield* DesktopBackendMode.DesktopBackendMode;43+ const lifecycle = yield* DesktopLifecycle.DesktopLifecycle;44+ const settings = yield* DesktopAppSettings.DesktopAppSettings;45+ const change = yield* settings.setBackendMode(mode);46+ const launchState = yield* launchMode.get;47+ const state = {48+ ...launchState,49+ configuredMode: change.settings.backendMode,50+ };51+ if (52+ change.changed &&53+ launchState.cliOverride === null &&54+ launchState.effectiveMode !== change.settings.backendMode55+ ) {56+ yield* lifecycle.relaunch(`backendMode=${mode}`);57+ }
- apps/web/src/components/settings/ConnectionsSettings.logic.ts line 28Resolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -3,2 +8,21 @@38 type WslEnableBridge = Pick<DesktopBridge, "setWslBackendEnabled" | "setWslDistro" | "setWslOnly">;4910+export interface LocalServerPairingCandidate {11+ readonly advertisement: LocalServerAdvertisement;12+ readonly pairAgain: boolean;13+}14+15+export function selectLocalServerPairingCandidates(16+ advertisements: ReadonlyArray<LocalServerAdvertisement>,17+ environments: ReadonlyArray<{18+ readonly environmentId: EnvironmentId;19+ readonly connection: { readonly phase: string };20+ }>,21+): ReadonlyArray<LocalServerPairingCandidate> {22+ return advertisements.flatMap((advertisement) => {23+ const savedEnvironment = environments.find(24+ (environment) => environment.environmentId === advertisement.environmentId,25+ );26+ if (savedEnvironment && savedEnvironment.connection.phase !== "error") {27+ return [];28+ }
- apps/desktop/src/app/DesktopApp.ts line 223Resolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -149,0 +203,21 @@203+ yield* electronProtocol.registerDesktopProtocol({204+ scheme: ElectronProtocol.getDesktopScheme(true),205+ source: "proxy",206+ targetOrigin: Option.getOrThrow(environment.devServerUrl),207+ clerkFrontendApiHostname: DesktopClerk.desktopClerkFrontendApiHostname,208+ });209+ } else {210+ const staticRoot = yield* resolvePackagedClientRoot(environment.packagedClientRootCandidates);211+ yield* electronProtocol.registerDesktopProtocol({212+ scheme: ElectronProtocol.getDesktopScheme(false),213+ source: "static",214+ staticRoot,215+ clerkFrontendApiHostname: DesktopClerk.desktopClerkFrontendApiHostname,216+ });217+ yield* logBootstrapInfo("bootstrap resolved packaged renderer", { staticRoot });218+ }219+220+ yield* installDesktopIpcHandlers();221+ yield* logBootstrapInfo("bootstrap ipc handlers registered");222+ if (!(yield* Ref.get(state.quitting))) {223+ yield* handleClientOnlyRendererReady(desktopWindow.handleRendererReady);
- apps/desktop/src/app/DesktopApp.ts lines 163 to 172Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -137,2 +152,21 @@137152 handleFatalStartupError(stage, Cause.pretty(cause)).pipe(Effect.andThen(Effect.failCause(cause)));138153154+export const latchDesktopBackendModeForStartup = Effect.fn(155+ "desktop.startup.latchDesktopBackendMode",156+)(function* (configuredMode: DesktopBackendModeValue) {157+ const backendMode = yield* DesktopBackendMode.DesktopBackendMode;158+ return yield* backendMode159+ .latch(configuredMode)160+ .pipe(Effect.catchCause((cause) => fatalStartupCause("backendMode", cause)));161+});162+163+export const handleClientOnlyRendererReady = <E extends { readonly message: string }>(164+ rendererReady: Effect.Effect<void, E>,165+): Effect.Effect<void> =>166+ rendererReady.pipe(167+ Effect.catch((error) =>168+ logBootstrapWarning("failed to open main window after renderer readiness", {169+ error: error.message,170+ }),171+ ),172+ );apps/server/src/startupAccess.ts line 108OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -97,3 +97,12 @@9797 return url.toString();9898 };9999100+export const resolveLocalAdvertisementHttpBaseUrl = (101+ host: string | undefined,102+ port: number,103+): string | null => {104+ if (!isLoopbackHost(host)) {105+ return null;106+ }107+ const normalized = host ? normalizeHost(host) : "127.0.0.1";108+ const canonicalHost = normalized === "localhost" ? "127.0.0.1" : formatHostForUrl(normalized);
- apps/web/src/components/settings/ConnectionsSettings.tsx line 3575Resolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -3317,0 +3542,21 @@3542+ variant="ghost"3543+ disabled={isDiscoveringLocalServers}3544+ onClick={() => void refreshLocalServerAdvertisements()}3545+ >3546+ {isDiscoveringLocalServers ? (3547+ <Spinner className="size-3" />3548+ ) : (3549+ <RefreshCwIcon className="size-3" />3550+ )}3551+ Scan again3552+ </Button>3553+ }3554+ >3555+ <p className="px-1 text-xs text-muted-foreground">3556+ These loopback servers published credential-free presence records. Pairing verifies the3557+ server belongs to your local user, then saves the connection; this desktop will not3558+ manage the server process.3559+ </p>3560+ {renderLocalServerPairingCandidates()}3561+ </SettingsSection>3562+ ) : null}
- apps/server/src/startupAccess.ts line 116OutdatedResolvedby colonelpanic8(GitHub profile, opens in a new tab)@@ -97,3 +97,20 @@9797 return url.toString();9898 };9999100+export const resolveLocalAdvertisementHttpBaseUrl = (101+ host: string | undefined,102+ port: number,103+ listeningHost?: string,104+): string | null => {105+ if (!isLoopbackHost(host)) {106+ return null;107+ }108+ const normalizedListeningHost = listeningHost ? normalizeHost(listeningHost) : null;109+ if (normalizedListeningHost !== null && !isLoopbackHost(normalizedListeningHost)) {110+ return null;111+ }112+ const normalized = normalizedListeningHost ?? (host ? normalizeHost(host) : "127.0.0.1");113+ const canonicalHost =114+ listeningHost === undefined && normalized === "localhost"115+ ? "127.0.0.1"116+ : formatHostForUrl(normalized);
- apps/web/src/components/settings/ConnectionsSettings.tsx line 1765OutdatedResolvedby colonelpanic8(GitHub profile, opens in a new tab)@@ -1734,3 +1753,13 @@17341753 .toSorted((left, right) => left.label.localeCompare(right.label)),17351754 [environments],17361755 );1756+ const hasUsableClientOnlyEnvironment = savedEnvironments.some(1757+ (environment) => !isDesktopLocalConnectionTarget(environment.entry.target),1758+ );1759+ const isClientOnlyDesktop = desktopBackendModeState?.effectiveMode === "client-only";1760+ const localServerPairingCandidates = useMemo(1761+ () => selectLocalServerPairingCandidates(localServerAdvertisements, environments),1762+ [environments, localServerAdvertisements],1763+ );1764+ const hasLocalServerDiscoveryContent =1765+ localServerPairingCandidates.length > 0 || localServerDiscoveryError !== null;
- apps/web/src/components/settings/ConnectionsSettings.tsx line 1779Resolvedby colonelpanic8(GitHub profile, opens in a new tab)@@ -1736,0 +1758,21 @@1758+ );1759+ const isClientOnlyDesktop = desktopBackendModeState?.effectiveMode === "client-only";1760+ const localServerPairingCandidates = useMemo(1761+ () => selectLocalServerPairingCandidates(localServerAdvertisements, environments),1762+ [environments, localServerAdvertisements],1763+ );1764+ const hasLocalServerDiscoveryContent =1765+ isDiscoveringLocalServers ||1766+ localServerPairingCandidates.length > 0 ||1767+ localServerDiscoveryError !== null;1768+ const refreshLocalServerAdvertisements = useCallback(async () => {1769+ const discoverLocalServers = desktopBridge?.discoverLocalServers;1770+ if (!discoverLocalServers) {1771+ setLocalServerAdvertisements(EMPTY_LOCAL_SERVER_ADVERTISEMENTS);1772+ return EMPTY_LOCAL_SERVER_ADVERTISEMENTS;1773+ }1774+ setIsDiscoveringLocalServers(true);1775+ try {1776+ const discovered = await discoverLocalServers();1777+ setLocalServerAdvertisements(discovered);1778+ setLocalServerDiscoveryError(null);
- apps/desktop/src/ipc/methods/backendMode.ts line 59Resolvedby colonelpanic8(GitHub profile, opens in a new tab)@@ -0,0 +41,21 @@41+ handler: Effect.fn("desktop.ipc.backendMode.set")(function* (mode) {42+ const launchMode = yield* DesktopBackendMode.DesktopBackendMode;43+ const lifecycle = yield* DesktopLifecycle.DesktopLifecycle;44+ const settings = yield* DesktopAppSettings.DesktopAppSettings;45+ const previousMode = (yield* settings.get).backendMode;46+ const change = yield* settings.setBackendMode(mode);47+ const launchState = yield* launchMode.get;48+ const relaunchRequired =49+ change.changed &&50+ launchState.cliOverride === null &&51+ launchState.effectiveMode !== change.settings.backendMode;52+ if (relaunchRequired) {53+ yield* lifecycle54+ .relaunch(`backendMode=${mode}`)55+ .pipe(Effect.tapError(() => settings.setBackendMode(previousMode)));56+ // The current process is still running in its latched launch mode until57+ // Electron exits. Keep both fields coherent during that brief interval.58+ return {59+ ...launchState,60+ configuredMode: launchState.effectiveMode,61+ };apps/desktop/src/app/DesktopLocalServerDiscovery.ts line 277Resolvedby colonelpanic8(GitHub profile, opens in a new tab)@@ -0,0 +256,21 @@256+ yield* fileSystem.makeDirectory(challengeDirectory, {257+ recursive: true,258+ mode: LOCAL_SERVER_CHALLENGE_DIRECTORY_MODE,259+ });260+ // `makeDirectory` honours the umask and is a no-op when the directory261+ // already exists, so tighten the mode unconditionally.262+ yield* fileSystem.chmod(challengeDirectory, LOCAL_SERVER_CHALLENGE_DIRECTORY_MODE);263+ yield* fileSystem.writeFileString(challengePath, nonce, {264+ mode: LOCAL_SERVER_CHALLENGE_FILE_MODE,265+ });266+ yield* fileSystem.chmod(challengePath, LOCAL_SERVER_CHALLENGE_FILE_MODE);267+ }).pipe(268+ Effect.mapError(269+ (cause) =>270+ new LocalServerPairingError({271+ reason: "challenge_failed",272+ detail: "Could not write the local pairing challenge.",273+ cause,274+ }),275+ ),276+ );
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:
a785a55a-8f3e-43b9-90ba-ac92f97bab88You 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)
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