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 22, 22:00 UTC
revert: fourteen unverified desktop fixes from the takeover campaign (#22222)
Co-authored-by: Julius Marminge <julius@marminge.se>
Julius Marminge committed
Oct 20, 2026 at 01:45 UTC
8fc72daee4fd63615e2c1eb2dcbe070f20ec907b
49 files changed
+416
-2579
apps/desktop/src/app/DesktopApp.ts
+4
-3
@@ -153,8 +153,7 @@ export const stopAllPoolInstances = Effect.fn("desktop.app.stopAllPoolInstances"
153
const instances = yield* pool.list;
154
yield* Effect.forEach(
155
instances,
156
- // Exceeds the backend's 30s graceful termination and output drain budget.
157
- (instance) => instance.stop({ timeout: Duration.seconds(45) }),
156
+ (instance) => instance.stop({ timeout: Duration.seconds(5) }),
157
{ concurrency: "unbounded" },
158
);
159
},
@@ -240,7 +239,9 @@ const bootstrap = Effect.gen(function* () {
239
}
240
241
if (!(yield* Ref.get(state.quitting))) {
243
- yield* desktopWindow.showConnectingSplash;
242
+ if (settings.wslOnly === true && settings.wslBackendEnabled === true) {
243
+ yield* desktopWindow.showConnectingSplash;
244
+ }
245
yield* primaryBackend.start;
246
yield* logBootstrapInfo("bootstrap backend start requested");
247
yield* appActivation.start.pipe(
apps/desktop/src/app/DesktopClerk.test.ts
+2
-68
@@ -1,7 +1,6 @@
1
// @effect-diagnostics nodeBuiltinImport:off globalFetchInEffect:off - Hosted handoff test uses a real localhost listener without an OpenAI account.
2
import * as NodeHttp from "node:http";
3
-import * as NodePath from "node:path";
4
-import * as PlatformNodePath from "@effect/platform-node/NodePath";
3
+import * as NodePath from "@effect/platform-node/NodePath";
4
import { codexAuthHandoffUrl, readCodexAuthDelivery } from "@t3tools/shared/codexAuthHandoff";
5
import { EnvironmentId, ProviderInstanceId } from "@t3tools/contracts";
6
import * as HostProcess from "@t3tools/shared/HostProcess";
@@ -60,15 +59,11 @@ const layerDesktopClerk = (
59
copyText: () => Effect.void,
60
},
61
listeners = new Map<string, (...args: unknown[]) => void>(),
63
- isPackaged = false,
62
) => {
63
const environment = DesktopEnvironment.DesktopEnvironment.of({
64
stateDir: "/tmp/t3-state",
65
isDevelopment,
66
appDataDirectory: "/tmp/app-data",
69
- isPackaged,
70
- dirname: platform === "win32" ? String.raw`C:\T3 Code\dist-electron` : "/tmp/dist-electron",
71
- path: platform === "win32" ? NodePath.win32 : NodePath.posix,
67
platform,
68
} as unknown as DesktopEnvironment.DesktopEnvironment["Service"]);
69
@@ -100,7 +95,7 @@ const layerDesktopClerk = (
95
return DesktopClerk.layer.pipe(
96
Layer.provide(
97
Layer.mergeAll(
103
- PlatformNodePath.layerPosix,
98
+ NodePath.layerPosix,
99
Layer.succeed(DesktopEnvironment.DesktopEnvironment, environment),
100
Layer.succeed(ElectronApp.ElectronApp, electronApp),
101
Layer.succeed(ElectronShell.ElectronShell, shell),
@@ -117,67 +112,6 @@ describe("DesktopClerk", () => {
112
storageMock.mockReset();
113
});
114
120
- it.effect.each([
121
- { platform: "win32", isPackaged: false, isDevelopment: false, registers: true },
122
- { platform: "win32", isPackaged: false, isDevelopment: true, registers: false },
123
- { platform: "win32", isPackaged: true, isDevelopment: false, registers: false },
124
- { platform: "darwin", isPackaged: false, isDevelopment: false, registers: false },
125
- { platform: "linux", isPackaged: false, isDevelopment: false, registers: false },
126
- ] as const)(
127
- "registers an entry point only for unpackaged non-development Windows ($platform, packaged=$isPackaged, development=$isDevelopment)",
128
- ({ platform, isPackaged, isDevelopment, registers }) => {
129
- const events: string[] = [];
130
- storageMock.mockReturnValue(storageAdapter);
131
- createClerkBridgeMock.mockImplementation(() => {
132
- events.push("bridge");
133
- return { cleanup: vi.fn() };
134
- });
135
- const setAsDefaultProtocolClient = vi.fn(() =>
136
- Effect.sync(() => {
137
- events.push("register");
138
- return true;
139
- }),
140
- );
141
- const electronApp = {
142
- on: () => Effect.void,
143
- setAsDefaultProtocolClient,
144
- } as unknown as ElectronApp.ElectronApp["Service"];
145
-
146
- return Effect.gen(function* () {
147
- const clerk = yield* DesktopClerk.DesktopClerk;
148
- yield* clerk.configure;
149
-
150
- assert.deepEqual(
151
- setAsDefaultProtocolClient.mock.calls,
152
- registers
153
- ? [["t3code", process.execPath, [String.raw`C:\T3 Code\dist-electron\main.cjs`]]]
154
- : [],
155
- );
156
- assert.deepEqual(events, registers ? ["bridge", "register"] : ["bridge"]);
157
- }).pipe(
158
- Effect.scoped,
159
- Effect.provide(
160
- layerDesktopClerk(
161
- isDevelopment,
162
- [],
163
- platform,
164
- undefined,
165
- undefined,
166
- undefined,
167
- isPackaged,
168
- ),
169
- ),
170
- Effect.provideService(ElectronApp.ElectronApp, electronApp),
171
- Effect.provideService(
172
- ElectronWindow.ElectronWindow,
173
- {} as ElectronWindow.ElectronWindow["Service"],
174
- ),
175
- Effect.provideService(DesktopWebLinks.DesktopWebLinks, ignoreWebLinks),
176
- Effect.provideService(HostProcess.Arguments, ["electron"]),
177
- );
178
- },
179
- );
180
-
115
it.effect("acquires and releases the SDK bridge with the layer", () => {
116
const cleanup = vi.fn();
117
const events: string[] = [];
apps/desktop/src/app/DesktopClerk.ts
-14
@@ -151,20 +151,6 @@ export const make = Effect.gen(function* () {
151
const context = yield* Effect.context<ElectronWindow.ElectronWindow>();
152
const runPromise = Effect.runPromiseWith(context);
153
154
- // Clerk's bare scheme registration omits the app entry on unpackaged Windows.
155
- // Development callbacks also need dev server environment this command cannot restore.
156
- if (
157
- !environment.isPackaged &&
158
- !environment.isDevelopment &&
159
- environment.platform === "win32"
160
- ) {
161
- yield* electronApp.setAsDefaultProtocolClient(
162
- ElectronProtocol.getDesktopScheme(environment.isDevelopment),
163
- process.execPath,
164
- [environment.path.join(environment.dirname, "main.cjs")],
165
- );
166
- }
167
-
154
const startProviderAuthHandoff = (value: string | undefined) => {
155
if (!value) return false;
156
const request = readCodexAuthHandoff(value, environment.isDevelopment);
apps/desktop/src/app/DesktopLifecycle.test.ts
+9
-110
@@ -1,13 +1,6 @@
1
-// @effect-diagnostics-next-line nodeBuiltinImport:off - A real Node process verifies OS signal ownership outside Effect's process runtime.
2
-import * as NodeChildProcess from "node:child_process";
3
-import * as NodeReadline from "node:readline";
4
-import * as NodeURL from "node:url";
5
-
1
import { assert, describe, it } from "@effect/vitest";
7
-import * as HostProcess from "@t3tools/shared/HostProcess";
2
import * as Deferred from "effect/Deferred";
3
import * as Effect from "effect/Effect";
10
-import * as Fiber from "effect/Fiber";
4
import * as Layer from "effect/Layer";
5
import * as Ref from "effect/Ref";
6
@@ -110,67 +103,6 @@ function layerDesktopWindow(
103
}
104
105
describe("DesktopLifecycle", () => {
113
- it.skipIf(HostProcess.Platform.defaultValue() === "win32")(
114
- "leaves SIGTERM to the lifecycle until its graceful shutdown completes",
115
- async ({ onTestFinished }) => {
116
- const runner = new URL("./DesktopRuntime.ts", import.meta.url).href;
117
- const child = NodeChildProcess.spawn(
118
- process.execPath,
119
- [
120
- "--experimental-strip-types",
121
- "--input-type=module",
122
- "-e",
123
- `
124
- import * as Effect from 'effect/Effect';
125
- import * as Deferred from 'effect/Deferred';
126
- import { runMain } from ${JSON.stringify(runner)};
127
- process.stdin.resume();
128
- let released = false;
129
- runMain(Effect.scoped(Effect.gen(function* () {
130
- const done = yield* Deferred.make();
131
- yield* Effect.addFinalizer(() => Effect.sync(() => console.log(released ? 'CLEANED' : 'PREMATURE')));
132
- process.once('SIGTERM', () => {
133
- console.log('STOPPING');
134
- process.stdin.once('data', () => {
135
- released = true;
136
- void Effect.runPromise(Deferred.succeed(done, undefined)).then(() => process.stdin.destroy());
137
- });
138
- });
139
- console.log('READY');
140
- yield* Deferred.await(done);
141
- })));
142
- `,
143
- ],
144
- {
145
- cwd: NodeURL.fileURLToPath(new URL("../../", import.meta.url)),
146
- stdio: ["pipe", "pipe", "pipe"],
147
- },
148
- );
149
- const exited = new Promise<readonly [number | null, string | null]>((resolve, reject) => {
150
- child.once("exit", (code, signal) => resolve([code, signal]));
151
- child.once("error", reject);
152
- });
153
- const lines: string[] = [];
154
- let stderr = "";
155
- child.stderr.on("data", (chunk) => {
156
- stderr += chunk;
157
- });
158
- onTestFinished(async () => {
159
- if (child.exitCode === null && child.signalCode === null) {
160
- child.kill("SIGKILL");
161
- await exited;
162
- }
163
- });
164
- for await (const line of NodeReadline.createInterface({ input: child.stdout })) {
165
- lines.push(line);
166
- if (line === "READY") child.kill("SIGTERM");
167
- if (line === "STOPPING") child.stdin.write("finish");
168
- }
169
- assert.deepEqual(await exited, [0, null], stderr);
170
- assert.deepEqual(lines, ["READY", "STOPPING", "CLEANED"]);
171
- },
172
- );
173
-
106
it.effect.each(["darwin", "win32", "linux"] satisfies ReadonlyArray<NodeJS.Platform>)(
107
"lets the updater's quit event proceed on %s",
108
(platform) => {
@@ -226,18 +158,12 @@ describe("DesktopLifecycle", () => {
158
},
159
);
160
229
- it.effect("destroys windows and retains signal ownership until backend shutdown completes", () =>
161
+ it.effect("destroys windows before waiting for backend shutdown", () =>
162
Effect.gen(function* () {
163
const appListeners = new Map<string, (...args: readonly unknown[]) => void>();
164
const shutdownRequested = yield* Deferred.make<void>();
165
const allowShutdown = yield* Deferred.make<void>();
166
const quitRequested = yield* Deferred.make<void>();
235
- const backendStopping = yield* Deferred.make<void>();
236
- const finishBackendShutdown = yield* Deferred.make<void>();
237
- const originalSignals = {
238
- SIGINT: process.listeners("SIGINT"),
239
- SIGTERM: process.listeners("SIGTERM"),
240
- };
167
const events: string[] = [];
168
169
const quit = Effect.sync(() => {
@@ -278,47 +204,20 @@ describe("DesktopLifecycle", () => {
204
yield* Effect.scoped(
205
Effect.gen(function* () {
206
const lifecycle = yield* DesktopLifecycle.DesktopLifecycle;
281
- const shutdown = yield* DesktopShutdown.DesktopShutdown;
282
- const program = yield* Effect.scoped(
283
- Effect.gen(function* () {
284
- yield* Effect.addFinalizer(() =>
285
- Deferred.succeed(backendStopping, undefined).pipe(
286
- Effect.andThen(Deferred.await(finishBackendShutdown)),
287
- Effect.andThen(shutdown.markComplete),
288
- ),
289
- );
290
- yield* lifecycle.register;
291
- const event = { preventDefault: () => undefined } as Electron.Event;
292
- appListeners.get("before-quit")?.(event);
293
- yield* shutdown.awaitRequest;
294
- }),
295
- ).pipe(Effect.forkScoped);
296
-
297
- yield* Deferred.await(backendStopping);
298
- yield* Effect.addFinalizer(() =>
299
- Deferred.succeed(finishBackendShutdown, undefined).pipe(Effect.asVoid),
300
- );
207
+ yield* lifecycle.register;
208
302
- for (const signal of ["SIGINT", "SIGTERM"] as const) {
303
- const listeners = process
304
- .listeners(signal)
305
- .filter((listener) => !originalSignals[signal].includes(listener));
306
- assert.lengthOf(listeners, 1, `${signal} must remain owned during backend cleanup`);
307
- listeners[0]?.(signal);
308
- }
309
- assert.deepEqual(events, ["flush", "destroy", "request"]);
310
- assert.equal(appListeners.size, 0, "Electron listeners still follow the program scope");
311
- assert.isFalse(yield* shutdown.isComplete);
209
+ const event = { preventDefault: () => undefined } as Electron.Event;
210
+ appListeners.get("before-quit")?.(event);
211
313
- yield* Deferred.succeed(finishBackendShutdown, undefined);
314
- yield* Fiber.join(program);
212
+ yield* Deferred.await(shutdownRequested);
213
+ const eventsBeforeCleanup = [...events];
214
+ yield* Deferred.succeed(allowShutdown, undefined);
215
yield* Deferred.await(quitRequested);
216
+
217
+ assert.deepEqual(eventsBeforeCleanup, ["flush", "destroy", "request"]);
218
assert.deepEqual(events, ["flush", "destroy", "request", "quit"]);
219
}),
220
).pipe(Effect.provide(layer));
319
-
320
- assert.deepEqual(process.listeners("SIGINT"), originalSignals.SIGINT);
321
- assert.deepEqual(process.listeners("SIGTERM"), originalSignals.SIGTERM);
221
}),
222
);
223
apps/desktop/src/app/DesktopLifecycle.ts
+99
-104
@@ -160,113 +160,108 @@ function quitFromSignal(
160
}
161
162
/** @public Service construction is part of the canonical Effect module API. */
163
-export const make = Effect.gen(function* () {
164
- const signalScope = yield* Scope.Scope;
165
- return DesktopLifecycle.of({
166
- relaunch: Effect.fn("desktop.lifecycle.relaunch")(function* (reason) {
167
- const electronApp = yield* ElectronApp.ElectronApp;
168
- const environment = yield* DesktopEnvironment.DesktopEnvironment;
169
- const state = yield* DesktopState.DesktopState;
170
- yield* logLifecycleInfo("desktop relaunch requested", { reason });
171
- yield* Effect.gen(function* () {
172
- yield* Effect.yieldNow;
173
- yield* Ref.set(state.quitting, true);
174
- yield* requestDesktopShutdownAndWait();
175
- if (environment.isDevelopment) {
176
- yield* electronApp.exit(75);
177
- return;
178
- }
179
- yield* electronApp.relaunch({
180
- execPath: process.execPath,
181
- args: process.argv.slice(1),
182
- });
183
- yield* electronApp.exit(0);
184
- }).pipe(
185
- Effect.catchCause((cause) => {
186
- const error = new DesktopLifecycleRelaunchError({ reason, cause });
187
- return logLifecycleError(error.message, { error });
188
- }),
189
- Effect.forkDetach,
190
- Effect.asVoid,
191
- );
192
- }),
193
- register: Effect.gen(function* () {
194
- const desktopWindow = yield* DesktopWindow.DesktopWindow;
195
- const electronWindow = yield* ElectronWindow.ElectronWindow;
196
- const electronApp = yield* ElectronApp.ElectronApp;
197
- const electronTheme = yield* ElectronTheme.ElectronTheme;
198
- const environment = yield* DesktopEnvironment.DesktopEnvironment;
199
- const context = yield* Effect.context<DesktopLifecycleRegistrationServices>();
200
- const runEffect = Effect.runPromiseWith(context);
201
- let quitAllowed = false;
202
- let updaterQuitAllowed = false;
203
- yield* electronTheme.onUpdated(() => {
204
- void runEffect(
205
- desktopWindow.syncAppearance.pipe(Effect.withSpan("desktop.lifecycle.themeUpdated")),
206
- );
163
+export const make = DesktopLifecycle.of({
164
+ relaunch: Effect.fn("desktop.lifecycle.relaunch")(function* (reason) {
165
+ const electronApp = yield* ElectronApp.ElectronApp;
166
+ const environment = yield* DesktopEnvironment.DesktopEnvironment;
167
+ const state = yield* DesktopState.DesktopState;
168
+ yield* logLifecycleInfo("desktop relaunch requested", { reason });
169
+ yield* Effect.gen(function* () {
170
+ yield* Effect.yieldNow;
171
+ yield* Ref.set(state.quitting, true);
172
+ yield* requestDesktopShutdownAndWait();
173
+ if (environment.isDevelopment) {
174
+ yield* electronApp.exit(75);
175
+ return;
176
+ }
177
+ yield* electronApp.relaunch({
178
+ execPath: process.execPath,
179
+ args: process.argv.slice(1),
180
});
208
- yield* electronApp.onBeforeQuitForUpdate(() => {
209
- // Electron's updater owns the remaining quit/install/relaunch sequence.
210
- // Cancelling the following app "before-quit" event breaks that sequence,
211
- // most visibly on macOS where the native updater performs the relaunch.
212
- updaterQuitAllowed = true;
213
- // This event is synchronous and the updater's quit proceeds as soon as
214
- // the listener returns, so a forked destroyAll would race the quit
215
- // and windows could still be open when the process exits (visible on
216
- // macOS). Destroy them inline.
217
- Effect.runSyncWith(context)(
218
- electronWindow.destroyAll.pipe(
219
- Effect.andThen(logLifecycleInfo("allowing updater-controlled quit")),
220
- Effect.catchCause((cause) =>
221
- logLifecycleError("failed to destroy windows before updater quit", { cause }),
222
- ),
223
- Effect.withSpan("desktop.lifecycle.beforeQuitForUpdate"),
181
+ yield* electronApp.exit(0);
182
+ }).pipe(
183
+ Effect.catchCause((cause) => {
184
+ const error = new DesktopLifecycleRelaunchError({ reason, cause });
185
+ return logLifecycleError(error.message, { error });
186
+ }),
187
+ Effect.forkDetach,
188
+ Effect.asVoid,
189
+ );
190
+ }),
191
+ register: Effect.gen(function* () {
192
+ const desktopWindow = yield* DesktopWindow.DesktopWindow;
193
+ const electronWindow = yield* ElectronWindow.ElectronWindow;
194
+ const electronApp = yield* ElectronApp.ElectronApp;
195
+ const electronTheme = yield* ElectronTheme.ElectronTheme;
196
+ const environment = yield* DesktopEnvironment.DesktopEnvironment;
197
+ const context = yield* Effect.context<DesktopLifecycleRegistrationServices>();
198
+ const runEffect = Effect.runPromiseWith(context);
199
+ let quitAllowed = false;
200
+ let updaterQuitAllowed = false;
201
+ yield* electronTheme.onUpdated(() => {
202
+ void runEffect(
203
+ desktopWindow.syncAppearance.pipe(Effect.withSpan("desktop.lifecycle.themeUpdated")),
204
+ );
205
+ });
206
+ yield* electronApp.onBeforeQuitForUpdate(() => {
207
+ // Electron's updater owns the remaining quit/install/relaunch sequence.
208
+ // Cancelling the following app "before-quit" event breaks that sequence,
209
+ // most visibly on macOS where the native updater performs the relaunch.
210
+ updaterQuitAllowed = true;
211
+ // This event is synchronous and the updater's quit proceeds as soon as
212
+ // the listener returns, so a forked destroyAll would race the quit
213
+ // and windows could still be open when the process exits (visible on
214
+ // macOS). Destroy them inline.
215
+ Effect.runSyncWith(context)(
216
+ electronWindow.destroyAll.pipe(
217
+ Effect.andThen(logLifecycleInfo("allowing updater-controlled quit")),
218
+ Effect.catchCause((cause) =>
219
+ logLifecycleError("failed to destroy windows before updater quit", { cause }),
220
),
225
- );
226
- });
227
- yield* electronApp.on("before-quit", (event: Electron.Event) => {
228
- handleBeforeQuit(
229
- event,
230
- runEffect,
231
- () => quitAllowed || updaterQuitAllowed,
232
- () => {
233
- quitAllowed = true;
234
- },
235
- );
236
- });
237
- yield* electronApp.on("activate", () => {
238
- void runEffect(
239
- Effect.gen(function* () {
240
- const state = yield* DesktopState.DesktopState;
241
- if (yield* Ref.get(state.quitting)) return;
242
- yield* desktopWindow.activate;
243
- }).pipe(Effect.withSpan("desktop.lifecycle.activate")),
244
- );
221
+ Effect.withSpan("desktop.lifecycle.beforeQuitForUpdate"),
222
+ ),
223
+ );
224
+ });
225
+ yield* electronApp.on("before-quit", (event: Electron.Event) => {
226
+ handleBeforeQuit(
227
+ event,
228
+ runEffect,
229
+ () => quitAllowed || updaterQuitAllowed,
230
+ () => {
231
+ quitAllowed = true;
232
+ },
233
+ );
234
+ });
235
+ yield* electronApp.on("activate", () => {
236
+ void runEffect(
237
+ Effect.gen(function* () {
238
+ const state = yield* DesktopState.DesktopState;
239
+ if (yield* Ref.get(state.quitting)) return;
240
+ yield* desktopWindow.activate;
241
+ }).pipe(Effect.withSpan("desktop.lifecycle.activate")),
242
+ );
243
+ });
244
+ yield* electronApp.on("window-all-closed", () => {
245
+ void runEffect(
246
+ Effect.gen(function* () {
247
+ const app = yield* ElectronApp.ElectronApp;
248
+ const state = yield* DesktopState.DesktopState;
249
+ if (environment.platform !== "darwin" && !(yield* Ref.get(state.quitting))) {
250
+ yield* app.quit;
251
+ }
252
+ }).pipe(Effect.withSpan("desktop.lifecycle.windowAllClosed")),
253
+ );
254
+ });
255
+
256
+ if (environment.platform !== "win32") {
257
+ yield* addScopedListener(process, "SIGINT", () => {
258
+ quitFromSignal("SIGINT", runEffect);
259
});
246
- yield* electronApp.on("window-all-closed", () => {
247
- void runEffect(
248
- Effect.gen(function* () {
249
- const app = yield* ElectronApp.ElectronApp;
250
- const state = yield* DesktopState.DesktopState;
251
- if (environment.platform !== "darwin" && !(yield* Ref.get(state.quitting))) {
252
- yield* app.quit;
253
- }
254
- }).pipe(Effect.withSpan("desktop.lifecycle.windowAllClosed")),
255
- );
260
+ yield* addScopedListener(process, "SIGTERM", () => {
261
+ quitFromSignal("SIGTERM", runEffect);
262
});
257
-
258
- if (environment.platform !== "win32") {
259
- // The layer outlives program finalizers, so repeated signals stay owned
260
- // while backends stop. Electron listeners still follow the program scope.
261
- yield* addScopedListener(process, "SIGINT", () => {
262
- quitFromSignal("SIGINT", runEffect);
263
- }).pipe(Scope.provide(signalScope));
264
- yield* addScopedListener(process, "SIGTERM", () => {
265
- quitFromSignal("SIGTERM", runEffect);
266
- }).pipe(Scope.provide(signalScope));
267
- }
268
- }).pipe(Effect.withSpan("desktop.lifecycle.register")),
269
- });
263
+ }
264
+ }).pipe(Effect.withSpan("desktop.lifecycle.register")),
265
});
266
272
-export const layer = Layer.effect(DesktopLifecycle, make);
267
+export const layer = Layer.succeed(DesktopLifecycle, make);
apps/desktop/src/app/DesktopLinuxUrlHandler.test.ts
+27
-91
@@ -22,31 +22,8 @@ interface RecordedRegistration {
22
readonly files: Array<{ readonly path: string; readonly content: string }>;
23
readonly commands: Array<{ readonly command: string; readonly args: ReadonlyArray<string> }>;
24
readonly copies: Array<{ readonly source: string; readonly destination: string }>;
25
- readonly binaryReads: string[];
26
- readonly binaryWrites: Array<{
27
- readonly path: string;
28
- readonly bytes: Uint8Array;
29
- readonly mode: number | undefined;
30
- }>;
25
}
26
33
-const iconSource = "/tmp/.mount_T3/resources/app.asar/apps/desktop/prod-resources/icon.png";
34
-const iconPath = "/home/alice/.local/share/icons/com.t3tools.T3Code.desktop.png";
35
-const iconBytes = new Uint8Array([0x89, 0x50, 0x00, 0xff, 0x80, 0x0a]);
36
-const currentDesktopEntry = DesktopLinuxUrlHandler.renderUrlHandlerDesktopEntry({
37
- displayName: "T3 Code (Alpha)",
38
- execTarget: "/home/alice/Applications/T3-Code.AppImage",
39
- scheme: "t3code",
40
- iconPath,
41
-});
42
-const registrationCommands = [
43
- { command: "update-desktop-database", args: ["/home/alice/.local/share/applications"] },
44
- {
45
- command: "xdg-mime",
46
- args: ["default", "com.t3tools.T3Code.desktop", "x-scheme-handler/t3code"],
47
- },
48
-];
49
-
27
const makeEnvironment = (path: Path.Path, overrides: Record<string, unknown> = {}) =>
28
DesktopEnvironment.DesktopEnvironment.of({
29
platform: "linux",
@@ -87,8 +64,7 @@ const layerHandler = (
64
readonly writeError?: PlatformError.PlatformError;
65
readonly existingEntry?: string;
66
readonly iconSource?: string;
90
- readonly existingIcon?: Uint8Array;
91
- readonly iconReadError?: PlatformError.PlatformError;
67
+ readonly iconCopyError?: PlatformError.PlatformError;
68
} = {},
69
) =>
70
DesktopLinuxUrlHandler.layer.pipe(
@@ -111,34 +87,11 @@ const layerHandler = (
87
}),
88
FileSystem.layerNoop({
89
copyFile: (source, destination) =>
114
- Effect.sync(() => {
115
- recorded.copies.push({ source, destination });
116
- }),
117
- readFile: (path) =>
118
- Effect.gen(function* () {
119
- recorded.binaryReads.push(path);
120
- if (path === input.iconSource) {
121
- if (input.iconReadError) return yield* input.iconReadError;
122
- return new Uint8Array(iconBytes);
123
- }
124
- if (path === iconPath && input.existingIcon !== undefined) {
125
- return input.existingIcon;
126
- }
127
- return yield* PlatformError.systemError({
128
- _tag: "NotFound",
129
- module: "FileSystem",
130
- method: "readFile",
131
- pathOrDescriptor: path,
132
- });
133
- }),
134
- writeFile: (path, bytes, options) =>
135
- Effect.sync(() => {
136
- recorded.binaryWrites.push({
137
- path,
138
- bytes: new Uint8Array(bytes),
139
- mode: options?.mode,
140
- });
141
- }),
90
+ input.iconCopyError
91
+ ? Effect.fail(input.iconCopyError)
92
+ : Effect.sync(() => {
93
+ recorded.copies.push({ source, destination });
94
+ }),
95
readFileString: () => Effect.succeed(input.existingEntry ?? ""),
96
makeDirectory: (path) =>
97
Effect.sync(() => {
@@ -203,8 +156,6 @@ const emptyRecording = (): RecordedRegistration => ({
156
files: [],
157
commands: [],
158
copies: [],
206
- binaryReads: [],
207
- binaryWrites: [],
159
});
160
161
describe("DesktopLinuxUrlHandler", () => {
@@ -355,57 +306,42 @@ describe("DesktopLinuxUrlHandler", () => {
306
307
it.effect("installs a persistent icon even when the desktop entry is already current", () => {
308
const recorded = emptyRecording();
309
+ const iconPath = "/home/alice/.local/share/icons/com.t3tools.T3Code.desktop.png";
310
return Effect.gen(function* () {
311
yield* runRegister(recorded, {
360
- iconSource,
361
- existingEntry: currentDesktopEntry,
362
- });
363
- assert.deepEqual(recorded.files, []);
364
- assert.deepEqual(recorded.copies, []);
365
- assert.deepEqual(recorded.binaryReads, [iconSource, iconPath]);
366
- assert.deepEqual(recorded.binaryWrites, [{ path: iconPath, bytes: iconBytes, mode: 0o600 }]);
367
- assert.deepEqual(recorded.commands, registrationCommands);
368
- });
369
- });
370
-
371
- it.effect("refreshes a stale icon and skips equal bytes on the next registration", () => {
372
- const recorded = emptyRecording();
373
- return Effect.gen(function* () {
374
- yield* runRegister(recorded, {
375
- iconSource,
376
- existingEntry: currentDesktopEntry,
377
- existingIcon: new Uint8Array([0x89, 0x50, 0x00, 0xfe, 0x80, 0x0a]),
378
- });
379
- assert.deepEqual(recorded.binaryWrites, [{ path: iconPath, bytes: iconBytes, mode: 0o600 }]);
380
- yield* runRegister(recorded, {
381
- iconSource,
382
- existingEntry: currentDesktopEntry,
383
- existingIcon: new Uint8Array(recorded.binaryWrites[0]!.bytes),
312
+ iconSource: "/tmp/.mount_T3/resources/icon.png",
313
+ existingEntry: DesktopLinuxUrlHandler.renderUrlHandlerDesktopEntry({
314
+ displayName: "T3 Code (Alpha)",
315
+ execTarget: "/home/alice/Applications/T3-Code.AppImage",
316
+ scheme: "t3code",
317
+ iconPath,
318
+ }),
319
});
385
- assert.equal(recorded.binaryWrites.length, 1);
386
- assert.deepEqual(recorded.copies, []);
320
assert.deepEqual(recorded.files, []);
388
- assert.deepEqual(recorded.commands, [...registrationCommands, ...registrationCommands]);
321
+ assert.deepEqual(recorded.copies, [
322
+ { source: "/tmp/.mount_T3/resources/icon.png", destination: iconPath },
323
+ ]);
324
+ assert.equal(recorded.commands.at(-1)?.command, "xdg-mime");
325
});
326
});
327
392
- it.effect("still registers the handler when reading its icon fails", () => {
328
+ it.effect("still registers the handler when copying its icon fails", () => {
329
const recorded = emptyRecording();
330
return Effect.gen(function* () {
331
yield* runRegister(recorded, {
396
- iconSource,
397
- iconReadError: PlatformError.systemError({
332
+ iconSource: "/tmp/.mount_T3/resources/icon.png",
333
+ iconCopyError: PlatformError.systemError({
334
_tag: "PermissionDenied",
335
module: "FileSystem",
400
- method: "readFile",
401
- description: "unreadable bundled icon",
336
+ method: "copyFile",
337
+ description: "read-only icon directory",
338
}),
339
});
404
- assert.deepEqual(recorded.binaryReads, [iconSource]);
405
- assert.deepEqual(recorded.binaryWrites, []);
406
- assert.deepEqual(recorded.copies, []);
340
assert.equal(recorded.files.length, 1);
408
- assert.deepEqual(recorded.commands, registrationCommands);
341
+ assert.deepEqual(
342
+ recorded.commands.map(({ command }) => command),
343
+ ["update-desktop-database", "xdg-mime"],
344
+ );
345
});
346
});
347
apps/desktop/src/app/DesktopLinuxUrlHandler.ts
+2
-6
@@ -301,16 +301,12 @@ export const make = Effect.gen(function* () {
301
yield* Effect.gen(function* () {
302
const { png } = yield* assets.iconPaths;
303
if (Option.isNone(png)) return;
304
- // Electron's copyFile extracts ASAR entries to temporary files it never removes.
305
- const icon = yield* fileSystem.readFile(png.value);
306
- const current = yield* fileSystem.readFile(iconPath).pipe(Effect.option);
307
- if (Option.isSome(current) && sameBytes(current.value, icon)) return;
304
// The AppImage mount is temporary; the chooser needs the icon after exit.
305
yield* fileSystem.makeDirectory(iconsDir, { recursive: true });
310
- yield* fileSystem.writeFile(iconPath, icon, { mode: 0o600 });
306
+ yield* fileSystem.copyFile(png.value, iconPath);
307
}).pipe(
308
Effect.catch((error) =>
313
- logWarning("URL handler icon install failed", { iconPath, category: error.reason._tag }),
309
+ logWarning("URL handler icon copy failed", { iconPath, category: error.reason._tag }),
310
),
311
);
312
apps/desktop/src/app/DesktopPreReadyPlatform.test.ts
+14
-76
@@ -12,10 +12,10 @@ const {
12
registerSchemesMock,
13
setDesktopNameMock,
14
mkdirSyncMock,
15
- readFileSyncMock,
15
writeFileSyncMock,
16
copyFileSyncMock,
17
execFileSyncMock,
18
+ readFileSyncMock,
19
} = vi.hoisted(() => ({
20
appendSwitchMock: vi.fn(),
21
getSwitchValueMock: vi.fn(),
@@ -23,10 +23,10 @@ const {
23
registerSchemesMock: vi.fn(),
24
setDesktopNameMock: vi.fn(),
25
mkdirSyncMock: vi.fn(),
26
- readFileSyncMock: vi.fn(),
26
writeFileSyncMock: vi.fn(),
27
copyFileSyncMock: vi.fn(),
28
execFileSyncMock: vi.fn(),
29
+ readFileSyncMock: vi.fn(),
30
}));
31
32
vi.mock("electron", () => ({
@@ -59,11 +59,6 @@ vi.mock("node:child_process", () => ({
59
60
import * as DesktopPreReadyPlatform from "./DesktopPreReadyPlatform.ts";
61
62
-const iconSource = "/tmp/.mount_T3/resources/app.asar/apps/desktop/prod-resources/icon.png";
63
-const iconPath = "/xdg/icons/com.t3tools.T3Code.desktop.png";
64
-const desktopEntryPath = "/xdg/applications/com.t3tools.T3Code.desktop";
65
-const iconBytes = Buffer.from([0x89, 0x50, 0x00, 0xff, 0x80, 0x0a]);
66
-
62
describe("DesktopPreReadyPlatform", () => {
63
beforeEach(() => {
64
appendSwitchMock.mockReset();
@@ -72,15 +67,10 @@ describe("DesktopPreReadyPlatform", () => {
67
registerSchemesMock.mockReset();
68
setDesktopNameMock.mockReset();
69
mkdirSyncMock.mockReset();
75
- readFileSyncMock.mockReset();
70
writeFileSyncMock.mockReset();
71
copyFileSyncMock.mockReset();
72
execFileSyncMock.mockReset();
79
- readFileSyncMock.mockReset().mockImplementation((path: string) => {
80
- if (path.endsWith("/desktop-settings.json")) return "{}";
81
- if (path === iconSource) return Buffer.from(iconBytes);
82
- throw new Error(`missing file: ${path}`);
83
- });
73
+ readFileSyncMock.mockReset().mockReturnValue("{}");
74
});
75
76
it.effect("persists Linux scaling synchronously across relaunches and settings rewrites", () => {
@@ -222,13 +212,14 @@ describe("DesktopPreReadyPlatform", () => {
212
let desktopName = "t3code.desktop";
213
let desktopEntry = previousEntry;
214
let iconInstalled = false;
215
+ copyFileSyncMock.mockImplementation((_source: string, destination: string) => {
216
+ iconInstalled = destination === "/xdg/icons/com.t3tools.T3Code.desktop.png";
217
+ });
218
setDesktopNameMock.mockImplementation((name: string) => {
219
desktopName = name;
220
});
228
- writeFileSyncMock.mockImplementation((path: string, contents: string | Buffer) => {
229
- if (path === iconPath)
230
- iconInstalled = Buffer.isBuffer(contents) && contents.equals(iconBytes);
231
- if (path === desktopEntryPath && typeof contents === "string") desktopEntry = contents;
221
+ writeFileSyncMock.mockImplementation((path: string, contents: string) => {
222
+ if (path === "/xdg/applications/com.t3tools.T3Code.desktop") desktopEntry = contents;
223
});
224
225
return Effect.scoped(
@@ -253,15 +244,6 @@ describe("DesktopPreReadyPlatform", () => {
244
"Icon=/xdg/icons/com.t3tools.T3Code.desktop.png",
245
);
246
assert.isTrue(identity.iconInstalled);
256
- assert.deepEqual(
257
- readFileSyncMock.mock.calls.filter(([path]) => path === iconSource),
258
- [[iconSource]],
259
- );
260
- assert.deepEqual(
261
- writeFileSyncMock.mock.calls.filter(([path]) => path === iconPath),
262
- [[iconPath, iconBytes, { mode: 0o600 }]],
263
- );
264
- assert.equal(copyFileSyncMock.mock.calls.length, 0);
247
}),
248
).pipe(Effect.ensuring(Effect.sync(() => vi.unstubAllEnvs())));
249
});
@@ -278,62 +260,18 @@ describe("DesktopPreReadyPlatform", () => {
260
);
261
});
262
281
- it.effect("refreshes a stale icon once across repeated launches", () => {
282
- vi.stubEnv("VITE_DEV_SERVER_URL", "");
283
- vi.stubEnv("XDG_DATA_HOME", "/xdg");
263
+ it.effect("still prepares the portal entry when the bundled icon cannot be copied", () => {
264
getSwitchValueMock.mockReturnValue("");
285
- let installedIcon = Buffer.from([0x89, 0x50, 0x00, 0xfe, 0x80, 0x0a]);
286
- readFileSyncMock.mockImplementation((path: string) => {
287
- if (path === iconSource) return Buffer.from(iconBytes);
288
- if (path === iconPath) return Buffer.from(installedIcon);
289
- return "{}";
265
+ copyFileSyncMock.mockImplementation(() => {
266
+ throw new Error("missing bundled icon");
267
});
291
- writeFileSyncMock.mockImplementation((path: string, contents: Buffer) => {
292
- if (path === iconPath) installedIcon = Buffer.from(contents);
293
- });
294
-
268
return Effect.gen(function* () {
269
yield* DesktopPreReadyPlatform.make;
297
- assert.deepEqual(installedIcon, iconBytes);
298
- yield* DesktopPreReadyPlatform.make;
299
- assert.deepEqual(
300
- writeFileSyncMock.mock.calls.filter(([path]) => path === iconPath),
301
- [[iconPath, iconBytes, { mode: 0o600 }]],
302
- );
303
- assert.equal(copyFileSyncMock.mock.calls.length, 0);
304
- assert.equal(
305
- writeFileSyncMock.mock.calls.filter(([path]) => path === desktopEntryPath).length,
306
- 2,
307
- );
308
- assert.equal(setDesktopNameMock.mock.calls.length, 2);
309
- }).pipe(
310
- Effect.provideService(HostProcess.Platform, "linux"),
311
- Effect.ensuring(Effect.sync(() => vi.unstubAllEnvs())),
312
- );
313
- });
314
-
315
- it.effect("still prepares the portal entry when the bundled icon cannot be read", () => {
316
- vi.stubEnv("VITE_DEV_SERVER_URL", "");
317
- vi.stubEnv("XDG_DATA_HOME", "/xdg");
318
- getSwitchValueMock.mockReturnValue("");
319
- readFileSyncMock.mockImplementation((path: string) => {
320
- if (path === iconSource) throw new Error("unreadable bundled icon");
321
- return "{}";
322
- });
323
- return Effect.gen(function* () {
324
- yield* DesktopPreReadyPlatform.make;
325
- assert.isTrue(readFileSyncMock.mock.calls.some(([path]) => path === iconSource));
326
- assert.equal(copyFileSyncMock.mock.calls.length, 0);
327
- assert.equal(writeFileSyncMock.mock.calls.length, 1);
328
- const [path, contents] = writeFileSyncMock.mock.calls[0]!;
329
- assert.equal(path, desktopEntryPath);
270
+ const contents = writeFileSyncMock.mock.calls[0]?.[1];
271
assert.include(contents, "MimeType=x-scheme-handler/t3code;");
331
- assert.include(contents, `Icon=${iconPath}`);
272
+ assert.include(contents, "Icon=");
273
assert.equal(setDesktopNameMock.mock.calls.length, 1);
333
- }).pipe(
334
- Effect.provideService(HostProcess.Platform, "linux"),
335
- Effect.ensuring(Effect.sync(() => vi.unstubAllEnvs())),
336
- );
274
+ }).pipe(Effect.provideService(HostProcess.Platform, "linux"));
275
});
276
277
it.effect(
apps/desktop/src/app/DesktopPreReadyPlatform.ts
+3
-10
@@ -92,21 +92,14 @@ export const make = Effect.gen(function* () {
92
: undefined;
93
if (iconPath !== undefined) {
94
try {
95
- // Electron's copyFile extracts ASAR entries to temporary files it never removes.
96
- const icon = NodeFS.readFileSync(
95
+ NodeFS.mkdirSync(NodePath.posix.dirname(iconPath), { recursive: true });
96
+ NodeFS.copyFileSync(
97
NodePath.posix.join(
98
Electron.app.getAppPath(),
99
"apps/desktop/prod-resources/icon.png",
100
),
101
+ iconPath,
102
);
102
- let current: Buffer | null = null;
103
- try {
104
- current = NodeFS.readFileSync(iconPath);
105
- } catch {}
106
- if (current === null || !current.equals(icon)) {
107
- NodeFS.mkdirSync(NodePath.posix.dirname(iconPath), { recursive: true });
108
- NodeFS.writeFileSync(iconPath, icon, { mode: 0o600 });
109
- }
103
} catch {}
104
}
105
NodeFS.writeFileSync(
apps/desktop/src/app/DesktopRuntime.ts
deleted
-11
@@ -1,11 +0,0 @@
1
-import * as Runtime from "effect/Runtime";
2
-
3
-// DesktopLifecycle owns signals and waits for backend shutdown before quitting
4
-// Electron. NodeRuntime's competing signal handler interrupts that sequence.
5
-export const runMain = Runtime.makeRunMain(({ fiber, teardown }) => {
6
- fiber.addObserver((exit) => {
7
- teardown(exit, (code) => {
8
- if (code !== 0) process.exit(code);
9
- });
10
- });
11
-});
apps/desktop/src/backend/DesktopBackendManager.test.ts
+10
-21
@@ -262,7 +262,7 @@ describe("DesktopBackendManager", () => {
262
assert.equal(spawnedCommand.options.additionalFds?.fd5?.type, "output");
263
assert.equal(
264
Duration.toMillis(Duration.fromInputUnsafe(spawnedCommand.options.forceKillAfter)),
265
- 30_000,
265
+ 5_000,
266
);
267
268
assert.deepEqual(yield* decodeBootstrap(bootstrapJson), configWithObservability);
@@ -1546,15 +1546,14 @@ describe("DesktopBackendManager", () => {
1546
),
1547
);
1548
1549
- it.effect("stopAllPoolInstances allows slow cleanup but bounds hung backends", () =>
1549
+ it.effect("stopAllPoolInstances bounds the quit finalizer when backends hang", () =>
1550
Effect.scoped(
1551
Effect.gen(function* () {
1552
const teardownStarted = yield* Queue.unbounded<string>();
1553
const teardownFinished = yield* Queue.unbounded<string>();
1554
- const allowSlowTeardown = yield* Deferred.make<void>();
1555
- const allowHungTeardown = yield* Deferred.make<void>();
1554
+ const allowTeardown = yield* Deferred.make<void>();
1555
1557
- const makeInstance = (name: string, allowTeardown: Deferred.Deferred<void>) =>
1556
+ const makeInstance = (name: string) =>
1557
makeTestInstance({
1558
spawnerLayer: Layer.succeed(
1559
ChildProcessSpawner.ChildProcessSpawner,
@@ -1576,8 +1575,8 @@ describe("DesktopBackendManager", () => {
1575
httpClientLayer: layerHttpClient(() => Effect.never),
1576
});
1577
1579
- const instance1 = yield* makeInstance("instance1", allowSlowTeardown);
1580
- const instance2 = yield* makeInstance("instance2", allowHungTeardown);
1578
+ const instance1 = yield* makeInstance("instance1");
1579
+ const instance2 = yield* makeInstance("instance2");
1580
1581
yield* instance1.start;
1582
yield* instance2.start;
@@ -1595,25 +1594,15 @@ describe("DesktopBackendManager", () => {
1594
).pipe(Effect.provide(layerMockPool), Effect.forkChild);
1595
1596
const started = yield* Queue.takeN(teardownStarted, 2);
1598
- yield* Effect.addFinalizer(() =>
1599
- Deferred.succeed(allowSlowTeardown, undefined).pipe(
1600
- Effect.andThen(Deferred.succeed(allowHungTeardown, undefined)),
1601
- ),
1602
- );
1597
assert.deepEqual(started.toSorted(), ["instance1", "instance2"]);
1598
1605
- yield* TestClock.adjust(Duration.seconds(6));
1606
- assert.isUndefined(quitFiber.pollUnsafe());
1607
- yield* Deferred.succeed(allowSlowTeardown, undefined);
1608
- assert.equal(yield* Queue.take(teardownFinished), "instance1");
1609
- assert.isUndefined(quitFiber.pollUnsafe());
1610
- yield* TestClock.adjust(Duration.seconds(39));
1611
-
1599
+ yield* TestClock.adjust(Duration.seconds(5));
1600
yield* Fiber.join(quitFiber);
1601
assert.equal(yield* Queue.size(teardownFinished), 0);
1602
1615
- yield* Deferred.succeed(allowHungTeardown, undefined);
1616
- assert.equal(yield* Queue.take(teardownFinished), "instance2");
1603
+ yield* Deferred.succeed(allowTeardown, undefined);
1604
+ const finished = yield* Queue.takeN(teardownFinished, 2);
1605
+ assert.deepEqual(finished.toSorted(), ["instance1", "instance2"]);
1606
}).pipe(Effect.provide(TestClock.layer())),
1607
),
1608
);
apps/desktop/src/backend/DesktopBackendManager.ts
+3
-2
@@ -37,8 +37,9 @@ const MAX_PREFLIGHT_FAILURE_ATTEMPTS = 5;
37
const DEFAULT_BACKEND_READINESS_TIMEOUT = Duration.minutes(1);
38
const DEFAULT_BACKEND_READINESS_INTERVAL = Duration.millis(100);
39
const DEFAULT_BACKEND_READINESS_REQUEST_TIMEOUT = Duration.seconds(1);
40
-// Give busy backends time to stop provider sessions before forcing termination.
41
-const DEFAULT_BACKEND_TERMINATE_GRACE = Duration.seconds(30);
40
+// Same as the service launcher. A killed backend leaves its agents running,
41
+// and a busy one needs a few seconds to stop every provider session.
42
+const DEFAULT_BACKEND_TERMINATE_GRACE = Duration.seconds(5);
43
const DEFAULT_BACKEND_OUTPUT_DRAIN_TIMEOUT = Duration.seconds(5);
44
const BACKEND_READINESS_PATH = "/.well-known/t3/environment";
45
const { logWarning: logBackendProcessWarning } =
apps/desktop/src/electron/ElectronUpdater.test.ts
+2
-308
@@ -1,27 +1,8 @@
1
-// @effect-diagnostics nodeBuiltinImport:off -- Build real electron-updater disk fixtures with its SHA-512 encoding.
2
-import * as NodeServices from "@effect/platform-node/NodeServices";
3
-import * as NodeCrypto from "node:crypto";
4
-import * as NodeEvents from "node:events";
5
-import * as NodeModule from "node:module";
6
-import * as NodePath from "node:path";
7
-import * as Deferred from "effect/Deferred";
8
-import * as FileSystem from "effect/FileSystem";
9
-import * as Option from "effect/Option";
10
-import { AppImageUpdater } from "electron-updater/out/AppImageUpdater.js";
11
-import { DebUpdater } from "electron-updater/out/DebUpdater.js";
12
-import { MacUpdater } from "electron-updater/out/MacUpdater.js";
13
-import { GenericProvider } from "electron-updater/out/providers/GenericProvider.js";
14
-import type { UpdateDownloadedEvent } from "electron-updater/out/types.js";
15
-import { NsisUpdater } from "electron-updater/out/NsisUpdater.js";
16
-import * as DesktopUpdates from "../updates/DesktopUpdates.ts";
17
-import { flushCallbacks, makeHarness } from "../updates/updatesTestHarness.ts";
1
import { assert, describe, it } from "@effect/vitest";
2
import * as Effect from "effect/Effect";
20
-import type { VerifyUpdateCodeSignature } from "electron-updater";
3
import { beforeEach, vi } from "vite-plus/test";
4
23
-const { autoUpdaterMock, updaterOverride } = vi.hoisted(() => ({
24
- updaterOverride: { current: undefined as import("electron-updater").AppUpdater | undefined },
5
+const { autoUpdaterMock } = vi.hoisted(() => ({
6
autoUpdaterMock: {
7
allowDowngrade: false,
8
allowPrerelease: false,
@@ -32,8 +13,6 @@ const { autoUpdaterMock, updaterOverride } = vi.hoisted(() => ({
13
fullChangelog: false,
14
checkForUpdates: vi.fn(() => Promise.resolve(null)),
15
downloadUpdate: vi.fn(() => Promise.resolve([])),
35
- logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn() },
36
- verifyUpdateCodeSignature: undefined as VerifyUpdateCodeSignature | undefined,
16
on: vi.fn(),
17
quitAndInstall: vi.fn(),
18
removeListener: vi.fn(),
@@ -42,9 +21,7 @@ const { autoUpdaterMock, updaterOverride } = vi.hoisted(() => ({
21
}));
22
23
vi.mock("electron-updater", () => ({
45
- get autoUpdater() {
46
- return updaterOverride.current ?? autoUpdaterMock;
47
- },
24
+ autoUpdater: autoUpdaterMock,
25
}));
26
27
import * as ElectronUpdater from "./ElectronUpdater.ts";
@@ -66,7 +43,6 @@ describe("ElectronUpdater", () => {
43
autoUpdaterMock.quitAndInstall.mockClear();
44
autoUpdaterMock.removeListener.mockClear();
45
autoUpdaterMock.setFeedURL.mockClear();
69
- autoUpdaterMock.verifyUpdateCodeSignature = undefined;
46
});
47
48
it.effect("scopes updater event listeners", () =>
@@ -160,286 +136,4 @@ describe("ElectronUpdater", () => {
136
assert.deepEqual(autoUpdaterMock.quitAndInstall.mock.calls, [[true, false]]);
137
}).pipe(Effect.provide(ElectronUpdater.layer)),
138
);
163
-
164
- describe("Windows update signature check", () => {
165
- const publisherNames = ["T3 Tools Inc"];
166
- const installerPath = "C:\\updater\\pending\\temp-T3-Code-x64.exe";
167
- // execFile marks the error killed when the verifier exceeds its 20-second timeout.
168
- const timedOut = () =>
169
- Object.assign(new Error("Command failed: powershell.exe"), { killed: true });
170
-
171
- const downloadVerifyingSignature = () => {
172
- autoUpdaterMock.downloadUpdate.mockImplementationOnce(async () => {
173
- const rejection = await autoUpdaterMock.verifyUpdateCodeSignature!(
174
- publisherNames,
175
- installerPath,
176
- );
177
- // NSIS accepts only null as a successful signature check.
178
- if (rejection !== null) throw new Error(`Invalid signature: ${rejection}`);
179
- return [];
180
- });
181
- return Effect.flatMap(ElectronUpdater.ElectronUpdater, (updater) => updater.downloadUpdate);
182
- };
183
-
184
- it.effect("retries a timed-out signature check with the same verifier and installer", () =>
185
- Effect.gen(function* () {
186
- const verify = vi
187
- .fn<VerifyUpdateCodeSignature>()
188
- .mockRejectedValueOnce(timedOut())
189
- .mockResolvedValueOnce(null);
190
- autoUpdaterMock.verifyUpdateCodeSignature = verify;
191
-
192
- yield* downloadVerifyingSignature();
193
-
194
- assert.deepEqual(verify.mock.calls, [
195
- [publisherNames, installerPath],
196
- [publisherNames, installerPath],
197
- ]);
198
- }).pipe(Effect.provide(ElectronUpdater.layer)),
199
- );
200
-
201
- it.effect("fails on invalid signatures, other errors and two timeouts on each download", () =>
202
- Effect.gen(function* () {
203
- const cases = [
204
- { outcome: () => Promise.resolve("Invalid publisher"), calls: 1 },
205
- { outcome: () => Promise.reject(new Error("Cannot execute PowerShell")), calls: 1 },
206
- { outcome: () => Promise.reject(timedOut()), calls: 2 },
207
- ];
208
- for (const { outcome, calls } of cases) {
209
- const verify = vi.fn<VerifyUpdateCodeSignature>(outcome);
210
- autoUpdaterMock.verifyUpdateCodeSignature = verify;
211
-
212
- // Reusing the installed verifier must neither stack retries nor exhaust future retries.
213
- for (let download = 1; download <= 2; download++) {
214
- const error = yield* downloadVerifyingSignature().pipe(Effect.flip);
215
- assert.instanceOf(error, ElectronUpdater.ElectronUpdaterDownloadUpdateError);
216
- assert.equal(verify.mock.calls.length, calls * download);
217
- }
218
- }
219
- }).pipe(Effect.provide(ElectronUpdater.layer)),
220
- );
221
-
222
- it.effect("rejects a retry when the upstream capability probe skips verification", () =>
223
- Effect.gen(function* () {
224
- const verify = vi
225
- .fn<VerifyUpdateCodeSignature>()
226
- .mockRejectedValueOnce(timedOut())
227
- .mockImplementationOnce(async () => {
228
- // Upstream resolves null even though its failed capability probe skips verification.
229
- autoUpdaterMock.logger.warn(
230
- "Cannot execute ConvertTo-Json: spawnSync powershell.exe ETIMEDOUT. Ignoring signature validation due to unsupported powershell version. Please upgrade to powershell 3 or higher.",
231
- );
232
- return null;
233
- });
234
- autoUpdaterMock.verifyUpdateCodeSignature = verify;
235
-
236
- const error = yield* downloadVerifyingSignature().pipe(Effect.flip);
237
-
238
- assert.instanceOf(error, ElectronUpdater.ElectronUpdaterDownloadUpdateError);
239
- assert.equal(verify.mock.calls.length, 2);
240
- }).pipe(Effect.provide(ElectronUpdater.layer)),
241
- );
242
- });
243
-});
244
-
245
-describe("installed electron-updater cache recovery", () => {
246
- it.effect.each([
247
- {
248
- name: "Intel Mac",
249
- platform: "darwin",
250
- Updater: MacUpdater,
251
- selected: "x64.zip",
252
- other: "arm64.zip",
253
- rosetta: false,
254
- },
255
- {
256
- name: "Apple Silicon running Intel",
257
- platform: "darwin",
258
- Updater: MacUpdater,
259
- selected: "arm64.zip",
260
- other: "x64.zip",
261
- rosetta: true,
262
- },
263
- {
264
- name: "Windows",
265
- platform: "win32",
266
- Updater: NsisUpdater,
267
- selected: "x64.exe",
268
- other: "arm64.exe",
269
- rosetta: false,
270
- },
271
- {
272
- name: "Debian",
273
- platform: "linux",
274
- Updater: DebUpdater,
275
- selected: "x64.deb",
276
- other: "x64.AppImage",
277
- rosetta: false,
278
- },
279
- {
280
- name: "AppImage",
281
- platform: "linux",
282
- Updater: AppImageUpdater,
283
- selected: "x64.AppImage",
284
- other: "x64.deb",
285
- rosetta: false,
286
- },
287
- ] as const)("restores only the package selected by $name", (scenario) =>
288
- Effect.scoped(
289
- Effect.gen(function* () {
290
- const fs = yield* FileSystem.FileSystem;
291
- const directory = yield* fs.makeTempDirectoryScoped();
292
- const cacheDirectory = NodePath.join(directory, "custom-updater-cache", "pending");
293
- const configPath = NodePath.join(directory, "app-update.yml");
294
- yield* fs.writeFileString(configPath, "updaterCacheDirName: custom-updater-cache\n");
295
- yield* fs.makeDirectory(cacheDirectory, { recursive: true });
296
-
297
- const require = NodeModule.createRequire(import.meta.url);
298
- require("electron");
299
- const electronModule = require.cache[require.resolve("electron")]!;
300
- const childProcess = require("node:child_process") as typeof import("node:child_process");
301
- const originalElectron = electronModule.exports;
302
- const originalArch = Object.getOwnPropertyDescriptor(process, "arch")!;
303
- yield* Effect.acquireRelease(
304
- Effect.sync(() => {
305
- // MacUpdater's native Squirrel bridge and host probes are OS boundaries.
306
- electronModule.exports = { autoUpdater: new NodeEvents.EventEmitter() };
307
- Object.defineProperty(process, "arch", { value: "x64", configurable: true });
308
- return vi
309
- .spyOn(childProcess, "execFileSync")
310
- .mockReturnValue(scenario.rosetta ? "sysctl.proc_translated: 1" : "x86_64");
311
- }),
312
- (probe) =>
313
- Effect.sync(() => {
314
- probe.mockRestore();
315
- Object.defineProperty(process, "arch", originalArch);
316
- electronModule.exports = originalElectron;
317
- updaterOverride.current = undefined;
318
- }),
319
- );
320
-
321
- const extensions =
322
- scenario.platform === "darwin"
323
- ? ["arm64.dmg", "x64.dmg", "arm64.zip", "x64.zip"]
324
- : scenario.platform === "win32"
325
- ? ["arm64.exe", "x64.exe"]
326
- : ["arm64.AppImage", "x64.AppImage", "arm64.deb", "x64.deb"];
327
- const files = extensions.map((extension) => {
328
- const url = `T3-Code-1.2.4-${extension}`;
329
- return { url, sha512: NodeCrypto.createHash("sha512").update(url).digest("base64") };
330
- });
331
- const info = {
332
- version: "1.2.4",
333
- releaseDate: "2026-10-01T00:00:00Z",
334
- files,
335
- path: files[0]!.url,
336
- sha512: files[0]!.sha512,
337
- };
338
- yield* Effect.acquireRelease(
339
- Effect.sync(() =>
340
- vi.spyOn(GenericProvider.prototype, "getLatestVersion").mockResolvedValue(info),
341
- ),
342
- (feed) => Effect.sync(() => feed.mockRestore()),
343
- );
344
-
345
- // A fresh instance for each launch forces disk validation rather than in-memory reuse.
346
- yield* Effect.forEach([scenario.other, scenario.selected], (cachedExtension) =>
347
- Effect.scoped(
348
- Effect.gen(function* () {
349
- const cached = files.find((file) => file.url.endsWith(`-${cachedExtension}`))!;
350
- yield* fs.writeFileString(NodePath.join(cacheDirectory, cached.url), cached.url);
351
- yield* fs.writeFileString(
352
- NodePath.join(cacheDirectory, "update-info.json"),
353
- JSON.stringify({
354
- fileName: cached.url,
355
- sha512: cached.sha512,
356
- isAdminRightsRequired: false,
357
- }),
358
- );
359
- const updater = new scenario.Updater(undefined, {
360
- version: "1.2.3",
361
- name: "T3 Code",
362
- isPackaged: true,
363
- appUpdateConfigPath: configPath,
364
- userDataPath: directory,
365
- baseCachePath: directory,
366
- whenReady: () => Promise.resolve(),
367
- relaunch: vi.fn(),
368
- quit: vi.fn(),
369
- onQuit: vi.fn(),
370
- });
371
- updater.logger = null;
372
- const networkDownload = vi.fn(() =>
373
- Promise.reject(new Error("unexpected network download")),
374
- );
375
- Object.assign(updater, { httpExecutor: { download: networkDownload } });
376
- if (updater instanceof MacUpdater) {
377
- // Keep real selection, executeDownload, and hash validation; stop at native handoff.
378
- Object.assign(updater, {
379
- updateDownloaded: async (_file: unknown, event: UpdateDownloadedEvent) => {
380
- updater.emit("update-downloaded", event);
381
- return [];
382
- },
383
- });
384
- }
385
- updaterOverride.current = updater;
386
- assert.deepEqual(
387
- yield* ElectronUpdater.make.pendingDownloadDirectory,
388
- Option.some(cacheDirectory),
389
- );
390
-
391
- const inspected = Deferred.makeUnsafe<void>();
392
- const downloadFinished = Deferred.makeUnsafe<void>();
393
- const download = vi.spyOn(updater, "downloadUpdate");
394
- const harness = makeHarness({
395
- platform: scenario.platform,
396
- runningUnderArm64Translation: scenario.rosetta,
397
- env: scenario.selected.endsWith("AppImage")
398
- ? { APPIMAGE: "/test/T3-Code.AppImage" }
399
- : {},
400
- updater: {
401
- ...ElectronUpdater.make,
402
- downloadUpdate: ElectronUpdater.make.downloadUpdate.pipe(
403
- Effect.ensuring(Deferred.succeed(downloadFinished, undefined)),
404
- ),
405
- },
406
- fileSystem: {
407
- ...fs,
408
- readFileString: (path, encoding) =>
409
- path === "/missing/resources/package-type" && scenario.selected.endsWith("deb")
410
- ? Effect.succeed("deb")
411
- : fs.readFileString(path, encoding),
412
- exists: (path) =>
413
- fs.exists(path).pipe(Effect.tap(() => Deferred.succeed(inspected, undefined))),
414
- },
415
- });
416
- yield* Effect.scoped(
417
- Effect.gen(function* () {
418
- const updates = yield* DesktopUpdates.DesktopUpdates;
419
- yield* updates.configure;
420
- // AppImage activation reads the host environment; the fixture is intentionally not installed.
421
- vi.spyOn(updater, "isUpdaterActive").mockReturnValue(true);
422
- assert.isTrue((yield* updates.check("startup")).checked);
423
- yield* Deferred.await(inspected);
424
- yield* flushCallbacks;
425
-
426
- if (cachedExtension === scenario.other) {
427
- assert.equal(download.mock.calls.length, 0);
428
- assert.equal((yield* updates.getState).status, "available");
429
- } else {
430
- yield* Deferred.await(downloadFinished);
431
- yield* flushCallbacks;
432
- assert.equal(download.mock.calls.length, 1);
433
- assert.equal((yield* updates.getState).status, "downloaded");
434
- assert.equal((yield* updates.getState).downloadedVersion, "1.2.4");
435
- }
436
- assert.equal(networkDownload.mock.calls.length, 0);
437
- }),
438
- ).pipe(Effect.provide(harness.layer));
439
- }),
440
- ),
441
- );
442
- }),
443
- ).pipe(Effect.provide(NodeServices.layer)),
444
- );
139
});
apps/desktop/src/electron/ElectronUpdater.ts
-54
@@ -1,12 +1,10 @@
1
import * as Context from "effect/Context";
2
import * as Effect from "effect/Effect";
3
import * as Layer from "effect/Layer";
4
-import * as Option from "effect/Option";
4
import * as Schema from "effect/Schema";
5
import * as Scope from "effect/Scope";
6
7
import { autoUpdater } from "electron-updater";
9
-import type { NsisUpdater, VerifyUpdateCodeSignature } from "electron-updater";
8
9
type AutoUpdater = typeof autoUpdater;
10
@@ -69,7 +67,6 @@ export class ElectronUpdater extends Context.Service<
67
readonly setAllowDowngrade: (value: boolean) => Effect.Effect<void>;
68
readonly setFullChangelog: (value: boolean) => Effect.Effect<void>;
69
readonly setDisableDifferentialDownload: (value: boolean) => Effect.Effect<void>;
72
- readonly pendingDownloadDirectory: Effect.Effect<Option.Option<string>>;
70
readonly checkForUpdates: Effect.Effect<void, ElectronUpdaterCheckForUpdatesError>;
71
readonly downloadUpdate: Effect.Effect<void, ElectronUpdaterDownloadUpdateError>;
72
readonly quitAndInstall: (options: {
@@ -83,45 +80,6 @@ export class ElectronUpdater extends Context.Service<
80
}
81
>()("@t3tools/desktop/electron/ElectronUpdater") {}
82
86
-const signatureChecksWithRetry = new WeakSet<VerifyUpdateCodeSignature>();
87
-
88
-const retrySignatureCheckAfterTimeout = () => {
89
- // Only the Windows NSIS updater exposes this hook; its PowerShell check times out after 20 s.
90
- const updater = autoUpdater as AutoUpdater &
91
- Partial<Pick<NsisUpdater, "verifyUpdateCodeSignature">>;
92
- const verify = updater.verifyUpdateCodeSignature;
93
- if (verify === undefined || signatureChecksWithRetry.has(verify)) return;
94
-
95
- const verifyWithRetry: VerifyUpdateCodeSignature = async (publisherNames, path) => {
96
- try {
97
- return await verify(publisherNames, path);
98
- } catch (error) {
99
- if (!(error instanceof Error && "killed" in error && error.killed === true)) throw error;
100
- }
101
-
102
- const logger = updater.logger;
103
- let skipped = false;
104
- updater.logger = {
105
- info: (message) => logger?.info(message),
106
- warn: (message) => {
107
- // A failed capability probe makes electron-updater warn and return null without checking.
108
- skipped ||= String(message).includes("Ignoring signature validation");
109
- logger?.warn(message);
110
- },
111
- error: (message) => logger?.error(message),
112
- debug: (message) => logger?.debug?.(message),
113
- };
114
- try {
115
- const result = await verify(publisherNames, path);
116
- return skipped ? "Signature validation was skipped after a timed-out check." : result;
117
- } finally {
118
- updater.logger = logger;
119
- }
120
- };
121
- signatureChecksWithRetry.add(verifyWithRetry);
122
- updater.verifyUpdateCodeSignature = verifyWithRetry;
123
-};
124
-
83
/** @public Service construction is part of the canonical Effect module API. */
84
export const make = ElectronUpdater.of({
85
setFeedURL: (options) =>
@@ -165,17 +123,6 @@ export const make = ElectronUpdater.of({
123
autoUpdater.disableDifferentialDownload = value;
124
return Effect.void;
125
}),
168
- // Use the updater's helper so cache lookup follows the same configuration as downloads.
169
- pendingDownloadDirectory: Effect.tryPromise(() =>
170
- (
171
- autoUpdater as unknown as {
172
- getOrCreateDownloadHelper: () => Promise<{ readonly cacheDirForPendingUpdate: string }>;
173
- }
174
- ).getOrCreateDownloadHelper(),
175
- ).pipe(
176
- Effect.map((helper) => helper.cacheDirForPendingUpdate),
177
- Effect.option,
178
- ),
126
checkForUpdates: Effect.suspend(() => {
127
const channel = autoUpdater.channel;
128
return Effect.tryPromise({
@@ -184,7 +131,6 @@ export const make = ElectronUpdater.of({
131
}).pipe(Effect.asVoid);
132
}),
133
downloadUpdate: Effect.suspend(() => {
187
- retrySignatureCheckAfterTimeout();
134
const channel = autoUpdater.channel;
135
return Effect.tryPromise({
136
try: () => autoUpdater.downloadUpdate(),
apps/desktop/src/ipc/DesktopIpcHandlers.ts
-2
@@ -40,7 +40,6 @@ import {
40
import {
41
getAppBranding,
42
getLocalEnvironmentBootstraps,
43
- readLocalEnvironmentBootstraps,
43
getLocalEnvironmentBearerToken,
44
getRelayTelemetryEnabled,
45
getSystemLocale,
@@ -101,7 +100,6 @@ export const installDesktopIpcHandlers = Effect.fn("desktop.ipc.installHandlers"
100
yield* ipc.handleSync(getSystemLocale);
101
yield* ipc.handleSync(getWindowFullscreenState);
102
yield* ipc.handleSync(getLocalEnvironmentBootstraps);
104
- yield* ipc.handle(readLocalEnvironmentBootstraps);
103
yield* ipc.handleSync(getLocalEnvironmentEnabled);
104
yield* ipc.handle(setLocalEnvironmentEnabled);
105
yield* ipc.handle(getLocalEnvironmentBearerToken);
apps/desktop/src/ipc/methods/window.ts
+47
-58
@@ -99,68 +99,57 @@ export const getWindowFullscreenState = DesktopIpc.makeSyncIpcMethod({
99
}),
100
});
101
102
-const readLocalEnvironmentBootstrapSnapshot = Effect.fn(
103
- "desktop.ipc.window.getLocalEnvironmentBootstraps",
104
-)(function* () {
105
- const pool = yield* DesktopBackendPool.DesktopBackendPool;
106
- const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
107
- const instances = yield* pool.list;
108
- const bootstraps: DesktopEnvironmentBootstrap[] = [];
109
- for (const instance of instances) {
110
- const isPrimary = instance.id === PRIMARY_LOCAL_ENVIRONMENT_ID;
111
- const config = yield* instance.currentConfig;
112
- const snapshot = yield* instance.snapshot;
113
- if (Option.isNone(config) || Option.isSome(config.value.preflightFailure)) {
114
- const fatalPreflight =
115
- Option.isSome(config) &&
116
- Option.isSome(config.value.preflightFailure) &&
117
- config.value.preflightFailure.value.fatal;
118
- const stoppedPreflight =
119
- Option.isSome(config) &&
120
- Option.isSome(config.value.preflightFailure) &&
121
- (!snapshot.desiredRunning || !snapshot.restartScheduled);
122
- if (isPrimary || fatalPreflight || stoppedPreflight) continue;
102
+export const getLocalEnvironmentBootstraps = DesktopIpc.makeSyncIpcMethod({
103
+ channel: IpcChannels.GET_LOCAL_ENVIRONMENT_BOOTSTRAPS_CHANNEL,
104
+ result: Schema.Array(DesktopEnvironmentBootstrapSchema),
105
+ handler: Effect.fn("desktop.ipc.window.getLocalEnvironmentBootstraps")(function* () {
106
+ const pool = yield* DesktopBackendPool.DesktopBackendPool;
107
+ const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
108
+ const instances = yield* pool.list;
109
+ const bootstraps: DesktopEnvironmentBootstrap[] = [];
110
+ for (const instance of instances) {
111
+ const isPrimary = instance.id === PRIMARY_LOCAL_ENVIRONMENT_ID;
112
+ const config = yield* instance.currentConfig;
113
+ const snapshot = yield* instance.snapshot;
114
+ if (Option.isNone(config) || Option.isSome(config.value.preflightFailure)) {
115
+ const fatalPreflight =
116
+ Option.isSome(config) &&
117
+ Option.isSome(config.value.preflightFailure) &&
118
+ config.value.preflightFailure.value.fatal;
119
+ const stoppedPreflight =
120
+ Option.isSome(config) &&
121
+ Option.isSome(config.value.preflightFailure) &&
122
+ (!snapshot.desiredRunning || !snapshot.restartScheduled);
123
+ if (isPrimary || fatalPreflight || stoppedPreflight) continue;
124
+ bootstraps.push({
125
+ id: instance.id,
126
+ label: yield* instance.label,
127
+ runningDistro: null,
128
+ httpBaseUrl: null,
129
+ wsBaseUrl: null,
130
+ });
131
+ continue;
132
+ }
133
+ const { bootstrap, httpBaseUrl } = config.value;
134
+ const runningDistro = config.value.runningDistro ?? null;
135
bootstraps.push({
136
id: instance.id,
125
- label: yield* instance.label,
126
- runningDistro: null,
127
- httpBaseUrl: null,
128
- wsBaseUrl: null,
137
+ label: runningDistro === null ? yield* instance.label : `WSL (${runningDistro})`,
138
+ runningDistro,
139
+ httpBaseUrl: httpBaseUrl.href,
140
+ wsBaseUrl: toWebSocketBaseUrl(httpBaseUrl),
141
+ // A backend launched with the desktop secret accepts whichever token the secret derives
142
+ // for the current window, so hand out that one rather than the token frozen into its
143
+ // launch config.
144
+ ...(bootstrap.desktopBootstrapSecret
145
+ ? { bootstrapToken: yield* configuration.currentBootstrapToken }
146
+ : bootstrap.desktopBootstrapToken
147
+ ? { bootstrapToken: bootstrap.desktopBootstrapToken }
148
+ : {}),
149
});
130
- continue;
150
}
132
- const { bootstrap, httpBaseUrl } = config.value;
133
- const runningDistro = config.value.runningDistro ?? null;
134
- bootstraps.push({
135
- id: instance.id,
136
- label: runningDistro === null ? yield* instance.label : `WSL (${runningDistro})`,
137
- runningDistro,
138
- httpBaseUrl: httpBaseUrl.href,
139
- wsBaseUrl: toWebSocketBaseUrl(httpBaseUrl),
140
- // A backend launched with the desktop secret accepts whichever token the secret derives
141
- // for the current window, so hand out that one rather than the token frozen into its
142
- // launch config.
143
- ...(bootstrap.desktopBootstrapSecret
144
- ? { bootstrapToken: yield* configuration.currentBootstrapToken }
145
- : bootstrap.desktopBootstrapToken
146
- ? { bootstrapToken: bootstrap.desktopBootstrapToken }
147
- : {}),
148
- });
149
- }
150
- return bootstraps;
151
-});
152
-
153
-export const getLocalEnvironmentBootstraps = DesktopIpc.makeSyncIpcMethod({
154
- channel: IpcChannels.GET_LOCAL_ENVIRONMENT_BOOTSTRAPS_CHANNEL,
155
- result: Schema.Array(DesktopEnvironmentBootstrapSchema),
156
- handler: readLocalEnvironmentBootstrapSnapshot,
157
-});
158
-
159
-export const readLocalEnvironmentBootstraps = DesktopIpc.makeIpcMethod({
160
- channel: IpcChannels.GET_LOCAL_ENVIRONMENT_BOOTSTRAPS_CHANNEL,
161
- payload: Schema.Void,
162
- result: Schema.Array(DesktopEnvironmentBootstrapSchema),
163
- handler: readLocalEnvironmentBootstrapSnapshot,
151
+ return bootstraps;
152
+ }),
153
});
154
155
function extractWslDistroFromEnvironmentId(envId: string): string | null {
apps/desktop/src/ipc/methods/wsl.test.ts
-37
@@ -120,43 +120,6 @@ describe("WSL IPC", () => {
120
),
121
);
122
123
- it.effect("does not enumerate distros until the WSL backend is enabled", () => {
124
- const distros = [
125
- { name: "Ubuntu", isDefault: true, version: 2 as const },
126
- { name: "Debian", isDefault: false, version: 2 as const },
127
- ];
128
- const layer = Layer.mergeAll(
129
- DesktopAppSettings.layerTest({
130
- ...DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS,
131
- wslDistro: "Debian",
132
- }),
133
- DesktopWslEnvironment.layerTest({ isAvailable: true, distros }),
134
- layerWslBackend(),
135
- layerLifecycle([]),
136
- layerUnusedLifecycleRuntime,
137
- );
138
-
139
- return Effect.gen(function* () {
140
- const wsl = yield* DesktopWslEnvironment.DesktopWslEnvironment;
141
- const state = yield* getWslState.handler(undefined).pipe(
142
- Effect.provideService(DesktopWslEnvironment.DesktopWslEnvironment, {
143
- ...wsl,
144
- listDistros: Effect.die("must not enumerate distros"),
145
- }),
146
- Effect.flatMap(decodeWslState),
147
- );
148
- assert.equal(state.enabled, false);
149
- assert.equal(state.available, true);
150
- assert.equal(state.distro, "Debian");
151
- assert.deepEqual(state.distros, []);
152
-
153
- const enabledState = yield* invokeSetWslBackendEnabled(true);
154
- assert.equal(enabledState.enabled, true);
155
- assert.equal(enabledState.distro, "Debian");
156
- assert.deepEqual(enabledState.distros, distros);
157
- }).pipe(Effect.provide(layer));
158
- });
159
-
123
it.effect("stages dual-backend preferences before enabling without relaunching", () => {
124
const relaunchReasons: Array<string> = [];
125
const layer = Layer.mergeAll(
apps/desktop/src/ipc/methods/wsl.ts
+3
-3
@@ -22,9 +22,9 @@ const readWslState: Effect.Effect<
22
const wslBackend = yield* DesktopWslBackend.DesktopWslBackend;
23
const settings = yield* appSettings.get;
24
const available = settings.localEnvironmentEnabled && (yield* wslEnvironment.isAvailable);
25
- // Windows ships a wsl.exe stub that can prompt to install WSL when invoked.
26
- // Keep disabled state reads from launching it to enumerate distros.
27
- const distros = available && settings.wslBackendEnabled ? yield* wslEnvironment.listDistros : [];
25
+ // Only enumerate distros when WSL is actually available — listDistros on a
26
+ // non-WSL host would spawn wsl.exe and hit the timeout for nothing.
27
+ const distros = available ? yield* wslEnvironment.listDistros : [];
28
const preflightError = yield* wslBackend.lastPreflightError;
29
return {
30
enabled: settings.wslBackendEnabled,
apps/desktop/src/main.ts
+2
-2
@@ -6,6 +6,7 @@ for (const stream of [process.stdout, process.stderr]) {
6
}
7
8
import * as NodeHttpClient from "@effect/platform-node/NodeHttpClient";
9
+import * as NodeRuntime from "@effect/platform-node/NodeRuntime";
10
import * as NodeServices from "@effect/platform-node/NodeServices";
11
// @effect-diagnostics-next-line nodeBuiltinImport:off - Version output must flush before Electron exits, without acquiring the runtime.
12
import * as NodeFS from "node:fs";
@@ -21,7 +22,6 @@ import * as HostProcess from "@t3tools/shared/HostProcess";
22
import type { RemoteT3RunnerOptions } from "@t3tools/ssh/tunnel";
23
import serverPackageJson from "../../server/package.json" with { type: "json" };
24
24
-import * as DesktopRuntime from "./app/DesktopRuntime.ts";
25
import * as DesktopIpc from "./ipc/DesktopIpc.ts";
26
import * as ElectronApp from "./electron/ElectronApp.ts";
27
import * as ElectronDialog from "./electron/ElectronDialog.ts";
@@ -242,4 +242,4 @@ const layerDesktopRuntime = layerDesktopClerk.pipe(
242
Layer.provideMerge(DesktopPreReadyPlatform.layer),
243
);
244
245
-DesktopApp.program.pipe(Effect.provide(layerDesktopRuntime), DesktopRuntime.runMain);
245
+DesktopApp.program.pipe(Effect.provide(layerDesktopRuntime), NodeRuntime.runMain);
apps/desktop/src/preload.ts
+8
-17
@@ -12,7 +12,6 @@ import { contextBridge, ipcRenderer, webFrame, webUtils } from "electron";
12
13
import * as IpcChannels from "./ipc/channels.ts";
14
import { mergeLegacyLocalStorage } from "./legacyLocalStorageMerge.ts";
15
-import { createPreloadSnapshot } from "./preloadSnapshot.ts";
15
16
const SNAP_SHOT_EVENT_TYPES = new Set([
17
"requested",
@@ -75,18 +74,6 @@ function unwrapEnsureSshEnvironmentResult(result: unknown) {
74
return result as Awaited<ReturnType<DesktopBridge["ensureSshEnvironment"]>>;
75
}
76
78
-const readBootstraps = (
79
- result: unknown,
80
-): ReturnType<DesktopBridge["getLocalEnvironmentBootstraps"]> =>
81
- Array.isArray(result) ? result : [];
82
-const localEnvironmentBootstraps = createPreloadSnapshot(
83
- () => readBootstraps(ipcRenderer.sendSync(IpcChannels.GET_LOCAL_ENVIRONMENT_BOOTSTRAPS_CHANNEL)),
84
- async () =>
85
- readBootstraps(await ipcRenderer.invoke(IpcChannels.GET_LOCAL_ENVIRONMENT_BOOTSTRAPS_CHANNEL)),
86
-);
87
-// Changes take effect on relaunch, so renderer reads can reuse the startup value.
88
-let localEnvironmentEnabled: boolean | undefined;
89
-
77
contextBridge.exposeInMainWorld("desktopBridge", {
78
getAppBranding: () => {
79
const result = ipcRenderer.sendSync(IpcChannels.GET_APP_BRANDING_CHANNEL);
@@ -116,13 +103,17 @@ contextBridge.exposeInMainWorld("desktopBridge", {
103
const result = ipcRenderer.sendSync(IpcChannels.GET_SYSTEM_LOCALE_CHANNEL);
104
return typeof result === "string" ? result : null;
105
},
119
- getLocalEnvironmentBootstraps: localEnvironmentBootstraps.read,
120
- readLocalEnvironmentBootstraps: localEnvironmentBootstraps.refresh,
106
+ getLocalEnvironmentBootstraps: () => {
107
+ const result = ipcRenderer.sendSync(IpcChannels.GET_LOCAL_ENVIRONMENT_BOOTSTRAPS_CHANNEL);
108
+ if (!Array.isArray(result)) {
109
+ return [];
110
+ }
111
+ return result as ReturnType<DesktopBridge["getLocalEnvironmentBootstraps"]>;
112
+ },
113
getLocalEnvironmentBearerToken: () =>
114
ipcRenderer.invoke(IpcChannels.GET_LOCAL_ENVIRONMENT_BEARER_TOKEN_CHANNEL),
115
getLocalEnvironmentEnabled: () =>
124
- (localEnvironmentEnabled ??=
125
- ipcRenderer.sendSync(IpcChannels.GET_LOCAL_ENVIRONMENT_ENABLED_CHANNEL) !== false),
116
+ ipcRenderer.sendSync(IpcChannels.GET_LOCAL_ENVIRONMENT_ENABLED_CHANNEL) !== false,
117
setLocalEnvironmentEnabled: (enabled) =>
118
ipcRenderer.invoke(IpcChannels.SET_LOCAL_ENVIRONMENT_ENABLED_CHANNEL, enabled),
119
getClientSettings: () => ipcRenderer.invoke(IpcChannels.GET_CLIENT_SETTINGS_CHANNEL),
apps/desktop/src/preloadSnapshot.test.ts
deleted
-45
@@ -1,45 +0,0 @@
1
-import { expect, it, vi } from "vite-plus/test";
2
-
3
-import { createPreloadSnapshot } from "./preloadSnapshot.ts";
4
-
5
-it("serves the startup snapshot while a shared asynchronous refresh is pending", async () => {
6
- const initial = ["primary"];
7
- const latest = Promise.withResolvers<string[]>();
8
- const readInitial = vi.fn(() => initial);
9
- const readLatest = vi.fn(() => latest.promise);
10
- const snapshot = createPreloadSnapshot(readInitial, readLatest);
11
-
12
- expect(snapshot.read()).toBe(initial);
13
- const first = snapshot.refresh();
14
- const second = snapshot.refresh();
15
- expect(snapshot.read()).toBe(initial);
16
- expect(snapshot.read()).toBe(initial);
17
- expect(readInitial).toHaveBeenCalledTimes(1);
18
- expect(readLatest).toHaveBeenCalledTimes(1);
19
-
20
- const connected = ["primary", "wsl"];
21
- latest.resolve(connected);
22
- expect(await first).toBe(connected);
23
- expect(await second).toBe(connected);
24
- expect(snapshot.read()).toBe(connected);
25
- expect(readInitial).toHaveBeenCalledTimes(1);
26
-});
27
-
28
-it("retains an async snapshot through failure and replaces it on successful recovery", async () => {
29
- const connected = ["primary", "wsl"];
30
- const readInitial = vi.fn(() => ["stale"]);
31
- const readLatest = vi
32
- .fn<() => Promise<string[]>>()
33
- .mockResolvedValueOnce(connected)
34
- .mockRejectedValueOnce(new Error("IPC unavailable"))
35
- .mockResolvedValueOnce([]);
36
- const snapshot = createPreloadSnapshot(readInitial, readLatest);
37
-
38
- await snapshot.refresh();
39
- expect(snapshot.read()).toBe(connected);
40
- await expect(snapshot.refresh()).rejects.toThrow("IPC unavailable");
41
- expect(snapshot.read()).toBe(connected);
42
- await expect(snapshot.refresh()).resolves.toEqual([]);
43
- expect(snapshot.read()).toEqual([]);
44
- expect(readInitial).not.toHaveBeenCalled();
45
-});
apps/desktop/src/preloadSnapshot.ts
deleted
-23
@@ -1,23 +0,0 @@
1
-export function createPreloadSnapshot<T>(readInitial: () => T, readLatest: () => Promise<T>) {
2
- let snapshot: { readonly value: T } | undefined;
3
- let pending: Promise<T> | undefined;
4
-
5
- return {
6
- read: () => {
7
- snapshot ??= { value: readInitial() };
8
- return snapshot.value;
9
- },
10
- refresh: () => {
11
- if (pending !== undefined) return pending;
12
- pending = readLatest()
13
- .then((value) => {
14
- snapshot = { value };
15
- return value;
16
- })
17
- .finally(() => {
18
- pending = undefined;
19
- });
20
- return pending;
21
- },
22
- };
23
-}
apps/desktop/src/preview/BrowserImport/ChromiumCookies.test.ts
+47
-48
@@ -151,57 +151,56 @@ describe("readChromiumCookieDatabase", () => {
151
}).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
152
);
153
154
- it.effect.each([14, 24])(
155
- "imports mixed TEXT and BLOB cookie values, including empty values, in schema %i",
156
- (schemaVersion) =>
157
- Effect.gen(function* () {
158
- const fileSystem = yield* FileSystem.FileSystem;
159
- const directory = yield* fileSystem.makeTempDirectoryScoped({
160
- prefix: "t3code-chromium-cookies-",
161
- });
162
- const filename = `${directory}/Cookies`;
163
- const key = Buffer.from("0123456789abcdef");
164
- const host = "secure.example";
165
- const value = "stored encrypted";
166
- const payload =
167
- schemaVersion >= 24
168
- ? Buffer.concat([
169
- NodeCrypto.createHash("sha256").update(host).digest(),
170
- Buffer.from(value),
171
- ])
172
- : Buffer.from(value);
173
- const encrypted = encryptV10(payload, key);
154
+ it.effect("reads plaintext, encrypted, and genuinely empty cookie values", () =>
155
+ Effect.gen(function* () {
156
+ const fileSystem = yield* FileSystem.FileSystem;
157
+ const directory = yield* fileSystem.makeTempDirectoryScoped({
158
+ prefix: "t3code-chromium-cookies-",
159
+ });
160
+ const filename = `${directory}/Cookies`;
161
+ const key = Buffer.from("0123456789abcdef");
162
175
- yield* Effect.gen(function* () {
176
- const sql = yield* SqlClient.SqlClient;
177
- yield* sql`create table meta (key text primary key, value text not null)`;
178
- yield* sql`insert into meta values ('version', ${schemaVersion})`;
179
- yield* sql`create table cookies (
180
- host_key text not null, name text not null, value text not null,
181
- encrypted_value blob not null, path text not null, expires_utc integer not null,
182
- is_secure integer not null, is_httponly integer not null, samesite integer not null
183
- )`;
184
- if (schemaVersion >= 15) {
185
- yield* sql`alter table cookies add column top_frame_site_key text not null default ''`;
186
- }
187
- yield* sql`insert into cookies
188
- (host_key, name, value, encrypted_value, path, expires_utc, is_secure, is_httponly, samesite) values
189
- ('plain.example', 'plain', 'stored plaintext', '', '/', 0, 0, 0, -1),
190
- (${host}, 'text-encrypted', '', cast(${encrypted} as text), '/', 0, 1, 1, 2),
191
- (${host}, 'blob-encrypted', '', ${encrypted}, '/', 0, 1, 1, 2),
192
- ('empty.example', 'empty', '', ${new Uint8Array()}, '/', 0, 0, 0, 0)`;
193
- }).pipe(Effect.provide(NodeSqliteClient.layer({ filename })));
163
+ yield* Effect.gen(function* () {
164
+ const sql = yield* SqlClient.SqlClient;
165
+ yield* sql`create table meta (key text primary key, value text not null)`;
166
+ yield* sql`insert into meta values ('version', 23)`;
167
+ yield* sql`
168
+ create table cookies (
169
+ host_key text not null,
170
+ name text not null,
171
+ value text not null,
172
+ encrypted_value blob not null,
173
+ path text not null,
174
+ expires_utc integer not null,
175
+ is_secure integer not null,
176
+ is_httponly integer not null,
177
+ samesite integer not null,
178
+ top_frame_site_key text not null default ''
179
+ )
180
+ `;
181
+ yield* sql`
182
+ insert into cookies (host_key, name, value, encrypted_value, path, expires_utc, is_secure, is_httponly, samesite) values
183
+ ('plain.example', 'plain', 'stored plaintext', ${new Uint8Array()}, '/', 0, 0, 0, -1)
184
+ `;
185
+ yield* sql`
186
+ insert into cookies (host_key, name, value, encrypted_value, path, expires_utc, is_secure, is_httponly, samesite) values
187
+ ('secure.example', 'encrypted', '', ${encryptV10("stored encrypted", key)}, '/', 0, 1, 1, 2)
188
+ `;
189
+ yield* sql`
190
+ insert into cookies (host_key, name, value, encrypted_value, path, expires_utc, is_secure, is_httponly, samesite) values
191
+ ('empty.example', 'empty', '', ${new Uint8Array()}, '/', 0, 0, 0, 0)
192
+ `;
193
+ }).pipe(Effect.provide(NodeSqliteClient.layer({ filename })));
194
195
- const result = yield* readChromiumCookieDatabase(filename, { cbcV10: key }, "darwin");
195
+ const result = yield* readChromiumCookieDatabase(filename, { cbcV10: key }, "darwin");
196
197
- expect(result.undecryptable).toBe(0);
198
- expect(result.cookies.map(({ name, value }) => ({ name, value }))).toEqual([
199
- { name: "plain", value: "stored plaintext" },
200
- { name: "text-encrypted", value },
201
- { name: "blob-encrypted", value },
202
- { name: "empty", value: "" },
203
- ]);
204
- }).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
197
+ expect(result.undecryptable).toBe(0);
198
+ expect(result.cookies.map(({ name, value }) => ({ name, value }))).toEqual([
199
+ { name: "plain", value: "stored plaintext" },
200
+ { name: "encrypted", value: "stored encrypted" },
201
+ { name: "empty", value: "" },
202
+ ]);
203
+ }).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
204
);
205
206
it.effect("enforces domain binding only for schema 24 and newer", () =>
apps/desktop/src/preview/BrowserImport/ChromiumCookies.ts
+2
-4
@@ -200,14 +200,12 @@ export const readChromiumCookieDatabase = Effect.fn("ChromiumCookies.readChromiu
200
Effect.flatMap(decodeSchemaVersion),
201
Effect.map(([row]) => row.value),
202
);
203
- // SQLite's BLOB affinity still permits TEXT. Cast before Node decodes
204
- // those bytes as UTF-8, which can corrupt an encrypted payload.
203
const raw =
204
schemaVersion >= 15
207
- ? yield* sql`select host_key, name, value, cast(encrypted_value as blob) as encrypted_value, path,
205
+ ? yield* sql`select host_key, name, value, encrypted_value, path,
206
expires_utc / 1000000 as expires_seconds, is_secure, is_httponly,
207
samesite, top_frame_site_key from cookies`
210
- : yield* sql`select host_key, name, value, cast(encrypted_value as blob) as encrypted_value, path,
208
+ : yield* sql`select host_key, name, value, encrypted_value, path,
209
expires_utc / 1000000 as expires_seconds, is_secure, is_httponly,
210
samesite, '' as top_frame_site_key from cookies`;
211
return { rows: yield* decodeCookieRows(raw), schemaVersion };
apps/desktop/src/preview/Manager.test.ts
+3
-391
@@ -1,4 +1,3 @@
1
-import * as NodeVM from "node:vm";
1
import { it as effectIt } from "@effect/vitest";
2
import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
3
import { DESKTOP_PREVIEW_RECORDING_CAPTURE_TRIGGER } from "@t3tools/contracts";
@@ -412,44 +411,6 @@ const makeTestPreviewWebContents = (
411
} as unknown as TestPreviewWebContents;
412
};
413
415
-const makeStillImage = (pixels = "fresh-png") => ({
416
- toPNG: () => Buffer.from(pixels),
417
- toJPEG: () => Buffer.from(pixels),
418
- getSize: () => ({ width: 100, height: 80 }),
419
-});
420
-
421
-const makeTestStillImageWebContents = (...args: Parameters<typeof makeTestPreviewWebContents>) => {
422
- const wc = makeTestPreviewWebContents(...args);
423
- Object.assign(wc, { isDevToolsOpened: () => false });
424
- holdStillImagePaint(wc, Promise.resolve());
425
- return wc;
426
-};
427
-
428
-const holdStillImagePaint = (wc: TestPreviewWebContents, paint: Promise<void>) => {
429
- vi.mocked(wc.debugger.sendCommand).mockImplementation(async (method) => {
430
- if (method === "Page.getFrameTree") return { frameTree: { frame: { id: "main" } } };
431
- if (method === "Page.createIsolatedWorld") return { executionContextId: 7 };
432
- if (method === "Runtime.evaluate") {
433
- await paint;
434
- return { result: { value: true } };
435
- }
436
- return undefined;
437
- });
438
-};
439
-
440
-const setupStill = (manager: PreviewManager.PreviewManager["Service"], paint = Promise.resolve()) =>
441
- Effect.gen(function* () {
442
- const image = makeStillImage();
443
- const capturePage = vi.fn<() => Promise<typeof image>>().mockResolvedValue(image);
444
- const wc = makeTestStillImageWebContents(capturePage);
445
- holdStillImagePaint(wc, paint);
446
- fromId.mockReturnValue(wc);
447
- yield* manager.createTab("tab_still");
448
- yield* manager.registerWebview("tab_still", wc.id);
449
- yield* manager.setColorScheme("tab_still", "system");
450
- return { image, capturePage, wc, capture: manager.captureScreenshot("tab_still") };
451
- });
452
-
414
const setupRecordingRaceTabs = (manager: PreviewManager.PreviewManager["Service"]) =>
415
Effect.gen(function* () {
416
const capturePage = vi.fn(async () => ({
@@ -2540,7 +2501,6 @@ describe("PreviewManager", () => {
2501
isDestroyed: () => false,
2502
getType: () => "webview",
2503
getURL: () => "https://example.com:8443/path?query=value",
2543
- setBackgroundThrottling: vi.fn(),
2504
getTitle: () => "Example",
2505
isLoadingMainFrame: () => false,
2506
getZoomFactor: () => 1,
@@ -2579,7 +2539,7 @@ describe("PreviewManager", () => {
2539
2540
const artifact = yield* manager.captureScreenshot("tab_1");
2541
2582
- expect(capturePage).toHaveBeenCalledTimes(2);
2542
+ expect(capturePage).toHaveBeenCalledOnce();
2543
expect(mkdir).toHaveBeenCalledWith("/tmp/t3/dev/browser-artifacts");
2544
expect(writeFile).toHaveBeenCalledWith(artifact.path, png);
2545
expect(artifact).toMatchObject({
@@ -2602,21 +2562,18 @@ describe("PreviewManager", () => {
2562
yield* TestClock.adjust(1_000);
2563
const retriedExit = yield* Fiber.join(retriedFiber);
2564
expect(Exit.isSuccess(retriedExit)).toBe(true);
2605
- expect(capturePage).toHaveBeenCalledTimes(4);
2565
+ expect(capturePage).toHaveBeenCalledTimes(3);
2566
2567
capturePage.mockClear();
2568
const captureCause = new Error("capture failed");
2569
capturePage.mockRejectedValue(captureCause);
2610
- const writesBeforeFailure = writeFile.mock.calls.length;
2570
const failingFiber = yield* Effect.exit(manager.captureScreenshot("tab_1")).pipe(
2571
Effect.forkChild({ startImmediately: true }),
2572
);
2573
yield* TestClock.adjust(1_000);
2574
const exit = yield* Fiber.join(failingFiber);
2575
expect(Exit.isFailure(exit)).toBe(true);
2617
- expect(capturePage).toHaveBeenCalledTimes(6);
2618
- expect(writeFile).toHaveBeenCalledTimes(writesBeforeFailure);
2619
- expect(fromId(42)?.setBackgroundThrottling).toHaveBeenLastCalledWith(true);
2576
+ expect(capturePage).toHaveBeenCalledTimes(3);
2577
if (Exit.isSuccess(exit)) return;
2578
const error = Option.getOrThrow(Cause.findErrorOption(exit.cause));
2579
expect(error).toMatchObject({
@@ -2630,30 +2587,6 @@ describe("PreviewManager", () => {
2587
),
2588
);
2589
2633
- effectIt.effect("captures final pixels after warmup fails and paint readiness settles", () =>
2634
- withManager((manager) =>
2635
- Effect.gen(function* () {
2636
- const paint = Promise.withResolvers<void>();
2637
- const { capturePage, wc, capture } = yield* setupStill(manager, paint.promise);
2638
- capturePage
2639
- .mockRejectedValueOnce(new Error("UnknownVizError"))
2640
- .mockRejectedValueOnce(new Error("UnknownVizError"))
2641
- .mockRejectedValueOnce(new Error("UnknownVizError"))
2642
- .mockResolvedValue(makeStillImage("final-png"));
2643
- const fiber = yield* capture.pipe(Effect.forkChild({ startImmediately: true }));
2644
- yield* TestClock.adjust(300);
2645
- expect(capturePage).toHaveBeenCalledTimes(3);
2646
- expect(writeFile).not.toHaveBeenCalled();
2647
- expect(wc.setBackgroundThrottling.mock.calls).toEqual([[false]]);
2648
- paint.resolve();
2649
- const artifact = yield* Fiber.join(fiber);
2650
- expect(capturePage).toHaveBeenCalledTimes(4);
2651
- expect(writeFile.mock.calls).toEqual([[artifact.path, Buffer.from("final-png")]]);
2652
- expect(wc.setBackgroundThrottling.mock.calls).toEqual([[false], [true]]);
2653
- }),
2654
- ),
2655
- );
2656
-
2590
effectIt.effect("preserves both screenshots of the same site in the same millisecond", () =>
2591
withManager((manager) =>
2592
Effect.gen(function* () {
@@ -2667,8 +2600,6 @@ describe("PreviewManager", () => {
2600
const capturePage = vi
2601
.fn<() => Promise<ReturnType<typeof pngImage>>>()
2602
.mockResolvedValueOnce(pngImage(firstPng))
2670
- .mockResolvedValueOnce(pngImage(firstPng))
2671
- .mockResolvedValueOnce(pngImage(secondPng))
2603
.mockResolvedValueOnce(pngImage(secondPng));
2604
fromId.mockReturnValue(makeTestPreviewWebContents(capturePage));
2605
yield* manager.createTab("tab_1");
@@ -2690,325 +2621,6 @@ describe("PreviewManager", () => {
2621
),
2622
);
2623
2693
- effectIt.effect(
2694
- "waits for paint before capturing and restores rendering after overlapping requests",
2695
- () =>
2696
- withManager((manager) =>
2697
- Effect.gen(function* () {
2698
- const paint = Promise.withResolvers<void>();
2699
- const { image, capturePage, wc, capture } = yield* setupStill(manager, paint.promise);
2700
- const first = Promise.withResolvers<typeof image>();
2701
- const second = Promise.withResolvers<typeof image>();
2702
- capturePage
2703
- .mockResolvedValueOnce(makeStillImage("discarded-warmup"))
2704
- .mockResolvedValueOnce(makeStillImage("discarded-warmup"))
2705
- .mockReturnValueOnce(first.promise)
2706
- .mockReturnValueOnce(second.promise);
2707
- const hostThrottling = vi.fn();
2708
- yield* manager.setMainWindow({
2709
- isDestroyed: () => false,
2710
- once: vi.fn(),
2711
- webContents: { setBackgroundThrottling: hostThrottling },
2712
- } as never);
2713
- const one = yield* capture.pipe(Effect.forkChild({ startImmediately: true }));
2714
- const two = yield* capture.pipe(Effect.forkChild({ startImmediately: true }));
2715
- yield* TestClock.adjust(0);
2716
- expect(capturePage).toHaveBeenCalledTimes(2);
2717
- expect(writeFile).not.toHaveBeenCalled();
2718
- expect(hostThrottling.mock.calls).toEqual([[false]]);
2719
- expect(wc.setBackgroundThrottling.mock.calls).toEqual([[false]]);
2720
- paint.resolve();
2721
- yield* TestClock.adjust(0);
2722
- expect(capturePage).toHaveBeenCalledTimes(4);
2723
- first.resolve(image);
2724
- yield* Fiber.join(one);
2725
- expect(wc.setBackgroundThrottling.mock.calls).toEqual([[false]]);
2726
- second.resolve(image);
2727
- yield* Fiber.join(two);
2728
- expect(writeFile.mock.calls.map((call) => call[1])).toEqual([
2729
- Buffer.from("fresh-png"),
2730
- Buffer.from("fresh-png"),
2731
- ]);
2732
- expect(hostThrottling.mock.calls).toEqual([[false], [true]]);
2733
- expect(wc.setBackgroundThrottling.mock.calls).toEqual([[false], [true]]);
2734
- }),
2735
- ),
2736
- );
2737
-
2738
- effectIt.effect("keeps picture-in-picture rendering after a still image completes", () =>
2739
- withManager((manager) =>
2740
- Effect.gen(function* () {
2741
- const { image, capturePage, wc, capture } = yield* setupStill(manager);
2742
- const pending = Promise.withResolvers<typeof image>();
2743
- capturePage
2744
- .mockResolvedValueOnce(image)
2745
- .mockResolvedValueOnce(makeStillImage("discarded-warmup"))
2746
- .mockReturnValueOnce(pending.promise);
2747
- const { pictureInPictureWindow } = makeTestPictureInPictureWindow();
2748
- browserWindowConstructor.mockImplementation(function () {
2749
- return pictureInPictureWindow;
2750
- });
2751
- yield* manager.openPictureInPicture("tab_still");
2752
- const still = yield* capture.pipe(Effect.forkChild({ startImmediately: true }));
2753
- yield* TestClock.adjust(0);
2754
- expect(capturePage).toHaveBeenCalledTimes(3);
2755
- expect(writeFile).not.toHaveBeenCalled();
2756
- pending.resolve(image);
2757
- yield* Fiber.join(still);
2758
- expect(writeFile.mock.calls.map((call) => call[1])).toEqual([Buffer.from("fresh-png")]);
2759
- expect(wc.setBackgroundThrottling.mock.calls).toEqual([[false]]);
2760
- yield* manager.closePictureInPicture("tab_still");
2761
- expect(wc.setBackgroundThrottling.mock.calls).toEqual([[false], [true]]);
2762
- }),
2763
- ),
2764
- );
2765
-
2766
- effectIt.effect("keeps a pending still image rendering when recording ends", () =>
2767
- withManager((manager) =>
2768
- Effect.gen(function* () {
2769
- const { image, capturePage, wc, capture } = yield* setupStill(manager);
2770
- const pending = Promise.withResolvers<typeof image>();
2771
- capturePage.mockResolvedValueOnce(image).mockReturnValue(pending.promise);
2772
- yield* manager.startRecording("tab_still");
2773
- const fiber = yield* capture.pipe(Effect.forkChild({ startImmediately: true }));
2774
- yield* TestClock.adjust(0);
2775
- yield* manager.stopRecording("tab_still");
2776
- expect(wc.setBackgroundThrottling.mock.calls).toEqual([[false]]);
2777
- pending.resolve(image);
2778
- yield* Fiber.join(fiber);
2779
- expect(wc.setBackgroundThrottling.mock.calls).toEqual([[false], [true]]);
2780
- }),
2781
- ),
2782
- );
2783
-
2784
- effectIt.effect(
2785
- "ignores late native warmup completion after interruption while recording owns rendering",
2786
- () =>
2787
- withManager((manager) =>
2788
- Effect.gen(function* () {
2789
- const { image, capturePage, wc, capture } = yield* setupStill(manager);
2790
- const warmup = Promise.withResolvers<typeof image>();
2791
- let nativeCompleted = false;
2792
- const nativePromise = warmup.promise.then((result) => {
2793
- nativeCompleted = true;
2794
- return result;
2795
- });
2796
- capturePage.mockReturnValueOnce(nativePromise);
2797
- const fiber = yield* capture.pipe(Effect.forkChild({ startImmediately: true }));
2798
- yield* TestClock.adjust(0);
2799
- yield* manager.startRecording("tab_still");
2800
- yield* Fiber.interrupt(fiber);
2801
- expect(nativeCompleted).toBe(false);
2802
- expect(wc.setBackgroundThrottling.mock.calls).toEqual([[false]]);
2803
- warmup.resolve(image);
2804
- yield* TestClock.adjust(0);
2805
- expect(nativeCompleted).toBe(true);
2806
- expect(capturePage).toHaveBeenCalledTimes(2);
2807
- expect(writeFile).not.toHaveBeenCalled();
2808
- expect(wc.setBackgroundThrottling.mock.calls).toEqual([[false]]);
2809
- yield* manager.stopRecording("tab_still");
2810
- expect(wc.setBackgroundThrottling.mock.calls).toEqual([[false], [true]]);
2811
- }),
2812
- ),
2813
- );
2814
-
2815
- effectIt.effect(
2816
- "ignores an interrupted warmup that resolves while the replacement guest is capturing",
2817
- () =>
2818
- withManager((manager) =>
2819
- Effect.gen(function* () {
2820
- const fresh = makeStillImage("replacement-png");
2821
- const late = Promise.withResolvers<typeof fresh>();
2822
- const finalCapture = Promise.withResolvers<typeof fresh>();
2823
- const oldCapture = vi.fn(() => late.promise);
2824
- const replacementCapture = vi
2825
- .fn()
2826
- .mockResolvedValueOnce(fresh)
2827
- .mockReturnValue(finalCapture.promise);
2828
- const hostThrottling = vi.fn();
2829
- const host = Object.assign(makeTestHostWebContents(), {
2830
- setBackgroundThrottling: hostThrottling,
2831
- });
2832
- const original = makeTestStillImageWebContents(oldCapture, 42, host);
2833
- const replacement = makeTestStillImageWebContents(replacementCapture, 43, host);
2834
- holdStillImagePaint(original, new Promise(() => {}));
2835
- fromId.mockImplementation((id) => (id === 42 ? original : replacement));
2836
- yield* manager.createTab("tab_still");
2837
- yield* manager.registerWebview("tab_still", 42);
2838
- yield* manager.setColorScheme("tab_still", "system");
2839
- yield* manager.setMainWindow({
2840
- isDestroyed: () => false,
2841
- once: vi.fn(),
2842
- webContents: host,
2843
- } as never);
2844
- const failed = yield* Effect.exit(manager.captureScreenshot("tab_still")).pipe(
2845
- Effect.forkChild({ startImmediately: true }),
2846
- );
2847
- yield* TestClock.adjust(0);
2848
- yield* Fiber.interrupt(failed);
2849
- yield* manager.registerWebview("tab_still", 43);
2850
- yield* manager.setColorScheme("tab_still", "system");
2851
- const healthy = yield* manager
2852
- .captureScreenshot("tab_still")
2853
- .pipe(Effect.forkChild({ startImmediately: true }));
2854
- yield* TestClock.adjust(0);
2855
- late.resolve({ ...fresh, toPNG: () => Buffer.from("late-old-warmup") });
2856
- yield* TestClock.adjust(0);
2857
- expect(writeFile).not.toHaveBeenCalled();
2858
- expect(oldCapture).toHaveBeenCalledOnce();
2859
- expect(replacementCapture).toHaveBeenCalledTimes(2);
2860
- expect(hostThrottling.mock.calls).toEqual([[false], [true], [false]]);
2861
- expect(replacement.setBackgroundThrottling.mock.calls).toEqual([[false]]);
2862
- finalCapture.resolve(fresh);
2863
- yield* Fiber.join(healthy);
2864
- expect(writeFile.mock.calls.map((call) => call[1])).toEqual([
2865
- Buffer.from("replacement-png"),
2866
- ]);
2867
- expect(hostThrottling.mock.calls).toEqual([[false], [true], [false], [true]]);
2868
- expect(replacement.setBackgroundThrottling.mock.calls).toEqual([[false], [true]]);
2869
- }),
2870
- ),
2871
- );
2872
-
2873
- effectIt.effect("paints a loading document with isolated scheduling despite page overrides", () =>
2874
- withManager((manager) =>
2875
- Effect.gen(function* () {
2876
- for (const mode of ["suppressed", "synchronous", "timeout-before", "timeout-after"]) {
2877
- writeFile.mockClear();
2878
- let pixels = "old-pixels";
2879
- const frames: Array<() => void> = [];
2880
- let expire = () => {};
2881
- let paintConfirmed: unknown;
2882
- const clearTimeout = vi.fn();
2883
- const probeStarted = Promise.withResolvers<void>();
2884
- const pageFrame = vi.fn((callback: () => void) => {
2885
- if (mode === "synchronous") callback();
2886
- });
2887
- const page = NodeVM.createContext({
2888
- Promise: undefined,
2889
- requestAnimationFrame: pageFrame,
2890
- });
2891
- const isolated = NodeVM.createContext({
2892
- requestAnimationFrame: (callback: () => void) => frames.push(callback),
2893
- cancelAnimationFrame: (id: number) => {
2894
- frames.splice(id - 1, 1);
2895
- },
2896
- setTimeout: (callback: () => void, delay: number) => {
2897
- expect(delay).toBe(1_000);
2898
- expire = callback;
2899
- return 1;
2900
- },
2901
- clearTimeout,
2902
- });
2903
- const capturePage = vi.fn(async () => makeStillImage(pixels));
2904
- const wc = makeTestStillImageWebContents(capturePage);
2905
- Object.assign(wc, { isLoading: () => true });
2906
- vi.mocked(wc.executeJavaScript).mockImplementation(async (expression) =>
2907
- NodeVM.runInContext(expression, page),
2908
- );
2909
- vi.mocked(wc.debugger.sendCommand).mockImplementation(async (method, params) => {
2910
- if (method === "Page.getFrameTree") return { frameTree: { frame: { id: "main" } } };
2911
- if (method === "Page.createIsolatedWorld") return { executionContextId: 7 };
2912
- if (method === "Runtime.evaluate") {
2913
- const pending = NodeVM.runInContext(params?.["expression"] as string, isolated);
2914
- probeStarted.resolve();
2915
- paintConfirmed = await pending;
2916
- return { result: { value: paintConfirmed } };
2917
- }
2918
- return undefined;
2919
- });
2920
- fromId.mockReturnValue(wc);
2921
- const tabId = `tab_loading_${mode}`;
2922
- yield* manager.createTab(tabId);
2923
- yield* manager.registerWebview(tabId, wc.id);
2924
- yield* manager.setColorScheme(tabId, "system");
2925
- const still = yield* manager
2926
- .captureScreenshot(tabId)
2927
- .pipe(Effect.forkChild({ startImmediately: true }));
2928
- yield* Effect.promise(() => probeStarted.promise);
2929
- yield* TestClock.adjust(0);
2930
- expect(capturePage).toHaveBeenCalledOnce();
2931
- expect(writeFile).not.toHaveBeenCalled();
2932
- if (mode !== "timeout-before") frames.shift()?.();
2933
- pixels = "new-pixels";
2934
- yield* TestClock.adjust(0);
2935
- expect(writeFile).not.toHaveBeenCalled();
2936
- if (mode.startsWith("timeout")) expire();
2937
- else frames.shift()?.();
2938
- yield* Fiber.join(still);
2939
- expect(paintConfirmed).toBe(!mode.startsWith("timeout"));
2940
- expect(frames).toHaveLength(0);
2941
- expect(clearTimeout.mock.calls).toEqual(mode.startsWith("timeout") ? [] : [[1]]);
2942
- expect(writeFile.mock.calls.map((call) => call[1])).toEqual([Buffer.from("new-pixels")]);
2943
- expect(pageFrame).not.toHaveBeenCalled();
2944
- expect(wc.setBackgroundThrottling.mock.calls).toEqual([[false], [true]]);
2945
- yield* manager.closeTab(tabId);
2946
- }
2947
- }),
2948
- ),
2949
- );
2950
-
2951
- effectIt.effect("captures available pixels without taking another debugger's ownership", () =>
2952
- withManager((manager) =>
2953
- Effect.gen(function* () {
2954
- for (const devToolsOpen of [true, false]) {
2955
- const capturePage = vi.fn(async () => makeStillImage("available-pixels"));
2956
- const wc = makeTestStillImageWebContents(capturePage);
2957
- Object.assign(wc, { isDevToolsOpened: () => devToolsOpen });
2958
- vi.spyOn(wc.debugger, "isAttached").mockReturnValue(true);
2959
- fromId.mockReturnValue(wc);
2960
- const tabId = `tab_foreign_debugger_${devToolsOpen}`;
2961
- yield* manager.createTab(tabId);
2962
- yield* manager.registerWebview(tabId, wc.id);
2963
- yield* manager.captureScreenshot(tabId);
2964
- expect(capturePage).toHaveBeenCalledTimes(2);
2965
- expect(wc.debugger.attach).not.toHaveBeenCalled();
2966
- expect(wc.debugger.sendCommand).not.toHaveBeenCalled();
2967
- expect(writeFile).toHaveBeenLastCalledWith(
2968
- expect.any(String),
2969
- Buffer.from("available-pixels"),
2970
- );
2971
- expect(wc.setBackgroundThrottling.mock.calls).toEqual([[false], [true]]);
2972
- yield* manager.closeTab(tabId);
2973
- }
2974
- }),
2975
- ),
2976
- );
2977
-
2978
- effectIt.effect(
2979
- "bounds paint readiness and ignores its late completion during another capture",
2980
- () =>
2981
- withManager((manager) =>
2982
- Effect.gen(function* () {
2983
- const paint = Promise.withResolvers<void>();
2984
- const { image, capturePage, wc, capture } = yield* setupStill(manager, paint.promise);
2985
- const first = yield* Effect.exit(capture).pipe(
2986
- Effect.forkChild({ startImmediately: true }),
2987
- );
2988
- yield* TestClock.adjust(1_001);
2989
- expect(Exit.isSuccess(yield* Fiber.join(first))).toBe(true);
2990
- expect(capturePage).toHaveBeenCalledTimes(2);
2991
- expect(writeFile.mock.calls.map((call) => call[1])).toEqual([Buffer.from("fresh-png")]);
2992
- expect(wc.setBackgroundThrottling.mock.calls).toEqual([[false], [true]]);
2993
-
2994
- holdStillImagePaint(wc, Promise.resolve());
2995
- const finalCapture = Promise.withResolvers<typeof image>();
2996
- capturePage.mockResolvedValueOnce(image).mockReturnValueOnce(finalCapture.promise);
2997
- const second = yield* capture.pipe(Effect.forkChild({ startImmediately: true }));
2998
- yield* TestClock.adjust(0);
2999
- paint.resolve();
3000
- yield* TestClock.adjust(0);
3001
- expect(writeFile).toHaveBeenCalledOnce();
3002
- expect(capturePage).toHaveBeenCalledTimes(4);
3003
- expect(wc.setBackgroundThrottling.mock.calls).toEqual([[false], [true], [false]]);
3004
- finalCapture.resolve(image);
3005
- yield* Fiber.join(second);
3006
- expect(writeFile).toHaveBeenCalledTimes(2);
3007
- expect(wc.setBackgroundThrottling.mock.calls).toEqual([[false], [true], [false], [true]]);
3008
- }),
3009
- ),
3010
- );
3011
-
2624
effectIt.effect("keeps every recorded guest unthrottled until its frame capture stops", () =>
2625
withManager((manager) =>
2626
Effect.gen(function* () {
apps/desktop/src/preview/Manager.ts
+2
-101
@@ -391,8 +391,7 @@ interface ManagedListeners {
391
readonly webContents: Electron.WebContents;
392
}
393
394
-// Each still-image request owns a separate, short-lived rendering lease.
395
-type FrameCaptureConsumer = "picture-in-picture" | "recording" | symbol;
394
+type FrameCaptureConsumer = "picture-in-picture" | "recording";
395
396
interface FrameCaptureSession {
397
readonly recordingInputOptions?: RecordingInputOptions;
@@ -2488,7 +2487,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
2487
const [createdAt, millis, image] = yield* Effect.all([
2488
currentIso,
2489
currentMillis,
2491
- captureStillImage(
2490
+ capturePageWithRetry(
2491
{
2492
operation: "captureScreenshot.capturePage",
2493
tabId,
@@ -2536,104 +2535,6 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
2535
};
2536
});
2537
2539
- const captureStillImage = Effect.fn("PreviewManager.captureStillImage")(function* (
2540
- errorContext: PreviewOperationContext,
2541
- tabId: string,
2542
- wc: Electron.WebContents,
2543
- ) {
2544
- const consumer = Symbol("still-image");
2545
- return yield* Effect.acquireUseRelease(
2546
- startFrameCapture(tabId, consumer),
2547
- () =>
2548
- Effect.gen(function* () {
2549
- // A DOM mutation can precede its compositor frame even in a shown
2550
- // window. Keep the original guest rendering through the next paint;
2551
- // a hidden guest otherwise returns old pixels or never completes.
2552
- const probe = Effect.fn("PreviewManager.probeStillImagePaint")(function* (
2553
- send: (
2554
- method: string,
2555
- params?: Record<string, unknown>,
2556
- ) => Effect.Effect<unknown, PreviewOperationError>,
2557
- ) {
2558
- // CDP executes against the current document without Electron's
2559
- // did-stop-loading gate. Isolate scheduling globals from page code.
2560
- const tree = (yield* send("Page.getFrameTree")) as
2561
- | { frameTree?: { frame?: { id?: string } } }
2562
- | undefined;
2563
- const frameId = tree?.frameTree?.frame?.id;
2564
- if (typeof frameId !== "string")
2565
- return yield* new PreviewOperationError({
2566
- ...errorContext,
2567
- cause: new Error("The preview paint frame is unavailable."),
2568
- });
2569
- const world = (yield* send("Page.createIsolatedWorld", {
2570
- frameId,
2571
- worldName: "t3-preview-still-image",
2572
- })) as { executionContextId?: number } | undefined;
2573
- if (typeof world?.executionContextId !== "number")
2574
- return yield* new PreviewOperationError({
2575
- ...errorContext,
2576
- cause: new Error("The preview paint context is unavailable."),
2577
- });
2578
- const response = (yield* send("Runtime.evaluate", {
2579
- // Settle and release scheduled work when only timers keep running.
2580
- // The outer deadline still bounds a frozen renderer.
2581
- expression: `new Promise(resolve => { let frame; const timer = setTimeout(() => { cancelAnimationFrame(frame); resolve(false); }, ${CAPTURE_PAGE_ATTEMPT_TIMEOUT_MS}); frame = requestAnimationFrame(() => { frame = requestAnimationFrame(() => { clearTimeout(timer); resolve(true); }); }); })`,
2582
- contextId: world.executionContextId,
2583
- awaitPromise: true,
2584
- returnByValue: true,
2585
- })) as { result?: { value?: unknown }; exceptionDetails?: unknown } | undefined;
2586
- if (response?.exceptionDetails || response?.result?.value !== true)
2587
- return yield* new PreviewOperationError({
2588
- ...errorContext,
2589
- cause: new Error("The preview paint boundary was not confirmed."),
2590
- });
2591
- });
2592
- const paintReady = Effect.gen(function* () {
2593
- // Only use an existing owned session; never attach or displace
2594
- // another debugger to obtain a screenshot.
2595
- const control = (yield* SynchronizedRef.get(controlSessionsRef)).get(wc.id);
2596
- if (!control)
2597
- return yield* new PreviewOperationError({
2598
- ...errorContext,
2599
- cause: new Error("The preview paint session is unavailable."),
2600
- });
2601
- return yield* control.semaphore.withPermit(
2602
- probe((method, params) =>
2603
- attemptPromise(errorContext, () => control.debugger.sendCommand(method, params)),
2604
- ),
2605
- );
2606
- }).pipe(
2607
- Effect.timeout(CAPTURE_PAGE_ATTEMPT_TIMEOUT_MS),
2608
- Effect.catch((error) =>
2609
- Effect.logWarning(
2610
- "Preview paint readiness was not confirmed; capturing available pixels with mutation freshness unconfirmed.",
2611
- { tabId, webContentsId: wc.id, error },
2612
- ),
2613
- ),
2614
- );
2615
- // capturePage temporarily marks the original guest as captured. A
2616
- // minimized page can otherwise keep animation frames suspended even
2617
- // with scheduler throttling disabled. Discard this warmup image and
2618
- // accept its output only after readiness settles. If the bounded
2619
- // probe cannot confirm paint, retain the native capture fallback.
2620
- const warmup = capturePageWithRetry(errorContext, tabId, wc).pipe(
2621
- Effect.catchTags({
2622
- PreviewOperationError: (error) =>
2623
- Effect.logWarning("Preview warmup capture failed; continuing with final capture.", {
2624
- tabId,
2625
- webContentsId: wc.id,
2626
- error,
2627
- }),
2628
- }),
2629
- );
2630
- yield* Effect.all([paintReady, warmup], { concurrency: 2, discard: true });
2631
- return yield* capturePageWithRetry(errorContext, tabId, wc);
2632
- }),
2633
- () => stopFrameCapture(tabId, consumer),
2634
- );
2635
- });
2636
-
2538
const capturePreviewFrame = Effect.fn("PreviewManager.capturePreviewFrame")(function* (
2539
tabId: string,
2540
) {
apps/desktop/src/settings/DesktopAppSettings.test.ts
+3
-10
@@ -283,7 +283,7 @@ describe("DesktopSettings", () => {
283
Effect.gen(function* () {
284
const settings = yield* DesktopAppSettings.DesktopAppSettings;
285
yield* writeSettingsPatch({
286
- mainWindowBounds: { x: 10, y: 20, width: 599, height: 620 },
286
+ mainWindowBounds: { x: 10.5, y: 20, width: 839, height: 620 },
287
mainWindowMaximized: true,
288
serverExposureMode: "network-accessible",
289
});
@@ -342,24 +342,17 @@ describe("DesktopSettings", () => {
342
const fileSystem = yield* FileSystem.FileSystem;
343
const settings = yield* DesktopAppSettings.DesktopAppSettings;
344
345
- yield* settings.setMainWindowBounds({ x: -1200, y: 40, width: 600, height: 620 }, true);
345
+ yield* settings.setMainWindowBounds({ x: -1200, y: 40, width: 1440, height: 960 }, true);
346
yield* settings.setServerExposureMode("network-accessible");
347
348
const persisted = yield* decodeDesktopSettingsPatch(
349
yield* fileSystem.readFileString(environment.desktopSettingsPath),
350
);
351
assert.deepEqual(persisted, {
352
- mainWindowBounds: { x: -1200, y: 40, width: 600, height: 620 },
352
+ mainWindowBounds: { x: -1200, y: 40, width: 1440, height: 960 },
353
mainWindowMaximized: true,
354
serverExposureMode: "network-accessible",
355
} satisfies typeof DesktopSettingsPatch.Type);
356
-
357
- const restored = yield* Effect.gen(function* () {
358
- const freshSettings = yield* DesktopAppSettings.DesktopAppSettings;
359
- return yield* freshSettings.load;
360
- }).pipe(Effect.provide(DesktopAppSettings.layer));
361
- assert.deepEqual(restored.mainWindowBounds, persisted.mainWindowBounds);
362
- assert.isTrue(restored.mainWindowMaximized);
356
}),
357
),
358
);
apps/desktop/src/settings/DesktopAppSettings.ts
+2
-2
@@ -48,8 +48,8 @@ export interface DesktopSettingsChange {
48
}
49
50
const DEFAULT_TAILSCALE_SERVE_PORT = 443;
51
-export const MIN_MAIN_WINDOW_SIZE = {
52
- width: 600,
51
+const MIN_MAIN_WINDOW_SIZE = {
52
+ width: 840,
53
height: 620,
54
} as const;
55
export const DesktopWindowBoundsSchema = Schema.Struct({
apps/desktop/src/shell/DesktopShellEnvironment.test.ts
+1
-131
@@ -1,10 +1,7 @@
1
// @effect-diagnostics nodeBuiltinImport:off -- The process fixture runs real shell commands with isolated config files.
2
import * as NodeServices from "@effect/platform-node/NodeServices";
3
-import * as Clock from "effect/Clock";
3
import { assert, describe, it } from "@effect/vitest";
5
-import * as Deferred from "effect/Deferred";
4
import * as Effect from "effect/Effect";
7
-import * as Fiber from "effect/Fiber";
5
import * as Layer from "effect/Layer";
6
import * as Logger from "effect/Logger";
7
import * as PlatformError from "effect/PlatformError";
@@ -15,7 +12,6 @@ import * as ChildProcess from "effect/process/ChildProcess";
12
import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
13
import * as NodeChildProcess from "node:child_process";
14
import * as NodeFS from "node:fs";
18
-import * as TestClock from "effect/testing/TestClock";
15
import * as NodeOS from "node:os";
16
import * as NodePath from "node:path";
17
import { vi } from "vite-plus/test";
@@ -82,10 +78,7 @@ function runShellEnvironment(input: {
78
readonly userShell?: string;
79
readonly handler: (
80
command: ChildProcess.Command,
85
- ) =>
86
- | string
87
- | { output: string; exitCode: number }
88
- | Effect.Effect<ChildProcessSpawner.ChildProcessHandle, PlatformError.PlatformError>;
81
+ ) => string | { output: string; exitCode: number };
82
readonly failure?: PlatformError.PlatformError;
83
}) {
84
const layerEnvironment = Layer.succeed(
@@ -99,7 +92,6 @@ function runShellEnvironment(input: {
92
ChildProcessSpawner.make((command) => {
93
if (input.failure !== undefined) return Effect.fail(input.failure);
94
const result = input.handler(command);
102
- if (Effect.isEffect(result)) return result;
95
return Effect.succeed(
96
typeof result === "string"
97
? makeProcess(result)
@@ -572,85 +564,6 @@ describe("DesktopShellEnvironment", () => {
564
}),
565
);
566
575
- it.effect("waits at most 5 seconds in total when the PowerShell profile hangs", () =>
576
- Effect.gen(function* () {
577
- const env: NodeJS.ProcessEnv = { PATH: "C:\\Windows\\System32" };
578
- const profileShells: string[] = [];
579
- const started = yield* Deferred.make<void>();
580
- const completed = yield* Deferred.make<void>();
581
- const baseClock = yield* Clock.Clock;
582
- let wallTime = 0;
583
- const clockWithBackwardWallJump: Clock.Clock = {
584
- ...baseClock,
585
- currentTimeMillisUnsafe: () => wallTime,
586
- currentTimeMillis: Effect.sync(() => wallTime),
587
- };
588
-
589
- const install = yield* Effect.forkChild(
590
- runShellEnvironment({
591
- env,
592
- platform: "win32",
593
- handler: (command) => {
594
- if (command._tag !== "StandardCommand") return "";
595
- if (command.args.includes("-NoProfile")) {
596
- return envOutput({ PATH: "C:\\NoProfile\\Bin;C:\\Windows\\System32" });
597
- }
598
- profileShells.push(command.command);
599
- return Deferred.succeed(started, undefined).pipe(
600
- Effect.as(
601
- ChildProcessSpawner.makeHandle({
602
- ...makeProcess(""),
603
- stdout: Stream.never,
604
- all: Stream.never,
605
- exitCode: Effect.never,
606
- isRunning: Effect.succeed(true),
607
- }),
608
- ),
609
- );
610
- },
611
- }).pipe(
612
- Effect.tap(() => Deferred.succeed(completed, undefined)),
613
- Effect.provide(Logger.layer([])),
614
- Effect.provideService(Clock.Clock, clockWithBackwardWallJump),
615
- ),
616
- );
617
- yield* Deferred.await(started);
618
- wallTime = -60_000;
619
- yield* TestClock.adjust("5 seconds");
620
- assert.isTrue(yield* Deferred.isDone(completed), "finishes within the shared budget");
621
- assert.isFalse(yield* Fiber.join(install));
622
- assert.deepEqual(profileShells, ["pwsh.exe"]);
623
- assert.equal(env.PATH, "C:\\NoProfile\\Bin;C:\\Windows\\System32");
624
- }),
625
- );
626
-
627
- it.effect("falls back to Windows PowerShell when pwsh.exe is not installed", () =>
628
- Effect.gen(function* () {
629
- const env: NodeJS.ProcessEnv = { PATH: "C:\\Windows\\System32" };
630
- const missing = PlatformError.systemError({
631
- _tag: "NotFound",
632
- module: "ChildProcess",
633
- method: "spawn",
634
- pathOrDescriptor: "pwsh.exe",
635
- });
636
-
637
- const prepared = yield* runShellEnvironment({
638
- env,
639
- platform: "win32",
640
- handler: (command) => {
641
- if (command._tag !== "StandardCommand") return "";
642
- if (command.command === "pwsh.exe") return Effect.fail(missing);
643
- return command.args.includes("-NoProfile")
644
- ? envOutput({ PATH: "C:\\Windows\\System32" })
645
- : envOutput({ PATH: "C:\\Profile\\Node;C:\\Windows\\System32" });
646
- },
647
- }).pipe(Effect.provide(Logger.layer([])));
648
-
649
- assert.isTrue(prepared);
650
- assert.equal(env.PATH, "C:\\Profile\\Node;C:\\Windows\\System32");
651
- }),
652
- );
653
-
567
it.effect.each([false, true])(
568
"leaves Windows preparation incomplete when loadProfile=%s fails",
569
(loadProfile) =>
@@ -692,49 +605,6 @@ describe("DesktopShellEnvironment", () => {
605
}),
606
);
607
695
- it.effect("drops earlier AppImage launches' mount dirs from the search paths on linux", () =>
696
- Effect.gen(function* () {
697
- const current = "/var/tmp/.mount_cur";
698
- const env: NodeJS.ProcessEnv = {
699
- SHELL: "/bin/zsh",
700
- APPIMAGE: "/home/me/T3-Code.AppImage",
701
- APPDIR: `${current}/`,
702
- PATH: `${current}/usr/bin:/tmp/.mount_old/usr/bin:/usr/bin`,
703
- LD_LIBRARY_PATH: `/tmp/.mount_old/usr/lib:${current}/usr/lib::/opt/lib`,
704
- XDG_DATA_DIRS: "/tmp/.mount_old/usr/share:/var/tmp/.mount_cur2/usr/share",
705
- };
706
-
707
- yield* runShellEnvironment({
708
- env,
709
- platform: "linux",
710
- handler: () => envOutput({ PATH: "/tmp/.mount_older/usr/bin:/home/me/.local/bin" }),
711
- });
712
-
713
- assert.equal(env.PATH, `/home/me/.local/bin:${current}/usr/bin:/usr/bin`);
714
- assert.equal(env.LD_LIBRARY_PATH, `${current}/usr/lib::/opt/lib`);
715
- assert.equal(env.XDG_DATA_DIRS, undefined);
716
- }),
717
- );
718
-
719
- it.effect("keeps AppImage-looking search paths outside an AppImage launch", () =>
720
- Effect.gen(function* () {
721
- const env: NodeJS.ProcessEnv = {
722
- SHELL: "/bin/zsh",
723
- PATH: "/tmp/.mount_old/usr/bin:/usr/bin",
724
- LD_LIBRARY_PATH: "/tmp/.mount_old/usr/lib",
725
- };
726
-
727
- yield* runShellEnvironment({
728
- env,
729
- platform: "linux",
730
- handler: () => envOutput({ PATH: "/usr/bin" }),
731
- });
732
-
733
- assert.equal(env.PATH, "/usr/bin:/tmp/.mount_old/usr/bin");
734
- assert.equal(env.LD_LIBRARY_PATH, "/tmp/.mount_old/usr/lib");
735
- }),
736
- );
737
-
608
it.effect("prefers login-shell desktop session hints over inherited values on linux", () =>
609
Effect.gen(function* () {
610
const env: NodeJS.ProcessEnv = {
apps/desktop/src/shell/DesktopShellEnvironment.ts
+1
-40
@@ -3,7 +3,6 @@ import {
3
listLoginShellCandidates,
4
setWindowsPath,
5
} from "@t3tools/shared/shell";
6
-import * as Clock from "effect/Clock";
6
import * as Context from "effect/Context";
7
import * as Duration from "effect/Duration";
8
import * as Effect from "effect/Effect";
@@ -119,37 +118,6 @@ const readEnvPath = (env: NodeJS.ProcessEnv): Option.Option<string> =>
118
119
const normalizeRuntimeDir = (value: string): string => value.replace(/\/+$/u, "");
120
122
-const APPIMAGE_SEARCH_PATH_ENV_NAMES = ["PATH", "LD_LIBRARY_PATH", "XDG_DATA_DIRS"] as const;
123
-
124
-// The AppImage runtime mounts each launch at `$TMPDIR/.mount_<id>` and prepends
125
-// it to the search paths above. A launch started from a shell that inherited an
126
-// earlier launch's env carries that mount too, and once it is unmounted every
127
-// spawn that walks PATH (git first of all) fails with ENOTCONN.
128
-const APPIMAGE_MOUNT_ROOT = /^(.*?\/\.mount_[^/]+)(?:\/|$)/u;
129
-
130
-const stripStaleAppImageMounts = (env: NodeJS.ProcessEnv): void => {
131
- if (env.APPIMAGE === undefined && env.APPDIR === undefined) return;
132
- const appDir = env.APPDIR === undefined ? undefined : normalizeRuntimeDir(env.APPDIR);
133
- for (const name of APPIMAGE_SEARCH_PATH_ENV_NAMES) {
134
- const value = env[name];
135
- if (value === undefined) continue;
136
- // glibc's loader also splits LD_LIBRARY_PATH on `;`.
137
- const segments = value.split(name === "LD_LIBRARY_PATH" ? /[:;]/u : ":");
138
- const kept = segments.filter((segment) => {
139
- const mountRoot = APPIMAGE_MOUNT_ROOT.exec(segment)?.[1];
140
- return mountRoot === undefined || mountRoot === appDir;
141
- });
142
- if (kept.length === segments.length) continue;
143
- if (kept.length === 0) {
144
- delete env[name];
145
- } else {
146
- // An empty segment is the current dir to the loader and to PATH lookup,
147
- // but a lone one joins to "", which reads as unset.
148
- env[name] = kept.join(":") || ":";
149
- }
150
- }
151
-};
152
-
121
const linuxRuntimeDirCandidates = (
122
env: NodeJS.ProcessEnv,
123
uid: number | undefined,
@@ -371,16 +339,12 @@ const readWindowsEnvironment = Effect.fn("desktop.shellEnvironment.readWindowsEn
339
captureWindowsEnvironmentCommand(names),
340
];
341
374
- const deadline =
375
- (yield* Clock.monotonicTimeNanos) + Duration.toNanosUnsafe(LOGIN_SHELL_TIMEOUT);
342
for (const command of WINDOWS_SHELL_CANDIDATES) {
377
- const remainingNanos = deadline - (yield* Clock.monotonicTimeNanos);
378
- if (remainingNanos <= 0n) break;
343
const output = yield* runCommandOutput({
344
probe: options.loadProfile ? "powershell-profile" : "powershell-no-profile",
345
command,
346
args,
383
- timeout: Duration.nanos(remainingNanos),
347
+ timeout: LOGIN_SHELL_TIMEOUT,
348
});
349
const environment = extractEnvironment(output, names);
350
if (Object.keys(environment).length > 0) {
@@ -459,9 +423,6 @@ const installPosixEnvironment = Effect.fn("desktop.shellEnvironment.installPosix
423
if (Option.isSome(mergedPath)) {
424
config.env.PATH = mergedPath.value;
425
}
462
- // The server, relaunch and updater all inherit process.env, so scrubbing
463
- // here keeps earlier AppImage launches' mounts out of every one of them.
464
- stripStaleAppImageMounts(config.env);
426
if (!config.env.SSH_AUTH_SOCK && shellEnvironment.SSH_AUTH_SOCK) {
427
config.env.SSH_AUTH_SOCK = shellEnvironment.SSH_AUTH_SOCK;
428
}
apps/desktop/src/snapShot/ActiveWindow.test.ts
+13
-128
@@ -28,34 +28,19 @@ function stubMacLookup(stdout: string) {
28
);
29
}
30
31
-function macLookup(
32
- windows: ReadonlyArray<{
33
- id: number;
34
- title: string;
35
- bounds: { x: number; y: number; width: number; height: number };
36
- alpha?: number;
37
- }>,
38
-) {
39
- return JSON.stringify({
40
- owner: {
41
- name: "Editor",
42
- processId: 123,
43
- path: "/Applications/Editor.app",
44
- bundleId: "com.example.editor",
45
- },
46
- windows: windows.map((window) => ({ ...window, alpha: window.alpha ?? 1 })),
47
- });
48
-}
49
-
31
it("parses the frontmost macOS window from the osascript lookup", async () => {
32
stubMacLookup(
52
- macLookup([
53
- {
54
- id: 42,
55
- title: "main.ts",
56
- bounds: { x: 10, y: 20, width: 800, height: 600 },
33
+ JSON.stringify({
34
+ id: 42,
35
+ title: "main.ts",
36
+ bounds: { x: 10, y: 20, width: 800, height: 600 },
37
+ owner: {
38
+ name: "Editor",
39
+ processId: 123,
40
+ path: "/Applications/Editor.app",
41
+ bundleId: "com.example.editor",
42
},
58
- ]) + "\n",
43
+ }) + "\n",
44
);
45
46
const window = await activeWindow("darwin");
@@ -81,15 +66,10 @@ it("parses the frontmost macOS window from the osascript lookup", async () => {
66
it("omits an empty macOS bundle identifier", async () => {
67
stubMacLookup(
68
JSON.stringify({
69
+ id: 7,
70
+ title: "",
71
+ bounds: { x: 0, y: 0, width: 1, height: 1 },
72
owner: { name: "cli", processId: 9, path: "", bundleId: "" },
85
- windows: [
86
- {
87
- id: 7,
88
- title: "",
89
- bounds: { x: 0, y: 0, width: 1, height: 1 },
90
- alpha: 1,
91
- },
92
- ],
73
}),
74
);
75
@@ -98,107 +78,12 @@ it("omits an empty macOS bundle identifier", async () => {
78
assert.deepEqual(window?.owner, { name: "cli", processId: 9, path: "" });
79
});
80
101
-it.each([
102
- {
103
- name: "transparent and untitled helpers",
104
- helpers: [
105
- {
106
- id: 1,
107
- title: "",
108
- bounds: { x: -1, y: -44, width: 1_680, height: 44 },
109
- alpha: 0,
110
- },
111
- { id: 2, title: "", bounds: { x: 0, y: 0, width: 1_680, height: 68 } },
112
- ],
113
- content: {
114
- id: 3,
115
- title: "Document",
116
- bounds: { x: 0, y: 0, width: 1_680, height: 1_050 },
117
- },
118
- },
119
- {
120
- name: "Chrome strips stacked above the content window",
121
- helpers: [
122
- { id: 75, title: "", bounds: { x: 0, y: 39, width: 1_800, height: 41 } },
123
- { id: 74, title: "", bounds: { x: 0, y: 80, width: 1_800, height: 81 } },
124
- { id: 1691, title: "", bounds: { x: 0, y: 39, width: 1_800, height: 158 } },
125
- ],
126
- content: {
127
- id: 71,
128
- title: "(10) Video - YouTube",
129
- bounds: { x: 0, y: 161, width: 1_800, height: 1_008 },
130
- },
131
- },
132
- {
133
- name: "a smaller front window's strips with a larger background window",
134
- helpers: [
135
- { id: 75, title: "", bounds: { x: 100, y: 139, width: 1_200, height: 41 } },
136
- { id: 74, title: "", bounds: { x: 100, y: 180, width: 1_200, height: 81 } },
137
- ],
138
- content: {
139
- id: 71,
140
- title: "Video - YouTube",
141
- bounds: { x: 100, y: 261, width: 1_200, height: 700 },
142
- },
143
- background: [
144
- { id: 80, title: "Other document", bounds: { x: 0, y: 39, width: 1_800, height: 1_130 } },
145
- ],
146
- },
147
-])("selects the content window behind $name", async ({ helpers, content, background = [] }) => {
148
- stubMacLookup(macLookup([...helpers, content, ...background]));
149
-
150
- const window = await activeWindow("darwin");
151
-
152
- assert.strictEqual(window?.id, content.id);
153
- assert.deepEqual(window?.bounds, content.bounds);
154
-});
155
-
156
-it.each([
157
- { name: "untitled dialog", title: "", bounds: { x: 300, y: 200, width: 400, height: 240 } },
158
- { name: "titled palette", title: "Palette", bounds: { x: 0, y: 0, width: 800, height: 50 } },
159
- { name: "offset untitled strip", title: "", bounds: { x: 100, y: 100, width: 800, height: 50 } },
160
- { name: "tall untitled window", title: "", bounds: { x: 0, y: 0, width: 800, height: 900 } },
161
-])("keeps a frontmost $name ahead of a larger document", async ({ title, bounds }) => {
162
- stubMacLookup(
163
- macLookup([
164
- { id: 1, title, bounds },
165
- { id: 2, title: "Document", bounds: { x: 0, y: 0, width: 800, height: 1_000 } },
166
- ]),
167
- );
168
-
169
- const window = await activeWindow("darwin");
170
-
171
- assert.strictEqual(window?.id, 1);
172
- assert.deepEqual(window?.bounds, bounds);
173
-});
174
-
175
-it("keeps an untitled content window ahead of a much taller background window", async () => {
176
- const bounds = { x: 0, y: 0, width: 800, height: 900 };
177
- stubMacLookup(
178
- macLookup([
179
- { id: 1, title: "", bounds },
180
- { id: 2, title: "Background document", bounds: { x: 0, y: 0, width: 800, height: 4_000 } },
181
- ]),
182
- );
183
-
184
- const window = await activeWindow("darwin");
185
-
186
- assert.strictEqual(window?.id, 1);
187
- assert.deepEqual(window?.bounds, bounds);
188
-});
189
-
81
it("resolves undefined when macOS has no frontmost window", async () => {
82
stubMacLookup("\n");
83
84
assert.isUndefined(await activeWindow("darwin"));
85
});
86
196
-it("resolves undefined when macOS reports no visible windows", async () => {
197
- stubMacLookup(macLookup([]));
198
-
199
- assert.isUndefined(await activeWindow("darwin"));
200
-});
201
-
87
it("composes the Windows foreground window from Win32 calls", async () => {
88
const api = {
89
getForegroundWindow: vi.fn(() => 0x1_f123_4567n),
apps/desktop/src/snapShot/ActiveWindow.ts
+24
-63
@@ -30,32 +30,23 @@ export type ActiveWindow = {
30
31
const MAC_LOOKUP_TIMEOUT_MS = 5_000;
32
33
-const MAC_HELPER_STRIP_MAX_THICKNESS_RATIO = 0.25;
34
-
35
-const MacActiveWindowLookup = Schema.Struct({
33
+const MacActiveWindow = Schema.Struct({
34
+ id: Schema.Number,
35
+ title: Schema.String,
36
+ bounds: Schema.Struct({
37
+ x: Schema.Number,
38
+ y: Schema.Number,
39
+ width: Schema.Number,
40
+ height: Schema.Number,
41
+ }),
42
owner: Schema.Struct({
43
name: Schema.String,
44
processId: Schema.Number,
45
path: Schema.String,
46
bundleId: Schema.String,
47
}),
42
- windows: Schema.Array(
43
- Schema.Struct({
44
- id: Schema.Number,
45
- title: Schema.String,
46
- bounds: Schema.Struct({
47
- x: Schema.Number,
48
- y: Schema.Number,
49
- width: Schema.Number,
50
- height: Schema.Number,
51
- }),
52
- alpha: Schema.Number,
53
- }),
54
- ),
48
});
56
-const decodeMacActiveWindowLookup = Schema.decodeUnknownSync(
57
- Schema.fromJsonString(MacActiveWindowLookup),
58
-);
49
+const decodeMacActiveWindow = Schema.decodeUnknownSync(Schema.fromJsonString(MacActiveWindow));
50
51
const MAC_LOOKUP_SCRIPT = `
52
ObjC.import("CoreGraphics");
@@ -64,38 +55,30 @@ function run() {
55
const app = $.NSWorkspace.sharedWorkspace.frontmostApplication;
56
if (app.isNil()) return "";
57
const pid = app.processIdentifier;
67
- let ownerName = String(app.localizedName.js || "");
58
const list = $.CGWindowListCopyWindowInfo(
59
$.kCGWindowListOptionOnScreenOnly | $.kCGWindowListExcludeDesktopElements,
60
$.kCGNullWindowID,
61
);
62
$.CFMakeCollectable(list);
63
const count = $.CFArrayGetCount(list);
74
- const windows = [];
64
for (let i = 0; i < count; i++) {
65
const w = ObjC.castRefToObject($.CFArrayGetValueAtIndex(list, i));
66
if (w.objectForKey("kCGWindowOwnerPID").js !== pid) continue;
67
if (w.objectForKey("kCGWindowLayer").js !== 0) continue;
79
- if (!ownerName) {
80
- ownerName = String(ObjC.unwrap(w.objectForKey("kCGWindowOwnerName")) || "");
81
- }
68
const b = ObjC.deepUnwrap(w.objectForKey("kCGWindowBounds"));
83
- windows.push({
69
+ return JSON.stringify({
70
id: w.objectForKey("kCGWindowNumber").js,
71
title: String(ObjC.unwrap(w.objectForKey("kCGWindowName")) || ""),
72
bounds: { x: b.X, y: b.Y, width: b.Width, height: b.Height },
87
- alpha: w.objectForKey("kCGWindowAlpha").js,
73
+ owner: {
74
+ name: String(app.localizedName.js || ObjC.unwrap(w.objectForKey("kCGWindowOwnerName")) || ""),
75
+ processId: pid,
76
+ path: String(app.bundleURL.path.js || ""),
77
+ bundleId: String(app.bundleIdentifier.js || ""),
78
+ },
79
});
80
}
90
- return JSON.stringify({
91
- owner: {
92
- name: ownerName,
93
- processId: pid,
94
- path: String(app.bundleURL.path.js || ""),
95
- bundleId: String(app.bundleIdentifier.js || ""),
96
- },
97
- windows,
98
- });
81
+ return "";
82
}`;
83
84
function runMacLookup(): Promise<string> {
@@ -103,7 +86,7 @@ function runMacLookup(): Promise<string> {
86
NodeChildProcess.execFile(
87
"/usr/bin/osascript",
88
["-l", "JavaScript", "-e", MAC_LOOKUP_SCRIPT],
106
- { timeout: MAC_LOOKUP_TIMEOUT_MS, maxBuffer: 1024 * 1024 },
89
+ { timeout: MAC_LOOKUP_TIMEOUT_MS, maxBuffer: 64 * 1024 },
90
(error, stdout) => {
91
if (error) reject(error);
92
else resolve(stdout);
@@ -115,39 +98,17 @@ function runMacLookup(): Promise<string> {
98
async function macActiveWindow(): Promise<ActiveWindow | undefined> {
99
const output = (await runMacLookup()).trim();
100
if (!output) return undefined;
118
- const lookup = decodeMacActiveWindowLookup(output);
119
- const visible = lookup.windows.filter(
120
- (window) => window.alpha > 0 && window.bounds.width > 0 && window.bounds.height > 0,
121
- );
122
- // Helpers belong to the content behind them, which may not be the app's largest window.
123
- const window = visible.find((candidate, index) => {
124
- if (candidate.title.trim() !== "") return true;
125
- const bounds = candidate.bounds;
126
- return !visible.some((reference, referenceIndex) => {
127
- if (referenceIndex <= index) return false;
128
- return (
129
- (bounds.x === reference.bounds.x &&
130
- bounds.width === reference.bounds.width &&
131
- bounds.height <= bounds.width * MAC_HELPER_STRIP_MAX_THICKNESS_RATIO &&
132
- bounds.height <= reference.bounds.height * MAC_HELPER_STRIP_MAX_THICKNESS_RATIO) ||
133
- (bounds.y === reference.bounds.y &&
134
- bounds.height === reference.bounds.height &&
135
- bounds.width <= bounds.height * MAC_HELPER_STRIP_MAX_THICKNESS_RATIO &&
136
- bounds.width <= reference.bounds.width * MAC_HELPER_STRIP_MAX_THICKNESS_RATIO)
137
- );
138
- });
139
- });
140
- if (!window) return undefined;
101
+ const window = decodeMacActiveWindow(output);
102
return {
103
platform: "macos",
104
id: window.id,
105
title: window.title,
106
bounds: window.bounds,
107
owner: {
147
- name: lookup.owner.name,
148
- processId: lookup.owner.processId,
149
- path: lookup.owner.path,
150
- ...(lookup.owner.bundleId ? { bundleId: lookup.owner.bundleId } : {}),
108
+ name: window.owner.name,
109
+ processId: window.owner.processId,
110
+ path: window.owner.path,
111
+ ...(window.owner.bundleId ? { bundleId: window.owner.bundleId } : {}),
112
},
113
};
114
}
apps/desktop/src/updates/DesktopUpdates.test.ts
-110
@@ -273,116 +273,6 @@ describe("DesktopUpdates", () => {
273
).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
274
});
275
276
- it.effect("reuses an update an earlier launch downloaded once its check finishes", () => {
277
- const releaseCheck = Deferred.makeUnsafe<void>();
278
- const harness = makeHarness({
279
- cachedDownloadSha512: "sha-1.2.4",
280
- // electron-updater reports update-available while the check is running.
281
- checkForUpdates: Effect.sync(() =>
282
- harness.emit("update-available", {
283
- version: "1.2.4",
284
- files: [{ url: "T3-Code-1.2.4.zip", sha512: "sha-1.2.4" }],
285
- }),
286
- ).pipe(Effect.andThen(Deferred.await(releaseCheck))),
287
- downloadUpdate: Effect.sync(() => harness.emit("update-downloaded", { version: "1.2.4" })),
288
- });
289
-
290
- return Effect.scoped(
291
- Effect.gen(function* () {
292
- const updates = yield* DesktopUpdates.DesktopUpdates;
293
- yield* updates.configure;
294
-
295
- const check = yield* Effect.forkChild(updates.check("startup"));
296
- yield* flushCallbacks;
297
- assert.equal(harness.downloadCount(), 0);
298
- assert.equal((yield* updates.getState).status, "available");
299
-
300
- yield* Deferred.succeed(releaseCheck, undefined);
301
- yield* Fiber.join(check);
302
- yield* flushCallbacks;
303
-
304
- assert.equal(harness.downloadCount(), 1);
305
- const state = yield* updates.getState;
306
- assert.equal(state.status, "downloaded");
307
- assert.equal(state.downloadedVersion, "1.2.4");
308
- }),
309
- ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
310
- });
311
-
312
- it.effect.each([
313
- { name: "a newer release", cachedDownloadSha512: "older-release" },
314
- { name: "an interrupted download", cachedFileExists: false },
315
- { name: "unfinished metadata", cachedDownloadInfo: "{" },
316
- ])("keeps $name click-to-download", (cache) => {
317
- const harness = makeHarness({ cachedDownloadSha512: "release-sha", ...cache });
318
-
319
- return Effect.scoped(
320
- Effect.gen(function* () {
321
- const updates = yield* DesktopUpdates.DesktopUpdates;
322
- yield* updates.configure;
323
- harness.emit("update-available", {
324
- version: "1.2.5",
325
- files: [{ url: "T3-Code-1.2.5.zip", sha512: "release-sha" }],
326
- });
327
- yield* flushCallbacks;
328
-
329
- assert.equal(harness.downloadCount(), 0);
330
- assert.equal((yield* updates.getState).status, "available");
331
- assert.isTrue((yield* updates.download).accepted);
332
- assert.equal(harness.downloadCount(), 1);
333
- }),
334
- ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
335
- });
336
-
337
- it.effect.each(["quitting", "newer release", "no longer available"] as const)(
338
- "abandons pending cache recovery after %s",
339
- (change) => {
340
- const releaseCheck = Deferred.makeUnsafe<void>();
341
- const harness = makeHarness({
342
- cachedDownloadSha512: "cached-release",
343
- checkForUpdates: Effect.sync(() =>
344
- harness.emit("update-available", {
345
- version: "1.2.4",
346
- files: [{ url: "T3-Code-1.2.4.zip", sha512: "cached-release" }],
347
- }),
348
- ).pipe(Effect.andThen(Deferred.await(releaseCheck))),
349
- });
350
-
351
- return Effect.scoped(
352
- Effect.gen(function* () {
353
- const updates = yield* DesktopUpdates.DesktopUpdates;
354
- yield* updates.configure;
355
- const check = yield* Effect.forkChild(updates.check("startup"));
356
- yield* flushCallbacks;
357
- assert.equal((yield* updates.getState).status, "available");
358
- assert.equal(harness.downloadCount(), 0);
359
-
360
- if (change === "quitting") {
361
- const desktop = yield* DesktopState.DesktopState;
362
- yield* Ref.set(desktop.quitting, true);
363
- } else if (change === "newer release") {
364
- harness.emit("update-available", {
365
- version: "1.2.5",
366
- files: [{ url: "T3-Code-1.2.5.zip", sha512: "new-release" }],
367
- });
368
- } else {
369
- harness.emit("update-not-available");
370
- }
371
- yield* flushCallbacks;
372
- yield* Deferred.succeed(releaseCheck, undefined);
373
- yield* Fiber.join(check);
374
- yield* flushCallbacks;
375
-
376
- assert.equal(harness.downloadCount(), 0);
377
- assert.equal(
378
- (yield* updates.getState).status,
379
- change === "no longer available" ? "up-to-date" : "available",
380
- );
381
- }),
382
- ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
383
- },
384
- );
385
-
276
it.effect("preserves a queued installer when the feed has no update", () => {
277
const harness = makeHarness();
278
apps/desktop/src/updates/DesktopUpdates.ts
+1
-88
@@ -68,17 +68,8 @@ const UpdateInfo = Schema.Struct({
68
// fail the decode and block the update state transition. The shape is
69
// validated defensively in normalizeDesktopUpdateReleaseNotes.
70
releaseNotes: Schema.optional(Schema.Unknown),
71
- files: Schema.optional(Schema.Unknown),
71
});
72
74
-const ReleaseFile = Schema.Struct({ url: Schema.String, sha512: Schema.String });
75
-type ReleaseFile = typeof ReleaseFile.Type;
76
-const ReleaseFiles = Schema.Array(ReleaseFile);
77
-
78
-const CachedDownloadInfo = Schema.fromJsonString(
79
- Schema.Struct({ fileName: Schema.String, sha512: Schema.String }),
80
-);
81
-
73
const DownloadProgressInfo = Schema.Struct({
74
percent: Schema.Number,
75
});
@@ -92,8 +83,6 @@ const encodeInstallRecord = Schema.encodeEffect(DesktopUpdateInstallRecord);
83
const decodeAppUpdateYmlConfig = Schema.decodeUnknownEffect(AppUpdateYmlConfig);
84
const decodeUpdateInfo = Schema.decodeUnknownEffect(UpdateInfo);
85
const decodeDownloadProgressInfo = Schema.decodeUnknownEffect(DownloadProgressInfo);
95
-const decodeReleaseFiles = Schema.decodeUnknownOption(ReleaseFiles);
96
-const decodeCachedDownloadInfo = Schema.decodeUnknownEffect(CachedDownloadInfo);
86
87
const currentIsoTimestamp = DateTime.now.pipe(Effect.map(DateTime.formatIso));
88
@@ -346,32 +335,6 @@ function isArm64HostRunningIntelBuild(runtimeInfo: DesktopRuntimeInfo): boolean
335
return runtimeInfo.hostArch === "arm64" && runtimeInfo.appArch === "x64";
336
}
337
349
-// Match electron-updater 6.8.9's MacUpdater.filterFilesForArch and Provider.findFile
350
-// for T3's package feeds. Matching any artifact can trigger a different download.
351
-function selectUpdateFile(
352
- files: ReadonlyArray<ReleaseFile>,
353
- platform: NodeJS.Platform,
354
- isDebPackage: boolean,
355
- runtimeInfo: DesktopRuntimeInfo,
356
-): ReleaseFile | undefined {
357
- let candidates = files;
358
- if (platform === "darwin") {
359
- const isArm64File = (file: ReleaseFile) => file.url.includes("arm64");
360
- const preferArm64 = runtimeInfo.hostArch === "arm64" && files.some(isArm64File);
361
- candidates = files.filter((file) => isArm64File(file) === preferArm64);
362
- }
363
- const extension =
364
- platform === "darwin"
365
- ? ".zip"
366
- : platform === "win32"
367
- ? ".exe"
368
- : isDebPackage
369
- ? ".deb"
370
- : ".appimage";
371
- const packageFiles = candidates.filter((file) => file.url.toLowerCase().endsWith(extension));
372
- return packageFiles.find((file) => file.url.includes(runtimeInfo.appArch)) ?? packageFiles[0];
373
-}
374
-
338
/** @public Service construction is part of the canonical Effect module API. */
339
export const make = Effect.gen(function* () {
340
const config = yield* DesktopConfig.DesktopConfig;
@@ -490,15 +453,6 @@ export const make = Effect.gen(function* () {
453
),
454
);
455
493
- const awaitIdleUpdateAction = Effect.scoped(
494
- Effect.gen(function* () {
495
- const completions = yield* PubSub.subscribe(finishedUpdateActions);
496
- while (Option.isSome(yield* activeUpdateAction)) {
497
- yield* PubSub.take(completions);
498
- }
499
- }),
500
- );
501
-
456
const applyAutoUpdaterChannel = Effect.fn("desktop.updates.applyAutoUpdaterChannel")(function* (
457
channel: DesktopUpdateChannel,
458
) {
@@ -801,7 +755,7 @@ export const make = Effect.gen(function* () {
755
yield* Ref.set(installRunningBackendsRef, runningInstances);
756
yield* Effect.forEach(
757
instances,
804
- (instance) => instance.stop({ timeout: Duration.seconds(45) }),
758
+ (instance) => instance.stop({ timeout: Duration.seconds(5) }),
759
{ concurrency: "unbounded" },
760
);
761
yield* electronUpdater.quitAndInstall({
@@ -899,44 +853,6 @@ export const make = Effect.gen(function* () {
853
);
854
}).pipe(Effect.withSpan("desktop.updates.startPollers"));
855
902
- const cachedDownloadSha512 = Effect.gen(function* () {
903
- const pendingDirectory = yield* electronUpdater.pendingDownloadDirectory;
904
- if (Option.isNone(pendingDirectory)) return Option.none<string>();
905
- const info = yield* fileSystem
906
- .readFileString(environment.path.join(pendingDirectory.value, "update-info.json"))
907
- .pipe(Effect.flatMap(decodeCachedDownloadInfo));
908
- const fileExists = yield* fileSystem.exists(
909
- environment.path.join(pendingDirectory.value, info.fileName),
910
- );
911
- return fileExists ? Option.some(info.sha512) : Option.none<string>();
912
- }).pipe(Effect.orElseSucceed(() => Option.none<string>()));
913
-
914
- // downloadUpdate validates the cached bytes and restores install readiness.
915
- // Only resume the selected artifact; a cache miss would start a network download.
916
- const resumeCachedDownload = Effect.fn("desktop.updates.resumeCachedDownload")(function* (
917
- version: string,
918
- files: unknown,
919
- ) {
920
- const releaseFiles = decodeReleaseFiles(files);
921
- if (Option.isNone(releaseFiles)) return;
922
- const updateFile = selectUpdateFile(
923
- releaseFiles.value,
924
- environment.platform,
925
- isDebPackage,
926
- environment.runtimeInfo,
927
- );
928
- if (!updateFile) return;
929
- const cachedSha512 = yield* cachedDownloadSha512;
930
- if (Option.isNone(cachedSha512) || updateFile.sha512 !== cachedSha512.value) return;
931
-
932
- // update-available arrives while its check still holds the action reservation.
933
- yield* awaitIdleUpdateAction;
934
- if (yield* Ref.get(desktopState.quitting)) return;
935
- const state = yield* Ref.get(updateStateRef);
936
- if (state.status !== "available" || state.availableVersion !== version) return;
937
- yield* downloadAvailableUpdate;
938
- });
939
-
856
const handleUpdateAvailable = Effect.fn("desktop.updates.handleUpdateAvailable")(function* (
857
raw: unknown,
858
) {
@@ -976,9 +892,6 @@ export const make = Effect.gen(function* () {
892
releaseNoteGroups: releaseNotes.length,
893
omittedReleaseCount,
894
});
979
- if (state.downloadedVersion !== info.version) {
980
- yield* resumeCachedDownload(info.version, info.files);
981
- }
895
}),
896
),
897
Effect.catchCause((cause) => {
apps/desktop/src/updates/updatesTestHarness.ts
+12
-46
@@ -26,13 +26,6 @@ export interface UpdatesHarnessOptions {
26
readonly setUpdateChannelError?: DesktopAppSettings.DesktopSettingsWriteError;
27
readonly setDisableDifferentialDownload?: Effect.Effect<void>;
28
readonly downloadUpdate?: Effect.Effect<void>;
29
- /** sha512 of a download an earlier launch left in electron-updater's cache. */
30
- readonly cachedDownloadSha512?: string;
31
- readonly cachedDownloadInfo?: string;
32
- readonly cachedFileExists?: boolean;
33
- readonly updater?: ElectronUpdater.ElectronUpdater["Service"];
34
- readonly fileSystem?: FileSystem.FileSystem;
35
- readonly runningUnderArm64Translation?: boolean;
29
readonly quitAndInstall?: Effect.Effect<void, ElectronUpdater.ElectronUpdaterQuitAndInstallError>;
30
readonly stopBackend?: Effect.Effect<void>;
31
readonly startBackend?: Effect.Effect<void>;
@@ -44,8 +37,6 @@ export interface UpdatesHarnessOptions {
37
readonly installRecord?: string | undefined;
38
}
39
47
-const PENDING_DOWNLOAD_DIRECTORY = "/cache/t3code-updater/pending";
48
-
40
export function makeHarness(options: UpdatesHarnessOptions = {}) {
41
let checkCount = 0;
42
let quitAndInstallCount = 0;
@@ -74,7 +65,7 @@ export function makeHarness(options: UpdatesHarnessOptions = {}) {
65
}
66
};
67
77
- const stubUpdater = {
68
+ const layerUpdater = Layer.succeed(ElectronUpdater.ElectronUpdater, {
69
setFeedURL: (options) =>
70
Effect.sync(() => {
71
feedUrls.push(options);
@@ -93,11 +84,6 @@ export function makeHarness(options: UpdatesHarnessOptions = {}) {
84
fullChangelog = value;
85
}),
86
setDisableDifferentialDownload: () => options.setDisableDifferentialDownload ?? Effect.void,
96
- pendingDownloadDirectory: Effect.succeed(
97
- options.cachedDownloadSha512 === undefined
98
- ? Option.none()
99
- : Option.some(PENDING_DOWNLOAD_DIRECTORY),
100
- ),
87
checkForUpdates: Effect.sync(() => {
88
checkCount += 1;
89
}).pipe(Effect.andThen(options.checkForUpdates ?? Effect.void)),
@@ -119,11 +105,7 @@ export function makeHarness(options: UpdatesHarnessOptions = {}) {
105
removeListener(eventName, listener as unknown as (...args: readonly unknown[]) => void);
106
}),
107
).pipe(Effect.asVoid),
122
- } satisfies ElectronUpdater.ElectronUpdater["Service"];
123
- const layerUpdater = Layer.succeed(
124
- ElectronUpdater.ElectronUpdater,
125
- options.updater ?? stubUpdater,
126
- );
108
+ } satisfies ElectronUpdater.ElectronUpdater["Service"]);
109
110
const layerWindow = Layer.succeed(ElectronWindow.ElectronWindow, {
111
create: () => Effect.die("unexpected BrowserWindow creation"),
@@ -179,7 +161,7 @@ export function makeHarness(options: UpdatesHarnessOptions = {}) {
161
appPath: "/repo",
162
isPackaged: true,
163
resourcesPath: "/missing/resources",
182
- runningUnderArm64Translation: options.runningUnderArm64Translation ?? false,
164
+ runningUnderArm64Translation: false,
165
}).pipe(
166
Layer.provide(
167
Layer.mergeAll(
@@ -236,7 +218,7 @@ export function makeHarness(options: UpdatesHarnessOptions = {}) {
218
let previousInstallRecord = options.installRecord;
219
const isInstallRecord = (path: string) =>
220
path.endsWith(DesktopUpdates.DESKTOP_UPDATE_INSTALL_RECORD_FILE);
239
- const stubFileSystem = FileSystem.layerNoop({
221
+ const layerFileSystem = FileSystem.layerNoop({
222
readFileString: (path) => {
223
const installRecord = isInstallRecord(path)
224
? (installRecords.get(path) ?? previousInstallRecord)
@@ -244,28 +226,15 @@ export function makeHarness(options: UpdatesHarnessOptions = {}) {
226
if (installRecord !== undefined) return Effect.succeed(installRecord);
227
return path === "/missing/resources/package-type" && options.packageType !== undefined
228
? Effect.succeed(options.packageType)
247
- : path === `${PENDING_DOWNLOAD_DIRECTORY}/update-info.json` &&
248
- options.cachedDownloadSha512 !== undefined
249
- ? Effect.succeed(
250
- options.cachedDownloadInfo ??
251
- JSON.stringify({
252
- fileName: "update.zip",
253
- sha512: options.cachedDownloadSha512,
254
- }),
255
- )
256
- : Effect.fail(
257
- PlatformError.systemError({
258
- module: "FileSystem",
259
- method: "readFileString",
260
- _tag: "NotFound",
261
- pathOrDescriptor: path,
262
- }),
263
- );
229
+ : Effect.fail(
230
+ PlatformError.systemError({
231
+ module: "FileSystem",
232
+ method: "readFileString",
233
+ _tag: "NotFound",
234
+ pathOrDescriptor: path,
235
+ }),
236
+ );
237
},
265
- exists: (path) =>
266
- Effect.succeed(
267
- options.cachedFileExists !== false && path === `${PENDING_DOWNLOAD_DIRECTORY}/update.zip`,
268
- ),
238
makeDirectory: () => Effect.void,
239
writeFileString: (path, data) =>
240
Effect.sync(() => {
@@ -280,9 +249,6 @@ export function makeHarness(options: UpdatesHarnessOptions = {}) {
249
}),
250
});
251
283
- const layerFileSystem = options.fileSystem
284
- ? Layer.succeed(FileSystem.FileSystem, options.fileSystem)
285
- : stubFileSystem;
252
const layer = DesktopUpdates.layer.pipe(
253
Layer.provide(layerFileSystem),
254
Layer.provideMerge(layerUpdater),
apps/desktop/src/window/DesktopWindow.test.ts
+9
-205
@@ -27,8 +27,6 @@ vi.mock("electron", async (importOriginal) => ({
27
setUserAgent: vi.fn(),
28
})),
29
},
30
- BrowserWindow: { getAllWindows: () => [], getFocusedWindow: () => null },
31
- app: { setBadgeCount: vi.fn() },
30
screen: {
31
getAllDisplays: vi.fn(() => [
32
{
@@ -38,42 +36,6 @@ vi.mock("electron", async (importOriginal) => ({
36
},
37
}));
38
41
-import * as NetService from "@t3tools/shared/Net";
42
-import { HttpClient } from "effect/http";
43
-import * as BrowserImport from "../preview/BrowserImport/BrowserImport.ts";
44
-import * as DesktopBackendConfiguration from "../backend/DesktopBackendConfiguration.ts";
45
-import * as DesktopLocalEnvironmentAuth from "../backend/DesktopLocalEnvironmentAuth.ts";
46
-import * as DesktopCliCommand from "../app/DesktopCliCommand.ts";
47
-import * as DesktopConnectionCatalogStore from "../app/DesktopConnectionCatalogStore.ts";
48
-import * as DesktopWebLinks from "../app/DesktopWebLinks.ts";
49
-import * as DesktopSshEnvironment from "../ssh/DesktopSshEnvironment.ts";
50
-import * as DesktopSshPasswordPrompts from "../ssh/DesktopSshPasswordPrompts.ts";
51
-import * as DesktopWslEnvironment from "../wsl/DesktopWslEnvironment.ts";
52
-import * as MacPermissions from "../permissions/MacPermissions.ts";
53
-
54
-import * as HostProcess from "@t3tools/shared/HostProcess";
55
-import * as Stream from "effect/Stream";
56
-import * as DesktopApp from "../app/DesktopApp.ts";
57
-import * as DesktopAppActivation from "../app/DesktopAppActivation.ts";
58
-import * as DesktopAppIdentity from "../app/DesktopAppIdentity.ts";
59
-import * as DesktopClerk from "../app/DesktopClerk.ts";
60
-import * as DesktopLegacyLocalStorage from "../app/DesktopLegacyLocalStorage.ts";
61
-import * as DesktopLifecycle from "../app/DesktopLifecycle.ts";
62
-import * as DesktopLinuxUrlHandler from "../app/DesktopLinuxUrlHandler.ts";
63
-import * as DesktopPreReadyPlatform from "../app/DesktopPreReadyPlatform.ts";
64
-import * as DesktopShutdown from "../app/DesktopShutdown.ts";
65
-import * as DesktopBackendPool from "../backend/DesktopBackendPool.ts";
66
-import * as ElectronDialog from "../electron/ElectronDialog.ts";
67
-import * as ElectronProtocol from "../electron/ElectronProtocol.ts";
68
-import * as ElectronSafeStorage from "../electron/ElectronSafeStorage.ts";
69
-import * as DesktopIpc from "../ipc/DesktopIpc.ts";
70
-import * as DesktopSnapShot from "../snapShot/DesktopSnapShot.ts";
71
-import * as DesktopShellEnvironment from "../shell/DesktopShellEnvironment.ts";
72
-import * as DesktopTelemetryPublisher from "../telemetry/DesktopTelemetryPublisher.ts";
73
-import * as DesktopUpdates from "../updates/DesktopUpdates.ts";
74
-import * as DesktopApplicationMenu from "./DesktopApplicationMenu.ts";
75
-import * as DesktopWslBackend from "../wsl/DesktopWslBackend.ts";
76
-
39
import * as DesktopAssets from "../app/DesktopAssets.ts";
40
import * as DesktopConfig from "../app/DesktopConfig.ts";
41
import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
@@ -170,7 +132,6 @@ function makeFakeBrowserWindow() {
132
133
return {
134
window: window as unknown as Electron.BrowserWindow,
173
- close: window.close,
135
getBounds: window.getBounds,
136
getNormalBounds: window.getNormalBounds,
137
isDestroyed: window.isDestroyed,
@@ -392,10 +353,7 @@ function layerTest(input: {
353
);
354
}
355
395
-const makeSplashScenario = (
396
- createOutcomes: readonly (Electron.BrowserWindow | null)[],
397
- settings = DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS,
398
-) =>
356
+const makeSplashScenario = (createOutcomes: readonly (Electron.BrowserWindow | null)[]) =>
357
Effect.gen(function* () {
358
const createdWindows = yield* Ref.make<Electron.BrowserWindow[]>([]);
359
const createCalls = yield* Ref.make(0);
@@ -461,7 +419,7 @@ const makeSplashScenario = (
419
} satisfies ElectronWindow.ElectronWindow["Service"];
420
421
const layer = DesktopWindow.layer.pipe(
464
- Layer.provideMerge(
422
+ Layer.provide(
423
Layer.mergeAll(
424
layerDesktopAssets,
425
Layer.succeed(DesktopRendererHistory.DesktopRendererHistory, {
@@ -470,7 +428,7 @@ const makeSplashScenario = (
428
shutdown: Effect.void,
429
}),
430
layerDesktopEnvironment,
473
- DesktopAppSettings.layerTest(settings),
431
+ DesktopAppSettings.layerTest(),
432
layerDesktopClientSettings,
433
layerDesktopServerExposure,
434
DesktopState.layer,
@@ -484,17 +442,11 @@ const makeSplashScenario = (
442
layerElectronTheme,
443
Layer.succeed(ElectronWindow.ElectronWindow, electronWindowShape),
444
Layer.mock(PreviewPasskeys.PreviewPasskeys)({
487
- configure: Effect.void,
445
bridgeEnabled: false,
446
installSessionHandlers: () => {},
447
attachGuest: () => () => {},
448
}),
449
Layer.mock(PreviewManager.PreviewManager)({
493
- subscribeStateChanges: () => Effect.void,
494
- subscribeRecordingFrames: () => Effect.void,
495
- subscribeRecordingInputs: () => Effect.void,
496
- subscribePointerEvents: () => Effect.void,
497
- subscribeOpenLinks: () => Effect.void,
450
getBrowserSession: () => Effect.succeed({} as Electron.Session),
451
setMainWindow: () => Effect.void,
452
isBrowserPartition: (partition) => partition.startsWith("persist:t3code-preview-"),
@@ -511,152 +463,6 @@ const captureOne = DesktopSnapShotId.make("11111111-1111-4111-8111-111111111111"
463
const captureTwo = DesktopSnapShotId.make("22222222-2222-4222-8222-222222222222");
464
465
describe("DesktopWindow", () => {
514
- it.effect.each([
515
- { mode: "native", localEnvironmentEnabled: true, wslBackendEnabled: false, wslOnly: false },
516
- { mode: "WSL-only", localEnvironmentEnabled: true, wslBackendEnabled: true, wslOnly: true },
517
- { mode: "dual", localEnvironmentEnabled: true, wslBackendEnabled: true, wslOnly: false },
518
- { mode: "disabled", localEnvironmentEnabled: false, wslBackendEnabled: false, wslOnly: false },
519
- ])("hands startup from the splash to the main window in $mode mode", (settings) =>
520
- Effect.gen(function* () {
521
- const splash = makeFakeBrowserWindow();
522
- const main = makeFakeBrowserWindow();
523
- const scenario = yield* makeSplashScenario(
524
- settings.localEnvironmentEnabled ? [splash.window, main.window] : [main.window],
525
- { ...DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS, ...settings },
526
- );
527
- const bootstrapped = yield* Deferred.make<void>();
528
- const windowsAtBackendStart: number[] = [];
529
- const primary = {
530
- id: DesktopBackendPool.PRIMARY_INSTANCE_ID,
531
- label: Effect.succeed("Primary"),
532
- start: Ref.get(scenario.createCalls).pipe(
533
- Effect.tap((count) => Effect.sync(() => windowsAtBackendStart.push(count))),
534
- Effect.asVoid,
535
- ),
536
- stop: () => Effect.void,
537
- currentConfig: Effect.succeedNone,
538
- snapshot: Effect.never,
539
- waitForReady: () => Effect.succeed(false),
540
- } satisfies DesktopBackendPool.DesktopBackendInstance;
541
- const startupLayer = Layer.mergeAll(
542
- // IPC registration captures these services but startup does not invoke their handlers.
543
- Layer.mock(BrowserImport.BrowserImport)({}),
544
- Layer.mock(DesktopBackendConfiguration.DesktopBackendConfiguration)({}),
545
- Layer.mock(DesktopLocalEnvironmentAuth.DesktopLocalEnvironmentAuth)({}),
546
- Layer.mock(DesktopCliCommand.DesktopCliCommand)({}),
547
- Layer.mock(DesktopConnectionCatalogStore.DesktopConnectionCatalogStore)({}),
548
- Layer.mock(DesktopWebLinks.DesktopWebLinks)({}),
549
- Layer.mock(DesktopSshEnvironment.DesktopSshEnvironment)({}),
550
- Layer.mock(DesktopSshPasswordPrompts.DesktopSshPasswordPrompts)({}),
551
- Layer.mock(DesktopWslEnvironment.DesktopWslEnvironment)({}),
552
- Layer.mock(MacPermissions.MacPermissions)({}),
553
- Layer.succeed(
554
- HttpClient.HttpClient,
555
- HttpClient.make(() => Effect.die("unexpected HTTP request")),
556
- ),
557
- Layer.mock(NetService.NetService)({}),
558
- Layer.mock(ElectronApp.ElectronApp)({
559
- whenReady: Effect.void,
560
- setPath: () => Effect.void,
561
- on: () => Effect.void,
562
- }),
563
- Layer.mock(DesktopAppIdentity.DesktopAppIdentity)({
564
- resolveUserDataPath: Effect.succeed("/unused"),
565
- configure: Effect.void,
566
- }),
567
- Layer.mock(DesktopLifecycle.DesktopLifecycle)({ register: Effect.void }),
568
- Layer.mock(DesktopClerk.DesktopClerk)({ configure: Effect.void }),
569
- Layer.mock(DesktopApplicationMenu.DesktopApplicationMenu)({ configure: Effect.void }),
570
- Layer.mock(DesktopLinuxUrlHandler.DesktopLinuxUrlHandler)({ register: Effect.void }),
571
- Layer.mock(DesktopShellEnvironment.DesktopShellEnvironment)({
572
- installIntoProcess: Effect.succeed(true),
573
- }),
574
- Layer.succeed(DesktopPreReadyPlatform.DesktopPreReadyElectronOptions, {
575
- linux: null,
576
- linuxPasswordStoreCommandLine: null,
577
- }),
578
- Layer.mock(ElectronSafeStorage.ElectronSafeStorage)({}),
579
- Layer.mock(ElectronProtocol.ElectronProtocol)({
580
- registerDesktopProtocol: () => Effect.void,
581
- }),
582
- Layer.mock(ElectronDialog.ElectronDialog)({}),
583
- Layer.mock(DesktopIpc.DesktopIpc)({
584
- handle: () => Effect.void,
585
- handleSync: () => Effect.void,
586
- }),
587
- Layer.mock(DesktopLegacyLocalStorage.DesktopLegacyLocalStorage)({
588
- load: () => Effect.void,
589
- }),
590
- Layer.mock(DesktopSnapShot.DesktopSnapShot)({ initialize: Effect.void }),
591
- Layer.mock(DesktopAppActivation.DesktopAppActivation)({ start: Effect.void }),
592
- Layer.mock(DesktopWslBackend.DesktopWslBackend)({ reconcile: Effect.void }),
593
- Layer.mock(DesktopBackendPool.DesktopBackendPool)({
594
- primary: Effect.succeed(primary),
595
- list: Effect.succeed([]),
596
- }),
597
- Layer.mock(DesktopServerExposure.DesktopServerExposure)({
598
- configureFromSettings: () =>
599
- Effect.succeed({
600
- mode: "local-only",
601
- advertisedHost: null,
602
- endpointUrl: null,
603
- tailscaleServeEnabled: false,
604
- tailscaleServePort: 443,
605
- }),
606
- backendConfig: Effect.succeed({
607
- port: 3773,
608
- bindHost: "127.0.0.1",
609
- httpBaseUrl: new URL("http://127.0.0.1:3773"),
610
- tailscaleServeEnabled: false,
611
- tailscaleServePort: 443,
612
- }),
613
- }),
614
- Layer.mock(DesktopUpdates.DesktopUpdates)({
615
- configure: Effect.void,
616
- subscribe: Effect.never,
617
- }),
618
- Layer.mock(DesktopTelemetryPublisher.DesktopTelemetryPublisher)({
619
- updateRequests: Stream.empty,
620
- updateCancellations: Stream.empty,
621
- updateCommits: Stream.empty,
622
- }),
623
- Layer.mock(DesktopShutdown.DesktopShutdown)({
624
- awaitRequest: Deferred.succeed(bootstrapped, undefined).pipe(
625
- Effect.andThen(Effect.never),
626
- ),
627
- markComplete: Effect.void,
628
- }),
629
- Layer.succeed(HostProcess.Platform, "darwin"),
630
- NodeServices.layer,
631
- );
632
- yield* Effect.gen(function* () {
633
- const desktopWindow = yield* DesktopWindow.DesktopWindow;
634
- const app = yield* DesktopApp.program.pipe(Effect.forkScoped);
635
- yield* Effect.raceFirst(Deferred.await(bootstrapped), Fiber.join(app));
636
-
637
- assert.deepEqual(windowsAtBackendStart, settings.localEnvironmentEnabled ? [1] : []);
638
- assert.equal(yield* Ref.get(scenario.createCalls), 1);
639
- if (settings.localEnvironmentEnabled) {
640
- assert.isTrue(Option.isNone(yield* Ref.get(scenario.mainWindow)));
641
- yield* desktopWindow.handleBackendReady(new URL("http://127.0.0.1:3773"));
642
- assert.equal(yield* Ref.get(scenario.createCalls), 2);
643
- }
644
- assert.deepEqual(yield* Ref.get(scenario.mainWindow), Option.some(main.window));
645
- assert.equal(splash.close.mock.calls.length, 0);
646
- const readyToShow = main.windowListeners.get("ready-to-show");
647
- assert.isDefined(readyToShow);
648
- readyToShow();
649
- assert.deepEqual(yield* Ref.get(scenario.revealedWindows), [main.window]);
650
- assert.equal(splash.close.mock.calls.length, settings.localEnvironmentEnabled ? 1 : 0);
651
- readyToShow();
652
- assert.equal(splash.close.mock.calls.length, settings.localEnvironmentEnabled ? 1 : 0);
653
- }).pipe(
654
- Effect.scoped,
655
- Effect.provide(Layer.mergeAll(scenario.layer, startupLayer, DesktopState.layer)),
656
- );
657
- }),
658
- );
659
-
466
it.effect("shows native context menus for browser guests and sign-in popups", () =>
467
Effect.gen(function* () {
468
const host = makeFakeBrowserWindow();
@@ -854,8 +660,6 @@ describe("DesktopWindow", () => {
660
assert.equal(yield* Ref.get(createCount), 1);
661
assert.equal(createdWindowOptions[0]?.width, 1100);
662
assert.equal(createdWindowOptions[0]?.height, 780);
857
- assert.equal(createdWindowOptions[0]?.minWidth, 600);
858
- assert.equal(createdWindowOptions[0]?.minHeight, 620);
663
assert.isUndefined(createdWindowOptions[0]?.x);
664
assert.isUndefined(createdWindowOptions[0]?.y);
665
assert.isTrue(createdWindowOptions[0]?.disableAutoHideCursor);
@@ -1114,7 +918,7 @@ describe("DesktopWindow", () => {
918
createdWindowOptions,
919
desktopSettings: {
920
...DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS,
1117
- mainWindowBounds: { x: 120, y: 80, width: 768, height: 780 },
921
+ mainWindowBounds: { x: 120, y: 80, width: 1320, height: 880 },
922
},
923
});
924
@@ -1122,8 +926,8 @@ describe("DesktopWindow", () => {
926
const desktopWindow = yield* DesktopWindow.DesktopWindow;
927
yield* desktopWindow.handleBackendReady(new URL("http://127.0.0.1:3773"));
928
1125
- assert.equal(createdWindowOptions[0]?.width, 768);
1126
- assert.equal(createdWindowOptions[0]?.height, 780);
929
+ assert.equal(createdWindowOptions[0]?.width, 1320);
930
+ assert.equal(createdWindowOptions[0]?.height, 880);
931
assert.equal(createdWindowOptions[0]?.x, 120);
932
assert.equal(createdWindowOptions[0]?.y, 80);
933
}).pipe(Effect.provide(layer));
@@ -1348,14 +1152,14 @@ describe("DesktopWindow", () => {
1152
move();
1153
yield* TestClock.adjust(250);
1154
1351
- fakeWindow.getBounds.mockReturnValue({ x: 160, y: 100, width: 664, height: 780 });
1155
+ fakeWindow.getBounds.mockReturnValue({ x: 160, y: 100, width: 1360, height: 900 });
1156
resize();
1157
yield* TestClock.adjust(499);
1158
assert.deepEqual(mainWindowBoundsUpdates, []);
1159
1160
yield* TestClock.adjust(1);
1161
yield* Effect.promise(() => Promise.resolve());
1358
- assert.deepEqual(mainWindowBoundsUpdates, [{ x: 160, y: 100, width: 664, height: 780 }]);
1162
+ assert.deepEqual(mainWindowBoundsUpdates, [{ x: 160, y: 100, width: 1360, height: 900 }]);
1163
}).pipe(Effect.provide(layer));
1164
}),
1165
);
@@ -1437,7 +1241,7 @@ describe("DesktopWindow", () => {
1241
it.effect("does not persist bounds that fail the domain schema", () =>
1242
Effect.gen(function* () {
1243
const fakeWindow = makeFakeBrowserWindow();
1440
- fakeWindow.getBounds.mockReturnValue({ x: 100, y: 80, width: 599, height: 620 });
1244
+ fakeWindow.getBounds.mockReturnValue({ x: 100.4, y: 80.2, width: 839.4, height: 619.4 });
1245
const createCount = yield* Ref.make(0);
1246
const mainWindow = yield* Ref.make<Option.Option<Electron.BrowserWindow>>(Option.none());
1247
const mainWindowBoundsUpdates: DesktopAppSettings.DesktopWindowBounds[] = [];
apps/desktop/src/window/DesktopWindow.ts
+10
-11
@@ -176,12 +176,12 @@ export function resolveInitialMainWindowBounds(
176
return DesktopAppSettings.DEFAULT_MAIN_WINDOW_SIZE;
177
}
178
179
-function buildConnectingSplashDataUrl(shouldUseDarkColors: boolean, text: string): string {
179
+function buildConnectingSplashDataUrl(shouldUseDarkColors: boolean): string {
180
const background = getInitialWindowBackgroundColor(shouldUseDarkColors);
181
const label = shouldUseDarkColors ? "#9ca3af" : "#6b7280";
182
const accent = shouldUseDarkColors ? "#f8fafc" : "#1f2937";
183
const track = shouldUseDarkColors ? "rgba(248,250,252,0.18)" : "rgba(31,41,55,0.18)";
184
- const html = `<!doctype html><html><head><meta charset="utf-8"><meta http-equiv="Content-Security-Policy" content="default-src 'none'; style-src 'unsafe-inline'"><style>html,body{margin:0;height:100%}body{background:${background};color:${label};font-family:system-ui,-apple-system,'Segoe UI',sans-serif;display:flex;flex-direction:column;align-items:center;justify-content:center;gap:18px;-webkit-user-select:none;user-select:none;-webkit-app-region:drag}.spinner{width:26px;height:26px;border:3px solid ${track};border-top-color:${accent};border-radius:50%;animation:spin .8s linear infinite}.label{font-size:13px}@keyframes spin{to{transform:rotate(360deg)}}</style></head><body><div class="spinner"></div><div class="label">${text}</div></body></html>`;
184
+ const html = `<!doctype html><html><head><meta charset="utf-8"><meta http-equiv="Content-Security-Policy" content="default-src 'none'; style-src 'unsafe-inline'"><style>html,body{margin:0;height:100%}body{background:${background};color:${label};font-family:system-ui,-apple-system,'Segoe UI',sans-serif;display:flex;flex-direction:column;align-items:center;justify-content:center;gap:18px;-webkit-user-select:none;user-select:none;-webkit-app-region:drag}.spinner{width:26px;height:26px;border:3px solid ${track};border-top-color:${accent};border-radius:50%;animation:spin .8s linear infinite}.label{font-size:13px}@keyframes spin{to{transform:rotate(360deg)}}</style></head><body><div class="spinner"></div><div class="label">Connecting to WSL…</div></body></html>`;
185
return `data:text/html;charset=utf-8,${encodeURIComponent(html)}`;
186
}
187
@@ -315,7 +315,11 @@ export const make = Effect.gen(function* () {
315
}
316
});
317
318
- // Window lookups fall back to the first window, which may be the splash.
318
+ // currentMainOrFirst / focusedMainOrFirst fall back to "any first window",
319
+ // which during WSL-only boot is the connecting splash. The splash is never
320
+ // registered via setMain, so it must be treated as "no real main window" --
321
+ // otherwise ensureMain/activate/dispatchMenuAction latch onto it and never
322
+ // open (or retry) the real main.
323
const withoutSplash = (window: Option.Option<Electron.BrowserWindow>) =>
324
Ref.get(splashWindowRef).pipe(
325
Effect.map((splash) =>
@@ -379,8 +383,8 @@ export const make = Effect.gen(function* () {
383
if (yield* Ref.get(desktopState.quitting)) return Option.none();
384
const window = yield* electronWindow.create({
385
...initialBounds,
382
- minWidth: DesktopAppSettings.MIN_MAIN_WINDOW_SIZE.width,
383
- minHeight: DesktopAppSettings.MIN_MAIN_WINDOW_SIZE.height,
386
+ minWidth: 840,
387
+ minHeight: 620,
388
show: false,
389
autoHideMenuBar: true,
390
...(environment.platform === "darwin" ? { disableAutoHideCursor: true } : {}),
@@ -899,11 +903,6 @@ export const make = Effect.gen(function* () {
903
904
const shouldUseDarkColors = yield* electronTheme.shouldUseDarkColors;
905
if (yield* Ref.get(desktopState.quitting)) return;
902
- const settings = yield* desktopSettings.get;
903
- const text =
904
- settings.wslOnly === true && settings.wslBackendEnabled === true
905
- ? "Connecting to WSL…"
906
- : "Starting T3 Code…";
906
const splash = yield* electronWindow.create({
907
width: 360,
908
height: 220,
@@ -937,7 +936,7 @@ export const make = Effect.gen(function* () {
936
splash.show();
937
}
938
});
940
- void splash.loadURL(buildConnectingSplashDataUrl(shouldUseDarkColors, text));
939
+ void splash.loadURL(buildConnectingSplashDataUrl(shouldUseDarkColors));
940
yield* logWindowInfo("connecting splash shown");
941
}).pipe(
942
Effect.catch((error) =>
apps/web/src/components/AppSidebarLayout.tsx
-1
@@ -321,7 +321,6 @@ export function AppSidebarLayout({ children }: { children: ReactNode }) {
321
className="h-dvh! min-h-0!"
322
data-panel-animations={routePanelAnimationsActive ? "true" : "false"}
323
defaultOpen
324
- mobileBreakpoint={sidebarMinimumWidth + THREAD_MAIN_CONTENT_MIN_WIDTH}
324
style={sidebarProviderStyle}
325
>
326
<SidebarBrandWidthProbe onWidthChange={setBrandWidth} />
apps/web/src/components/LegacySidebar.tsx
+2
-1
@@ -204,6 +204,7 @@ import {
204
import { sortThreads } from "../lib/threadSort";
205
import { SidebarChromeFooter, SidebarChromeHeader } from "./sidebar/SidebarChrome";
206
import { useCopyToClipboard } from "~/hooks/useCopyToClipboard";
207
+import { useIsMobile } from "~/hooks/useMediaQuery";
208
import { CommandDialogTrigger } from "./ui/command";
209
import { useClientSettings, updateClientSettings } from "~/hooks/useSettings";
210
import { primaryServerKeybindingsAtom } from "../state/server";
@@ -419,7 +420,7 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThreadRowP
420
environmentId: thread.environmentId,
421
threadId: thread.id,
422
});
422
- const { isMobile } = useSidebar();
423
+ const isMobile = useIsMobile();
424
const discoveredPorts = useThreadDiscoveredPorts({
425
environmentId: thread.environmentId,
426
threadId: thread.id,
apps/web/src/components/settings/ConnectionsSettings.tsx
+3
-10
@@ -3307,16 +3307,9 @@ export function ConnectionsSettings() {
3307
Off
3308
</SelectItem>
3309
{desktopWslState.distros.length === 0 ? (
3310
- <>
3311
- <SelectItem hideIndicator value={BACKEND_VALUE_DEFAULT_WSL}>
3312
- Default distro
3313
- </SelectItem>
3314
- {desktopWslState.distro !== null ? (
3315
- <SelectItem hideIndicator value={desktopWslState.distro}>
3316
- {desktopWslState.distro}
3317
- </SelectItem>
3318
- ) : null}
3319
- </>
3310
+ <SelectItem hideIndicator value={BACKEND_VALUE_DEFAULT_WSL}>
3311
+ Default distro
3312
+ </SelectItem>
3313
) : (
3314
desktopWslState.distros.map((distro) => (
3315
<SelectItem hideIndicator key={distro.name} value={distro.name}>
apps/web/src/components/sidebar/SidebarChrome.tsx
+9
-12
@@ -36,7 +36,6 @@ export const SidebarChromeHeader = memo(function SidebarChromeHeader({
36
}: {
37
isElectron: boolean;
38
}) {
39
- const { isMobile } = useSidebar();
39
const stageLabel = useEnvironmentStageLabel();
40
const environmentIdentificationMode = useEnvironmentIdentificationMode();
41
const backdropVariant = resolveSidebarStageBackdropVariant(
@@ -56,17 +55,15 @@ export const SidebarChromeHeader = memo(function SidebarChromeHeader({
55
)}
56
>
57
{backdropVariant ? <SidebarStageBackdrop variant={backdropVariant} /> : null}
59
- {isMobile ? (
60
- <div className="relative top-[calc(var(--workspace-controls-top)-env(safe-area-inset-top))] z-10 ml-[calc(var(--workspace-controls-left)+1px-env(safe-area-inset-left))] flex shrink-0 items-center">
61
- <SidebarTrigger
62
- variant={backdropVariant ? "media-navigation" : "ghost"}
63
- className="relative top-auto translate-y-0"
64
- aria-label="Toggle main sidebar"
65
- />
66
- </div>
67
- ) : null}
58
+ <div className="relative top-[calc(var(--workspace-controls-top)-env(safe-area-inset-top))] z-10 ml-[calc(var(--workspace-controls-left)+1px-env(safe-area-inset-left))] flex shrink-0 items-center md:hidden">
59
+ <SidebarTrigger
60
+ variant={backdropVariant ? "media-navigation" : "ghost"}
61
+ className="relative top-auto translate-y-0"
62
+ aria-label="Toggle main sidebar"
63
+ />
64
+ </div>
65
<div className="relative z-10 flex h-8 min-w-0 flex-1 flex-wrap content-start items-center gap-x-2 overflow-hidden py-0.5">
69
- {!isMobile ? <SidebarBrand onBackdrop={backdropVariant !== null} /> : null}
66
+ <SidebarBrand onBackdrop={backdropVariant !== null} />
67
{pillLabel ? (
68
<div className="ml-1 flex h-7 items-center">
69
<Badge data-environment-identification="pill" size="sm" variant="secondary">
@@ -108,7 +105,7 @@ function SidebarBrand({ onBackdrop }: { onBackdrop: boolean }) {
105
<Link
106
aria-label="Go to threads"
107
className={cn(
111
- "relative z-10 ml-[var(--workspace-titlebar-content-left)] flex h-7 w-fit min-w-0 shrink-0 items-center overflow-hidden rounded-md outline-hidden ring-ring focus-visible:ring-2 focus-visible:ring-inset",
108
+ "relative z-10 ml-[var(--workspace-titlebar-content-left)] hidden h-7 w-fit min-w-0 shrink-0 items-center overflow-hidden rounded-md outline-hidden ring-ring focus-visible:ring-2 focus-visible:ring-inset md:flex",
109
onBackdrop ? "text-white" : "text-foreground",
110
)}
111
to="/"
apps/web/src/components/ui/sidebar.tsx
+4
-12
@@ -17,7 +17,7 @@ import {
17
} from "~/components/ui/sheet";
18
import { Tooltip, TooltipPopup, TooltipTrigger } from "~/components/ui/tooltip";
19
import { useResizeDrag } from "~/hooks/useResizeDrag";
20
-import { useMediaQuery } from "~/hooks/useMediaQuery";
20
+import { useIsMobile } from "~/hooks/useMediaQuery";
21
import { getLocalStorageItem, setLocalStorageItem } from "~/hooks/useLocalStorage";
22
import { resolveSidebarState, type ResponsiveSidebarState } from "./sidebarState";
23
import * as Schema from "effect/Schema";
@@ -96,7 +96,6 @@ function useSidebarVisibility() {
96
97
function SidebarProvider({
98
defaultOpen = true,
99
- mobileBreakpoint,
99
open: openProp,
100
onOpenChange: setOpenProp,
101
className,
@@ -105,17 +104,11 @@ function SidebarProvider({
104
...props
105
}: React.ComponentProps<"div"> & {
106
defaultOpen?: boolean;
108
- mobileBreakpoint?: number;
107
open?: boolean;
108
onOpenChange?: (open: boolean) => void;
109
}) {
112
- const isMobile = useMediaQuery(
113
- mobileBreakpoint === undefined ? "max-md" : { max: mobileBreakpoint },
114
- );
110
+ const isMobile = useIsMobile();
111
const [openMobile, setOpenMobile] = React.useState(false);
116
- if (!isMobile && openMobile) {
117
- setOpenMobile(false);
118
- }
112
const [mobileSheetMounted, setMobileSheetMounted] = React.useState(false);
113
const setMobileSheetElement = (element: HTMLDivElement | null) => {
114
setMobileSheetMounted(element !== null);
@@ -165,7 +158,6 @@ function SidebarProvider({
158
SIDEBAR_TITLEBAR_CONTROL_SIZE,
159
className,
160
)}
168
- data-sidebar-mobile={isMobile}
161
data-sidebar-state={state}
162
data-slot="sidebar-wrapper"
163
style={
@@ -306,7 +298,7 @@ function Sidebar({
298
<SidebarInstanceContext value={instanceContextValue}>
299
<div
300
ref={desktopSidebarRef}
309
- className="group peer text-sidebar-foreground"
301
+ className="group peer hidden text-sidebar-foreground md:block"
302
data-collapsible={state === "collapsed" ? collapsible : ""}
303
data-side={side}
304
data-slot="sidebar"
@@ -327,7 +319,7 @@ function Sidebar({
319
/>
320
<div
321
className={cn(
330
- "fixed inset-y-0 z-10 flex h-svh w-(--sidebar-width)",
322
+ "fixed inset-y-0 z-10 hidden h-svh w-(--sidebar-width) md:flex",
323
"[[data-panel-animations=true]_&]:transition-[left,right,width] [[data-panel-animations=true]_&]:[transition-duration:var(--panel-animation-duration)] [[data-panel-animations=true]_&]:ease-out",
324
side === "left"
325
? "left-0 group-data-[collapsible=offcanvas]:left-[calc(var(--sidebar-width)*-1)]"
apps/web/src/connection/desktopLocal.test.ts
+2
-52
@@ -7,7 +7,7 @@ import {
7
EnvironmentId,
8
PRIMARY_LOCAL_ENVIRONMENT_ID,
9
} from "@t3tools/contracts";
10
-import { describe, expect, it, vi } from "vite-plus/test";
10
+import { describe, expect, it } from "vite-plus/test";
11
12
import {
13
createDesktopSecondaryBootstrapsReader,
@@ -55,52 +55,7 @@ describe("desktop local connection identity", () => {
55
});
56
57
describe("desktop local topology reads", () => {
58
- it("refreshes topology asynchronously, retaining identity through unchanged reads and failures", async () => {
59
- const secondary: DesktopEnvironmentBootstrap = {
60
- id: "wsl:default",
61
- label: "WSL",
62
- runningDistro: "Ubuntu",
63
- httpBaseUrl: "http://127.0.0.1:4000",
64
- wsBaseUrl: "ws://127.0.0.1:4000",
65
- bootstrapToken: "bootstrap-1",
66
- };
67
- let entries = [secondary, { ...secondary, id: PRIMARY_LOCAL_ENVIRONMENT_ID }];
68
- let cached = entries;
69
- const getLocalEnvironmentBootstraps = vi.fn(() => cached);
70
- const readLocalEnvironmentBootstraps = vi.fn(async () => {
71
- cached = entries.map((entry) => ({ ...entry }));
72
- return cached;
73
- });
74
- const reader = createDesktopSecondaryBootstrapsReader(() => ({
75
- getLocalEnvironmentBootstraps,
76
- readLocalEnvironmentBootstraps,
77
- }));
78
-
79
- const connected = await reader.refresh();
80
- expect(connected).toEqual({ _tag: "Success", bootstraps: [secondary] });
81
- expect(getLocalEnvironmentBootstraps).not.toHaveBeenCalled();
82
- if (connected._tag !== "Success") throw new Error("expected connected topology");
83
-
84
- const unchanged = await reader.refresh();
85
- if (unchanged._tag !== "Success") throw new Error("expected unchanged topology");
86
- expect(unchanged.bootstraps).toBe(connected.bootstraps);
87
- expect(getLocalEnvironmentBootstraps).not.toHaveBeenCalled();
88
- expect(reader.readSnapshot()).toBe(connected.bootstraps);
89
-
90
- const cause = new Error("IPC unavailable");
91
- readLocalEnvironmentBootstraps.mockRejectedValueOnce(cause);
92
- expect(await reader.refresh()).toEqual({ _tag: "Failure", cause });
93
- expect(reader.readSnapshot()).toBe(connected.bootstraps);
94
-
95
- entries = [];
96
- const removed = await reader.refresh();
97
- expect(removed).toEqual({ _tag: "Success", bootstraps: [] });
98
- if (removed._tag !== "Success") throw new Error("expected empty topology");
99
- expect(reader.readSnapshot()).toBe(removed.bootstraps);
100
- expect(removed.bootstraps).not.toBe(connected.bootstraps);
101
- });
102
-
103
- it("reuses snapshots when polling returns fresh objects for the same topology", async () => {
58
+ it("reuses snapshots when polling returns fresh objects for the same topology", () => {
59
const secondary: DesktopEnvironmentBootstrap = {
60
id: "wsl:default",
61
label: "WSL",
@@ -115,16 +70,11 @@ describe("desktop local topology reads", () => {
70
}));
71
72
const connected = reader.readSnapshot();
118
- const refreshed = await reader.refresh();
119
- expect(refreshed).toEqual({ _tag: "Success", bootstraps: [secondary] });
120
- if (refreshed._tag !== "Success") throw new Error("expected legacy topology");
121
- expect(refreshed.bootstraps).toBe(connected);
73
expect(reader.readSnapshot()).toBe(connected);
74
expect(reader.readResult()).toEqual({ _tag: "Success", bootstraps: connected });
75
expect(reader.readSnapshot()).toBe(connected);
76
77
entries = [];
127
- expect(await reader.refresh()).toEqual({ _tag: "Success", bootstraps: [] });
78
const empty = reader.readSnapshot();
79
expect(empty).toEqual([]);
80
expect(reader.readSnapshot()).toBe(empty);
apps/web/src/connection/desktopLocal.ts
+24
-40
@@ -47,7 +47,6 @@ export type DesktopSecondaryBootstrapsRead =
47
48
export interface DesktopSecondaryBootstrapsReader {
49
readonly readResult: () => DesktopSecondaryBootstrapsRead;
50
- readonly refresh: () => Promise<DesktopSecondaryBootstrapsRead>;
50
readonly readSnapshot: () => ReadonlyArray<DesktopEnvironmentBootstrap>;
51
}
52
@@ -56,36 +55,10 @@ export interface DesktopSecondaryBootstrapsReader {
55
* consumers cannot temporarily disagree with the platform's retained registrations.
56
*/
57
export function createDesktopSecondaryBootstrapsReader(
59
- resolveBridge: () =>
60
- | Pick<DesktopBridge, "getLocalEnvironmentBootstraps" | "readLocalEnvironmentBootstraps">
61
- | undefined,
58
+ resolveBridge: () => Pick<DesktopBridge, "getLocalEnvironmentBootstraps"> | undefined,
59
): DesktopSecondaryBootstrapsReader {
60
let snapshot: ReadonlyArray<DesktopEnvironmentBootstrap> = [];
61
65
- const updateSnapshot = (
66
- entries: ReadonlyArray<DesktopEnvironmentBootstrap>,
67
- ): DesktopSecondaryBootstrapsRead => {
68
- const next = entries.filter((entry) => entry.id !== PRIMARY_LOCAL_ENVIRONMENT_ID);
69
- if (
70
- next.length !== snapshot.length ||
71
- next.some((entry, index) => {
72
- const previous = snapshot[index];
73
- return (
74
- previous === undefined ||
75
- entry.id !== previous.id ||
76
- entry.label !== previous.label ||
77
- entry.runningDistro !== previous.runningDistro ||
78
- entry.httpBaseUrl !== previous.httpBaseUrl ||
79
- entry.wsBaseUrl !== previous.wsBaseUrl ||
80
- entry.bootstrapToken !== previous.bootstrapToken
81
- );
82
- })
83
- ) {
84
- snapshot = next;
85
- }
86
- return { _tag: "Success", bootstraps: snapshot };
87
- };
88
-
62
const readResult = (): DesktopSecondaryBootstrapsRead => {
63
const bridge = resolveBridge();
64
if (bridge === undefined) {
@@ -93,7 +66,27 @@ export function createDesktopSecondaryBootstrapsReader(
66
return { _tag: "Success", bootstraps: snapshot };
67
}
68
try {
96
- return updateSnapshot(bridge.getLocalEnvironmentBootstraps());
69
+ const next = bridge
70
+ .getLocalEnvironmentBootstraps()
71
+ .filter((entry) => entry.id !== PRIMARY_LOCAL_ENVIRONMENT_ID);
72
+ if (
73
+ next.length !== snapshot.length ||
74
+ next.some((entry, index) => {
75
+ const previous = snapshot[index];
76
+ return (
77
+ previous === undefined ||
78
+ entry.id !== previous.id ||
79
+ entry.label !== previous.label ||
80
+ entry.runningDistro !== previous.runningDistro ||
81
+ entry.httpBaseUrl !== previous.httpBaseUrl ||
82
+ entry.wsBaseUrl !== previous.wsBaseUrl ||
83
+ entry.bootstrapToken !== previous.bootstrapToken
84
+ );
85
+ })
86
+ ) {
87
+ snapshot = next;
88
+ }
89
+ return { _tag: "Success", bootstraps: snapshot };
90
} catch (cause) {
91
return { _tag: "Failure", cause };
92
}
@@ -101,15 +94,6 @@ export function createDesktopSecondaryBootstrapsReader(
94
95
return {
96
readResult,
104
- refresh: async () => {
105
- const bridge = resolveBridge();
106
- if (bridge?.readLocalEnvironmentBootstraps === undefined) return readResult();
107
- try {
108
- return updateSnapshot(await bridge.readLocalEnvironmentBootstraps());
109
- } catch (cause) {
110
- return { _tag: "Failure", cause };
111
- }
112
- },
97
readSnapshot: () => {
98
const result = readResult();
99
return result._tag === "Success" ? result.bootstraps : snapshot;
@@ -121,8 +105,8 @@ const desktopSecondaryBootstrapsReader = createDesktopSecondaryBootstrapsReader(
105
() => window.desktopBridge,
106
);
107
124
-export function readDesktopSecondaryBootstrapsResult(): Promise<DesktopSecondaryBootstrapsRead> {
125
- return desktopSecondaryBootstrapsReader.refresh();
108
+export function readDesktopSecondaryBootstrapsResult(): DesktopSecondaryBootstrapsRead {
109
+ return desktopSecondaryBootstrapsReader.readResult();
110
}
111
112
export function readDesktopSecondaryBootstraps(): ReadonlyArray<DesktopEnvironmentBootstrap> {
apps/web/src/connection/platform.ts
+1
-1
@@ -682,7 +682,7 @@ const layerPlatformConnectionSource = Layer.effect(
682
}
683
}
684
685
- const topologyRead = yield* Effect.promise(readDesktopSecondaryBootstrapsResult);
685
+ const topologyRead = readDesktopSecondaryBootstrapsResult();
686
for (const [id, cached] of secondaryRegistrationsToRetainAfterTopologyRead(
687
previous,
688
topologyRead,
apps/web/src/hooks/useMediaQuery.ts
+4
@@ -77,3 +77,7 @@ export function useMediaQuery(query: BreakpointQuery | MediaQueryInput | (string
77
78
return useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot);
79
}
80
+
81
+export function useIsMobile(): boolean {
82
+ return useMediaQuery("max-md");
83
+}
apps/web/src/workspaceTitlebar.ts
+1
-1
@@ -1,2 +1,2 @@
1
export const COLLAPSED_SIDEBAR_TITLEBAR_INSET_CLASS =
2
- "[[data-sidebar-state=collapsed]_&]:pl-[var(--workspace-titlebar-content-left)] [[data-sidebar-mobile=true][data-sidebar-state=expanded]_&]:pl-[var(--workspace-titlebar-content-left)]";
2
+ "[[data-sidebar-state=collapsed]_&]:pl-[var(--workspace-titlebar-content-left)] max-md:[[data-sidebar-state=expanded]_&]:pl-[var(--workspace-titlebar-content-left)]";
docs/internals/performance-regressions.md
+1
-4
@@ -98,10 +98,7 @@ viewport, including a small overscan region. Cached badges remain available whil
98
released. Local Git status reads skip divergence calculations; callers that need ahead/behind
99
counts keep the full status path. Cached fetch failures share the existing backoff and log only
100
the actual failed attempt. Unchanged desktop environment bootstrap reads retain their array
101
-identity so polling does not invalidate subscribers. The desktop preload keeps the synchronous
102
-startup snapshot, while topology polling refreshes it through asynchronous IPC. Recurring
103
-`sendSync` calls block the renderer behind unrelated main-process work, even when the returned
104
-snapshot is unchanged.
101
+identity so polling does not invalidate subscribers.
102
103
Local trace records and provider event logs use asynchronous, serialized file writes and rotation.
104
Batching synchronous appends still stalls the server event loop on slow storage, especially on
packages/contracts/src/ipc.ts
-2
@@ -1047,8 +1047,6 @@ export interface DesktopBridge {
1047
*/
1048
getSystemLocale?: () => string | null;
1049
getLocalEnvironmentBootstraps: () => readonly DesktopEnvironmentBootstrap[];
1050
- /** Refresh the preload snapshot without blocking the renderer on synchronous IPC. */
1051
- readLocalEnvironmentBootstraps?: () => Promise<readonly DesktopEnvironmentBootstrap[]>;
1050
getLocalEnvironmentEnabled?: () => boolean;
1051
setLocalEnvironmentEnabled?: (enabled: boolean) => Promise<void>;
1052
getLocalEnvironmentBearerToken: () => Promise<string>;