fix(desktop): surface Tailscale Serve failures and fix AppImage restarts on Linux #4698
ClosedGenKerensky(GitHub profile, opens in a new tab)wants to merge 24 commits into
main fromrefs/pull/4698/headopened 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:unvouched
- apps/desktop/src/app/DesktopLifecycle.ts line 205OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -161,2 +181,21 @@181+ // the app just disappears and never comes back.182+ yield* Effect.tryPromise({183+ try: () => scheduleAppImageRelaunch(relaunchPlan),184+ catch: (cause) => new DesktopLifecycleRelaunchError({ reason, cause }),185+ });186+ } else {187+ yield* electronApp.relaunch({188+ execPath: relaunchPlan.execPath,189+ args: relaunchPlan.args,190+ });191+ }192+ // Only give up the lock once the relaunch is committed. Neither path has193+ // started the next process yet (app.relaunch defers its spawn to exit,194+ // the AppImage helper sleeps first), so releasing here still beats the195+ // successor's requestSingleInstanceLock() — but if the setup above threw,196+ // the catchCause below leaves us running, and holding the lock is what197+ // keeps the next manual launch focusing this window instead of opening a198+ // second full instance.199+ yield* electronApp.releaseSingleInstanceLock;161200 yield* electronApp.exit(0);162201 }).pipe(apps/desktop/src/app/DesktopLifecycle.ts line 182OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -158,3 +163,20 @@163+ appImagePath: process.env.APPIMAGE,158164 execPath: process.execPath,159- args: process.argv.slice(1),165+ argv: process.argv,166+ });167+ yield* logLifecycleInfo("desktop relaunch exec", {168+ reason,169+ kind: relaunchPlan.kind,170+ execPath:171+ relaunchPlan.kind === "appimage-delayed"172+ ? relaunchPlan.appImagePath173+ : relaunchPlan.execPath,174+ argumentCount: relaunchPlan.args.length,175+ ...(relaunchPlan.kind === "appimage-delayed" ? { delayMs: relaunchPlan.delayMs } : {}),160176 });177+ if (relaunchPlan.kind === "appimage-delayed") {178+ // Delayed shell re-exec avoids racing the AppImage FUSE unmount, which179+ // otherwise surfaces "Cannot mount AppImage, please check your FUSE setup."180+ // Await the spawn: a failure here must not fall through to exit(0), or181+ // the app just disappears and never comes back.182+ yield* Effect.tryPromise({apps/desktop/src/backend/DesktopServerExposure.ts line 636OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -494,0 +616,21 @@616+ }),617+ );618+ // Only roll back a binding this preflight actually created. When Serve619+ // was already enabled on the same port, `tailscale serve --bg` is a620+ // no-op and disabling it on a persistence failure would tear down a621+ // working HTTPS endpoint that settings still record as enabled.622+ preflightedServePort =623+ current.tailscaleServeEnabled && current.tailscaleServePort === servePort624+ ? null625+ : servePort;626+ } else {627+ // Tear Serve down here rather than leaving it to the child server's628+ // acquireRelease finalizer. That finalizer only exists when the *current*629+ // child booted with Serve enabled, so after a failed relaunch (which630+ // `lifecycle.relaunch` logs and swallows) disabling would persist631+ // `enabled: false` while `tailscale serve --https=<port>` stayed live on632+ // the tailnet. Fail loudly instead of reporting a teardown we did not do.633+ const current = yield* Ref.get(stateRef);634+ if (current.tailscaleServeEnabled) {635+ const servePort = current.tailscaleServePort;636+ yield* disableTailscaleServe({ servePort }).pipe(
- apps/desktop/src/app/resolveDesktopRelaunchOptions.ts line 79OutdatedResolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -0,0 +57,21 @@57+ return `'${value.replaceAll("'", `'\\''`)}'`;58+}59+60+/**61+ * Drop file descriptors inherited from the exiting app before re-exec.62+ *63+ * Chromium keeps fds open without CLOEXEC (`app.asar`, `icudtl.dat`, the `.pak`64+ * files, the mount directory itself), and `spawn` cannot close them for us.65+ * Inherited through this helper's `exec`, they keep the *outgoing* AppImage's66+ * FUSE mount busy forever: its runtime process parks in `fuse_dev_do_read` and67+ * never unmounts, so every restart strands a mount and a process.68+ *69+ * The multi-digit `exec N>&-` is inside an `eval` string on purpose. Shells70+ * differ on whether they accept fd numbers above 9, and a parse error in the71+ * script body would mean never reaching the exec at all — an app that quits and72+ * never returns. Deferring the parse to `eval` makes the worst case "fds stay73+ * open", not "the app is gone".74+ */75+const CLOSE_INHERITED_FDS_SNIPPET =76+ 'for fd in /proc/$$/fd/*; do n=${fd##*/}; case "$n" in 0|1|2) continue;; esac; ' +77+ 'eval "exec $n>&-" 2>/dev/null || true; done';
- apps/desktop/src/app/resolveDesktopRelaunchOptions.ts line 116Resolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -0,0 +83,21 @@83+ readonly args: readonly string[];84+ readonly delayMs: number;85+ /** Only safe under bash; see {@link CLOSE_INHERITED_FDS_SNIPPET}. */86+ readonly closeInheritedFds?: boolean;87+ /** Captures the helper's stderr, so a failed delayed `exec` is diagnosable. */88+ readonly logPath?: string | undefined;89+}): string {90+ // Whole seconds only: POSIX specifies `sleep` as taking an integer, and a91+ // /bin/sh whose sleep rejects "1.0" would short-circuit the `&&` and never92+ // exec — an app that quits and never returns, which is the failure this93+ // helper exists to avoid. The spawn succeeds either way, so nothing would94+ // report it.95+ const sleepSeconds = Math.max(1, Math.ceil(input.delayMs / 1_000));96+ const quotedPath = posixShellSingleQuote(input.appImagePath);97+ const quotedArgs = input.args.map(posixShellSingleQuote).join(" ");98+ const execTarget = quotedArgs.length > 0 ? `${quotedPath} ${quotedArgs}` : quotedPath;99+ // The exec happens after we have exited, so its failure (AppImage moved,100+ // execute bit dropped) can only be reported by leaving a trace behind.101+ const relaunch = input.logPath102+ ? `{ sleep ${sleepSeconds} && exec ${execTarget}; } 2>>${posixShellSingleQuote(input.logPath)}`103+ : `sleep ${sleepSeconds} && exec ${execTarget}`;apps/desktop/src/app/resolveDesktopRelaunchOptions.ts line 116Resolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -0,0 +83,21 @@83+ readonly args: readonly string[];84+ readonly delayMs: number;85+ /** Only safe under bash; see {@link CLOSE_INHERITED_FDS_SNIPPET}. */86+ readonly closeInheritedFds?: boolean;87+ /** Captures the helper's stderr, so a failed delayed `exec` is diagnosable. */88+ readonly logPath?: string | undefined;89+}): string {90+ // Whole seconds only: POSIX specifies `sleep` as taking an integer, and a91+ // /bin/sh whose sleep rejects "1.0" would short-circuit the `&&` and never92+ // exec — an app that quits and never returns, which is the failure this93+ // helper exists to avoid. The spawn succeeds either way, so nothing would94+ // report it.95+ const sleepSeconds = Math.max(1, Math.ceil(input.delayMs / 1_000));96+ const quotedPath = posixShellSingleQuote(input.appImagePath);97+ const quotedArgs = input.args.map(posixShellSingleQuote).join(" ");98+ const execTarget = quotedArgs.length > 0 ? `${quotedPath} ${quotedArgs}` : quotedPath;99+ // The exec happens after we have exited, so its failure (AppImage moved,100+ // execute bit dropped) can only be reported by leaving a trace behind.101+ const relaunch = input.logPath102+ ? `{ sleep ${sleepSeconds} && exec ${execTarget}; } 2>>${posixShellSingleQuote(input.logPath)}`103+ : `sleep ${sleepSeconds} && exec ${execTarget}`;
- apps/desktop/src/backend/DesktopServerExposure.ts line 605Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -494,0 +584,21 @@584+ // Preflight Serve configuration before persisting so Enable can fail loudly585+ // with the same CLI guidance (including the admin setup URL) instead of a586+ // silent restart that leaves the toggle unchecked. If settings write fails587+ // after Serve is already active, roll Serve back so we do not leave588+ // unintended network exposure with UI/settings still showing disabled.589+ let preflightedServePort: number | null = null;590+ let revertEnableBinding: { readonly servePort: number; readonly localPort: number } | null =591+ null;592+ if (input.enabled) {593+ const current = yield* Ref.get(stateRef);594+ const servePort = input.port ?? current.tailscaleServePort;595+ const localPort = current.port;596+ if (localPort <= 0) {597+ return yield* new DesktopTailscaleServeConfigureError({598+ enabled: true,599+ port: servePort,600+ localPort,601+ configureUrl: null,602+ });603+ }604+
- apps/desktop/src/backend/DesktopServerExposure.ts line 683Resolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -494,0 +648,21 @@648+ // the tailnet. Fail loudly instead of reporting a teardown we did not do.649+ const current = yield* Ref.get(stateRef);650+ if (current.tailscaleServeEnabled) {651+ const servePort = current.tailscaleServePort;652+ yield* disableTailscaleServe({ servePort }).pipe(653+ Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, childProcessSpawner),654+ Effect.mapError((cause) => {655+ const exitDetail =656+ cause._tag === "TailscaleCommandExitError"657+ ? describeTailscaleServeExitCause(cause)658+ : formatTailscaleServeUserMessage(cause);659+ return new DesktopTailscaleServeConfigureError({660+ enabled: false,661+ port: servePort,662+ localPort: current.port,663+ ...(exitDetail === undefined ? {} : { detail: exitDetail }),664+ configureUrl: null,665+ cause,666+ });667+ }),668+ );
- @@ -494,0 +619,21 @@619+ const exitDetail =620+ cause._tag === "TailscaleCommandExitError"621+ ? describeTailscaleServeExitCause(cause)622+ : formatTailscaleServeUserMessage(cause);623+ const configureUrl =624+ cause._tag === "TailscaleCommandExitError" ? (cause.configureUrl ?? null) : null;625+ return new DesktopTailscaleServeConfigureError({626+ enabled: true,627+ port: servePort,628+ localPort,629+ ...(exitDetail === undefined ? {} : { detail: exitDetail }),630+ configureUrl,631+ cause,632+ });633+ }),634+ );635+ // Only roll back a binding this preflight actually created. When Serve636+ // was already enabled on the same port, `tailscale serve --bg` is a637+ // no-op and disabling it on a persistence failure would tear down a638+ // working HTTPS endpoint that settings still record as enabled.639+ preflightedServePort =
- packages/tailscale/src/tailscale.ts line 150Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -95,3 +109,20 @@95109 ) {96110 override get message(): string {97- return `tailscale ${this.subcommand} exited with code ${this.exitCode}.`;111+ return formatTailscaleCommandExitMessage({112+ subcommand: this.subcommand,113+ exitCode: this.exitCode,114+ stderrDiagnostic: this.stderrDiagnostic,115+ configureUrl: this.configureUrl,116+ });117+ }118+}119+120+/** Admin console URL Tailscale prints when Serve/HTTPS is not enabled for the tailnet. */121+const TAILSCALE_SERVE_CONFIGURE_URL_PATTERN =122+ /https:\/\/login\.tailscale\.com\/f\/serve\?[A-Za-z0-9._~:/?#[\]@!$&'()*+,;=%-]+/i;123+124+/**125+ * Extract a Tailscale Serve enablement URL from CLI text.126+ * Only accepts `https://login.tailscale.com/f/serve...` URLs.127+ */128+export function extractTailscaleServeConfigureUrl(text: string): string | null {
- apps/desktop/src/backend/DesktopServerExposure.ts lines 663 to 667OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -494,0 +647,21 @@647+ // `lifecycle.relaunch` logs and swallows) disabling would persist648+ // `enabled: false` while `tailscale serve --https=<port>` stayed live on649+ // the tailnet. Fail loudly instead of reporting a teardown we did not do.650+ const current = yield* Ref.get(stateRef);651+ let removedBinding = false;652+ if (current.tailscaleServeEnabled) {653+ const servePort = current.tailscaleServePort;654+ removedBinding = yield* disableTailscaleServe({ servePort }).pipe(655+ Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, childProcessSpawner),656+ Effect.as(true),657+ // `serve off` on a port with nothing bound exits non-zero with658+ // "handler does not exist". The tailnet is already in the state the659+ // user asked for, so treating that as a failure would strand the660+ // toggle on and warn about an exposure that does not exist — and it661+ // would bite hardest in the very case this eager teardown exists662+ // for, where settings say enabled but no child ever bound Serve.663+ Effect.catchTag("TailscaleCommandExitError", (cause) =>664+ cause.stderrDiagnostic === "no-existing-handler"665+ ? Effect.succeed(false)666+ : Effect.fail(cause),667+ ),
- apps/web/src/components/settings/ConnectionsSettings.tsx line 3138Resolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -2878,9 +3087,18 @@3087+ className="size-3.5 text-muted-foreground"3088+ />3089+ ) : null}28783090 <Switch2879- checked={tailscaleHttpsEndpoint.status === "available"}3091+ // Reflect the persisted setting, not endpoint reachability. `status`3092+ // comes from an HTTP probe of the MagicDNS URL, so a provisioning3093+ // cert or a momentary tailnet blip would render this off while3094+ // `tailscale serve` is live — and turning it off would be3095+ // unreachable, since that path is behind the on state.3096+ checked={desktopServerExposureState?.tailscaleServeEnabled ?? false}28803097 disabled={isUpdatingTailscaleServe}28813098 onCheckedChange={(checked) => {28823099 if (checked) {2883- handleStartTailscaleServeSetup(tailscaleHttpsEndpoint);3100+ void handleEnableTailscaleHttps();28843101 return;28853102 }2886- handleStartTailscaleServeDisable(tailscaleHttpsEndpoint);3103+ // Disable confirmation does not require a resolved MagicDNS endpoint.3104+ openTailscaleServeDisableDialog();
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/web/src/components/settings/ConnectionsSettings.tsx line 2513Resolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -2297,0 +2489,21 @@2489+ const message = formatDesktopTailscaleServeError(2490+ error,2491+ "Failed to resolve Tailscale HTTPS endpoint.",2492+ );2493+ setTailscaleServeMutationError(message);2494+ toastManager.add(2495+ stackedThreadToast({2496+ type: "error",2497+ title: "Could not set up Tailscale HTTPS",2498+ description: message,2499+ }),2500+ );2501+ } finally {2502+ setIsUpdatingTailscaleServe(false);2503+ }2504+ }, [2505+ desktopBridge,2506+ handleStartTailscaleServeSetup,2507+ refreshDesktopNetworkAccessState,2508+ tailscaleHttpsEndpoint,2509+ ]);
- apps/web/src/components/settings/ConnectionsSettings.tsx line 2537Resolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -2309,5 +2521,13 @@23092521 : visibleDesktopNetworkAdvertisedEndpoints,23102522 [tailscaleHttpsEndpoint, visibleDesktopNetworkAdvertisedEndpoints],23112523 );2524+ // Persisted Serve counts as reachable on its own. Until this branch, Serve2525+ // implied network-accessible mode, so the first operand covered it and the2526+ // probe was only ever a tiebreaker. Now that Serve stands alone without LAN,2527+ // an unfinished cert or a momentary tailnet blip is enough to make `status`2528+ // miss — and "Authorized clients" would vanish while the toggle above it2529+ // correctly reads on. Same reason the switch tracks the setting, not the probe.23122530 const isLocalBackendRemotelyReachable =2313- isLocalBackendNetworkAccessible || tailscaleHttpsEndpoint?.status === "available";2531+ isLocalBackendNetworkAccessible ||2532+ (desktopServerExposureState?.tailscaleServeEnabled ?? false) ||2533+ tailscaleHttpsEndpoint?.status === "available";
GenKerensky(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:
6ca354f7-9c93-4661-a832-6f5a28948133You 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