()
| 222 | * declined — the caller then falls back to managed-spawn. |
| 223 | */ |
| 224 | const ensureSupervisedConnection = async (): Promise<SidecarConnection | null> => { |
| 225 | // 1. Already running → attach. |
| 226 | const attached = await attachToSupervisedDaemon(); |
| 227 | if (attached) { |
| 228 | if (!shouldReplaceDaemonForDesktop(attached)) return attached; |
| 229 | const settings = getServerSettings(); |
| 230 | return replaceSupervisedDaemonForDesktop(attached, { |
| 231 | install: () => |
| 232 | installSupervisedService({ |
| 233 | port: settings.port, |
| 234 | dataDir: DESKTOP_DATA_DIR, |
| 235 | }), |
| 236 | waitForAttach: () => waitForSupervisedAttach(30_000, { port: settings.port }), |
| 237 | attach: attachToSupervisedDaemon, |
| 238 | onInstallFailure: (error) => { |
| 239 | log.warn( |
| 240 | "Failed to replace older supervised daemon; re-checking before falling back", |
| 241 | error, |
| 242 | ); |
| 243 | }, |
| 244 | }); |
| 245 | } |
| 246 | |
| 247 | // Headless/e2e: the first-run background-service prompt and the systemd/ |
| 248 | // launchd install both need a user (and a real session bus) present. With |
| 249 | // this set, fall straight through to managed-spawn after the attach attempt |
| 250 | // so the packaged app can be driven without a window server. Mirrors |
| 251 | // EXECUTOR_TEST_AUTO_CONFIRM_RESET in reset-state.ts. |
| 252 | if (process.env.EXECUTOR_TEST_SKIP_BACKGROUND_SERVICE === "1") return null; |
| 253 | |
| 254 | const status = await supervisedServiceStatus(); |
| 255 | if (!status.supported) return null; |
| 256 | |
| 257 | // 2. Registered but not currently serving → kick it and wait. |
| 258 | if (status.registered) { |
| 259 | // oxlint-disable-next-line executor/no-try-catch-or-throw -- boundary: a restart failure just falls through to managed-spawn |
| 260 | try { |
| 261 | await restartSupervisedService(); |
| 262 | } catch (error) { |
| 263 | log.warn("Failed to kickstart supervised service", error); |
| 264 | } |
| 265 | return waitForSupervisedAttach(15_000); |
| 266 | } |
| 267 | |
| 268 | // 3. First run → ask, then install + start. The unit carries no secret; the |
| 269 | // supervised daemon mints/loads its bearer from auth.json under DESKTOP_DATA_DIR. |
| 270 | if (!(await confirmEnableBackgroundService())) return null; |
| 271 | const settings = getServerSettings(); |
| 272 | // oxlint-disable-next-line executor/no-try-catch-or-throw -- boundary: install failure falls back to managed-spawn so the app still launches |
| 273 | try { |
| 274 | await installSupervisedService({ |
| 275 | port: settings.port, |
| 276 | dataDir: DESKTOP_DATA_DIR, |
| 277 | }); |
| 278 | } catch (error) { |
| 279 | log.error("Failed to install supervised service; using managed sidecar", error); |
| 280 | return null; |
| 281 | } |
no test coverage detected