Add desktop WSL backend mode #2353
ClosedJgratton24(GitHub profile, opens in a new tab)wants to merge 15 commits into
main fromrefs/pull/2353/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:L
- @@ -1853,0 +1924,21 @@1924+1925+ ipcMain.removeHandler(WSL_SET_CONFIG_CHANNEL);1926+ ipcMain.handle(WSL_SET_CONFIG_CHANNEL, async (_event, config: unknown) => {1927+ if (1928+ typeof config !== "object" ||1929+ config === null ||1930+ typeof (config as Record<string, unknown>).enabled !== "boolean"1931+ ) {1932+ return false;1933+ }1934+ const typed = config as { enabled: boolean; distro?: unknown };1935+ const distro =1936+ typeof typed.distro === "string" && typed.distro.length > 0 ? typed.distro : null;1937+ const DISTRO_NAME_PATTERN = /^[\w][\w\s\-.]*$/;1938+ if (distro !== null && !DISTRO_NAME_PATTERN.test(distro)) {1939+ return false;1940+ }1941+ saveWslConfig(STATE_DIR, { enabled: typed.enabled, distro });1942+ stopBackend();1943+ startBackend();1944+ return true;@@ -1411,0 +1417,21 @@1417+ if (linuxEntry === windowsEntry) {1418+ scheduleBackendRestart("wslpath conversion failed for backend entry");1419+ return;1420+ }1421+1422+ const wslForwardedEnv: Record<string, string> = {};1423+ for (const key of ["OPENAI_API_KEY", "ANTHROPIC_API_KEY"]) {1424+ if (process.env[key]) wslForwardedEnv[key] = process.env[key]!;1425+ }1426+ child = ChildProcess.spawn(1427+ "wsl.exe",1428+ [...distroArgs, "--", "node", linuxEntry, "--bootstrap-fd", "0"],1429+ {1430+ cwd: resolveBackendCwd(),1431+ env: {1432+ ...wslForwardedEnv,1433+ WSLENV: Object.keys(wslForwardedEnv).join(":"),1434+ },1435+ stdio: captureBackendLogs ? ["pipe", "pipe", "pipe"] : ["pipe", "inherit", "inherit"],1436+ windowsHide: true,1437+ },@@ -1672,4 +1728,8 @@16721728 ipcMain.removeHandler(PICK_FOLDER_CHANNEL);16731729 ipcMain.handle(PICK_FOLDER_CHANNEL, async (_event, rawOptions: unknown) => {16741730 const owner = BrowserWindow.getFocusedWindow() ?? mainWindow;1675- const defaultPath = resolvePickFolderDefaultPath(rawOptions);1731+ const wslConfig = loadWslConfig(STATE_DIR);1732+ const useWsl = wslConfig.enabled && isWslAvailable();1733+ const defaultPath = useWsl1734+ ? `\\\\wsl.localhost\\${wslConfig.distro ?? "Ubuntu"}\\home`1735+ : resolvePickFolderDefaultPath(rawOptions);
- apps/desktop/src/backendReadiness.ts line 63OutdatedResolvedby Jgratton24(GitHub profile, opens in a new tab)@@ -60,4 +60,4 @@6060 const intervalMs = options?.intervalMs ?? DEFAULT_INTERVAL_MS;6161 const requestTimeoutMs = options?.requestTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS;6262 const readinessPath = options?.path ?? "/";63- const isReady = options?.isReady ?? ((response: Response) => response.ok);63+ const isReady = options?.isReady ?? ((response: Response) => response.status < 500);
- apps/desktop/src/backendReadiness.ts line 11OutdatedResolvedby Jgratton24(GitHub profile, opens in a new tab)@@ -8,4 +8,4 @@88 readonly isReady?: (response: Response) => boolean;99 }101011-const DEFAULT_TIMEOUT_MS = 30_000;11+const DEFAULT_TIMEOUT_MS = 300_000;apps/desktop/src/main.ts line 1758OutdatedResolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -1681,4 +1753,6 @@16811753 ? await dialog.showOpenDialog(owner, openDialogOptions)16821754 : await dialog.showOpenDialog(openDialogOptions);16831755 if (result.canceled) return null;1684- return result.filePaths[0] ?? null;1756+ const pickedPath = result.filePaths[0] ?? null;1757+ if (pickedPath === null) return null;1758+ return useWsl ? windowsToWslPath(wslConfig.distro, pickedPath) : pickedPath;apps/desktop/src/main.ts line 1421OutdatedResolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -1406,6 +1407,15 @@1406- ? { otlpTracesUrl: backendObservabilitySettings.otlpTracesUrl }1407- : {}),1408- ...(backendObservabilitySettings.otlpMetricsUrl1409- ? { otlpMetricsUrl: backendObservabilitySettings.otlpMetricsUrl }1410- : {}),1411- })}\n`,1407+1408+ let child: ChildProcess.ChildProcess;1409+1410+ if (useWsl) {1411+ const distroArgs = wslConfig.distro ? ["-d", wslConfig.distro] : [];1412+ const windowsEntry = resolveBackendEntry();1413+ if (!FS.existsSync(windowsEntry)) {1414+ scheduleBackendRestart(`missing server entry at ${windowsEntry}`);1415+ return;1416+ }1417+ const linuxEntry = windowsToWslPath(wslConfig.distro, windowsEntry);1418+ if (linuxEntry === windowsEntry) {1419+ scheduleBackendRestart("wslpath conversion failed for backend entry");1420+ return;1421+ }@@ -0,0 +26,21 @@26+ // wsl.exe --list --verbose outputs UTF-16LE with a BOM27+ let text = stdout.toString("utf16le");28+ if (text.charCodeAt(0) === 0xfeff) text = text.slice(1);29+30+ const lines = text.split(/\r?\n/).filter((line) => line.trim().length > 0);31+ // First line is the header ("NAME STATE VERSION"), skip it32+ const distros: WslDistro[] = [];33+ for (let i = 1; i < lines.length; i++) {34+ const line = lines[i]!;35+ const isDefault = line.startsWith("*");36+ const cleaned = isDefault ? line.slice(1).trim() : line.trim();37+ // Fields are separated by 2+ spaces38+ const fields = cleaned.split(/\s{2,}/);39+ if (fields.length < 3) continue;40+ const name = fields[0]!.trim();41+ const versionNum = parseInt(fields[2]!, 10);42+ if (!name || (versionNum !== 1 && versionNum !== 2)) continue;43+ distros.push({ name, isDefault, version: versionNum as 1 | 2 });44+ }45+ return distros;46+}@@ -0,0 +95,21 @@95+ resolve(parseWslDistroList(Buffer.concat(chunks)));96+ });97+ child.on("error", () => {98+ clearTimeout(timeout);99+ resolve([]);100+ });101+ });102+}103+104+export function loadWslConfig(stateDir: string): WslConfig {105+ try {106+ const raw = FS.readFileSync(Path.join(stateDir, WSL_CONFIG_FILENAME), "utf8");107+ const parsed = JSON.parse(raw) as Record<string, unknown>;108+ if (typeof parsed.enabled !== "boolean") return DEFAULT_WSL_CONFIG;109+ const distro =110+ typeof parsed.distro === "string" && parsed.distro.length > 0 ? parsed.distro : null;111+ return { enabled: parsed.enabled, distro };112+ } catch {113+ return DEFAULT_WSL_CONFIG;114+ }115+}apps/web/src/components/settings/ConnectionsSettings.tsx line 1372OutdatedResolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -1247,0 +1352,21 @@1352+ >1353+ <option value="">Default distro</option>1354+ {desktopWslDistros.map((distro) => (1355+ <option key={distro.name} value={distro.name}>1356+ {distro.name}1357+ {distro.isDefault ? " (default)" : ""}1358+ </option>1359+ ))}1360+ </select>1361+ <Switch1362+ checked={desktopWslConfig?.enabled ?? false}1363+ disabled={1364+ !desktopWslConfig || desktopWslDistros.length === 0 || isUpdatingDesktopWsl1365+ }1366+ onCheckedChange={(checked) => {1367+ void handleDesktopWslChange({1368+ enabled: checked,1369+ distro: desktopWslConfig?.distro ?? defaultDesktopWslDistro,1370+ });1371+ }}1372+ aria-label="Enable WSL backend"
- apps/desktop/src/main.ts line 1768OutdatedResolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -1681,4 +1762,7 @@16811762 ? await dialog.showOpenDialog(owner, openDialogOptions)16821763 : await dialog.showOpenDialog(openDialogOptions);16831764 if (result.canceled) return null;1684- return result.filePaths[0] ?? null;1765+ const pickedPath = result.filePaths[0] ?? null;1766+ if (pickedPath === null) return null;1767+ if (!useWsl) return pickedPath;1768+ return await windowsToWslPathAsync(wslConfig.distro, pickedPath);apps/desktop/src/main.ts line 1965OutdatedResolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -1853,0 +1945,21 @@1945+ ipcMain.handle(WSL_GET_CONFIG_CHANNEL, async () => loadWslConfig(STATE_DIR));1946+1947+ ipcMain.removeHandler(WSL_SET_CONFIG_CHANNEL);1948+ ipcMain.handle(WSL_SET_CONFIG_CHANNEL, async (_event, config: unknown) => {1949+ if (1950+ typeof config !== "object" ||1951+ config === null ||1952+ typeof (config as Record<string, unknown>).enabled !== "boolean"1953+ ) {1954+ return false;1955+ }1956+ const typed = config as { enabled: boolean; distro?: unknown };1957+ const distro =1958+ typeof typed.distro === "string" && typed.distro.length > 0 ? typed.distro : null;1959+ if (distro !== null && !DISTRO_NAME_PATTERN.test(distro)) {1960+ return false;1961+ }1962+ saveWslConfig(STATE_DIR, { enabled: typed.enabled, distro });1963+ await stopBackendAndWaitForExit();1964+ void startBackend();1965+ return true;apps/desktop/src/main.ts line 1756OutdatedResolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -1672,4 +1749,8 @@16721749 ipcMain.removeHandler(PICK_FOLDER_CHANNEL);16731750 ipcMain.handle(PICK_FOLDER_CHANNEL, async (_event, rawOptions: unknown) => {16741751 const owner = BrowserWindow.getFocusedWindow() ?? mainWindow;1675- const defaultPath = resolvePickFolderDefaultPath(rawOptions);1752+ const wslConfig = loadWslConfig(STATE_DIR);1753+ const useWsl = wslConfig.enabled && isWslAvailable();1754+ const defaultPath = useWsl1755+ ? resolveWslHomeUncPath(wslConfig, await listWslDistrosAsync())1756+ : resolvePickFolderDefaultPath(rawOptions);
github-actions[bot](GitHub profile, opens in a new tab) removed labelssize:L
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:XL
- apps/desktop/src/backendReadiness.ts line 11OutdatedResolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -8,4 +8,4 @@88 readonly isReady?: (response: Response) => boolean;99 }101011-const DEFAULT_TIMEOUT_MS = 30_000;11+const DEFAULT_TIMEOUT_MS = 300_000;apps/desktop/src/main.ts line 1975OutdatedResolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -1853,0 +1955,21 @@1955+ if (1956+ typeof config !== "object" ||1957+ config === null ||1958+ typeof (config as Record<string, unknown>).enabled !== "boolean"1959+ ) {1960+ return false;1961+ }1962+ const typed = config as { enabled: boolean; distro?: unknown };1963+ const distro =1964+ typeof typed.distro === "string" && typed.distro.length > 0 ? typed.distro : null;1965+ if (distro !== null && !DISTRO_NAME_PATTERN.test(distro)) {1966+ return false;1967+ }1968+ saveWslConfig(STATE_DIR, { enabled: typed.enabled, distro });1969+ await stopBackendAndWaitForExit();1970+ const started = await startBackend();1971+ if (!started && typed.enabled) {1972+ throw new Error("Could not start the backend inside WSL.");1973+ }1974+ return true;1975+ });apps/desktop/src/main.ts line 1774OutdatedResolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -1681,4 +1764,11 @@16811764 ? await dialog.showOpenDialog(owner, openDialogOptions)16821765 : await dialog.showOpenDialog(openDialogOptions);16831766 if (result.canceled) return null;1684- return result.filePaths[0] ?? null;1767+ const pickedPath = result.filePaths[0] ?? null;1768+ if (pickedPath === null) return null;1769+ if (!useWsl) return pickedPath;1770+ const wslPath = await windowsToWslPathAsync(wslConfig.distro, pickedPath);1771+ if (wslPath === null) {1772+ throw new Error("Could not convert the selected folder path for WSL.");1773+ }1774+ return wslPath;
- apps/web/src/components/settings/ConnectionsSettings.tsx line 1641OutdatedResolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -853,0 +876,21 @@876+ description: nextConfig.enabled877+ ? "The local backend is now launching inside WSL."878+ : "The local backend is now launching on Windows.",879+ });880+ } catch (error) {881+ const message =882+ error instanceof Error ? error.message : "Failed to update WSL backend mode.";883+ setDesktopWslError(message);884+ toastManager.add(885+ stackedThreadToast({886+ type: "error",887+ title: "Could not update WSL backend",888+ description: message,889+ }),890+ );891+ } finally {892+ setIsUpdatingDesktopWsl(false);893+ }894+ },895+ [desktopBridge],896+ );
- apps/desktop/src/main.ts line 2013OutdatedResolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -1853,0 +1993,21 @@1993+ return false;1994+ }1995+ const typed = config as { enabled: boolean; distro?: unknown };1996+ const distro =1997+ typeof typed.distro === "string" && typed.distro.length > 0 ? typed.distro : null;1998+ if (distro !== null && !DISTRO_NAME_PATTERN.test(distro)) {1999+ return false;2000+ }2001+ const previousConfig = loadWslConfig(STATE_DIR);2002+ saveWslConfig(STATE_DIR, { enabled: typed.enabled, distro });2003+ await stopBackendAndWaitForExit();2004+ const started = await startBackend();2005+ if (!started && typed.enabled) {2006+ // Roll back so the on-disk config matches the renderer's view; the2007+ // exponential-backoff restart will relaunch under the previous2008+ // configuration. Without this, the renderer's error toast leaves the2009+ // UI showing the old toggle while the next app launch silently honors2010+ // the never-confirmed configuration.2011+ saveWslConfig(STATE_DIR, previousConfig);2012+ throw new Error("Could not start the backend inside WSL.");2013+ }
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
- apps/desktop/src/wsl.ts lines 237 to 248OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +228,21 @@228+ child.kill();229+ settle(124, "\n[timeout]");230+ }, timeoutMs);231+ timeout.unref();232+233+ child.on("error", (error) => settle(127, `\n${error.message}`));234+ child.on("close", (code) => settle(code ?? 1));235+236+ const stdin = child.stdin;237+ if (stdin) {238+ stdin.once("error", (error) => settle(127, `\n${error.message}`));239+ try {240+ stdin.write(bashScript);241+ stdin.end();242+ } catch (error) {243+ settle(127, `\n${error instanceof Error ? error.message : String(error)}`);244+ }245+ } else {246+ settle(127, "\n[stdin pipe unavailable]");247+ }248+ });
- apps/desktop/src/main.ts line 2027OutdatedResolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -1853,0 +2007,21 @@2007+ await stopBackendAndWaitForExit();2008+ const started = await startBackend();2009+ if (!started) {2010+ throw new Error(2011+ typed.enabled2012+ ? "Could not start the backend inside WSL."2013+ : "Could not restart the backend on Windows.",2014+ );2015+ }2016+ await waitForBackendWindowReady(backendHttpUrl);2017+ return true;2018+ } catch (error) {2019+ // Roll back so the on-disk config matches the renderer's view; the2020+ // exponential-backoff restart will relaunch under the previous2021+ // configuration. Without this, the renderer's error toast leaves the2022+ // UI showing the old toggle while the next app launch silently honors2023+ // the never-confirmed configuration.2024+ saveWslConfig(STATE_DIR, previousConfig);2025+ throw error;2026+ }2027+ };
- @@ -0,0 +146,21 @@146+ if (trimmedPath.length === 0) {147+ return homePath;148+ }149+ if (trimmedPath.startsWith("\\\\")) {150+ return trimmedPath;151+ }152+153+ const distroName = config.distro ?? distros.find((distro) => distro.isDefault)?.name ?? null;154+ if (!distroName) {155+ return homePath;156+ }157+158+ const toUncPath = (linuxPath: string) =>159+ `\\\\wsl.localhost\\${distroName}${linuxPath.replaceAll("/", "\\")}`;160+161+ if (trimmedPath === "~") {162+ return homePath;163+ }164+ if (trimmedPath.startsWith("~/")) {165+ return homePath ? `${homePath}\\${trimmedPath.slice(2).replaceAll("/", "\\")}` : null;166+ }apps/desktop/src/main.ts line 1387OutdatedResolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -1369,19 +1387,8 @@13691387 }, delayMs);13701388 }137113891372-function startBackend(): void {1373- if (isQuitting || backendProcess) return;1390+async function startBackend(): Promise<boolean> {1391+ if (isQuitting || backendProcess || backendStartInFlight) return false;1374139213751393 backendObservabilitySettings = readPersistedBackendObservabilitySettings();1376- const backendEntry = resolveBackendEntry();1377- if (!FS.existsSync(backendEntry)) {1378- scheduleBackendRestart(`missing server entry at ${backendEntry}`);1379- return;1380- }1381-13821394 const captureBackendLogs = !isDevelopment;1383- const child = ChildProcess.spawn(process.execPath, [backendEntry, "--bootstrap-fd", "3"], {1384- cwd: resolveBackendCwd(),1385- // In Electron main, process.execPath points to the Electron binary.1386- // Run the child in Node mode so this backend process does not become a GUI app instance.1387- env: {
- apps/web/src/components/settings/ConnectionsSettings.tsx line 929OutdatedResolvedby Jgratton24(GitHub profile, opens in a new tab)@@ -853 +909,21 @@853909910+ const handleDesktopWslChange = useCallback(911+ async (nextConfig: DesktopWslConfig) => {912+ if (!desktopBridge) return;913+ setIsUpdatingDesktopWsl(true);914+ setDesktopWslChangeStage("restarting-backend");915+ setDesktopWslError(null);916+ try {917+ const normalizedConfig = normalizeDesktopWslConfig(nextConfig);918+ await leaveCurrentPrimaryThreadRoute();919+ await suppressWsConnectionLifecycle(async () => {920+ const updated = await desktopBridge.wslSetConfig(normalizedConfig);921+ if (!updated) {922+ throw new Error("The WSL backend configuration was rejected.");923+ }924+ setDesktopWslChangeStage("reauthenticating");925+ await refreshPrimaryEnvironmentDescriptor();926+ // Each backend signs sessions with its own key, so the OLD cookie is rejected927+ // by the new backend (401). Re-bootstrap before any WS reconnect attempts.928+ await reauthenticatePrimaryEnvironment();929+ });apps/web/src/rpc/wsConnectionState.ts line 218Resolvedby Jgratton24(GitHub profile, opens in a new tab)@@ -153,3 +155,21 @@153155 appAtomRegistry.set(wsConnectionStatusAtom, INITIAL_WS_CONNECTION_STATUS);154156 }155157158+export function resetWsConnectionState(): void {159+ appAtomRegistry.set(wsConnectionStatusAtom, INITIAL_WS_CONNECTION_STATUS);160+}161+162+export function isWsConnectionLifecycleSuppressed(): boolean {163+ return wsConnectionLifecycleSuppressionDepth > 0;164+}165+166+export async function suppressWsConnectionLifecycle<T>(operation: () => Promise<T>): Promise<T> {167+ wsConnectionLifecycleSuppressionDepth += 1;168+ resetWsConnectionState();169+ try {170+ return await operation();171+ } finally {172+ wsConnectionLifecycleSuppressionDepth -= 1;173+ resetWsConnectionState();174+ }175+}@@ -0,0 +80,21 @@80+ windowsHide: true,81+ });82+ } catch {83+ resolve(null);84+ return;85+ }86+87+ const settle = (path: string | null) => {88+ if (settled) return;89+ settled = true;90+ if (timeout) {91+ clearTimeout(timeout);92+ }93+ resolve(path);94+ };95+96+ timeout = setTimeout(() => {97+ child.kill();98+ settle(null);99+ }, 3_000);100+ timeout.unref();
- apps/desktop/src/main.ts line 1579OutdatedResolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -1499,2 +1560,20 @@1560+ ...(wslBackendEnv.WSLENV?.split(":").filter((name) => name.length > 0) ?? []),1561+ ...wslForwardedEnvNames,1562+ ];1563+ child = ChildProcess.spawn(1564+ "wsl.exe",1565+ [...distroArgs, "--", "node", linuxEntry, "--bootstrap-fd", "0"],1566+ {1567+ cwd: resolveBackendCwd(),1568+ env: {1569+ ...wslBackendEnv,1570+ ...wslForwardedEnv,1571+ ...(wslEnvNames.length > 0 ? { WSLENV: [...new Set(wslEnvNames)].join(":") } : {}),1572+ },1573+ stdio: captureBackendLogs ? ["pipe", "pipe", "pipe"] : ["pipe", "inherit", "inherit"],1574+ windowsHide: true,1575+ },14991576 );1500- bootstrapStream.end();1577+ if (child.stdin) {1578+ child.stdin.write(`${bootstrapEnvelope}\n`);1579+ child.stdin.end();apps/web/src/rpc/wsConnectionState.ts line 203OutdatedResolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -196,3 +198,6 @@196198 appAtomRegistry.set(wsConnectionStatusAtom, INITIAL_WS_CONNECTION_STATUS);197199 }198200201+export function resetWsConnectionState(): void {202+ appAtomRegistry.set(wsConnectionStatusAtom, INITIAL_WS_CONNECTION_STATUS);203+}
- @@ -0,0 +1,18 @@1+import * as ChildProcess from "node:child_process";2+import * as FS from "node:fs";3+import * as Path from "node:path";4+5+export interface WslDistro {6+ name: string;7+ isDefault: boolean;8+ version: 1 | 2;9+}10+11+export interface WslConfig {12+ enabled: boolean;13+ distro: string | null;14+}15+16+const DEFAULT_WSL_CONFIG: WslConfig = { enabled: false, distro: null };17+const WSL_CONFIG_FILENAME = "wsl-config.json";18+export const DISTRO_NAME_PATTERN = /^[\w][\w\s\-.]*$/;
- @@ -1498,0 +1515,21 @@1515+ if (!FS.existsSync(windowsEntry)) {1516+ scheduleBackendRestart(`missing server entry at ${windowsEntry}`);1517+ return false;1518+ }1519+ let resolveStartInFlight!: () => void;1520+ backendStartInFlight = new Promise<void>((resolve) => {1521+ resolveStartInFlight = resolve;1522+ });1523+ let linuxEntry: string | null = null;1524+ let nodePtyError: string | null = null;1525+ try {1526+ linuxEntry = await windowsToWslPathAsync(wslConfig.distro, windowsEntry);1527+ // node-pty's npm tarball ships prebuilds for darwin/win32 only, so a1528+ // Windows-side install has no Linux pty.node. Dev builds can compile it1529+ // on demand; packaged builds only reuse a verified staged binary.1530+ const result = await ensureWslNodePty(wslConfig.distro, ROOT_DIR, {1531+ allowBuild: !app.isPackaged,1532+ });1533+ if (!result.ok) {1534+ nodePtyError = result.reason;1535+ }@@ -0,0 +347,21 @@347+ windowsHide: true,348+ });349+ const chunks: Buffer[] = [];350+ child.stdout.on("data", (chunk: Buffer) => chunks.push(chunk));351+ const timeout = setTimeout(() => {352+ child.kill();353+ resolve([]);354+ }, 8_000);355+ child.on("close", (code) => {356+ clearTimeout(timeout);357+ if (code !== 0 || chunks.length === 0) {358+ resolve([]);359+ return;360+ }361+ resolve(parseWslDistroList(Buffer.concat(chunks)));362+ });363+ child.on("error", () => {364+ clearTimeout(timeout);365+ resolve([]);366+ });367+ });
- apps/desktop/src/main.ts lines 1592 to 1599OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -1499,2 +1580,20 @@1580+ },14991581 );1500- bootstrapStream.end();1582+ if (child.stdin) {1583+ // wsl.exe can exit immediately (bad distro, WSL service unavailable, etc.) and the1584+ // resulting EPIPE/'error' on stdin would otherwise crash the Electron main process.1585+ const wslChild = child;1586+ const handleStdinFailure = (error: unknown) => {1587+ wslChild.kill("SIGTERM");1588+ scheduleBackendRestart(1589+ `WSL bootstrap stdin error: ${error instanceof Error ? error.message : String(error)}`,1590+ );1591+ };1592+ child.stdin.once("error", handleStdinFailure);1593+ try {1594+ child.stdin.write(`${bootstrapEnvelope}\n`);1595+ child.stdin.end();1596+ } catch (error) {1597+ handleStdinFailure(error);1598+ return false;1599+ }
- @@ -1499,2 +1572,20 @@1572+ cwd: resolveBackendCwd(),1573+ env: {1574+ ...wslBackendEnv,1575+ ...wslForwardedEnv,1576+ ...(wslEnvNames.length > 0 ? { WSLENV: [...new Set(wslEnvNames)].join(":") } : {}),1577+ },1578+ stdio: captureBackendLogs ? ["pipe", "pipe", "pipe"] : ["pipe", "inherit", "inherit"],1579+ windowsHide: true,1580+ },14991581 );1500- bootstrapStream.end();1582+ if (child.stdin) {1583+ // wsl.exe can exit immediately (bad distro, WSL service unavailable, etc.) and the1584+ // resulting EPIPE/'error' on stdin would otherwise crash the Electron main process.1585+ const wslChild = child;1586+ const handleStdinFailure = (error: unknown) => {1587+ wslChild.kill("SIGTERM");1588+ scheduleBackendRestart(1589+ `WSL bootstrap stdin error: ${error instanceof Error ? error.message : String(error)}`,1590+ );1591+ };@@ -2198,4 +2419,6 @@2198241921992420 registerIpcHandlers();22002421 writeDesktopLogHeader("bootstrap ipc handlers registered");2201- startBackend();2422+ const shouldGateDevWindowOnBackend =2423+ isDevelopment && loadWslConfig(STATE_DIR).enabled && isWslAvailable();2424+ void startBackend();
- apps/web/src/rpc/wsConnectionState.ts line 218Resolvedby Jgratton24(GitHub profile, opens in a new tab)@@ -198,0 +202,21 @@202+ return wsConnectionLifecycleSuppressionDepth > 0;203+}204+205+export async function suppressWsConnectionLifecycle<T>(operation: () => Promise<T>): Promise<T> {206+ // Only reset on the outermost transition so a nested caller can't wipe207+ // connection state mid-flight while an outer suppression window is still208+ // open.209+ const wasSuppressed = wsConnectionLifecycleSuppressionDepth > 0;210+ wsConnectionLifecycleSuppressionDepth += 1;211+ if (!wasSuppressed) {212+ appAtomRegistry.set(wsConnectionStatusAtom, INITIAL_WS_CONNECTION_STATUS);213+ }214+ try {215+ return await operation();216+ } finally {217+ wsConnectionLifecycleSuppressionDepth -= 1;218+ if (wsConnectionLifecycleSuppressionDepth === 0) {219+ appAtomRegistry.set(wsConnectionStatusAtom, INITIAL_WS_CONNECTION_STATUS);220+ }221+ }222+}apps/desktop/src/main.ts line 1936OutdatedResolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -1786,4 +1931,6 @@17861931 ipcMain.removeHandler(PICK_FOLDER_CHANNEL);17871932 ipcMain.handle(PICK_FOLDER_CHANNEL, async (_event, rawOptions: unknown) => {17881933 const owner = BrowserWindow.getFocusedWindow() ?? mainWindow;1789- const defaultPath = resolvePickFolderDefaultPath(rawOptions);1934+ const wslConfig = loadWslConfig(STATE_DIR);1935+ const useWsl = wslConfig.enabled && isWslAvailable();1936+ const wslDistros = useWsl ? await listWslDistrosAsync() : [];
- @@ -0,0 +378,21 @@378+}379+380+export async function listWslDistrosAsync(): Promise<WslDistro[]> {381+ if (process.platform !== "win32") return [];382+ return new Promise((resolve) => {383+ let child: ChildProcess.ChildProcess;384+ try {385+ child = ChildProcess.spawn("wsl.exe", ["--list", "--verbose"], {386+ stdio: ["ignore", "pipe", "pipe"],387+ windowsHide: true,388+ });389+ } catch {390+ resolve([]);391+ return;392+ }393+ const chunks: Buffer[] = [];394+ child.stdout?.on("data", (chunk: Buffer) => chunks.push(chunk));395+ const timeout = setTimeout(() => {396+ child.kill();397+ resolve([]);398+ }, 8_000);
- apps/web/src/components/ProjectFavicon.tsx line 54OutdatedResolvedby Jgratton24(GitHub profile, opens in a new tab)@@ -44,9 +43,12 @@44- src={src}45- alt=""46- className={`size-3.5 shrink-0 rounded-sm object-contain ${status === "loaded" ? "" : "hidden"} ${input.className ?? ""}`}47- onLoad={() => {48- loadedProjectFaviconSrcs.add(src);49- setStatus("loaded");50- }}51- onError={() => setStatus("error")}52- />43+ {src ? (44+ <img45+ src={src}46+ alt=""47+ className={`size-3.5 shrink-0 rounded-sm object-contain ${status === "loaded" ? "" : "hidden"} ${input.className ?? ""}`}48+ onLoad={() => {49+ loadedProjectFaviconSrcs.add(src);50+ setStatus("loaded");51+ }}52+ onError={() => setStatus("error")}53+ />54+ ) : null}
- apps/web/src/components/settings/ConnectionsSettings.tsx line 1676OutdatedResolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -1575,0 +1656,21 @@1656+ type: "success",1657+ title: "Backend restarted",1658+ description: normalizedConfig.enabled1659+ ? "The local backend is running inside WSL."1660+ : "The local backend is running on Windows.",1661+ });1662+ } catch (error) {1663+ const message =1664+ error instanceof Error ? error.message : "Failed to update WSL backend mode.";1665+ setDesktopWslError(message);1666+ toastManager.add(1667+ stackedThreadToast({1668+ type: "error",1669+ title: "Could not update WSL backend",1670+ description: message,1671+ }),1672+ );1673+ } finally {1674+ setIsUpdatingDesktopWsl(false);1675+ setDesktopWslChangeStage(null);1676+ }apps/desktop/src/main.ts line 1618OutdatedResolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -1500,0 +1598,21 @@1598+ const wslChild = child;1599+ const stdinStream = child.stdin;1600+ const handleStdinFailure = (error: unknown) => {1601+ // Mark the child so the exit handler (registered below after backendProcess1602+ // is set) treats this as an expected exit and does not re-schedule a restart.1603+ expectedBackendExitChildren.add(wslChild);1604+ wslChild.kill("SIGTERM");1605+ scheduleBackendRestart(1606+ `WSL bootstrap stdin error: ${error instanceof Error ? error.message : String(error)}`,1607+ );1608+ };1609+ stdinStream.once("error", handleStdinFailure);1610+ try {1611+ stdinStream.write(`${bootstrapEnvelope}\n`);1612+ stdinStream.end();1613+ } catch (error) {1614+ // Drop the async listener so the same error doesn't fire handleStdinFailure1615+ // twice if the stream emits asynchronously after the synchronous throw.1616+ stdinStream.removeListener("error", handleStdinFailure);1617+ handleStdinFailure(error);1618+ return false;
- apps/desktop/src/main.ts line 1494OutdatedResolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -1479,16 +1517,6 @@1517+ ? { otlpTracesUrl: backendObservabilitySettings.otlpTracesUrl }1518+ : {}),1519+ ...(backendObservabilitySettings.otlpMetricsUrl1520+ ? { otlpMetricsUrl: backendObservabilitySettings.otlpMetricsUrl }1521+ : {}),14791522 });1480- const bootstrapStream = child.stdio[3];1481- if (bootstrapStream && "write" in bootstrapStream) {1482- bootstrapStream.write(1483- `${JSON.stringify({1484- mode: "desktop",1485- noBrowser: true,1486- port: backendPort,1487- t3Home: BASE_DIR,1488- host: backendBindHost,1489- desktopBootstrapToken: backendBootstrapToken,1490- tailscaleServeEnabled: desktopSettings.tailscaleServeEnabled,1491- tailscaleServePort: desktopSettings.tailscaleServePort,1492- ...(backendObservabilitySettings.otlpTracesUrl1493- ? { otlpTracesUrl: backendObservabilitySettings.otlpTracesUrl }1494- : {}),@@ -1444,4 +1474,4 @@14441474 function scheduleBackendRestart(reason: string): void {14451475 if (isQuitting || restartTimer) return;144614761447- const delayMs = Math.min(500 * 2 ** restartAttempt, 10_000);1477+ const wslActive = loadWslConfig(STATE_DIR).enabled && isWslAvailable();
- @@ -1453,0 +1485,21 @@1485+ startBackend()1486+ .then((started) => {1487+ if (started) return;1488+ // The prologue's isQuitting / backendProcess / backendStartInFlight1489+ // checks each have a path elsewhere that owns the retry (an in-flight1490+ // start's own scheduleBackendRestart calls, or its child's exit1491+ // handler). Log so a future regression that returns false without1492+ // scheduling a follow-up is visible instead of silently stalling.1493+ console.error(1494+ "[desktop] backend restart attempt resolved false; deferring to whichever path owns the retry",1495+ );1496+ })1497+ .catch((error) => {1498+ // startBackend is async; a synchronous throw inside it (bad spawn argv,1499+ // a wslpath/node-pty helper rejection) would otherwise surface as an1500+ // unhandled rejection. Log and let the next lifecycle event drive the1501+ // retry loop instead.1502+ console.error(1503+ `[desktop] backend restart attempt failed: ${error instanceof Error ? error.message : String(error)}`,1504+ );1505+ });
- @@ -0,0 +464,21 @@464+ const chunks: Buffer[] = [];465+ child.stdout?.on("data", (chunk: Buffer) => chunks.push(chunk));466+ const timeout = setTimeout(() => {467+ child.kill();468+ resolve([]);469+ }, 8_000);470+ timeout.unref();471+ child.on("close", (code) => {472+ clearTimeout(timeout);473+ if (code !== 0 || chunks.length === 0) {474+ resolve([]);475+ return;476+ }477+ resolve(parseWslDistroList(Buffer.concat(chunks)));478+ });479+ child.on("error", () => {480+ clearTimeout(timeout);481+ resolve([]);482+ });483+ });484+}@@ -1967,0 +2197,21 @@2197+ if (!started) {2198+ throw new Error(2199+ typed.enabled2200+ ? "Could not start the backend inside WSL."2201+ : "Could not restart the backend on Windows.",2202+ );2203+ }2204+ await waitForBackendWindowReady(backendHttpUrl);2205+ return true;2206+ } catch (error) {2207+ // Stop whatever started under the new config (it may still be alive2208+ // if startBackend succeeded but readiness then timed out), revert2209+ // the on-disk config, and relaunch under the previous configuration.2210+ // Without the explicit stop, runtime and persisted state can diverge2211+ // until the new-mode child exits on its own.2212+ await stopBackendAndWaitForExit().catch(() => {});2213+ saveWslConfig(STATE_DIR, previousConfig);2214+ const restarted = await startBackend().catch(() => false);2215+ if (!restarted) {2216+ scheduleBackendRestart("WSL config rollback");2217+ }
- apps/web/src/components/settings/ConnectionsSettings.tsx line 1572OutdatedResolvedby Jgratton24(GitHub profile, opens in a new tab)@@ -1516,0 +1552,21 @@1552+ );1553+1554+ const normalizeDesktopWslConfig = useCallback(1555+ (config: DesktopWslConfig): DesktopWslConfig => ({1556+ enabled: config.enabled,1557+ distro: config.distro === defaultDesktopWslDistro ? null : config.distro,1558+ }),1559+ [defaultDesktopWslDistro],1560+ );1561+1562+ const leaveCurrentPrimaryThreadRoute = useCallback(async () => {1563+ const primaryEnvironmentId = readPrimaryEnvironmentDescriptor()?.environmentId ?? null;1564+ if (!primaryEnvironmentId) {1565+ return;1566+ }1567+1568+ const routeEnvironmentId = pathname.split("/").filter(Boolean)[0] ?? null;1569+ if (routeEnvironmentId === primaryEnvironmentId) {1570+ await navigate({ to: "/", replace: true });1571+ }1572+ }, [navigate, pathname]);apps/web/src/components/settings/ConnectionsSettings.tsx line 1680OutdatedResolvedby Jgratton24(GitHub profile, opens in a new tab)@@ -1575,0 +1660,21 @@1660+ : "The local backend is running on Windows.",1661+ });1662+ } catch (error) {1663+ const message =1664+ error instanceof Error ? error.message : "Failed to update WSL backend mode.";1665+ setDesktopWslError(message);1666+ toastManager.add(1667+ stackedThreadToast({1668+ type: "error",1669+ title: "Could not update WSL backend",1670+ description: message,1671+ }),1672+ );1673+ // Main rolls back to the previous config on failure, but the rolled-back1674+ // backend is a fresh process with a fresh session-signing key. The1675+ // renderer's existing cookie was signed by the dying backend, so without1676+ // re-bootstrap the WS reconnect loop hits 401 forever. Best-effort: if1677+ // reauth fails (e.g. rolled-back backend never came up) we leave the1678+ // user disconnected but don't mask the original error.1679+ await refreshPrimaryEnvironmentDescriptor().catch(() => undefined);1680+ await reauthenticatePrimaryEnvironment().catch(() => undefined);@@ -1967,0 +2202,21 @@2202+ );2203+ }2204+ await waitForBackendWindowReady(backendHttpUrl);2205+ return true;2206+ } catch (error) {2207+ // Stop whatever started under the new config (it may still be alive2208+ // if startBackend succeeded but readiness then timed out), revert2209+ // the on-disk config, and relaunch under the previous configuration.2210+ // Without the explicit stop, runtime and persisted state can diverge2211+ // until the new-mode child exits on its own.2212+ await stopBackendAndWaitForExit().catch(() => {});2213+ saveWslConfig(STATE_DIR, previousConfig);2214+ const restarted = await startBackend().catch(() => false);2215+ if (!restarted) {2216+ // The rollback is a deliberate restart, not crash recovery; reset2217+ // the backoff counter so the first attempt waits the base 500ms2218+ // instead of inheriting an elevated delay from prior unrelated2219+ // failures.2220+ restartAttempt = 0;2221+ scheduleBackendRestart("WSL config rollback");2222+ }
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:
79caec88-84c6-4b1a-ad62-5a66d02a2bd5You 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