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