The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 21, 04:45 UTC
| 1 | import * as Clock from "effect/Clock"; |
| 2 | import * as Context from "effect/Context"; |
| 3 | import * as Duration from "effect/Duration"; |
| 4 | import * as Effect from "effect/Effect"; |
| 5 | import * as Layer from "effect/Layer"; |
| 6 | import * as Option from "effect/Option"; |
| 7 | import * as Ref from "effect/Ref"; |
| 8 | import * as Schema from "effect/Schema"; |
| 9 | import * as Scope from "effect/Scope"; |
| 10 | |
| 11 | import type * as Electron from "electron"; |
| 12 | |
| 13 | import * as HostProcess from "@t3tools/shared/HostProcess"; |
| 14 | |
| 15 | import * as DesktopEnvironment from "./DesktopEnvironment.ts"; |
| 16 | import { stopChildProcessesBeforeExit, stopZygotesBeforeExit } from "./DesktopExitChildren.ts"; |
| 17 | import { makeComponentLogger } from "./DesktopObservability.ts"; |
| 18 | import * as DesktopShutdown from "./DesktopShutdown.ts"; |
| 19 | import * as ElectronApp from "../electron/ElectronApp.ts"; |
| 20 | import * as ElectronProtocol from "../electron/ElectronProtocol.ts"; |
| 21 | import * as ElectronTheme from "../electron/ElectronTheme.ts"; |
| 22 | import * as ElectronWindow from "../electron/ElectronWindow.ts"; |
| 23 | import * as DesktopState from "./DesktopState.ts"; |
| 24 | import * as DesktopWindow from "../window/DesktopWindow.ts"; |
| 25 | |
| 26 | export class DesktopLifecycleRelaunchError extends Schema.TaggedError<DesktopLifecycleRelaunchError>()( |
| 27 | "DesktopLifecycleRelaunchError", |
| 28 | { |
| 29 | reason: Schema.String, |
| 30 | cause: Schema.Defect(), |
| 31 | }, |
| 32 | ) { |
| 33 | override get message(): string { |
| 34 | return `Desktop relaunch failed for reason "${this.reason}".`; |
| 35 | } |
| 36 | } |
| 37 | |
| 38 | export type DesktopLifecycleRuntimeServices = |
| 39 | | DesktopEnvironment.DesktopEnvironment |
| 40 | | DesktopShutdown.DesktopShutdown |
| 41 | | DesktopState.DesktopState |
| 42 | | DesktopWindow.DesktopWindow |
| 43 | | ElectronApp.ElectronApp |
| 44 | | ElectronTheme.ElectronTheme; |
| 45 | |
| 46 | type DesktopLifecycleRegistrationServices = |
| 47 | | DesktopLifecycleRuntimeServices |
| 48 | | ElectronWindow.ElectronWindow; |
| 49 | |
| 50 | /** |
| 51 | * @effect-expect-leaking DesktopEnvironment | DesktopShutdown | DesktopState | DesktopWindow | ElectronApp | ElectronTheme | ElectronWindow |
| 52 | */ |
| 53 | export class DesktopLifecycle extends Context.Service< |
| 54 | DesktopLifecycle, |
| 55 | { |
| 56 | readonly relaunch: ( |
| 57 | reason: string, |
| 58 | ) => Effect.Effect<void, never, DesktopLifecycleRuntimeServices>; |
| 59 | readonly register: Effect.Effect< |
| 60 | void, |
| 61 | never, |
| 62 | Scope.Scope | DesktopLifecycleRegistrationServices |
| 63 | >; |
| 64 | } |
| 65 | >()("@t3tools/desktop/app/DesktopLifecycle") {} |
| 66 | |
| 67 | const { logInfo: logLifecycleInfo, logError: logLifecycleError } = |
| 68 | makeComponentLogger("desktop-lifecycle"); |
| 69 | |
| 70 | function addScopedListener<Args extends ReadonlyArray<unknown>>( |
| 71 | target: unknown, |
| 72 | eventName: string, |
| 73 | listener: (...args: Args) => void, |
| 74 | options: { readonly prepend?: boolean } = {}, |
| 75 | ): Effect.Effect<void, never, Scope.Scope> { |
| 76 | const eventTarget = target as { |
| 77 | on: (eventName: string, listener: (...args: Array<unknown>) => void) => unknown; |
| 78 | prependListener: (eventName: string, listener: (...args: Array<unknown>) => void) => unknown; |
| 79 | removeListener: (eventName: string, listener: (...args: Array<unknown>) => void) => unknown; |
| 80 | }; |
| 81 | const untypedListener = listener as unknown as (...args: Array<unknown>) => void; |
| 82 | return Effect.acquireRelease( |
| 83 | Effect.sync(() => { |
| 84 | if (options.prepend) eventTarget.prependListener(eventName, untypedListener); |
| 85 | else eventTarget.on(eventName, untypedListener); |
| 86 | }), |
| 87 | () => |
| 88 | Effect.sync(() => { |
| 89 | eventTarget.removeListener(eventName, untypedListener); |
| 90 | }), |
| 91 | ).pipe(Effect.asVoid); |
| 92 | } |
| 93 | |
| 94 | const requestDesktopShutdownAndWait = Effect.fn("desktop.lifecycle.requestShutdownAndWait")( |
| 95 | function* ( |
| 96 | afterBoundsFlush: Effect.Effect<void> = Effect.void, |
| 97 | ): Effect.fn.Return<void, never, DesktopShutdown.DesktopShutdown | DesktopWindow.DesktopWindow> { |
| 98 | const shutdown = yield* DesktopShutdown.DesktopShutdown; |
| 99 | const desktopWindow = yield* DesktopWindow.DesktopWindow; |
| 100 | yield* desktopWindow.flushMainWindowBounds; |
| 101 | yield* afterBoundsFlush; |
| 102 | yield* shutdown.request; |
| 103 | yield* shutdown.awaitComplete; |
| 104 | }, |
| 105 | ); |
| 106 | |
| 107 | interface QuitState { |
| 108 | phase: "running" | "waiting" | "allowed"; |
| 109 | waitingSinceNanos: bigint; |
| 110 | } |
| 111 | |
| 112 | // Longer than a backend's stop budget (SIGTERM, 5s grace, SIGKILL, 1s wait), |
| 113 | // so a double Cmd-Q at the start of a normal quit cannot cut the backend stop |
| 114 | // short and orphan it. |
| 115 | const SHUTDOWN_STALL_THRESHOLD = Duration.seconds(10); |
| 116 | |
| 117 | const startWaitingForShutdown = Effect.fn("desktop.lifecycle.startWaitingForShutdown")(function* ( |
| 118 | quit: QuitState, |
| 119 | ) { |
| 120 | quit.phase = "waiting"; |
| 121 | quit.waitingSinceNanos = yield* Clock.monotonicTimeNanos; |
| 122 | }); |
| 123 | |
| 124 | // While a quit waits on shutdown, `quitting` makes activation open nothing. If |
| 125 | // that shutdown stalls, a repeated Quit or SIGTERM is the user's only way out |
| 126 | // short of SIGKILL. |
| 127 | const exitIfShutdownStalled = Effect.fn("desktop.lifecycle.exitIfShutdownStalled")(function* ( |
| 128 | quit: QuitState, |
| 129 | source: string, |
| 130 | ) { |
| 131 | const pendingMs = Number( |
| 132 | ((yield* Clock.monotonicTimeNanos) - quit.waitingSinceNanos) / 1_000_000n, |
| 133 | ); |
| 134 | if (pendingMs < Duration.toMillis(SHUTDOWN_STALL_THRESHOLD)) { |
| 135 | yield* logLifecycleInfo("quit already in progress", { source, pendingMs }); |
| 136 | return; |
| 137 | } |
| 138 | yield* logLifecycleError("desktop shutdown stalled; exiting without it", { source, pendingMs }); |
| 139 | const electronApp = yield* ElectronApp.ElectronApp; |
| 140 | yield* electronApp.exit(0); |
| 141 | }); |
| 142 | |
| 143 | function handleBeforeQuit( |
| 144 | event: Electron.Event, |
| 145 | runEffect: <A, E>( |
| 146 | effect: Effect.Effect<A, E, DesktopLifecycleRegistrationServices>, |
| 147 | ) => Promise<A>, |
| 148 | quit: QuitState, |
| 149 | ): void { |
| 150 | if (quit.phase === "allowed") { |
| 151 | void runEffect( |
| 152 | Effect.gen(function* () { |
| 153 | const state = yield* DesktopState.DesktopState; |
| 154 | yield* Ref.set(state.quitting, true); |
| 155 | yield* logLifecycleInfo("before-quit received"); |
| 156 | }).pipe(Effect.withSpan("desktop.lifecycle.beforeQuit")), |
| 157 | ); |
| 158 | return; |
| 159 | } |
| 160 | |
| 161 | event.preventDefault(); |
| 162 | if (quit.phase === "waiting") { |
| 163 | void runEffect(exitIfShutdownStalled(quit, "before-quit")); |
| 164 | return; |
| 165 | } |
| 166 | void runEffect( |
| 167 | Effect.gen(function* () { |
| 168 | const state = yield* DesktopState.DesktopState; |
| 169 | const electronWindow = yield* ElectronWindow.ElectronWindow; |
| 170 | yield* startWaitingForShutdown(quit); |
| 171 | yield* Ref.set(state.quitting, true); |
| 172 | yield* logLifecycleInfo("before-quit received"); |
| 173 | yield* requestDesktopShutdownAndWait( |
| 174 | electronWindow.destroyAll.pipe( |
| 175 | Effect.catchCause((cause) => |
| 176 | logLifecycleError("failed to destroy windows before shutdown", { cause }), |
| 177 | ), |
| 178 | ), |
| 179 | ); |
| 180 | }).pipe(Effect.withSpan("desktop.lifecycle.beforeQuit")), |
| 181 | ).finally(() => { |
| 182 | quit.phase = "allowed"; |
| 183 | void runEffect( |
| 184 | Effect.gen(function* () { |
| 185 | const electronApp = yield* ElectronApp.ElectronApp; |
| 186 | yield* electronApp.quit; |
| 187 | }).pipe(Effect.withSpan("desktop.lifecycle.quitAfterShutdown")), |
| 188 | ); |
| 189 | }); |
| 190 | } |
| 191 | |
| 192 | function quitFromSignal( |
| 193 | signal: "SIGINT" | "SIGTERM", |
| 194 | runEffect: <A, E>( |
| 195 | effect: Effect.Effect<A, E, DesktopLifecycleRegistrationServices>, |
| 196 | ) => Promise<A>, |
| 197 | quit: QuitState, |
| 198 | ): void { |
| 199 | if (quit.phase === "waiting") { |
| 200 | void runEffect(exitIfShutdownStalled(quit, signal)); |
| 201 | return; |
| 202 | } |
| 203 | void runEffect( |
| 204 | Effect.gen(function* () { |
| 205 | yield* Effect.annotateCurrentSpan({ signal }); |
| 206 | const electronApp = yield* ElectronApp.ElectronApp; |
| 207 | const state = yield* DesktopState.DesktopState; |
| 208 | const wasQuitting = yield* Ref.getAndSet(state.quitting, true); |
| 209 | if (wasQuitting) return; |
| 210 | yield* startWaitingForShutdown(quit); |
| 211 | yield* logLifecycleInfo("process signal received", { signal }); |
| 212 | yield* requestDesktopShutdownAndWait(); |
| 213 | quit.phase = "allowed"; |
| 214 | yield* electronApp.quit; |
| 215 | }).pipe(Effect.withSpan("desktop.lifecycle.processSignal")), |
| 216 | ); |
| 217 | } |
| 218 | |
| 219 | /** @public */ |
| 220 | export const make = DesktopLifecycle.of({ |
| 221 | relaunch: Effect.fn("desktop.lifecycle.relaunch")(function* (reason) { |
| 222 | const electronApp = yield* ElectronApp.ElectronApp; |
| 223 | const environment = yield* DesktopEnvironment.DesktopEnvironment; |
| 224 | const state = yield* DesktopState.DesktopState; |
| 225 | yield* logLifecycleInfo("desktop relaunch requested", { reason }); |
| 226 | yield* Effect.gen(function* () { |
| 227 | yield* Effect.yieldNow; |
| 228 | yield* Ref.set(state.quitting, true); |
| 229 | yield* requestDesktopShutdownAndWait(); |
| 230 | if (environment.isDevelopment) { |
| 231 | yield* electronApp.exit(75); |
| 232 | return; |
| 233 | } |
| 234 | // Startup already acted on the app link that launched it; passing it on replays it. |
| 235 | const appLinkPrefix = `${ElectronProtocol.getDesktopScheme(environment.isDevelopment)}:`; |
| 236 | const args = yield* HostProcess.Arguments; |
| 237 | yield* electronApp.relaunch({ |
| 238 | execPath: yield* HostProcess.ExecutablePath, |
| 239 | args: args.slice(1).filter((arg) => !arg.toLowerCase().startsWith(appLinkPrefix)), |
| 240 | }); |
| 241 | yield* electronApp.exit(0); |
| 242 | }).pipe( |
| 243 | Effect.catchCause((cause) => { |
| 244 | const error = new DesktopLifecycleRelaunchError({ reason, cause }); |
| 245 | return logLifecycleError(error.message, { error }); |
| 246 | }), |
| 247 | Effect.forkDetach, |
| 248 | Effect.asVoid, |
| 249 | ); |
| 250 | }), |
| 251 | register: Effect.gen(function* () { |
| 252 | const desktopWindow = yield* DesktopWindow.DesktopWindow; |
| 253 | const electronWindow = yield* ElectronWindow.ElectronWindow; |
| 254 | const electronApp = yield* ElectronApp.ElectronApp; |
| 255 | const electronTheme = yield* ElectronTheme.ElectronTheme; |
| 256 | const environment = yield* DesktopEnvironment.DesktopEnvironment; |
| 257 | const context = yield* Effect.context<DesktopLifecycleRegistrationServices>(); |
| 258 | const runEffect = Effect.runPromiseWith(context); |
| 259 | const quit: QuitState = { phase: "running", waitingSinceNanos: 0n }; |
| 260 | yield* electronTheme.onUpdated(() => { |
| 261 | void runEffect( |
| 262 | desktopWindow.syncAppearance.pipe(Effect.withSpan("desktop.lifecycle.themeUpdated")), |
| 263 | ); |
| 264 | }); |
| 265 | yield* electronApp.onBeforeQuitForUpdate(() => { |
| 266 | // Electron's updater owns the remaining quit/install/relaunch sequence. |
| 267 | // Cancelling the following app "before-quit" event breaks that sequence, |
| 268 | // most visibly on macOS where the native updater performs the relaunch. |
| 269 | quit.phase = "allowed"; |
| 270 | // This event is synchronous and the updater's quit proceeds as soon as |
| 271 | // the listener returns, so a forked destroyAll would race the quit |
| 272 | // and windows could still be open when the process exits (visible on |
| 273 | // macOS). Destroy them inline. |
| 274 | Effect.runSyncWith(context)( |
| 275 | electronWindow.destroyAll.pipe( |
| 276 | Effect.andThen(logLifecycleInfo("allowing updater-controlled quit")), |
| 277 | Effect.catchCause((cause) => |
| 278 | logLifecycleError("failed to destroy windows before updater quit", { cause }), |
| 279 | ), |
| 280 | Effect.withSpan("desktop.lifecycle.beforeQuitForUpdate"), |
| 281 | ), |
| 282 | ); |
| 283 | }); |
| 284 | yield* electronApp.on("before-quit", (event: Electron.Event) => { |
| 285 | handleBeforeQuit(event, runEffect, quit); |
| 286 | }); |
| 287 | yield* electronApp.on("activate", () => { |
| 288 | void runEffect( |
| 289 | Effect.gen(function* () { |
| 290 | const state = yield* DesktopState.DesktopState; |
| 291 | if (yield* Ref.get(state.quitting)) return; |
| 292 | yield* desktopWindow.activate; |
| 293 | }).pipe(Effect.withSpan("desktop.lifecycle.activate")), |
| 294 | ); |
| 295 | }); |
| 296 | yield* electronApp.on("window-all-closed", () => { |
| 297 | void runEffect( |
| 298 | Effect.gen(function* () { |
| 299 | const app = yield* ElectronApp.ElectronApp; |
| 300 | const state = yield* DesktopState.DesktopState; |
| 301 | if (environment.platform !== "darwin" && !(yield* Ref.get(state.quitting))) { |
| 302 | yield* app.quit; |
| 303 | } |
| 304 | }).pipe(Effect.withSpan("desktop.lifecycle.windowAllClosed")), |
| 305 | ); |
| 306 | }); |
| 307 | |
| 308 | // Electron can exit without before-quit, e.g. when the X11/Wayland connection drops. |
| 309 | // Children (the backend too) get SIGTERM while main still holds an AppImage mount open. |
| 310 | // Prepended so the record is buffered before the trace sink's own exit flush runs. |
| 311 | yield* addScopedListener( |
| 312 | process, |
| 313 | "exit", |
| 314 | (exitCode: number) => { |
| 315 | Effect.runSyncWith(context)( |
| 316 | Effect.gen(function* () { |
| 317 | const shutdown = yield* DesktopShutdown.DesktopShutdown; |
| 318 | // "allowed" without a finished shutdown is the updater's quit; its relaunched app is a child. |
| 319 | if (quit.phase === "allowed" || (yield* shutdown.isComplete)) return; |
| 320 | const attributes = { exitCode, quitPhase: quit.phase }; |
| 321 | yield* Effect.gen(function* () { |
| 322 | yield* logLifecycleError( |
| 323 | "desktop main process exiting before shutdown completed", |
| 324 | attributes, |
| 325 | ); |
| 326 | if (environment.platform !== "linux") return; |
| 327 | const killed = stopChildProcessesBeforeExit(process.pid); |
| 328 | yield* Effect.annotateCurrentSpan({ killedChildPids: killed }); |
| 329 | }).pipe(Effect.withSpan("desktop.lifecycle.exit", { attributes })); |
| 330 | }), |
| 331 | ); |
| 332 | }, |
| 333 | { prepend: true }, |
| 334 | ); |
| 335 | |
| 336 | if (environment.platform !== "win32") { |
| 337 | yield* addScopedListener(process, "SIGINT", () => { |
| 338 | quitFromSignal("SIGINT", runEffect, quit); |
| 339 | }); |
| 340 | yield* addScopedListener(process, "SIGTERM", () => { |
| 341 | quitFromSignal("SIGTERM", runEffect, quit); |
| 342 | }); |
| 343 | } |
| 344 | |
| 345 | // Unscoped: the app scope closes before Electron exits, and every exit path must run this. |
| 346 | if (environment.platform === "linux" && Option.isSome(environment.appImagePath)) { |
| 347 | yield* Effect.sync(() => { |
| 348 | process.once("exit", () => stopZygotesBeforeExit(process.pid)); |
| 349 | }); |
| 350 | } |
| 351 | }).pipe(Effect.withSpan("desktop.lifecycle.register")), |
| 352 | }); |
| 353 | |
| 354 | export const layer = Layer.succeed(DesktopLifecycle, make); |