Skip to content
TypeScript

revert: fourteen unverified desktop fixes from the takeover campaign (#22222)

Julius Marminge8fc72daee4fd
diff --git a/apps/desktop/src/app/DesktopApp.ts b/apps/desktop/src/app/DesktopApp.ts
index 7f5bdb80817..68febbc6386 100644
--- a/apps/desktop/src/app/DesktopApp.ts
+++ b/apps/desktop/src/app/DesktopApp.ts
@@ -153,8 +153,7 @@ export const stopAllPoolInstances = Effect.fn("desktop.app.stopAllPoolInstances"
const instances = yield* pool.list;
yield* Effect.forEach(
instances,
- // Exceeds the backend's 30s graceful termination and output drain budget.
- (instance) => instance.stop({ timeout: Duration.seconds(45) }),
+ (instance) => instance.stop({ timeout: Duration.seconds(5) }),
{ concurrency: "unbounded" },
);
},
@@ -240,7 +239,9 @@ const bootstrap = Effect.gen(function* () {
}
if (!(yield* Ref.get(state.quitting))) {
- yield* desktopWindow.showConnectingSplash;
+ if (settings.wslOnly === true && settings.wslBackendEnabled === true) {
+ yield* desktopWindow.showConnectingSplash;
+ }
yield* primaryBackend.start;
yield* logBootstrapInfo("bootstrap backend start requested");
yield* appActivation.start.pipe(
diff --git a/apps/desktop/src/app/DesktopClerk.test.ts b/apps/desktop/src/app/DesktopClerk.test.ts
index e415a15489d..58fff829789 100644
--- a/apps/desktop/src/app/DesktopClerk.test.ts
+++ b/apps/desktop/src/app/DesktopClerk.test.ts
@@ -1,7 +1,6 @@
// @effect-diagnostics nodeBuiltinImport:off globalFetchInEffect:off - Hosted handoff test uses a real localhost listener without an OpenAI account.
import * as NodeHttp from "node:http";
-import * as NodePath from "node:path";
-import * as PlatformNodePath from "@effect/platform-node/NodePath";
+import * as NodePath from "@effect/platform-node/NodePath";
import { codexAuthHandoffUrl, readCodexAuthDelivery } from "@t3tools/shared/codexAuthHandoff";
import { EnvironmentId, ProviderInstanceId } from "@t3tools/contracts";
import * as HostProcess from "@t3tools/shared/HostProcess";
@@ -60,15 +59,11 @@ const layerDesktopClerk = (
copyText: () => Effect.void,
},
listeners = new Map<string, (...args: unknown[]) => void>(),
- isPackaged = false,
) => {
const environment = DesktopEnvironment.DesktopEnvironment.of({
stateDir: "/tmp/t3-state",
isDevelopment,
appDataDirectory: "/tmp/app-data",
- isPackaged,
- dirname: platform === "win32" ? String.raw`C:\T3 Code\dist-electron` : "/tmp/dist-electron",
- path: platform === "win32" ? NodePath.win32 : NodePath.posix,
platform,
} as unknown as DesktopEnvironment.DesktopEnvironment["Service"]);
@@ -100,7 +95,7 @@ const layerDesktopClerk = (
return DesktopClerk.layer.pipe(
Layer.provide(
Layer.mergeAll(
- PlatformNodePath.layerPosix,
+ NodePath.layerPosix,
Layer.succeed(DesktopEnvironment.DesktopEnvironment, environment),
Layer.succeed(ElectronApp.ElectronApp, electronApp),
Layer.succeed(ElectronShell.ElectronShell, shell),
@@ -117,67 +112,6 @@ describe("DesktopClerk", () => {
storageMock.mockReset();
});
- it.effect.each([
- { platform: "win32", isPackaged: false, isDevelopment: false, registers: true },
- { platform: "win32", isPackaged: false, isDevelopment: true, registers: false },
- { platform: "win32", isPackaged: true, isDevelopment: false, registers: false },
- { platform: "darwin", isPackaged: false, isDevelopment: false, registers: false },
- { platform: "linux", isPackaged: false, isDevelopment: false, registers: false },
- ] as const)(
- "registers an entry point only for unpackaged non-development Windows ($platform, packaged=$isPackaged, development=$isDevelopment)",
- ({ platform, isPackaged, isDevelopment, registers }) => {
- const events: string[] = [];
- storageMock.mockReturnValue(storageAdapter);
- createClerkBridgeMock.mockImplementation(() => {
- events.push("bridge");
- return { cleanup: vi.fn() };
- });
- const setAsDefaultProtocolClient = vi.fn(() =>
- Effect.sync(() => {
- events.push("register");
- return true;
- }),
- );
- const electronApp = {
- on: () => Effect.void,
- setAsDefaultProtocolClient,
- } as unknown as ElectronApp.ElectronApp["Service"];
-
- return Effect.gen(function* () {
- const clerk = yield* DesktopClerk.DesktopClerk;
- yield* clerk.configure;
-
- assert.deepEqual(
- setAsDefaultProtocolClient.mock.calls,
- registers
- ? [["t3code", process.execPath, [String.raw`C:\T3 Code\dist-electron\main.cjs`]]]
- : [],
- );
- assert.deepEqual(events, registers ? ["bridge", "register"] : ["bridge"]);
- }).pipe(
- Effect.scoped,
- Effect.provide(
- layerDesktopClerk(
- isDevelopment,
- [],
- platform,
- undefined,
- undefined,
- undefined,
- isPackaged,
- ),
- ),
- Effect.provideService(ElectronApp.ElectronApp, electronApp),
- Effect.provideService(
- ElectronWindow.ElectronWindow,
- {} as ElectronWindow.ElectronWindow["Service"],
- ),
- Effect.provideService(DesktopWebLinks.DesktopWebLinks, ignoreWebLinks),
- Effect.provideService(HostProcess.Arguments, ["electron"]),
- );
- },
- );
-
it.effect("acquires and releases the SDK bridge with the layer", () => {
const cleanup = vi.fn();
const events: string[] = [];
diff --git a/apps/desktop/src/app/DesktopClerk.ts b/apps/desktop/src/app/DesktopClerk.ts
index f4de0b4ebaf..505b48194cf 100644
--- a/apps/desktop/src/app/DesktopClerk.ts
+++ b/apps/desktop/src/app/DesktopClerk.ts
@@ -151,20 +151,6 @@ export const make = Effect.gen(function* () {
const context = yield* Effect.context<ElectronWindow.ElectronWindow>();
const runPromise = Effect.runPromiseWith(context);
- // Clerk's bare scheme registration omits the app entry on unpackaged Windows.
- // Development callbacks also need dev server environment this command cannot restore.
- if (
- !environment.isPackaged &&
- !environment.isDevelopment &&
- environment.platform === "win32"
- ) {
- yield* electronApp.setAsDefaultProtocolClient(
- ElectronProtocol.getDesktopScheme(environment.isDevelopment),
- process.execPath,
- [environment.path.join(environment.dirname, "main.cjs")],
- );
- }
-
const startProviderAuthHandoff = (value: string | undefined) => {
if (!value) return false;
const request = readCodexAuthHandoff(value, environment.isDevelopment);
diff --git a/apps/desktop/src/app/DesktopLifecycle.test.ts b/apps/desktop/src/app/DesktopLifecycle.test.ts
index 43fb27cac6c..f9f38dea3dd 100644
--- a/apps/desktop/src/app/DesktopLifecycle.test.ts
+++ b/apps/desktop/src/app/DesktopLifecycle.test.ts
@@ -1,13 +1,6 @@
-// @effect-diagnostics-next-line nodeBuiltinImport:off - A real Node process verifies OS signal ownership outside Effect's process runtime.
-import * as NodeChildProcess from "node:child_process";
-import * as NodeReadline from "node:readline";
-import * as NodeURL from "node:url";
-
import { assert, describe, it } from "@effect/vitest";
-import * as HostProcess from "@t3tools/shared/HostProcess";
import * as Deferred from "effect/Deferred";
import * as Effect from "effect/Effect";
-import * as Fiber from "effect/Fiber";
import * as Layer from "effect/Layer";
import * as Ref from "effect/Ref";
@@ -110,67 +103,6 @@ function layerDesktopWindow(
}
describe("DesktopLifecycle", () => {
- it.skipIf(HostProcess.Platform.defaultValue() === "win32")(
- "leaves SIGTERM to the lifecycle until its graceful shutdown completes",
- async ({ onTestFinished }) => {
- const runner = new URL("./DesktopRuntime.ts", import.meta.url).href;
- const child = NodeChildProcess.spawn(
- process.execPath,
- [
- "--experimental-strip-types",
- "--input-type=module",
- "-e",
- `
- import * as Effect from 'effect/Effect';
- import * as Deferred from 'effect/Deferred';
- import { runMain } from ${JSON.stringify(runner)};
- process.stdin.resume();
- let released = false;
- runMain(Effect.scoped(Effect.gen(function* () {
- const done = yield* Deferred.make();
- yield* Effect.addFinalizer(() => Effect.sync(() => console.log(released ? 'CLEANED' : 'PREMATURE')));
- process.once('SIGTERM', () => {
- console.log('STOPPING');
- process.stdin.once('data', () => {
- released = true;
- void Effect.runPromise(Deferred.succeed(done, undefined)).then(() => process.stdin.destroy());
- });
- });
- console.log('READY');
- yield* Deferred.await(done);
- })));
- `,
- ],
- {
- cwd: NodeURL.fileURLToPath(new URL("../../", import.meta.url)),
- stdio: ["pipe", "pipe", "pipe"],
- },
- );
- const exited = new Promise<readonly [number | null, string | null]>((resolve, reject) => {
- child.once("exit", (code, signal) => resolve([code, signal]));
- child.once("error", reject);
- });
- const lines: string[] = [];
- let stderr = "";
- child.stderr.on("data", (chunk) => {
- stderr += chunk;
- });
- onTestFinished(async () => {
- if (child.exitCode === null && child.signalCode === null) {
- child.kill("SIGKILL");
- await exited;
- }
- });
- for await (const line of NodeReadline.createInterface({ input: child.stdout })) {
- lines.push(line);
- if (line === "READY") child.kill("SIGTERM");
- if (line === "STOPPING") child.stdin.write("finish");
- }
- assert.deepEqual(await exited, [0, null], stderr);
- assert.deepEqual(lines, ["READY", "STOPPING", "CLEANED"]);
- },
- );
-
it.effect.each(["darwin", "win32", "linux"] satisfies ReadonlyArray<NodeJS.Platform>)(
"lets the updater's quit event proceed on %s",
(platform) => {
@@ -226,18 +158,12 @@ describe("DesktopLifecycle", () => {
},
);
- it.effect("destroys windows and retains signal ownership until backend shutdown completes", () =>
+ it.effect("destroys windows before waiting for backend shutdown", () =>
Effect.gen(function* () {
const appListeners = new Map<string, (...args: readonly unknown[]) => void>();
const shutdownRequested = yield* Deferred.make<void>();
const allowShutdown = yield* Deferred.make<void>();
const quitRequested = yield* Deferred.make<void>();
- const backendStopping = yield* Deferred.make<void>();
- const finishBackendShutdown = yield* Deferred.make<void>();
- const originalSignals = {
- SIGINT: process.listeners("SIGINT"),
- SIGTERM: process.listeners("SIGTERM"),
- };
const events: string[] = [];
const quit = Effect.sync(() => {
@@ -278,47 +204,20 @@ describe("DesktopLifecycle", () => {
yield* Effect.scoped(
Effect.gen(function* () {
const lifecycle = yield* DesktopLifecycle.DesktopLifecycle;
- const shutdown = yield* DesktopShutdown.DesktopShutdown;
- const program = yield* Effect.scoped(
- Effect.gen(function* () {
- yield* Effect.addFinalizer(() =>
- Deferred.succeed(backendStopping, undefined).pipe(
- Effect.andThen(Deferred.await(finishBackendShutdown)),
- Effect.andThen(shutdown.markComplete),
- ),
- );
- yield* lifecycle.register;
- const event = { preventDefault: () => undefined } as Electron.Event;
- appListeners.get("before-quit")?.(event);
- yield* shutdown.awaitRequest;
- }),
- ).pipe(Effect.forkScoped);
-
- yield* Deferred.await(backendStopping);
- yield* Effect.addFinalizer(() =>
- Deferred.succeed(finishBackendShutdown, undefined).pipe(Effect.asVoid),
- );
+ yield* lifecycle.register;
- for (const signal of ["SIGINT", "SIGTERM"] as const) {
- const listeners = process
- .listeners(signal)
- .filter((listener) => !originalSignals[signal].includes(listener));
- assert.lengthOf(listeners, 1, `${signal} must remain owned during backend cleanup`);
- listeners[0]?.(signal);
- }
- assert.deepEqual(events, ["flush", "destroy", "request"]);
- assert.equal(appListeners.size, 0, "Electron listeners still follow the program scope");
- assert.isFalse(yield* shutdown.isComplete);
+ const event = { preventDefault: () => undefined } as Electron.Event;
+ appListeners.get("before-quit")?.(event);
- yield* Deferred.succeed(finishBackendShutdown, undefined);
- yield* Fiber.join(program);
+ yield* Deferred.await(shutdownRequested);
+ const eventsBeforeCleanup = [...events];
+ yield* Deferred.succeed(allowShutdown, undefined);
yield* Deferred.await(quitRequested);
+
+ assert.deepEqual(eventsBeforeCleanup, ["flush", "destroy", "request"]);
assert.deepEqual(events, ["flush", "destroy", "request", "quit"]);
}),
).pipe(Effect.provide(layer));
-
- assert.deepEqual(process.listeners("SIGINT"), originalSignals.SIGINT);
- assert.deepEqual(process.listeners("SIGTERM"), originalSignals.SIGTERM);
}),
);
diff --git a/apps/desktop/src/app/DesktopLifecycle.ts b/apps/desktop/src/app/DesktopLifecycle.ts
index 6a464021171..924341781aa 100644
--- a/apps/desktop/src/app/DesktopLifecycle.ts
+++ b/apps/desktop/src/app/DesktopLifecycle.ts
@@ -160,113 +160,108 @@ function quitFromSignal(
}
/** @public Service construction is part of the canonical Effect module API. */
-export const make = Effect.gen(function* () {
- const signalScope = yield* Scope.Scope;
- return DesktopLifecycle.of({
- relaunch: Effect.fn("desktop.lifecycle.relaunch")(function* (reason) {
- const electronApp = yield* ElectronApp.ElectronApp;
- const environment = yield* DesktopEnvironment.DesktopEnvironment;
- const state = yield* DesktopState.DesktopState;
- yield* logLifecycleInfo("desktop relaunch requested", { reason });
- yield* Effect.gen(function* () {
- yield* Effect.yieldNow;
- yield* Ref.set(state.quitting, true);
- yield* requestDesktopShutdownAndWait();
- if (environment.isDevelopment) {
- yield* electronApp.exit(75);
- return;
- }
- yield* electronApp.relaunch({
- execPath: process.execPath,
- args: process.argv.slice(1),
- });
- yield* electronApp.exit(0);
- }).pipe(
- Effect.catchCause((cause) => {
- const error = new DesktopLifecycleRelaunchError({ reason, cause });
- return logLifecycleError(error.message, { error });
- }),
- Effect.forkDetach,
- Effect.asVoid,
- );
- }),
- register: Effect.gen(function* () {
- const desktopWindow = yield* DesktopWindow.DesktopWindow;
- const electronWindow = yield* ElectronWindow.ElectronWindow;
- const electronApp = yield* ElectronApp.ElectronApp;
- const electronTheme = yield* ElectronTheme.ElectronTheme;
- const environment = yield* DesktopEnvironment.DesktopEnvironment;
- const context = yield* Effect.context<DesktopLifecycleRegistrationServices>();
- const runEffect = Effect.runPromiseWith(context);
- let quitAllowed = false;
- let updaterQuitAllowed = false;
- yield* electronTheme.onUpdated(() => {
- void runEffect(
- desktopWindow.syncAppearance.pipe(Effect.withSpan("desktop.lifecycle.themeUpdated")),
- );
+export const make = DesktopLifecycle.of({
+ relaunch: Effect.fn("desktop.lifecycle.relaunch")(function* (reason) {
+ const electronApp = yield* ElectronApp.ElectronApp;
+ const environment = yield* DesktopEnvironment.DesktopEnvironment;
+ const state = yield* DesktopState.DesktopState;
+ yield* logLifecycleInfo("desktop relaunch requested", { reason });
+ yield* Effect.gen(function* () {
+ yield* Effect.yieldNow;
+ yield* Ref.set(state.quitting, true);
+ yield* requestDesktopShutdownAndWait();
+ if (environment.isDevelopment) {
+ yield* electronApp.exit(75);
+ return;
+ }
+ yield* electronApp.relaunch({
+ execPath: process.execPath,
+ args: process.argv.slice(1),
});
- yield* electronApp.onBeforeQuitForUpdate(() => {
- // Electron's updater owns the remaining quit/install/relaunch sequence.
- // Cancelling the following app "before-quit" event breaks that sequence,
- // most visibly on macOS where the native updater performs the relaunch.
- updaterQuitAllowed = true;
- // This event is synchronous and the updater's quit proceeds as soon as
- // the listener returns, so a forked destroyAll would race the quit
- // and windows could still be open when the process exits (visible on
- // macOS). Destroy them inline.
- Effect.runSyncWith(context)(
- electronWindow.destroyAll.pipe(
- Effect.andThen(logLifecycleInfo("allowing updater-controlled quit")),
- Effect.catchCause((cause) =>
- logLifecycleError("failed to destroy windows before updater quit", { cause }),
- ),
- Effect.withSpan("desktop.lifecycle.beforeQuitForUpdate"),
+ yield* electronApp.exit(0);
+ }).pipe(
+ Effect.catchCause((cause) => {
+ const error = new DesktopLifecycleRelaunchError({ reason, cause });
+ return logLifecycleError(error.message, { error });
+ }),
+ Effect.forkDetach,
+ Effect.asVoid,
+ );
+ }),
+ register: Effect.gen(function* () {
+ const desktopWindow = yield* DesktopWindow.DesktopWindow;
+ const electronWindow = yield* ElectronWindow.ElectronWindow;
+ const electronApp = yield* ElectronApp.ElectronApp;
+ const electronTheme = yield* ElectronTheme.ElectronTheme;
+ const environment = yield* DesktopEnvironment.DesktopEnvironment;
+ const context = yield* Effect.context<DesktopLifecycleRegistrationServices>();
+ const runEffect = Effect.runPromiseWith(context);
+ let quitAllowed = false;
+ let updaterQuitAllowed = false;
+ yield* electronTheme.onUpdated(() => {
+ void runEffect(
+ desktopWindow.syncAppearance.pipe(Effect.withSpan("desktop.lifecycle.themeUpdated")),
+ );
+ });
+ yield* electronApp.onBeforeQuitForUpdate(() => {
+ // Electron's updater owns the remaining quit/install/relaunch sequence.
+ // Cancelling the following app "before-quit" event breaks that sequence,
+ // most visibly on macOS where the native updater performs the relaunch.
+ updaterQuitAllowed = true;
+ // This event is synchronous and the updater's quit proceeds as soon as
+ // the listener returns, so a forked destroyAll would race the quit
+ // and windows could still be open when the process exits (visible on
+ // macOS). Destroy them inline.
+ Effect.runSyncWith(context)(
+ electronWindow.destroyAll.pipe(
+ Effect.andThen(logLifecycleInfo("allowing updater-controlled quit")),
+ Effect.catchCause((cause) =>
+ logLifecycleError("failed to destroy windows before updater quit", { cause }),
),
- );
- });
- yield* electronApp.on("before-quit", (event: Electron.Event) => {
- handleBeforeQuit(
- event,
- runEffect,
- () => quitAllowed || updaterQuitAllowed,
- () => {
- quitAllowed = true;
- },
- );
- });
- yield* electronApp.on("activate", () => {
- void runEffect(
- Effect.gen(function* () {
- const state = yield* DesktopState.DesktopState;
- if (yield* Ref.get(state.quitting)) return;
- yield* desktopWindow.activate;
- }).pipe(Effect.withSpan("desktop.lifecycle.activate")),
- );
+ Effect.withSpan("desktop.lifecycle.beforeQuitForUpdate"),
+ ),
+ );
+ });
+ yield* electronApp.on("before-quit", (event: Electron.Event) => {
+ handleBeforeQuit(
+ event,
+ runEffect,
+ () => quitAllowed || updaterQuitAllowed,
+ () => {
+ quitAllowed = true;
+ },
+ );
+ });
+ yield* electronApp.on("activate", () => {
+ void runEffect(
+ Effect.gen(function* () {
+ const state = yield* DesktopState.DesktopState;
+ if (yield* Ref.get(state.quitting)) return;
+ yield* desktopWindow.activate;
+ }).pipe(Effect.withSpan("desktop.lifecycle.activate")),
+ );
+ });
+ yield* electronApp.on("window-all-closed", () => {
+ void runEffect(
+ Effect.gen(function* () {
+ const app = yield* ElectronApp.ElectronApp;
+ const state = yield* DesktopState.DesktopState;
+ if (environment.platform !== "darwin" && !(yield* Ref.get(state.quitting))) {
+ yield* app.quit;
+ }
+ }).pipe(Effect.withSpan("desktop.lifecycle.windowAllClosed")),
+ );
+ });
+
+ if (environment.platform !== "win32") {
+ yield* addScopedListener(process, "SIGINT", () => {
+ quitFromSignal("SIGINT", runEffect);
});
- yield* electronApp.on("window-all-closed", () => {
- void runEffect(
- Effect.gen(function* () {
- const app = yield* ElectronApp.ElectronApp;
- const state = yield* DesktopState.DesktopState;
- if (environment.platform !== "darwin" && !(yield* Ref.get(state.quitting))) {
- yield* app.quit;
- }
- }).pipe(Effect.withSpan("desktop.lifecycle.windowAllClosed")),
- );
+ yield* addScopedListener(process, "SIGTERM", () => {
+ quitFromSignal("SIGTERM", runEffect);
});
-
- if (environment.platform !== "win32") {
- // The layer outlives program finalizers, so repeated signals stay owned
- // while backends stop. Electron listeners still follow the program scope.
- yield* addScopedListener(process, "SIGINT", () => {
- quitFromSignal("SIGINT", runEffect);
- }).pipe(Scope.provide(signalScope));
- yield* addScopedListener(process, "SIGTERM", () => {
- quitFromSignal("SIGTERM", runEffect);
- }).pipe(Scope.provide(signalScope));
- }
- }).pipe(Effect.withSpan("desktop.lifecycle.register")),
- });
+ }
+ }).pipe(Effect.withSpan("desktop.lifecycle.register")),
});
-export const layer = Layer.effect(DesktopLifecycle, make);
+export const layer = Layer.succeed(DesktopLifecycle, make);
diff --git a/apps/desktop/src/app/DesktopLinuxUrlHandler.test.ts b/apps/desktop/src/app/DesktopLinuxUrlHandler.test.ts
index 41f20ef984d..295f63eafe4 100644
--- a/apps/desktop/src/app/DesktopLinuxUrlHandler.test.ts
+++ b/apps/desktop/src/app/DesktopLinuxUrlHandler.test.ts
@@ -22,31 +22,8 @@ interface RecordedRegistration {
readonly files: Array<{ readonly path: string; readonly content: string }>;
readonly commands: Array<{ readonly command: string; readonly args: ReadonlyArray<string> }>;
readonly copies: Array<{ readonly source: string; readonly destination: string }>;
- readonly binaryReads: string[];
- readonly binaryWrites: Array<{
- readonly path: string;
- readonly bytes: Uint8Array;
- readonly mode: number | undefined;
- }>;
}
-const iconSource = "/tmp/.mount_T3/resources/app.asar/apps/desktop/prod-resources/icon.png";
-const iconPath = "/home/alice/.local/share/icons/com.t3tools.T3Code.desktop.png";
-const iconBytes = new Uint8Array([0x89, 0x50, 0x00, 0xff, 0x80, 0x0a]);
-const currentDesktopEntry = DesktopLinuxUrlHandler.renderUrlHandlerDesktopEntry({
- displayName: "T3 Code (Alpha)",
- execTarget: "/home/alice/Applications/T3-Code.AppImage",
- scheme: "t3code",
- iconPath,
-});
-const registrationCommands = [
- { command: "update-desktop-database", args: ["/home/alice/.local/share/applications"] },
- {
- command: "xdg-mime",
- args: ["default", "com.t3tools.T3Code.desktop", "x-scheme-handler/t3code"],
- },
-];
-
const makeEnvironment = (path: Path.Path, overrides: Record<string, unknown> = {}) =>
DesktopEnvironment.DesktopEnvironment.of({
platform: "linux",
@@ -87,8 +64,7 @@ const layerHandler = (
readonly writeError?: PlatformError.PlatformError;
readonly existingEntry?: string;
readonly iconSource?: string;
- readonly existingIcon?: Uint8Array;
- readonly iconReadError?: PlatformError.PlatformError;
+ readonly iconCopyError?: PlatformError.PlatformError;
} = {},
) =>
DesktopLinuxUrlHandler.layer.pipe(
@@ -111,34 +87,11 @@ const layerHandler = (
}),
FileSystem.layerNoop({
copyFile: (source, destination) =>
- Effect.sync(() => {
- recorded.copies.push({ source, destination });
- }),
- readFile: (path) =>
- Effect.gen(function* () {
- recorded.binaryReads.push(path);
- if (path === input.iconSource) {
- if (input.iconReadError) return yield* input.iconReadError;
- return new Uint8Array(iconBytes);
- }
- if (path === iconPath && input.existingIcon !== undefined) {
- return input.existingIcon;
- }
- return yield* PlatformError.systemError({
- _tag: "NotFound",
- module: "FileSystem",
- method: "readFile",
- pathOrDescriptor: path,
- });
- }),
- writeFile: (path, bytes, options) =>
- Effect.sync(() => {
- recorded.binaryWrites.push({
- path,
- bytes: new Uint8Array(bytes),
- mode: options?.mode,
- });
- }),
+ input.iconCopyError
+ ? Effect.fail(input.iconCopyError)
+ : Effect.sync(() => {
+ recorded.copies.push({ source, destination });
+ }),
readFileString: () => Effect.succeed(input.existingEntry ?? ""),
makeDirectory: (path) =>
Effect.sync(() => {
@@ -203,8 +156,6 @@ const emptyRecording = (): RecordedRegistration => ({
files: [],
commands: [],
copies: [],
- binaryReads: [],
- binaryWrites: [],
});
describe("DesktopLinuxUrlHandler", () => {
@@ -355,57 +306,42 @@ describe("DesktopLinuxUrlHandler", () => {
it.effect("installs a persistent icon even when the desktop entry is already current", () => {
const recorded = emptyRecording();
+ const iconPath = "/home/alice/.local/share/icons/com.t3tools.T3Code.desktop.png";
return Effect.gen(function* () {
yield* runRegister(recorded, {
- iconSource,
- existingEntry: currentDesktopEntry,
- });
- assert.deepEqual(recorded.files, []);
- assert.deepEqual(recorded.copies, []);
- assert.deepEqual(recorded.binaryReads, [iconSource, iconPath]);
- assert.deepEqual(recorded.binaryWrites, [{ path: iconPath, bytes: iconBytes, mode: 0o600 }]);
- assert.deepEqual(recorded.commands, registrationCommands);
- });
- });
-
- it.effect("refreshes a stale icon and skips equal bytes on the next registration", () => {
- const recorded = emptyRecording();
- return Effect.gen(function* () {
- yield* runRegister(recorded, {
- iconSource,
- existingEntry: currentDesktopEntry,
- existingIcon: new Uint8Array([0x89, 0x50, 0x00, 0xfe, 0x80, 0x0a]),
- });
- assert.deepEqual(recorded.binaryWrites, [{ path: iconPath, bytes: iconBytes, mode: 0o600 }]);
- yield* runRegister(recorded, {
- iconSource,
- existingEntry: currentDesktopEntry,
- existingIcon: new Uint8Array(recorded.binaryWrites[0]!.bytes),
+ iconSource: "/tmp/.mount_T3/resources/icon.png",
+ existingEntry: DesktopLinuxUrlHandler.renderUrlHandlerDesktopEntry({
+ displayName: "T3 Code (Alpha)",
+ execTarget: "/home/alice/Applications/T3-Code.AppImage",
+ scheme: "t3code",
+ iconPath,
+ }),
});
- assert.equal(recorded.binaryWrites.length, 1);
- assert.deepEqual(recorded.copies, []);
assert.deepEqual(recorded.files, []);
- assert.deepEqual(recorded.commands, [...registrationCommands, ...registrationCommands]);
+ assert.deepEqual(recorded.copies, [
+ { source: "/tmp/.mount_T3/resources/icon.png", destination: iconPath },
+ ]);
+ assert.equal(recorded.commands.at(-1)?.command, "xdg-mime");
});
});
- it.effect("still registers the handler when reading its icon fails", () => {
+ it.effect("still registers the handler when copying its icon fails", () => {
const recorded = emptyRecording();
return Effect.gen(function* () {
yield* runRegister(recorded, {
- iconSource,
- iconReadError: PlatformError.systemError({
+ iconSource: "/tmp/.mount_T3/resources/icon.png",
+ iconCopyError: PlatformError.systemError({
_tag: "PermissionDenied",
module: "FileSystem",
- method: "readFile",
- description: "unreadable bundled icon",
+ method: "copyFile",
+ description: "read-only icon directory",
}),
});
- assert.deepEqual(recorded.binaryReads, [iconSource]);
- assert.deepEqual(recorded.binaryWrites, []);
- assert.deepEqual(recorded.copies, []);
assert.equal(recorded.files.length, 1);
- assert.deepEqual(recorded.commands, registrationCommands);
+ assert.deepEqual(
+ recorded.commands.map(({ command }) => command),
+ ["update-desktop-database", "xdg-mime"],
+ );
});
});
diff --git a/apps/desktop/src/app/DesktopLinuxUrlHandler.ts b/apps/desktop/src/app/DesktopLinuxUrlHandler.ts
index 83c595ea678..e03418964e3 100644
--- a/apps/desktop/src/app/DesktopLinuxUrlHandler.ts
+++ b/apps/desktop/src/app/DesktopLinuxUrlHandler.ts
@@ -301,16 +301,12 @@ export const make = Effect.gen(function* () {
yield* Effect.gen(function* () {
const { png } = yield* assets.iconPaths;
if (Option.isNone(png)) return;
- // Electron's copyFile extracts ASAR entries to temporary files it never removes.
- const icon = yield* fileSystem.readFile(png.value);
- const current = yield* fileSystem.readFile(iconPath).pipe(Effect.option);
- if (Option.isSome(current) && sameBytes(current.value, icon)) return;
// The AppImage mount is temporary; the chooser needs the icon after exit.
yield* fileSystem.makeDirectory(iconsDir, { recursive: true });
- yield* fileSystem.writeFile(iconPath, icon, { mode: 0o600 });
+ yield* fileSystem.copyFile(png.value, iconPath);
}).pipe(
Effect.catch((error) =>
- logWarning("URL handler icon install failed", { iconPath, category: error.reason._tag }),
+ logWarning("URL handler icon copy failed", { iconPath, category: error.reason._tag }),
),
);
diff --git a/apps/desktop/src/app/DesktopPreReadyPlatform.test.ts b/apps/desktop/src/app/DesktopPreReadyPlatform.test.ts
index 1612c7bbaac..d27251d7b2f 100644
--- a/apps/desktop/src/app/DesktopPreReadyPlatform.test.ts
+++ b/apps/desktop/src/app/DesktopPreReadyPlatform.test.ts
@@ -12,10 +12,10 @@ const {
registerSchemesMock,
setDesktopNameMock,
mkdirSyncMock,
- readFileSyncMock,
writeFileSyncMock,
copyFileSyncMock,
execFileSyncMock,
+ readFileSyncMock,
} = vi.hoisted(() => ({
appendSwitchMock: vi.fn(),
getSwitchValueMock: vi.fn(),
@@ -23,10 +23,10 @@ const {
registerSchemesMock: vi.fn(),
setDesktopNameMock: vi.fn(),
mkdirSyncMock: vi.fn(),
- readFileSyncMock: vi.fn(),
writeFileSyncMock: vi.fn(),
copyFileSyncMock: vi.fn(),
execFileSyncMock: vi.fn(),
+ readFileSyncMock: vi.fn(),
}));
vi.mock("electron", () => ({
@@ -59,11 +59,6 @@ vi.mock("node:child_process", () => ({
import * as DesktopPreReadyPlatform from "./DesktopPreReadyPlatform.ts";
-const iconSource = "/tmp/.mount_T3/resources/app.asar/apps/desktop/prod-resources/icon.png";
-const iconPath = "/xdg/icons/com.t3tools.T3Code.desktop.png";
-const desktopEntryPath = "/xdg/applications/com.t3tools.T3Code.desktop";
-const iconBytes = Buffer.from([0x89, 0x50, 0x00, 0xff, 0x80, 0x0a]);
-
describe("DesktopPreReadyPlatform", () => {
beforeEach(() => {
appendSwitchMock.mockReset();
@@ -72,15 +67,10 @@ describe("DesktopPreReadyPlatform", () => {
registerSchemesMock.mockReset();
setDesktopNameMock.mockReset();
mkdirSyncMock.mockReset();
- readFileSyncMock.mockReset();
writeFileSyncMock.mockReset();
copyFileSyncMock.mockReset();
execFileSyncMock.mockReset();
- readFileSyncMock.mockReset().mockImplementation((path: string) => {
- if (path.endsWith("/desktop-settings.json")) return "{}";
- if (path === iconSource) return Buffer.from(iconBytes);
- throw new Error(`missing file: ${path}`);
- });
+ readFileSyncMock.mockReset().mockReturnValue("{}");
});
it.effect("persists Linux scaling synchronously across relaunches and settings rewrites", () => {
@@ -222,13 +212,14 @@ describe("DesktopPreReadyPlatform", () => {
let desktopName = "t3code.desktop";
let desktopEntry = previousEntry;
let iconInstalled = false;
+ copyFileSyncMock.mockImplementation((_source: string, destination: string) => {
+ iconInstalled = destination === "/xdg/icons/com.t3tools.T3Code.desktop.png";
+ });
setDesktopNameMock.mockImplementation((name: string) => {
desktopName = name;
});
- writeFileSyncMock.mockImplementation((path: string, contents: string | Buffer) => {
- if (path === iconPath)
- iconInstalled = Buffer.isBuffer(contents) && contents.equals(iconBytes);
- if (path === desktopEntryPath && typeof contents === "string") desktopEntry = contents;
+ writeFileSyncMock.mockImplementation((path: string, contents: string) => {
+ if (path === "/xdg/applications/com.t3tools.T3Code.desktop") desktopEntry = contents;
});
return Effect.scoped(
@@ -253,15 +244,6 @@ describe("DesktopPreReadyPlatform", () => {
"Icon=/xdg/icons/com.t3tools.T3Code.desktop.png",
);
assert.isTrue(identity.iconInstalled);
- assert.deepEqual(
- readFileSyncMock.mock.calls.filter(([path]) => path === iconSource),
- [[iconSource]],
- );
- assert.deepEqual(
- writeFileSyncMock.mock.calls.filter(([path]) => path === iconPath),
- [[iconPath, iconBytes, { mode: 0o600 }]],
- );
- assert.equal(copyFileSyncMock.mock.calls.length, 0);
}),
).pipe(Effect.ensuring(Effect.sync(() => vi.unstubAllEnvs())));
});
@@ -278,62 +260,18 @@ describe("DesktopPreReadyPlatform", () => {
);
});
- it.effect("refreshes a stale icon once across repeated launches", () => {
- vi.stubEnv("VITE_DEV_SERVER_URL", "");
- vi.stubEnv("XDG_DATA_HOME", "/xdg");
+ it.effect("still prepares the portal entry when the bundled icon cannot be copied", () => {
getSwitchValueMock.mockReturnValue("");
- let installedIcon = Buffer.from([0x89, 0x50, 0x00, 0xfe, 0x80, 0x0a]);
- readFileSyncMock.mockImplementation((path: string) => {
- if (path === iconSource) return Buffer.from(iconBytes);
- if (path === iconPath) return Buffer.from(installedIcon);
- return "{}";
+ copyFileSyncMock.mockImplementation(() => {
+ throw new Error("missing bundled icon");
});
- writeFileSyncMock.mockImplementation((path: string, contents: Buffer) => {
- if (path === iconPath) installedIcon = Buffer.from(contents);
- });
-
return Effect.gen(function* () {
yield* DesktopPreReadyPlatform.make;
- assert.deepEqual(installedIcon, iconBytes);
- yield* DesktopPreReadyPlatform.make;
- assert.deepEqual(
- writeFileSyncMock.mock.calls.filter(([path]) => path === iconPath),
- [[iconPath, iconBytes, { mode: 0o600 }]],
- );
- assert.equal(copyFileSyncMock.mock.calls.length, 0);
- assert.equal(
- writeFileSyncMock.mock.calls.filter(([path]) => path === desktopEntryPath).length,
- 2,
- );
- assert.equal(setDesktopNameMock.mock.calls.length, 2);
- }).pipe(
- Effect.provideService(HostProcess.Platform, "linux"),
- Effect.ensuring(Effect.sync(() => vi.unstubAllEnvs())),
- );
- });
-
- it.effect("still prepares the portal entry when the bundled icon cannot be read", () => {
- vi.stubEnv("VITE_DEV_SERVER_URL", "");
- vi.stubEnv("XDG_DATA_HOME", "/xdg");
- getSwitchValueMock.mockReturnValue("");
- readFileSyncMock.mockImplementation((path: string) => {
- if (path === iconSource) throw new Error("unreadable bundled icon");
- return "{}";
- });
- return Effect.gen(function* () {
- yield* DesktopPreReadyPlatform.make;
- assert.isTrue(readFileSyncMock.mock.calls.some(([path]) => path === iconSource));
- assert.equal(copyFileSyncMock.mock.calls.length, 0);
- assert.equal(writeFileSyncMock.mock.calls.length, 1);
- const [path, contents] = writeFileSyncMock.mock.calls[0]!;
- assert.equal(path, desktopEntryPath);
+ const contents = writeFileSyncMock.mock.calls[0]?.[1];
assert.include(contents, "MimeType=x-scheme-handler/t3code;");
- assert.include(contents, `Icon=${iconPath}`);
+ assert.include(contents, "Icon=");
assert.equal(setDesktopNameMock.mock.calls.length, 1);
- }).pipe(
- Effect.provideService(HostProcess.Platform, "linux"),
- Effect.ensuring(Effect.sync(() => vi.unstubAllEnvs())),
- );
+ }).pipe(Effect.provideService(HostProcess.Platform, "linux"));
});
it.effect(
diff --git a/apps/desktop/src/app/DesktopPreReadyPlatform.ts b/apps/desktop/src/app/DesktopPreReadyPlatform.ts
index 848fcfca0a7..58670439a52 100644
--- a/apps/desktop/src/app/DesktopPreReadyPlatform.ts
+++ b/apps/desktop/src/app/DesktopPreReadyPlatform.ts
@@ -92,21 +92,14 @@ export const make = Effect.gen(function* () {
: undefined;
if (iconPath !== undefined) {
try {
- // Electron's copyFile extracts ASAR entries to temporary files it never removes.
- const icon = NodeFS.readFileSync(
+ NodeFS.mkdirSync(NodePath.posix.dirname(iconPath), { recursive: true });
+ NodeFS.copyFileSync(
NodePath.posix.join(
Electron.app.getAppPath(),
"apps/desktop/prod-resources/icon.png",
),
+ iconPath,
);
- let current: Buffer | null = null;
- try {
- current = NodeFS.readFileSync(iconPath);
- } catch {}
- if (current === null || !current.equals(icon)) {
- NodeFS.mkdirSync(NodePath.posix.dirname(iconPath), { recursive: true });
- NodeFS.writeFileSync(iconPath, icon, { mode: 0o600 });
- }
} catch {}
}
NodeFS.writeFileSync(
diff --git a/apps/desktop/src/app/DesktopRuntime.ts b/apps/desktop/src/app/DesktopRuntime.ts
deleted file mode 100644
index 17fc96b93b6..00000000000
--- a/apps/desktop/src/app/DesktopRuntime.ts
+++ /dev/null
@@ -1,11 +0,0 @@
-import * as Runtime from "effect/Runtime";
-
-// DesktopLifecycle owns signals and waits for backend shutdown before quitting
-// Electron. NodeRuntime's competing signal handler interrupts that sequence.
-export const runMain = Runtime.makeRunMain(({ fiber, teardown }) => {
- fiber.addObserver((exit) => {
- teardown(exit, (code) => {
- if (code !== 0) process.exit(code);
- });
- });
-});
diff --git a/apps/desktop/src/backend/DesktopBackendManager.test.ts b/apps/desktop/src/backend/DesktopBackendManager.test.ts
index 725779de476..eaf7fc30845 100644
--- a/apps/desktop/src/backend/DesktopBackendManager.test.ts
+++ b/apps/desktop/src/backend/DesktopBackendManager.test.ts
@@ -262,7 +262,7 @@ describe("DesktopBackendManager", () => {
assert.equal(spawnedCommand.options.additionalFds?.fd5?.type, "output");
assert.equal(
Duration.toMillis(Duration.fromInputUnsafe(spawnedCommand.options.forceKillAfter)),
- 30_000,
+ 5_000,
);
assert.deepEqual(yield* decodeBootstrap(bootstrapJson), configWithObservability);
@@ -1546,15 +1546,14 @@ describe("DesktopBackendManager", () => {
),
);
- it.effect("stopAllPoolInstances allows slow cleanup but bounds hung backends", () =>
+ it.effect("stopAllPoolInstances bounds the quit finalizer when backends hang", () =>
Effect.scoped(
Effect.gen(function* () {
const teardownStarted = yield* Queue.unbounded<string>();
const teardownFinished = yield* Queue.unbounded<string>();
- const allowSlowTeardown = yield* Deferred.make<void>();
- const allowHungTeardown = yield* Deferred.make<void>();
+ const allowTeardown = yield* Deferred.make<void>();
- const makeInstance = (name: string, allowTeardown: Deferred.Deferred<void>) =>
+ const makeInstance = (name: string) =>
makeTestInstance({
spawnerLayer: Layer.succeed(
ChildProcessSpawner.ChildProcessSpawner,
@@ -1576,8 +1575,8 @@ describe("DesktopBackendManager", () => {
httpClientLayer: layerHttpClient(() => Effect.never),
});
- const instance1 = yield* makeInstance("instance1", allowSlowTeardown);
- const instance2 = yield* makeInstance("instance2", allowHungTeardown);
+ const instance1 = yield* makeInstance("instance1");
+ const instance2 = yield* makeInstance("instance2");
yield* instance1.start;
yield* instance2.start;
@@ -1595,25 +1594,15 @@ describe("DesktopBackendManager", () => {
).pipe(Effect.provide(layerMockPool), Effect.forkChild);
const started = yield* Queue.takeN(teardownStarted, 2);
- yield* Effect.addFinalizer(() =>
- Deferred.succeed(allowSlowTeardown, undefined).pipe(
- Effect.andThen(Deferred.succeed(allowHungTeardown, undefined)),
- ),
- );
assert.deepEqual(started.toSorted(), ["instance1", "instance2"]);
- yield* TestClock.adjust(Duration.seconds(6));
- assert.isUndefined(quitFiber.pollUnsafe());
- yield* Deferred.succeed(allowSlowTeardown, undefined);
- assert.equal(yield* Queue.take(teardownFinished), "instance1");
- assert.isUndefined(quitFiber.pollUnsafe());
- yield* TestClock.adjust(Duration.seconds(39));
-
+ yield* TestClock.adjust(Duration.seconds(5));
yield* Fiber.join(quitFiber);
assert.equal(yield* Queue.size(teardownFinished), 0);
- yield* Deferred.succeed(allowHungTeardown, undefined);
- assert.equal(yield* Queue.take(teardownFinished), "instance2");
+ yield* Deferred.succeed(allowTeardown, undefined);
+ const finished = yield* Queue.takeN(teardownFinished, 2);
+ assert.deepEqual(finished.toSorted(), ["instance1", "instance2"]);
}).pipe(Effect.provide(TestClock.layer())),
),
);
diff --git a/apps/desktop/src/backend/DesktopBackendManager.ts b/apps/desktop/src/backend/DesktopBackendManager.ts
index 50587ac26f8..e74e98a079b 100644
--- a/apps/desktop/src/backend/DesktopBackendManager.ts
+++ b/apps/desktop/src/backend/DesktopBackendManager.ts
@@ -37,8 +37,9 @@ const MAX_PREFLIGHT_FAILURE_ATTEMPTS = 5;
const DEFAULT_BACKEND_READINESS_TIMEOUT = Duration.minutes(1);
const DEFAULT_BACKEND_READINESS_INTERVAL = Duration.millis(100);
const DEFAULT_BACKEND_READINESS_REQUEST_TIMEOUT = Duration.seconds(1);
-// Give busy backends time to stop provider sessions before forcing termination.
-const DEFAULT_BACKEND_TERMINATE_GRACE = Duration.seconds(30);
+// Same as the service launcher. A killed backend leaves its agents running,
+// and a busy one needs a few seconds to stop every provider session.
+const DEFAULT_BACKEND_TERMINATE_GRACE = Duration.seconds(5);
const DEFAULT_BACKEND_OUTPUT_DRAIN_TIMEOUT = Duration.seconds(5);
const BACKEND_READINESS_PATH = "/.well-known/t3/environment";
const { logWarning: logBackendProcessWarning } =
diff --git a/apps/desktop/src/electron/ElectronUpdater.test.ts b/apps/desktop/src/electron/ElectronUpdater.test.ts
index 969cd6fb40b..1e005d26fdf 100644
--- a/apps/desktop/src/electron/ElectronUpdater.test.ts
+++ b/apps/desktop/src/electron/ElectronUpdater.test.ts
@@ -1,27 +1,8 @@
-// @effect-diagnostics nodeBuiltinImport:off -- Build real electron-updater disk fixtures with its SHA-512 encoding.
-import * as NodeServices from "@effect/platform-node/NodeServices";
-import * as NodeCrypto from "node:crypto";
-import * as NodeEvents from "node:events";
-import * as NodeModule from "node:module";
-import * as NodePath from "node:path";
-import * as Deferred from "effect/Deferred";
-import * as FileSystem from "effect/FileSystem";
-import * as Option from "effect/Option";
-import { AppImageUpdater } from "electron-updater/out/AppImageUpdater.js";
-import { DebUpdater } from "electron-updater/out/DebUpdater.js";
-import { MacUpdater } from "electron-updater/out/MacUpdater.js";
-import { GenericProvider } from "electron-updater/out/providers/GenericProvider.js";
-import type { UpdateDownloadedEvent } from "electron-updater/out/types.js";
-import { NsisUpdater } from "electron-updater/out/NsisUpdater.js";
-import * as DesktopUpdates from "../updates/DesktopUpdates.ts";
-import { flushCallbacks, makeHarness } from "../updates/updatesTestHarness.ts";
import { assert, describe, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
-import type { VerifyUpdateCodeSignature } from "electron-updater";
import { beforeEach, vi } from "vite-plus/test";
-const { autoUpdaterMock, updaterOverride } = vi.hoisted(() => ({
- updaterOverride: { current: undefined as import("electron-updater").AppUpdater | undefined },
+const { autoUpdaterMock } = vi.hoisted(() => ({
autoUpdaterMock: {
allowDowngrade: false,
allowPrerelease: false,
@@ -32,8 +13,6 @@ const { autoUpdaterMock, updaterOverride } = vi.hoisted(() => ({
fullChangelog: false,
checkForUpdates: vi.fn(() => Promise.resolve(null)),
downloadUpdate: vi.fn(() => Promise.resolve([])),
- logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn() },
- verifyUpdateCodeSignature: undefined as VerifyUpdateCodeSignature | undefined,
on: vi.fn(),
quitAndInstall: vi.fn(),
removeListener: vi.fn(),
@@ -42,9 +21,7 @@ const { autoUpdaterMock, updaterOverride } = vi.hoisted(() => ({
}));
vi.mock("electron-updater", () => ({
- get autoUpdater() {
- return updaterOverride.current ?? autoUpdaterMock;
- },
+ autoUpdater: autoUpdaterMock,
}));
import * as ElectronUpdater from "./ElectronUpdater.ts";
@@ -66,7 +43,6 @@ describe("ElectronUpdater", () => {
autoUpdaterMock.quitAndInstall.mockClear();
autoUpdaterMock.removeListener.mockClear();
autoUpdaterMock.setFeedURL.mockClear();
- autoUpdaterMock.verifyUpdateCodeSignature = undefined;
});
it.effect("scopes updater event listeners", () =>
@@ -160,286 +136,4 @@ describe("ElectronUpdater", () => {
assert.deepEqual(autoUpdaterMock.quitAndInstall.mock.calls, [[true, false]]);
}).pipe(Effect.provide(ElectronUpdater.layer)),
);
-
- describe("Windows update signature check", () => {
- const publisherNames = ["T3 Tools Inc"];
- const installerPath = "C:\\updater\\pending\\temp-T3-Code-x64.exe";
- // execFile marks the error killed when the verifier exceeds its 20-second timeout.
- const timedOut = () =>
- Object.assign(new Error("Command failed: powershell.exe"), { killed: true });
-
- const downloadVerifyingSignature = () => {
- autoUpdaterMock.downloadUpdate.mockImplementationOnce(async () => {
- const rejection = await autoUpdaterMock.verifyUpdateCodeSignature!(
- publisherNames,
- installerPath,
- );
- // NSIS accepts only null as a successful signature check.
- if (rejection !== null) throw new Error(`Invalid signature: ${rejection}`);
- return [];
- });
- return Effect.flatMap(ElectronUpdater.ElectronUpdater, (updater) => updater.downloadUpdate);
- };
-
- it.effect("retries a timed-out signature check with the same verifier and installer", () =>
- Effect.gen(function* () {
- const verify = vi
- .fn<VerifyUpdateCodeSignature>()
- .mockRejectedValueOnce(timedOut())
- .mockResolvedValueOnce(null);
- autoUpdaterMock.verifyUpdateCodeSignature = verify;
-
- yield* downloadVerifyingSignature();
-
- assert.deepEqual(verify.mock.calls, [
- [publisherNames, installerPath],
- [publisherNames, installerPath],
- ]);
- }).pipe(Effect.provide(ElectronUpdater.layer)),
- );
-
- it.effect("fails on invalid signatures, other errors and two timeouts on each download", () =>
- Effect.gen(function* () {
- const cases = [
- { outcome: () => Promise.resolve("Invalid publisher"), calls: 1 },
- { outcome: () => Promise.reject(new Error("Cannot execute PowerShell")), calls: 1 },
- { outcome: () => Promise.reject(timedOut()), calls: 2 },
- ];
- for (const { outcome, calls } of cases) {
- const verify = vi.fn<VerifyUpdateCodeSignature>(outcome);
- autoUpdaterMock.verifyUpdateCodeSignature = verify;
-
- // Reusing the installed verifier must neither stack retries nor exhaust future retries.
- for (let download = 1; download <= 2; download++) {
- const error = yield* downloadVerifyingSignature().pipe(Effect.flip);
- assert.instanceOf(error, ElectronUpdater.ElectronUpdaterDownloadUpdateError);
- assert.equal(verify.mock.calls.length, calls * download);
- }
- }
- }).pipe(Effect.provide(ElectronUpdater.layer)),
- );
-
- it.effect("rejects a retry when the upstream capability probe skips verification", () =>
- Effect.gen(function* () {
- const verify = vi
- .fn<VerifyUpdateCodeSignature>()
- .mockRejectedValueOnce(timedOut())
- .mockImplementationOnce(async () => {
- // Upstream resolves null even though its failed capability probe skips verification.
- autoUpdaterMock.logger.warn(
- "Cannot execute ConvertTo-Json: spawnSync powershell.exe ETIMEDOUT. Ignoring signature validation due to unsupported powershell version. Please upgrade to powershell 3 or higher.",
- );
- return null;
- });
- autoUpdaterMock.verifyUpdateCodeSignature = verify;
-
- const error = yield* downloadVerifyingSignature().pipe(Effect.flip);
-
- assert.instanceOf(error, ElectronUpdater.ElectronUpdaterDownloadUpdateError);
- assert.equal(verify.mock.calls.length, 2);
- }).pipe(Effect.provide(ElectronUpdater.layer)),
- );
- });
-});
-
-describe("installed electron-updater cache recovery", () => {
- it.effect.each([
- {
- name: "Intel Mac",
- platform: "darwin",
- Updater: MacUpdater,
- selected: "x64.zip",
- other: "arm64.zip",
- rosetta: false,
- },
- {
- name: "Apple Silicon running Intel",
- platform: "darwin",
- Updater: MacUpdater,
- selected: "arm64.zip",
- other: "x64.zip",
- rosetta: true,
- },
- {
- name: "Windows",
- platform: "win32",
- Updater: NsisUpdater,
- selected: "x64.exe",
- other: "arm64.exe",
- rosetta: false,
- },
- {
- name: "Debian",
- platform: "linux",
- Updater: DebUpdater,
- selected: "x64.deb",
- other: "x64.AppImage",
- rosetta: false,
- },
- {
- name: "AppImage",
- platform: "linux",
- Updater: AppImageUpdater,
- selected: "x64.AppImage",
- other: "x64.deb",
- rosetta: false,
- },
- ] as const)("restores only the package selected by $name", (scenario) =>
- Effect.scoped(
- Effect.gen(function* () {
- const fs = yield* FileSystem.FileSystem;
- const directory = yield* fs.makeTempDirectoryScoped();
- const cacheDirectory = NodePath.join(directory, "custom-updater-cache", "pending");
- const configPath = NodePath.join(directory, "app-update.yml");
- yield* fs.writeFileString(configPath, "updaterCacheDirName: custom-updater-cache\n");
- yield* fs.makeDirectory(cacheDirectory, { recursive: true });
-
- const require = NodeModule.createRequire(import.meta.url);
- require("electron");
- const electronModule = require.cache[require.resolve("electron")]!;
- const childProcess = require("node:child_process") as typeof import("node:child_process");
- const originalElectron = electronModule.exports;
- const originalArch = Object.getOwnPropertyDescriptor(process, "arch")!;
- yield* Effect.acquireRelease(
- Effect.sync(() => {
- // MacUpdater's native Squirrel bridge and host probes are OS boundaries.
- electronModule.exports = { autoUpdater: new NodeEvents.EventEmitter() };
- Object.defineProperty(process, "arch", { value: "x64", configurable: true });
- return vi
- .spyOn(childProcess, "execFileSync")
- .mockReturnValue(scenario.rosetta ? "sysctl.proc_translated: 1" : "x86_64");
- }),
- (probe) =>
- Effect.sync(() => {
- probe.mockRestore();
- Object.defineProperty(process, "arch", originalArch);
- electronModule.exports = originalElectron;
- updaterOverride.current = undefined;
- }),
- );
-
- const extensions =
- scenario.platform === "darwin"
- ? ["arm64.dmg", "x64.dmg", "arm64.zip", "x64.zip"]
- : scenario.platform === "win32"
- ? ["arm64.exe", "x64.exe"]
- : ["arm64.AppImage", "x64.AppImage", "arm64.deb", "x64.deb"];
- const files = extensions.map((extension) => {
- const url = `T3-Code-1.2.4-${extension}`;
- return { url, sha512: NodeCrypto.createHash("sha512").update(url).digest("base64") };
- });
- const info = {
- version: "1.2.4",
- releaseDate: "2026-10-01T00:00:00Z",
- files,
- path: files[0]!.url,
- sha512: files[0]!.sha512,
- };
- yield* Effect.acquireRelease(
- Effect.sync(() =>
- vi.spyOn(GenericProvider.prototype, "getLatestVersion").mockResolvedValue(info),
- ),
- (feed) => Effect.sync(() => feed.mockRestore()),
- );
-
- // A fresh instance for each launch forces disk validation rather than in-memory reuse.
- yield* Effect.forEach([scenario.other, scenario.selected], (cachedExtension) =>
- Effect.scoped(
- Effect.gen(function* () {
- const cached = files.find((file) => file.url.endsWith(`-${cachedExtension}`))!;
- yield* fs.writeFileString(NodePath.join(cacheDirectory, cached.url), cached.url);
- yield* fs.writeFileString(
- NodePath.join(cacheDirectory, "update-info.json"),
- JSON.stringify({
- fileName: cached.url,
- sha512: cached.sha512,
- isAdminRightsRequired: false,
- }),
- );
- const updater = new scenario.Updater(undefined, {
- version: "1.2.3",
- name: "T3 Code",
- isPackaged: true,
- appUpdateConfigPath: configPath,
- userDataPath: directory,
- baseCachePath: directory,
- whenReady: () => Promise.resolve(),
- relaunch: vi.fn(),
- quit: vi.fn(),
- onQuit: vi.fn(),
- });
- updater.logger = null;
- const networkDownload = vi.fn(() =>
- Promise.reject(new Error("unexpected network download")),
- );
- Object.assign(updater, { httpExecutor: { download: networkDownload } });
- if (updater instanceof MacUpdater) {
- // Keep real selection, executeDownload, and hash validation; stop at native handoff.
- Object.assign(updater, {
- updateDownloaded: async (_file: unknown, event: UpdateDownloadedEvent) => {
- updater.emit("update-downloaded", event);
- return [];
- },
- });
- }
- updaterOverride.current = updater;
- assert.deepEqual(
- yield* ElectronUpdater.make.pendingDownloadDirectory,
- Option.some(cacheDirectory),
- );
-
- const inspected = Deferred.makeUnsafe<void>();
- const downloadFinished = Deferred.makeUnsafe<void>();
- const download = vi.spyOn(updater, "downloadUpdate");
- const harness = makeHarness({
- platform: scenario.platform,
- runningUnderArm64Translation: scenario.rosetta,
- env: scenario.selected.endsWith("AppImage")
- ? { APPIMAGE: "/test/T3-Code.AppImage" }
- : {},
- updater: {
- ...ElectronUpdater.make,
- downloadUpdate: ElectronUpdater.make.downloadUpdate.pipe(
- Effect.ensuring(Deferred.succeed(downloadFinished, undefined)),
- ),
- },
- fileSystem: {
- ...fs,
- readFileString: (path, encoding) =>
- path === "/missing/resources/package-type" && scenario.selected.endsWith("deb")
- ? Effect.succeed("deb")
- : fs.readFileString(path, encoding),
- exists: (path) =>
- fs.exists(path).pipe(Effect.tap(() => Deferred.succeed(inspected, undefined))),
- },
- });
- yield* Effect.scoped(
- Effect.gen(function* () {
- const updates = yield* DesktopUpdates.DesktopUpdates;
- yield* updates.configure;
- // AppImage activation reads the host environment; the fixture is intentionally not installed.
- vi.spyOn(updater, "isUpdaterActive").mockReturnValue(true);
- assert.isTrue((yield* updates.check("startup")).checked);
- yield* Deferred.await(inspected);
- yield* flushCallbacks;
-
- if (cachedExtension === scenario.other) {
- assert.equal(download.mock.calls.length, 0);
- assert.equal((yield* updates.getState).status, "available");
- } else {
- yield* Deferred.await(downloadFinished);
- yield* flushCallbacks;
- assert.equal(download.mock.calls.length, 1);
- assert.equal((yield* updates.getState).status, "downloaded");
- assert.equal((yield* updates.getState).downloadedVersion, "1.2.4");
- }
- assert.equal(networkDownload.mock.calls.length, 0);
- }),
- ).pipe(Effect.provide(harness.layer));
- }),
- ),
- );
- }),
- ).pipe(Effect.provide(NodeServices.layer)),
- );
});
diff --git a/apps/desktop/src/electron/ElectronUpdater.ts b/apps/desktop/src/electron/ElectronUpdater.ts
index 77709c4a2f3..e42ebc1003a 100644
--- a/apps/desktop/src/electron/ElectronUpdater.ts
+++ b/apps/desktop/src/electron/ElectronUpdater.ts
@@ -1,12 +1,10 @@
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
-import * as Option from "effect/Option";
import * as Schema from "effect/Schema";
import * as Scope from "effect/Scope";
import { autoUpdater } from "electron-updater";
-import type { NsisUpdater, VerifyUpdateCodeSignature } from "electron-updater";
type AutoUpdater = typeof autoUpdater;
@@ -69,7 +67,6 @@ export class ElectronUpdater extends Context.Service<
readonly setAllowDowngrade: (value: boolean) => Effect.Effect<void>;
readonly setFullChangelog: (value: boolean) => Effect.Effect<void>;
readonly setDisableDifferentialDownload: (value: boolean) => Effect.Effect<void>;
- readonly pendingDownloadDirectory: Effect.Effect<Option.Option<string>>;
readonly checkForUpdates: Effect.Effect<void, ElectronUpdaterCheckForUpdatesError>;
readonly downloadUpdate: Effect.Effect<void, ElectronUpdaterDownloadUpdateError>;
readonly quitAndInstall: (options: {
@@ -83,45 +80,6 @@ export class ElectronUpdater extends Context.Service<
}
>()("@t3tools/desktop/electron/ElectronUpdater") {}
-const signatureChecksWithRetry = new WeakSet<VerifyUpdateCodeSignature>();
-
-const retrySignatureCheckAfterTimeout = () => {
- // Only the Windows NSIS updater exposes this hook; its PowerShell check times out after 20 s.
- const updater = autoUpdater as AutoUpdater &
- Partial<Pick<NsisUpdater, "verifyUpdateCodeSignature">>;
- const verify = updater.verifyUpdateCodeSignature;
- if (verify === undefined || signatureChecksWithRetry.has(verify)) return;
-
- const verifyWithRetry: VerifyUpdateCodeSignature = async (publisherNames, path) => {
- try {
- return await verify(publisherNames, path);
- } catch (error) {
- if (!(error instanceof Error && "killed" in error && error.killed === true)) throw error;
- }
-
- const logger = updater.logger;
- let skipped = false;
- updater.logger = {
- info: (message) => logger?.info(message),
- warn: (message) => {
- // A failed capability probe makes electron-updater warn and return null without checking.
- skipped ||= String(message).includes("Ignoring signature validation");
- logger?.warn(message);
- },
- error: (message) => logger?.error(message),
- debug: (message) => logger?.debug?.(message),
- };
- try {
- const result = await verify(publisherNames, path);
- return skipped ? "Signature validation was skipped after a timed-out check." : result;
- } finally {
- updater.logger = logger;
- }
- };
- signatureChecksWithRetry.add(verifyWithRetry);
- updater.verifyUpdateCodeSignature = verifyWithRetry;
-};
-
/** @public Service construction is part of the canonical Effect module API. */
export const make = ElectronUpdater.of({
setFeedURL: (options) =>
@@ -165,17 +123,6 @@ export const make = ElectronUpdater.of({
autoUpdater.disableDifferentialDownload = value;
return Effect.void;
}),
- // Use the updater's helper so cache lookup follows the same configuration as downloads.
- pendingDownloadDirectory: Effect.tryPromise(() =>
- (
- autoUpdater as unknown as {
- getOrCreateDownloadHelper: () => Promise<{ readonly cacheDirForPendingUpdate: string }>;
- }
- ).getOrCreateDownloadHelper(),
- ).pipe(
- Effect.map((helper) => helper.cacheDirForPendingUpdate),
- Effect.option,
- ),
checkForUpdates: Effect.suspend(() => {
const channel = autoUpdater.channel;
return Effect.tryPromise({
@@ -184,7 +131,6 @@ export const make = ElectronUpdater.of({
}).pipe(Effect.asVoid);
}),
downloadUpdate: Effect.suspend(() => {
- retrySignatureCheckAfterTimeout();
const channel = autoUpdater.channel;
return Effect.tryPromise({
try: () => autoUpdater.downloadUpdate(),
diff --git a/apps/desktop/src/ipc/DesktopIpcHandlers.ts b/apps/desktop/src/ipc/DesktopIpcHandlers.ts
index e2e477e81ac..2d67aa56e6c 100644
--- a/apps/desktop/src/ipc/DesktopIpcHandlers.ts
+++ b/apps/desktop/src/ipc/DesktopIpcHandlers.ts
@@ -40,7 +40,6 @@ import {
import {
getAppBranding,
getLocalEnvironmentBootstraps,
- readLocalEnvironmentBootstraps,
getLocalEnvironmentBearerToken,
getRelayTelemetryEnabled,
getSystemLocale,
@@ -101,7 +100,6 @@ export const installDesktopIpcHandlers = Effect.fn("desktop.ipc.installHandlers"
yield* ipc.handleSync(getSystemLocale);
yield* ipc.handleSync(getWindowFullscreenState);
yield* ipc.handleSync(getLocalEnvironmentBootstraps);
- yield* ipc.handle(readLocalEnvironmentBootstraps);
yield* ipc.handleSync(getLocalEnvironmentEnabled);
yield* ipc.handle(setLocalEnvironmentEnabled);
yield* ipc.handle(getLocalEnvironmentBearerToken);
diff --git a/apps/desktop/src/ipc/methods/window.ts b/apps/desktop/src/ipc/methods/window.ts
index 924d20775cd..9066cf6f1a6 100644
--- a/apps/desktop/src/ipc/methods/window.ts
+++ b/apps/desktop/src/ipc/methods/window.ts
@@ -99,68 +99,57 @@ export const getWindowFullscreenState = DesktopIpc.makeSyncIpcMethod({
}),
});
-const readLocalEnvironmentBootstrapSnapshot = Effect.fn(
- "desktop.ipc.window.getLocalEnvironmentBootstraps",
-)(function* () {
- const pool = yield* DesktopBackendPool.DesktopBackendPool;
- const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
- const instances = yield* pool.list;
- const bootstraps: DesktopEnvironmentBootstrap[] = [];
- for (const instance of instances) {
- const isPrimary = instance.id === PRIMARY_LOCAL_ENVIRONMENT_ID;
- const config = yield* instance.currentConfig;
- const snapshot = yield* instance.snapshot;
- if (Option.isNone(config) || Option.isSome(config.value.preflightFailure)) {
- const fatalPreflight =
- Option.isSome(config) &&
- Option.isSome(config.value.preflightFailure) &&
- config.value.preflightFailure.value.fatal;
- const stoppedPreflight =
- Option.isSome(config) &&
- Option.isSome(config.value.preflightFailure) &&
- (!snapshot.desiredRunning || !snapshot.restartScheduled);
- if (isPrimary || fatalPreflight || stoppedPreflight) continue;
+export const getLocalEnvironmentBootstraps = DesktopIpc.makeSyncIpcMethod({
+ channel: IpcChannels.GET_LOCAL_ENVIRONMENT_BOOTSTRAPS_CHANNEL,
+ result: Schema.Array(DesktopEnvironmentBootstrapSchema),
+ handler: Effect.fn("desktop.ipc.window.getLocalEnvironmentBootstraps")(function* () {
+ const pool = yield* DesktopBackendPool.DesktopBackendPool;
+ const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
+ const instances = yield* pool.list;
+ const bootstraps: DesktopEnvironmentBootstrap[] = [];
+ for (const instance of instances) {
+ const isPrimary = instance.id === PRIMARY_LOCAL_ENVIRONMENT_ID;
+ const config = yield* instance.currentConfig;
+ const snapshot = yield* instance.snapshot;
+ if (Option.isNone(config) || Option.isSome(config.value.preflightFailure)) {
+ const fatalPreflight =
+ Option.isSome(config) &&
+ Option.isSome(config.value.preflightFailure) &&
+ config.value.preflightFailure.value.fatal;
+ const stoppedPreflight =
+ Option.isSome(config) &&
+ Option.isSome(config.value.preflightFailure) &&
+ (!snapshot.desiredRunning || !snapshot.restartScheduled);
+ if (isPrimary || fatalPreflight || stoppedPreflight) continue;
+ bootstraps.push({
+ id: instance.id,
+ label: yield* instance.label,
+ runningDistro: null,
+ httpBaseUrl: null,
+ wsBaseUrl: null,
+ });
+ continue;
+ }
+ const { bootstrap, httpBaseUrl } = config.value;
+ const runningDistro = config.value.runningDistro ?? null;
bootstraps.push({
id: instance.id,
- label: yield* instance.label,
- runningDistro: null,
- httpBaseUrl: null,
- wsBaseUrl: null,
+ label: runningDistro === null ? yield* instance.label : `WSL (${runningDistro})`,
+ runningDistro,
+ httpBaseUrl: httpBaseUrl.href,
+ wsBaseUrl: toWebSocketBaseUrl(httpBaseUrl),
+ // A backend launched with the desktop secret accepts whichever token the secret derives
+ // for the current window, so hand out that one rather than the token frozen into its
+ // launch config.
+ ...(bootstrap.desktopBootstrapSecret
+ ? { bootstrapToken: yield* configuration.currentBootstrapToken }
+ : bootstrap.desktopBootstrapToken
+ ? { bootstrapToken: bootstrap.desktopBootstrapToken }
+ : {}),
});
- continue;
}
- const { bootstrap, httpBaseUrl } = config.value;
- const runningDistro = config.value.runningDistro ?? null;
- bootstraps.push({
- id: instance.id,
- label: runningDistro === null ? yield* instance.label : `WSL (${runningDistro})`,
- runningDistro,
- httpBaseUrl: httpBaseUrl.href,
- wsBaseUrl: toWebSocketBaseUrl(httpBaseUrl),
- // A backend launched with the desktop secret accepts whichever token the secret derives
- // for the current window, so hand out that one rather than the token frozen into its
- // launch config.
- ...(bootstrap.desktopBootstrapSecret
- ? { bootstrapToken: yield* configuration.currentBootstrapToken }
- : bootstrap.desktopBootstrapToken
- ? { bootstrapToken: bootstrap.desktopBootstrapToken }
- : {}),
- });
- }
- return bootstraps;
-});
-
-export const getLocalEnvironmentBootstraps = DesktopIpc.makeSyncIpcMethod({
- channel: IpcChannels.GET_LOCAL_ENVIRONMENT_BOOTSTRAPS_CHANNEL,
- result: Schema.Array(DesktopEnvironmentBootstrapSchema),
- handler: readLocalEnvironmentBootstrapSnapshot,
-});
-
-export const readLocalEnvironmentBootstraps = DesktopIpc.makeIpcMethod({
- channel: IpcChannels.GET_LOCAL_ENVIRONMENT_BOOTSTRAPS_CHANNEL,
- payload: Schema.Void,
- result: Schema.Array(DesktopEnvironmentBootstrapSchema),
- handler: readLocalEnvironmentBootstrapSnapshot,
+ return bootstraps;
+ }),
});
function extractWslDistroFromEnvironmentId(envId: string): string | null {
diff --git a/apps/desktop/src/ipc/methods/wsl.test.ts b/apps/desktop/src/ipc/methods/wsl.test.ts
index 34c3c9080ea..644597eaf45 100644
--- a/apps/desktop/src/ipc/methods/wsl.test.ts
+++ b/apps/desktop/src/ipc/methods/wsl.test.ts
@@ -120,43 +120,6 @@ describe("WSL IPC", () => {
),
);
- it.effect("does not enumerate distros until the WSL backend is enabled", () => {
- const distros = [
- { name: "Ubuntu", isDefault: true, version: 2 as const },
- { name: "Debian", isDefault: false, version: 2 as const },
- ];
- const layer = Layer.mergeAll(
- DesktopAppSettings.layerTest({
- ...DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS,
- wslDistro: "Debian",
- }),
- DesktopWslEnvironment.layerTest({ isAvailable: true, distros }),
- layerWslBackend(),
- layerLifecycle([]),
- layerUnusedLifecycleRuntime,
- );
-
- return Effect.gen(function* () {
- const wsl = yield* DesktopWslEnvironment.DesktopWslEnvironment;
- const state = yield* getWslState.handler(undefined).pipe(
- Effect.provideService(DesktopWslEnvironment.DesktopWslEnvironment, {
- ...wsl,
- listDistros: Effect.die("must not enumerate distros"),
- }),
- Effect.flatMap(decodeWslState),
- );
- assert.equal(state.enabled, false);
- assert.equal(state.available, true);
- assert.equal(state.distro, "Debian");
- assert.deepEqual(state.distros, []);
-
- const enabledState = yield* invokeSetWslBackendEnabled(true);
- assert.equal(enabledState.enabled, true);
- assert.equal(enabledState.distro, "Debian");
- assert.deepEqual(enabledState.distros, distros);
- }).pipe(Effect.provide(layer));
- });
-
it.effect("stages dual-backend preferences before enabling without relaunching", () => {
const relaunchReasons: Array<string> = [];
const layer = Layer.mergeAll(
diff --git a/apps/desktop/src/ipc/methods/wsl.ts b/apps/desktop/src/ipc/methods/wsl.ts
index 6a36e87bbfc..3c10f04512b 100644
--- a/apps/desktop/src/ipc/methods/wsl.ts
+++ b/apps/desktop/src/ipc/methods/wsl.ts
@@ -22,9 +22,9 @@ const readWslState: Effect.Effect<
const wslBackend = yield* DesktopWslBackend.DesktopWslBackend;
const settings = yield* appSettings.get;
const available = settings.localEnvironmentEnabled && (yield* wslEnvironment.isAvailable);
- // Windows ships a wsl.exe stub that can prompt to install WSL when invoked.
- // Keep disabled state reads from launching it to enumerate distros.
- const distros = available && settings.wslBackendEnabled ? yield* wslEnvironment.listDistros : [];
+ // Only enumerate distros when WSL is actually available — listDistros on a
+ // non-WSL host would spawn wsl.exe and hit the timeout for nothing.
+ const distros = available ? yield* wslEnvironment.listDistros : [];
const preflightError = yield* wslBackend.lastPreflightError;
return {
enabled: settings.wslBackendEnabled,
diff --git a/apps/desktop/src/main.ts b/apps/desktop/src/main.ts
index a089720b6c0..3056ce1ea26 100644
--- a/apps/desktop/src/main.ts
+++ b/apps/desktop/src/main.ts
@@ -6,6 +6,7 @@ for (const stream of [process.stdout, process.stderr]) {
}
import * as NodeHttpClient from "@effect/platform-node/NodeHttpClient";
+import * as NodeRuntime from "@effect/platform-node/NodeRuntime";
import * as NodeServices from "@effect/platform-node/NodeServices";
// @effect-diagnostics-next-line nodeBuiltinImport:off - Version output must flush before Electron exits, without acquiring the runtime.
import * as NodeFS from "node:fs";
@@ -21,7 +22,6 @@ import * as HostProcess from "@t3tools/shared/HostProcess";
import type { RemoteT3RunnerOptions } from "@t3tools/ssh/tunnel";
import serverPackageJson from "../../server/package.json" with { type: "json" };
-import * as DesktopRuntime from "./app/DesktopRuntime.ts";
import * as DesktopIpc from "./ipc/DesktopIpc.ts";
import * as ElectronApp from "./electron/ElectronApp.ts";
import * as ElectronDialog from "./electron/ElectronDialog.ts";
@@ -242,4 +242,4 @@ const layerDesktopRuntime = layerDesktopClerk.pipe(
Layer.provideMerge(DesktopPreReadyPlatform.layer),
);
-DesktopApp.program.pipe(Effect.provide(layerDesktopRuntime), DesktopRuntime.runMain);
+DesktopApp.program.pipe(Effect.provide(layerDesktopRuntime), NodeRuntime.runMain);
diff --git a/apps/desktop/src/preload.ts b/apps/desktop/src/preload.ts
index 9fe0e9efa15..bffa02d9ca4 100644
--- a/apps/desktop/src/preload.ts
+++ b/apps/desktop/src/preload.ts
@@ -12,7 +12,6 @@ import { contextBridge, ipcRenderer, webFrame, webUtils } from "electron";
import * as IpcChannels from "./ipc/channels.ts";
import { mergeLegacyLocalStorage } from "./legacyLocalStorageMerge.ts";
-import { createPreloadSnapshot } from "./preloadSnapshot.ts";
const SNAP_SHOT_EVENT_TYPES = new Set([
"requested",
@@ -75,18 +74,6 @@ function unwrapEnsureSshEnvironmentResult(result: unknown) {
return result as Awaited<ReturnType<DesktopBridge["ensureSshEnvironment"]>>;
}
-const readBootstraps = (
- result: unknown,
-): ReturnType<DesktopBridge["getLocalEnvironmentBootstraps"]> =>
- Array.isArray(result) ? result : [];
-const localEnvironmentBootstraps = createPreloadSnapshot(
- () => readBootstraps(ipcRenderer.sendSync(IpcChannels.GET_LOCAL_ENVIRONMENT_BOOTSTRAPS_CHANNEL)),
- async () =>
- readBootstraps(await ipcRenderer.invoke(IpcChannels.GET_LOCAL_ENVIRONMENT_BOOTSTRAPS_CHANNEL)),
-);
-// Changes take effect on relaunch, so renderer reads can reuse the startup value.
-let localEnvironmentEnabled: boolean | undefined;
-
contextBridge.exposeInMainWorld("desktopBridge", {
getAppBranding: () => {
const result = ipcRenderer.sendSync(IpcChannels.GET_APP_BRANDING_CHANNEL);
@@ -116,13 +103,17 @@ contextBridge.exposeInMainWorld("desktopBridge", {
const result = ipcRenderer.sendSync(IpcChannels.GET_SYSTEM_LOCALE_CHANNEL);
return typeof result === "string" ? result : null;
},
- getLocalEnvironmentBootstraps: localEnvironmentBootstraps.read,
- readLocalEnvironmentBootstraps: localEnvironmentBootstraps.refresh,
+ getLocalEnvironmentBootstraps: () => {
+ const result = ipcRenderer.sendSync(IpcChannels.GET_LOCAL_ENVIRONMENT_BOOTSTRAPS_CHANNEL);
+ if (!Array.isArray(result)) {
+ return [];
+ }
+ return result as ReturnType<DesktopBridge["getLocalEnvironmentBootstraps"]>;
+ },
getLocalEnvironmentBearerToken: () =>
ipcRenderer.invoke(IpcChannels.GET_LOCAL_ENVIRONMENT_BEARER_TOKEN_CHANNEL),
getLocalEnvironmentEnabled: () =>
- (localEnvironmentEnabled ??=
- ipcRenderer.sendSync(IpcChannels.GET_LOCAL_ENVIRONMENT_ENABLED_CHANNEL) !== false),
+ ipcRenderer.sendSync(IpcChannels.GET_LOCAL_ENVIRONMENT_ENABLED_CHANNEL) !== false,
setLocalEnvironmentEnabled: (enabled) =>
ipcRenderer.invoke(IpcChannels.SET_LOCAL_ENVIRONMENT_ENABLED_CHANNEL, enabled),
getClientSettings: () => ipcRenderer.invoke(IpcChannels.GET_CLIENT_SETTINGS_CHANNEL),
diff --git a/apps/desktop/src/preloadSnapshot.test.ts b/apps/desktop/src/preloadSnapshot.test.ts
deleted file mode 100644
index 05783e83003..00000000000
--- a/apps/desktop/src/preloadSnapshot.test.ts
+++ /dev/null
@@ -1,45 +0,0 @@
-import { expect, it, vi } from "vite-plus/test";
-
-import { createPreloadSnapshot } from "./preloadSnapshot.ts";
-
-it("serves the startup snapshot while a shared asynchronous refresh is pending", async () => {
- const initial = ["primary"];
- const latest = Promise.withResolvers<string[]>();
- const readInitial = vi.fn(() => initial);
- const readLatest = vi.fn(() => latest.promise);
- const snapshot = createPreloadSnapshot(readInitial, readLatest);
-
- expect(snapshot.read()).toBe(initial);
- const first = snapshot.refresh();
- const second = snapshot.refresh();
- expect(snapshot.read()).toBe(initial);
- expect(snapshot.read()).toBe(initial);
- expect(readInitial).toHaveBeenCalledTimes(1);
- expect(readLatest).toHaveBeenCalledTimes(1);
-
- const connected = ["primary", "wsl"];
- latest.resolve(connected);
- expect(await first).toBe(connected);
- expect(await second).toBe(connected);
- expect(snapshot.read()).toBe(connected);
- expect(readInitial).toHaveBeenCalledTimes(1);
-});
-
-it("retains an async snapshot through failure and replaces it on successful recovery", async () => {
- const connected = ["primary", "wsl"];
- const readInitial = vi.fn(() => ["stale"]);
- const readLatest = vi
- .fn<() => Promise<string[]>>()
- .mockResolvedValueOnce(connected)
- .mockRejectedValueOnce(new Error("IPC unavailable"))
- .mockResolvedValueOnce([]);
- const snapshot = createPreloadSnapshot(readInitial, readLatest);
-
- await snapshot.refresh();
- expect(snapshot.read()).toBe(connected);
- await expect(snapshot.refresh()).rejects.toThrow("IPC unavailable");
- expect(snapshot.read()).toBe(connected);
- await expect(snapshot.refresh()).resolves.toEqual([]);
- expect(snapshot.read()).toEqual([]);
- expect(readInitial).not.toHaveBeenCalled();
-});
diff --git a/apps/desktop/src/preloadSnapshot.ts b/apps/desktop/src/preloadSnapshot.ts
deleted file mode 100644
index 4fe34b2719f..00000000000
--- a/apps/desktop/src/preloadSnapshot.ts
+++ /dev/null
@@ -1,23 +0,0 @@
-export function createPreloadSnapshot<T>(readInitial: () => T, readLatest: () => Promise<T>) {
- let snapshot: { readonly value: T } | undefined;
- let pending: Promise<T> | undefined;
-
- return {
- read: () => {
- snapshot ??= { value: readInitial() };
- return snapshot.value;
- },
- refresh: () => {
- if (pending !== undefined) return pending;
- pending = readLatest()
- .then((value) => {
- snapshot = { value };
- return value;
- })
- .finally(() => {
- pending = undefined;
- });
- return pending;
- },
- };
-}
diff --git a/apps/desktop/src/preview/BrowserImport/ChromiumCookies.test.ts b/apps/desktop/src/preview/BrowserImport/ChromiumCookies.test.ts
index 7cf73ef633b..eace39003e3 100644
--- a/apps/desktop/src/preview/BrowserImport/ChromiumCookies.test.ts
+++ b/apps/desktop/src/preview/BrowserImport/ChromiumCookies.test.ts
@@ -151,57 +151,56 @@ describe("readChromiumCookieDatabase", () => {
}).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
);
- it.effect.each([14, 24])(
- "imports mixed TEXT and BLOB cookie values, including empty values, in schema %i",
- (schemaVersion) =>
- Effect.gen(function* () {
- const fileSystem = yield* FileSystem.FileSystem;
- const directory = yield* fileSystem.makeTempDirectoryScoped({
- prefix: "t3code-chromium-cookies-",
- });
- const filename = `${directory}/Cookies`;
- const key = Buffer.from("0123456789abcdef");
- const host = "secure.example";
- const value = "stored encrypted";
- const payload =
- schemaVersion >= 24
- ? Buffer.concat([
- NodeCrypto.createHash("sha256").update(host).digest(),
- Buffer.from(value),
- ])
- : Buffer.from(value);
- const encrypted = encryptV10(payload, key);
+ it.effect("reads plaintext, encrypted, and genuinely empty cookie values", () =>
+ Effect.gen(function* () {
+ const fileSystem = yield* FileSystem.FileSystem;
+ const directory = yield* fileSystem.makeTempDirectoryScoped({
+ prefix: "t3code-chromium-cookies-",
+ });
+ const filename = `${directory}/Cookies`;
+ const key = Buffer.from("0123456789abcdef");
- yield* Effect.gen(function* () {
- const sql = yield* SqlClient.SqlClient;
- yield* sql`create table meta (key text primary key, value text not null)`;
- yield* sql`insert into meta values ('version', ${schemaVersion})`;
- yield* sql`create table cookies (
- host_key text not null, name text not null, value text not null,
- encrypted_value blob not null, path text not null, expires_utc integer not null,
- is_secure integer not null, is_httponly integer not null, samesite integer not null
- )`;
- if (schemaVersion >= 15) {
- yield* sql`alter table cookies add column top_frame_site_key text not null default ''`;
- }
- yield* sql`insert into cookies
- (host_key, name, value, encrypted_value, path, expires_utc, is_secure, is_httponly, samesite) values
- ('plain.example', 'plain', 'stored plaintext', '', '/', 0, 0, 0, -1),
- (${host}, 'text-encrypted', '', cast(${encrypted} as text), '/', 0, 1, 1, 2),
- (${host}, 'blob-encrypted', '', ${encrypted}, '/', 0, 1, 1, 2),
- ('empty.example', 'empty', '', ${new Uint8Array()}, '/', 0, 0, 0, 0)`;
- }).pipe(Effect.provide(NodeSqliteClient.layer({ filename })));
+ yield* Effect.gen(function* () {
+ const sql = yield* SqlClient.SqlClient;
+ yield* sql`create table meta (key text primary key, value text not null)`;
+ yield* sql`insert into meta values ('version', 23)`;
+ yield* sql`
+ create table cookies (
+ host_key text not null,
+ name text not null,
+ value text not null,
+ encrypted_value blob not null,
+ path text not null,
+ expires_utc integer not null,
+ is_secure integer not null,
+ is_httponly integer not null,
+ samesite integer not null,
+ top_frame_site_key text not null default ''
+ )
+ `;
+ yield* sql`
+ insert into cookies (host_key, name, value, encrypted_value, path, expires_utc, is_secure, is_httponly, samesite) values
+ ('plain.example', 'plain', 'stored plaintext', ${new Uint8Array()}, '/', 0, 0, 0, -1)
+ `;
+ yield* sql`
+ insert into cookies (host_key, name, value, encrypted_value, path, expires_utc, is_secure, is_httponly, samesite) values
+ ('secure.example', 'encrypted', '', ${encryptV10("stored encrypted", key)}, '/', 0, 1, 1, 2)
+ `;
+ yield* sql`
+ insert into cookies (host_key, name, value, encrypted_value, path, expires_utc, is_secure, is_httponly, samesite) values
+ ('empty.example', 'empty', '', ${new Uint8Array()}, '/', 0, 0, 0, 0)
+ `;
+ }).pipe(Effect.provide(NodeSqliteClient.layer({ filename })));
- const result = yield* readChromiumCookieDatabase(filename, { cbcV10: key }, "darwin");
+ const result = yield* readChromiumCookieDatabase(filename, { cbcV10: key }, "darwin");
- expect(result.undecryptable).toBe(0);
- expect(result.cookies.map(({ name, value }) => ({ name, value }))).toEqual([
- { name: "plain", value: "stored plaintext" },
- { name: "text-encrypted", value },
- { name: "blob-encrypted", value },
- { name: "empty", value: "" },
- ]);
- }).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
+ expect(result.undecryptable).toBe(0);
+ expect(result.cookies.map(({ name, value }) => ({ name, value }))).toEqual([
+ { name: "plain", value: "stored plaintext" },
+ { name: "encrypted", value: "stored encrypted" },
+ { name: "empty", value: "" },
+ ]);
+ }).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
);
it.effect("enforces domain binding only for schema 24 and newer", () =>
diff --git a/apps/desktop/src/preview/BrowserImport/ChromiumCookies.ts b/apps/desktop/src/preview/BrowserImport/ChromiumCookies.ts
index a3720f962b6..d5f7592b260 100644
--- a/apps/desktop/src/preview/BrowserImport/ChromiumCookies.ts
+++ b/apps/desktop/src/preview/BrowserImport/ChromiumCookies.ts
@@ -200,14 +200,12 @@ export const readChromiumCookieDatabase = Effect.fn("ChromiumCookies.readChromiu
Effect.flatMap(decodeSchemaVersion),
Effect.map(([row]) => row.value),
);
- // SQLite's BLOB affinity still permits TEXT. Cast before Node decodes
- // those bytes as UTF-8, which can corrupt an encrypted payload.
const raw =
schemaVersion >= 15
- ? yield* sql`select host_key, name, value, cast(encrypted_value as blob) as encrypted_value, path,
+ ? yield* sql`select host_key, name, value, encrypted_value, path,
expires_utc / 1000000 as expires_seconds, is_secure, is_httponly,
samesite, top_frame_site_key from cookies`
- : yield* sql`select host_key, name, value, cast(encrypted_value as blob) as encrypted_value, path,
+ : yield* sql`select host_key, name, value, encrypted_value, path,
expires_utc / 1000000 as expires_seconds, is_secure, is_httponly,
samesite, '' as top_frame_site_key from cookies`;
return { rows: yield* decodeCookieRows(raw), schemaVersion };
diff --git a/apps/desktop/src/preview/Manager.test.ts b/apps/desktop/src/preview/Manager.test.ts
index af45365b237..ad8ba85c9cb 100644
--- a/apps/desktop/src/preview/Manager.test.ts
+++ b/apps/desktop/src/preview/Manager.test.ts
@@ -1,4 +1,3 @@
-import * as NodeVM from "node:vm";
import { it as effectIt } from "@effect/vitest";
import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
import { DESKTOP_PREVIEW_RECORDING_CAPTURE_TRIGGER } from "@t3tools/contracts";
@@ -412,44 +411,6 @@ const makeTestPreviewWebContents = (
} as unknown as TestPreviewWebContents;
};
-const makeStillImage = (pixels = "fresh-png") => ({
- toPNG: () => Buffer.from(pixels),
- toJPEG: () => Buffer.from(pixels),
- getSize: () => ({ width: 100, height: 80 }),
-});
-
-const makeTestStillImageWebContents = (...args: Parameters<typeof makeTestPreviewWebContents>) => {
- const wc = makeTestPreviewWebContents(...args);
- Object.assign(wc, { isDevToolsOpened: () => false });
- holdStillImagePaint(wc, Promise.resolve());
- return wc;
-};
-
-const holdStillImagePaint = (wc: TestPreviewWebContents, paint: Promise<void>) => {
- vi.mocked(wc.debugger.sendCommand).mockImplementation(async (method) => {
- if (method === "Page.getFrameTree") return { frameTree: { frame: { id: "main" } } };
- if (method === "Page.createIsolatedWorld") return { executionContextId: 7 };
- if (method === "Runtime.evaluate") {
- await paint;
- return { result: { value: true } };
- }
- return undefined;
- });
-};
-
-const setupStill = (manager: PreviewManager.PreviewManager["Service"], paint = Promise.resolve()) =>
- Effect.gen(function* () {
- const image = makeStillImage();
- const capturePage = vi.fn<() => Promise<typeof image>>().mockResolvedValue(image);
- const wc = makeTestStillImageWebContents(capturePage);
- holdStillImagePaint(wc, paint);
- fromId.mockReturnValue(wc);
- yield* manager.createTab("tab_still");
- yield* manager.registerWebview("tab_still", wc.id);
- yield* manager.setColorScheme("tab_still", "system");
- return { image, capturePage, wc, capture: manager.captureScreenshot("tab_still") };
- });
-
const setupRecordingRaceTabs = (manager: PreviewManager.PreviewManager["Service"]) =>
Effect.gen(function* () {
const capturePage = vi.fn(async () => ({
@@ -2540,7 +2501,6 @@ describe("PreviewManager", () => {
isDestroyed: () => false,
getType: () => "webview",
getURL: () => "https://example.com:8443/path?query=value",
- setBackgroundThrottling: vi.fn(),
getTitle: () => "Example",
isLoadingMainFrame: () => false,
getZoomFactor: () => 1,
@@ -2579,7 +2539,7 @@ describe("PreviewManager", () => {
const artifact = yield* manager.captureScreenshot("tab_1");
- expect(capturePage).toHaveBeenCalledTimes(2);
+ expect(capturePage).toHaveBeenCalledOnce();
expect(mkdir).toHaveBeenCalledWith("/tmp/t3/dev/browser-artifacts");
expect(writeFile).toHaveBeenCalledWith(artifact.path, png);
expect(artifact).toMatchObject({
@@ -2602,21 +2562,18 @@ describe("PreviewManager", () => {
yield* TestClock.adjust(1_000);
const retriedExit = yield* Fiber.join(retriedFiber);
expect(Exit.isSuccess(retriedExit)).toBe(true);
- expect(capturePage).toHaveBeenCalledTimes(4);
+ expect(capturePage).toHaveBeenCalledTimes(3);
capturePage.mockClear();
const captureCause = new Error("capture failed");
capturePage.mockRejectedValue(captureCause);
- const writesBeforeFailure = writeFile.mock.calls.length;
const failingFiber = yield* Effect.exit(manager.captureScreenshot("tab_1")).pipe(
Effect.forkChild({ startImmediately: true }),
);
yield* TestClock.adjust(1_000);
const exit = yield* Fiber.join(failingFiber);
expect(Exit.isFailure(exit)).toBe(true);
- expect(capturePage).toHaveBeenCalledTimes(6);
- expect(writeFile).toHaveBeenCalledTimes(writesBeforeFailure);
- expect(fromId(42)?.setBackgroundThrottling).toHaveBeenLastCalledWith(true);
+ expect(capturePage).toHaveBeenCalledTimes(3);
if (Exit.isSuccess(exit)) return;
const error = Option.getOrThrow(Cause.findErrorOption(exit.cause));
expect(error).toMatchObject({
@@ -2630,30 +2587,6 @@ describe("PreviewManager", () => {
),
);
- effectIt.effect("captures final pixels after warmup fails and paint readiness settles", () =>
- withManager((manager) =>
- Effect.gen(function* () {
- const paint = Promise.withResolvers<void>();
- const { capturePage, wc, capture } = yield* setupStill(manager, paint.promise);
- capturePage
- .mockRejectedValueOnce(new Error("UnknownVizError"))
- .mockRejectedValueOnce(new Error("UnknownVizError"))
- .mockRejectedValueOnce(new Error("UnknownVizError"))
- .mockResolvedValue(makeStillImage("final-png"));
- const fiber = yield* capture.pipe(Effect.forkChild({ startImmediately: true }));
- yield* TestClock.adjust(300);
- expect(capturePage).toHaveBeenCalledTimes(3);
- expect(writeFile).not.toHaveBeenCalled();
- expect(wc.setBackgroundThrottling.mock.calls).toEqual([[false]]);
- paint.resolve();
- const artifact = yield* Fiber.join(fiber);
- expect(capturePage).toHaveBeenCalledTimes(4);
- expect(writeFile.mock.calls).toEqual([[artifact.path, Buffer.from("final-png")]]);
- expect(wc.setBackgroundThrottling.mock.calls).toEqual([[false], [true]]);
- }),
- ),
- );
-
effectIt.effect("preserves both screenshots of the same site in the same millisecond", () =>
withManager((manager) =>
Effect.gen(function* () {
@@ -2667,8 +2600,6 @@ describe("PreviewManager", () => {
const capturePage = vi
.fn<() => Promise<ReturnType<typeof pngImage>>>()
.mockResolvedValueOnce(pngImage(firstPng))
- .mockResolvedValueOnce(pngImage(firstPng))
- .mockResolvedValueOnce(pngImage(secondPng))
.mockResolvedValueOnce(pngImage(secondPng));
fromId.mockReturnValue(makeTestPreviewWebContents(capturePage));
yield* manager.createTab("tab_1");
@@ -2690,325 +2621,6 @@ describe("PreviewManager", () => {
),
);
- effectIt.effect(
- "waits for paint before capturing and restores rendering after overlapping requests",
- () =>
- withManager((manager) =>
- Effect.gen(function* () {
- const paint = Promise.withResolvers<void>();
- const { image, capturePage, wc, capture } = yield* setupStill(manager, paint.promise);
- const first = Promise.withResolvers<typeof image>();
- const second = Promise.withResolvers<typeof image>();
- capturePage
- .mockResolvedValueOnce(makeStillImage("discarded-warmup"))
- .mockResolvedValueOnce(makeStillImage("discarded-warmup"))
- .mockReturnValueOnce(first.promise)
- .mockReturnValueOnce(second.promise);
- const hostThrottling = vi.fn();
- yield* manager.setMainWindow({
- isDestroyed: () => false,
- once: vi.fn(),
- webContents: { setBackgroundThrottling: hostThrottling },
- } as never);
- const one = yield* capture.pipe(Effect.forkChild({ startImmediately: true }));
- const two = yield* capture.pipe(Effect.forkChild({ startImmediately: true }));
- yield* TestClock.adjust(0);
- expect(capturePage).toHaveBeenCalledTimes(2);
- expect(writeFile).not.toHaveBeenCalled();
- expect(hostThrottling.mock.calls).toEqual([[false]]);
- expect(wc.setBackgroundThrottling.mock.calls).toEqual([[false]]);
- paint.resolve();
- yield* TestClock.adjust(0);
- expect(capturePage).toHaveBeenCalledTimes(4);
- first.resolve(image);
- yield* Fiber.join(one);
- expect(wc.setBackgroundThrottling.mock.calls).toEqual([[false]]);
- second.resolve(image);
- yield* Fiber.join(two);
- expect(writeFile.mock.calls.map((call) => call[1])).toEqual([
- Buffer.from("fresh-png"),
- Buffer.from("fresh-png"),
- ]);
- expect(hostThrottling.mock.calls).toEqual([[false], [true]]);
- expect(wc.setBackgroundThrottling.mock.calls).toEqual([[false], [true]]);
- }),
- ),
- );
-
- effectIt.effect("keeps picture-in-picture rendering after a still image completes", () =>
- withManager((manager) =>
- Effect.gen(function* () {
- const { image, capturePage, wc, capture } = yield* setupStill(manager);
- const pending = Promise.withResolvers<typeof image>();
- capturePage
- .mockResolvedValueOnce(image)
- .mockResolvedValueOnce(makeStillImage("discarded-warmup"))
- .mockReturnValueOnce(pending.promise);
- const { pictureInPictureWindow } = makeTestPictureInPictureWindow();
- browserWindowConstructor.mockImplementation(function () {
- return pictureInPictureWindow;
- });
- yield* manager.openPictureInPicture("tab_still");
- const still = yield* capture.pipe(Effect.forkChild({ startImmediately: true }));
- yield* TestClock.adjust(0);
- expect(capturePage).toHaveBeenCalledTimes(3);
- expect(writeFile).not.toHaveBeenCalled();
- pending.resolve(image);
- yield* Fiber.join(still);
- expect(writeFile.mock.calls.map((call) => call[1])).toEqual([Buffer.from("fresh-png")]);
- expect(wc.setBackgroundThrottling.mock.calls).toEqual([[false]]);
- yield* manager.closePictureInPicture("tab_still");
- expect(wc.setBackgroundThrottling.mock.calls).toEqual([[false], [true]]);
- }),
- ),
- );
-
- effectIt.effect("keeps a pending still image rendering when recording ends", () =>
- withManager((manager) =>
- Effect.gen(function* () {
- const { image, capturePage, wc, capture } = yield* setupStill(manager);
- const pending = Promise.withResolvers<typeof image>();
- capturePage.mockResolvedValueOnce(image).mockReturnValue(pending.promise);
- yield* manager.startRecording("tab_still");
- const fiber = yield* capture.pipe(Effect.forkChild({ startImmediately: true }));
- yield* TestClock.adjust(0);
- yield* manager.stopRecording("tab_still");
- expect(wc.setBackgroundThrottling.mock.calls).toEqual([[false]]);
- pending.resolve(image);
- yield* Fiber.join(fiber);
- expect(wc.setBackgroundThrottling.mock.calls).toEqual([[false], [true]]);
- }),
- ),
- );
-
- effectIt.effect(
- "ignores late native warmup completion after interruption while recording owns rendering",
- () =>
- withManager((manager) =>
- Effect.gen(function* () {
- const { image, capturePage, wc, capture } = yield* setupStill(manager);
- const warmup = Promise.withResolvers<typeof image>();
- let nativeCompleted = false;
- const nativePromise = warmup.promise.then((result) => {
- nativeCompleted = true;
- return result;
- });
- capturePage.mockReturnValueOnce(nativePromise);
- const fiber = yield* capture.pipe(Effect.forkChild({ startImmediately: true }));
- yield* TestClock.adjust(0);
- yield* manager.startRecording("tab_still");
- yield* Fiber.interrupt(fiber);
- expect(nativeCompleted).toBe(false);
- expect(wc.setBackgroundThrottling.mock.calls).toEqual([[false]]);
- warmup.resolve(image);
- yield* TestClock.adjust(0);
- expect(nativeCompleted).toBe(true);
- expect(capturePage).toHaveBeenCalledTimes(2);
- expect(writeFile).not.toHaveBeenCalled();
- expect(wc.setBackgroundThrottling.mock.calls).toEqual([[false]]);
- yield* manager.stopRecording("tab_still");
- expect(wc.setBackgroundThrottling.mock.calls).toEqual([[false], [true]]);
- }),
- ),
- );
-
- effectIt.effect(
- "ignores an interrupted warmup that resolves while the replacement guest is capturing",
- () =>
- withManager((manager) =>
- Effect.gen(function* () {
- const fresh = makeStillImage("replacement-png");
- const late = Promise.withResolvers<typeof fresh>();
- const finalCapture = Promise.withResolvers<typeof fresh>();
- const oldCapture = vi.fn(() => late.promise);
- const replacementCapture = vi
- .fn()
- .mockResolvedValueOnce(fresh)
- .mockReturnValue(finalCapture.promise);
- const hostThrottling = vi.fn();
- const host = Object.assign(makeTestHostWebContents(), {
- setBackgroundThrottling: hostThrottling,
- });
- const original = makeTestStillImageWebContents(oldCapture, 42, host);
- const replacement = makeTestStillImageWebContents(replacementCapture, 43, host);
- holdStillImagePaint(original, new Promise(() => {}));
- fromId.mockImplementation((id) => (id === 42 ? original : replacement));
- yield* manager.createTab("tab_still");
- yield* manager.registerWebview("tab_still", 42);
- yield* manager.setColorScheme("tab_still", "system");
- yield* manager.setMainWindow({
- isDestroyed: () => false,
- once: vi.fn(),
- webContents: host,
- } as never);
- const failed = yield* Effect.exit(manager.captureScreenshot("tab_still")).pipe(
- Effect.forkChild({ startImmediately: true }),
- );
- yield* TestClock.adjust(0);
- yield* Fiber.interrupt(failed);
- yield* manager.registerWebview("tab_still", 43);
- yield* manager.setColorScheme("tab_still", "system");
- const healthy = yield* manager
- .captureScreenshot("tab_still")
- .pipe(Effect.forkChild({ startImmediately: true }));
- yield* TestClock.adjust(0);
- late.resolve({ ...fresh, toPNG: () => Buffer.from("late-old-warmup") });
- yield* TestClock.adjust(0);
- expect(writeFile).not.toHaveBeenCalled();
- expect(oldCapture).toHaveBeenCalledOnce();
- expect(replacementCapture).toHaveBeenCalledTimes(2);
- expect(hostThrottling.mock.calls).toEqual([[false], [true], [false]]);
- expect(replacement.setBackgroundThrottling.mock.calls).toEqual([[false]]);
- finalCapture.resolve(fresh);
- yield* Fiber.join(healthy);
- expect(writeFile.mock.calls.map((call) => call[1])).toEqual([
- Buffer.from("replacement-png"),
- ]);
- expect(hostThrottling.mock.calls).toEqual([[false], [true], [false], [true]]);
- expect(replacement.setBackgroundThrottling.mock.calls).toEqual([[false], [true]]);
- }),
- ),
- );
-
- effectIt.effect("paints a loading document with isolated scheduling despite page overrides", () =>
- withManager((manager) =>
- Effect.gen(function* () {
- for (const mode of ["suppressed", "synchronous", "timeout-before", "timeout-after"]) {
- writeFile.mockClear();
- let pixels = "old-pixels";
- const frames: Array<() => void> = [];
- let expire = () => {};
- let paintConfirmed: unknown;
- const clearTimeout = vi.fn();
- const probeStarted = Promise.withResolvers<void>();
- const pageFrame = vi.fn((callback: () => void) => {
- if (mode === "synchronous") callback();
- });
- const page = NodeVM.createContext({
- Promise: undefined,
- requestAnimationFrame: pageFrame,
- });
- const isolated = NodeVM.createContext({
- requestAnimationFrame: (callback: () => void) => frames.push(callback),
- cancelAnimationFrame: (id: number) => {
- frames.splice(id - 1, 1);
- },
- setTimeout: (callback: () => void, delay: number) => {
- expect(delay).toBe(1_000);
- expire = callback;
- return 1;
- },
- clearTimeout,
- });
- const capturePage = vi.fn(async () => makeStillImage(pixels));
- const wc = makeTestStillImageWebContents(capturePage);
- Object.assign(wc, { isLoading: () => true });
- vi.mocked(wc.executeJavaScript).mockImplementation(async (expression) =>
- NodeVM.runInContext(expression, page),
- );
- vi.mocked(wc.debugger.sendCommand).mockImplementation(async (method, params) => {
- if (method === "Page.getFrameTree") return { frameTree: { frame: { id: "main" } } };
- if (method === "Page.createIsolatedWorld") return { executionContextId: 7 };
- if (method === "Runtime.evaluate") {
- const pending = NodeVM.runInContext(params?.["expression"] as string, isolated);
- probeStarted.resolve();
- paintConfirmed = await pending;
- return { result: { value: paintConfirmed } };
- }
- return undefined;
- });
- fromId.mockReturnValue(wc);
- const tabId = `tab_loading_${mode}`;
- yield* manager.createTab(tabId);
- yield* manager.registerWebview(tabId, wc.id);
- yield* manager.setColorScheme(tabId, "system");
- const still = yield* manager
- .captureScreenshot(tabId)
- .pipe(Effect.forkChild({ startImmediately: true }));
- yield* Effect.promise(() => probeStarted.promise);
- yield* TestClock.adjust(0);
- expect(capturePage).toHaveBeenCalledOnce();
- expect(writeFile).not.toHaveBeenCalled();
- if (mode !== "timeout-before") frames.shift()?.();
- pixels = "new-pixels";
- yield* TestClock.adjust(0);
- expect(writeFile).not.toHaveBeenCalled();
- if (mode.startsWith("timeout")) expire();
- else frames.shift()?.();
- yield* Fiber.join(still);
- expect(paintConfirmed).toBe(!mode.startsWith("timeout"));
- expect(frames).toHaveLength(0);
- expect(clearTimeout.mock.calls).toEqual(mode.startsWith("timeout") ? [] : [[1]]);
- expect(writeFile.mock.calls.map((call) => call[1])).toEqual([Buffer.from("new-pixels")]);
- expect(pageFrame).not.toHaveBeenCalled();
- expect(wc.setBackgroundThrottling.mock.calls).toEqual([[false], [true]]);
- yield* manager.closeTab(tabId);
- }
- }),
- ),
- );
-
- effectIt.effect("captures available pixels without taking another debugger's ownership", () =>
- withManager((manager) =>
- Effect.gen(function* () {
- for (const devToolsOpen of [true, false]) {
- const capturePage = vi.fn(async () => makeStillImage("available-pixels"));
- const wc = makeTestStillImageWebContents(capturePage);
- Object.assign(wc, { isDevToolsOpened: () => devToolsOpen });
- vi.spyOn(wc.debugger, "isAttached").mockReturnValue(true);
- fromId.mockReturnValue(wc);
- const tabId = `tab_foreign_debugger_${devToolsOpen}`;
- yield* manager.createTab(tabId);
- yield* manager.registerWebview(tabId, wc.id);
- yield* manager.captureScreenshot(tabId);
- expect(capturePage).toHaveBeenCalledTimes(2);
- expect(wc.debugger.attach).not.toHaveBeenCalled();
- expect(wc.debugger.sendCommand).not.toHaveBeenCalled();
- expect(writeFile).toHaveBeenLastCalledWith(
- expect.any(String),
- Buffer.from("available-pixels"),
- );
- expect(wc.setBackgroundThrottling.mock.calls).toEqual([[false], [true]]);
- yield* manager.closeTab(tabId);
- }
- }),
- ),
- );
-
- effectIt.effect(
- "bounds paint readiness and ignores its late completion during another capture",
- () =>
- withManager((manager) =>
- Effect.gen(function* () {
- const paint = Promise.withResolvers<void>();
- const { image, capturePage, wc, capture } = yield* setupStill(manager, paint.promise);
- const first = yield* Effect.exit(capture).pipe(
- Effect.forkChild({ startImmediately: true }),
- );
- yield* TestClock.adjust(1_001);
- expect(Exit.isSuccess(yield* Fiber.join(first))).toBe(true);
- expect(capturePage).toHaveBeenCalledTimes(2);
- expect(writeFile.mock.calls.map((call) => call[1])).toEqual([Buffer.from("fresh-png")]);
- expect(wc.setBackgroundThrottling.mock.calls).toEqual([[false], [true]]);
-
- holdStillImagePaint(wc, Promise.resolve());
- const finalCapture = Promise.withResolvers<typeof image>();
- capturePage.mockResolvedValueOnce(image).mockReturnValueOnce(finalCapture.promise);
- const second = yield* capture.pipe(Effect.forkChild({ startImmediately: true }));
- yield* TestClock.adjust(0);
- paint.resolve();
- yield* TestClock.adjust(0);
- expect(writeFile).toHaveBeenCalledOnce();
- expect(capturePage).toHaveBeenCalledTimes(4);
- expect(wc.setBackgroundThrottling.mock.calls).toEqual([[false], [true], [false]]);
- finalCapture.resolve(image);
- yield* Fiber.join(second);
- expect(writeFile).toHaveBeenCalledTimes(2);
- expect(wc.setBackgroundThrottling.mock.calls).toEqual([[false], [true], [false], [true]]);
- }),
- ),
- );
-
effectIt.effect("keeps every recorded guest unthrottled until its frame capture stops", () =>
withManager((manager) =>
Effect.gen(function* () {
diff --git a/apps/desktop/src/preview/Manager.ts b/apps/desktop/src/preview/Manager.ts
index 17d8990fe17..b036a67ac8b 100644
--- a/apps/desktop/src/preview/Manager.ts
+++ b/apps/desktop/src/preview/Manager.ts
@@ -391,8 +391,7 @@ interface ManagedListeners {
readonly webContents: Electron.WebContents;
}
-// Each still-image request owns a separate, short-lived rendering lease.
-type FrameCaptureConsumer = "picture-in-picture" | "recording" | symbol;
+type FrameCaptureConsumer = "picture-in-picture" | "recording";
interface FrameCaptureSession {
readonly recordingInputOptions?: RecordingInputOptions;
@@ -2488,7 +2487,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
const [createdAt, millis, image] = yield* Effect.all([
currentIso,
currentMillis,
- captureStillImage(
+ capturePageWithRetry(
{
operation: "captureScreenshot.capturePage",
tabId,
@@ -2536,104 +2535,6 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
};
});
- const captureStillImage = Effect.fn("PreviewManager.captureStillImage")(function* (
- errorContext: PreviewOperationContext,
- tabId: string,
- wc: Electron.WebContents,
- ) {
- const consumer = Symbol("still-image");
- return yield* Effect.acquireUseRelease(
- startFrameCapture(tabId, consumer),
- () =>
- Effect.gen(function* () {
- // A DOM mutation can precede its compositor frame even in a shown
- // window. Keep the original guest rendering through the next paint;
- // a hidden guest otherwise returns old pixels or never completes.
- const probe = Effect.fn("PreviewManager.probeStillImagePaint")(function* (
- send: (
- method: string,
- params?: Record<string, unknown>,
- ) => Effect.Effect<unknown, PreviewOperationError>,
- ) {
- // CDP executes against the current document without Electron's
- // did-stop-loading gate. Isolate scheduling globals from page code.
- const tree = (yield* send("Page.getFrameTree")) as
- | { frameTree?: { frame?: { id?: string } } }
- | undefined;
- const frameId = tree?.frameTree?.frame?.id;
- if (typeof frameId !== "string")
- return yield* new PreviewOperationError({
- ...errorContext,
- cause: new Error("The preview paint frame is unavailable."),
- });
- const world = (yield* send("Page.createIsolatedWorld", {
- frameId,
- worldName: "t3-preview-still-image",
- })) as { executionContextId?: number } | undefined;
- if (typeof world?.executionContextId !== "number")
- return yield* new PreviewOperationError({
- ...errorContext,
- cause: new Error("The preview paint context is unavailable."),
- });
- const response = (yield* send("Runtime.evaluate", {
- // Settle and release scheduled work when only timers keep running.
- // The outer deadline still bounds a frozen renderer.
- 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); }); }); })`,
- contextId: world.executionContextId,
- awaitPromise: true,
- returnByValue: true,
- })) as { result?: { value?: unknown }; exceptionDetails?: unknown } | undefined;
- if (response?.exceptionDetails || response?.result?.value !== true)
- return yield* new PreviewOperationError({
- ...errorContext,
- cause: new Error("The preview paint boundary was not confirmed."),
- });
- });
- const paintReady = Effect.gen(function* () {
- // Only use an existing owned session; never attach or displace
- // another debugger to obtain a screenshot.
- const control = (yield* SynchronizedRef.get(controlSessionsRef)).get(wc.id);
- if (!control)
- return yield* new PreviewOperationError({
- ...errorContext,
- cause: new Error("The preview paint session is unavailable."),
- });
- return yield* control.semaphore.withPermit(
- probe((method, params) =>
- attemptPromise(errorContext, () => control.debugger.sendCommand(method, params)),
- ),
- );
- }).pipe(
- Effect.timeout(CAPTURE_PAGE_ATTEMPT_TIMEOUT_MS),
- Effect.catch((error) =>
- Effect.logWarning(
- "Preview paint readiness was not confirmed; capturing available pixels with mutation freshness unconfirmed.",
- { tabId, webContentsId: wc.id, error },
- ),
- ),
- );
- // capturePage temporarily marks the original guest as captured. A
- // minimized page can otherwise keep animation frames suspended even
- // with scheduler throttling disabled. Discard this warmup image and
- // accept its output only after readiness settles. If the bounded
- // probe cannot confirm paint, retain the native capture fallback.
- const warmup = capturePageWithRetry(errorContext, tabId, wc).pipe(
- Effect.catchTags({
- PreviewOperationError: (error) =>
- Effect.logWarning("Preview warmup capture failed; continuing with final capture.", {
- tabId,
- webContentsId: wc.id,
- error,
- }),
- }),
- );
- yield* Effect.all([paintReady, warmup], { concurrency: 2, discard: true });
- return yield* capturePageWithRetry(errorContext, tabId, wc);
- }),
- () => stopFrameCapture(tabId, consumer),
- );
- });
-
const capturePreviewFrame = Effect.fn("PreviewManager.capturePreviewFrame")(function* (
tabId: string,
) {
diff --git a/apps/desktop/src/settings/DesktopAppSettings.test.ts b/apps/desktop/src/settings/DesktopAppSettings.test.ts
index 7313b9b859e..a98aa96079e 100644
--- a/apps/desktop/src/settings/DesktopAppSettings.test.ts
+++ b/apps/desktop/src/settings/DesktopAppSettings.test.ts
@@ -283,7 +283,7 @@ describe("DesktopSettings", () => {
Effect.gen(function* () {
const settings = yield* DesktopAppSettings.DesktopAppSettings;
yield* writeSettingsPatch({
- mainWindowBounds: { x: 10, y: 20, width: 599, height: 620 },
+ mainWindowBounds: { x: 10.5, y: 20, width: 839, height: 620 },
mainWindowMaximized: true,
serverExposureMode: "network-accessible",
});
@@ -342,24 +342,17 @@ describe("DesktopSettings", () => {
const fileSystem = yield* FileSystem.FileSystem;
const settings = yield* DesktopAppSettings.DesktopAppSettings;
- yield* settings.setMainWindowBounds({ x: -1200, y: 40, width: 600, height: 620 }, true);
+ yield* settings.setMainWindowBounds({ x: -1200, y: 40, width: 1440, height: 960 }, true);
yield* settings.setServerExposureMode("network-accessible");
const persisted = yield* decodeDesktopSettingsPatch(
yield* fileSystem.readFileString(environment.desktopSettingsPath),
);
assert.deepEqual(persisted, {
- mainWindowBounds: { x: -1200, y: 40, width: 600, height: 620 },
+ mainWindowBounds: { x: -1200, y: 40, width: 1440, height: 960 },
mainWindowMaximized: true,
serverExposureMode: "network-accessible",
} satisfies typeof DesktopSettingsPatch.Type);
-
- const restored = yield* Effect.gen(function* () {
- const freshSettings = yield* DesktopAppSettings.DesktopAppSettings;
- return yield* freshSettings.load;
- }).pipe(Effect.provide(DesktopAppSettings.layer));
- assert.deepEqual(restored.mainWindowBounds, persisted.mainWindowBounds);
- assert.isTrue(restored.mainWindowMaximized);
}),
),
);
diff --git a/apps/desktop/src/settings/DesktopAppSettings.ts b/apps/desktop/src/settings/DesktopAppSettings.ts
index a26892d6984..1c131681295 100644
--- a/apps/desktop/src/settings/DesktopAppSettings.ts
+++ b/apps/desktop/src/settings/DesktopAppSettings.ts
@@ -48,8 +48,8 @@ export interface DesktopSettingsChange {
}
const DEFAULT_TAILSCALE_SERVE_PORT = 443;
-export const MIN_MAIN_WINDOW_SIZE = {
- width: 600,
+const MIN_MAIN_WINDOW_SIZE = {
+ width: 840,
height: 620,
} as const;
export const DesktopWindowBoundsSchema = Schema.Struct({
diff --git a/apps/desktop/src/shell/DesktopShellEnvironment.test.ts b/apps/desktop/src/shell/DesktopShellEnvironment.test.ts
index 6ff500a3eb3..3adf74bf76f 100644
--- a/apps/desktop/src/shell/DesktopShellEnvironment.test.ts
+++ b/apps/desktop/src/shell/DesktopShellEnvironment.test.ts
@@ -1,10 +1,7 @@
// @effect-diagnostics nodeBuiltinImport:off -- The process fixture runs real shell commands with isolated config files.
import * as NodeServices from "@effect/platform-node/NodeServices";
-import * as Clock from "effect/Clock";
import { assert, describe, it } from "@effect/vitest";
-import * as Deferred from "effect/Deferred";
import * as Effect from "effect/Effect";
-import * as Fiber from "effect/Fiber";
import * as Layer from "effect/Layer";
import * as Logger from "effect/Logger";
import * as PlatformError from "effect/PlatformError";
@@ -15,7 +12,6 @@ import * as ChildProcess from "effect/process/ChildProcess";
import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
import * as NodeChildProcess from "node:child_process";
import * as NodeFS from "node:fs";
-import * as TestClock from "effect/testing/TestClock";
import * as NodeOS from "node:os";
import * as NodePath from "node:path";
import { vi } from "vite-plus/test";
@@ -82,10 +78,7 @@ function runShellEnvironment(input: {
readonly userShell?: string;
readonly handler: (
command: ChildProcess.Command,
- ) =>
- | string
- | { output: string; exitCode: number }
- | Effect.Effect<ChildProcessSpawner.ChildProcessHandle, PlatformError.PlatformError>;
+ ) => string | { output: string; exitCode: number };
readonly failure?: PlatformError.PlatformError;
}) {
const layerEnvironment = Layer.succeed(
@@ -99,7 +92,6 @@ function runShellEnvironment(input: {
ChildProcessSpawner.make((command) => {
if (input.failure !== undefined) return Effect.fail(input.failure);
const result = input.handler(command);
- if (Effect.isEffect(result)) return result;
return Effect.succeed(
typeof result === "string"
? makeProcess(result)
@@ -572,85 +564,6 @@ describe("DesktopShellEnvironment", () => {
}),
);
- it.effect("waits at most 5 seconds in total when the PowerShell profile hangs", () =>
- Effect.gen(function* () {
- const env: NodeJS.ProcessEnv = { PATH: "C:\\Windows\\System32" };
- const profileShells: string[] = [];
- const started = yield* Deferred.make<void>();
- const completed = yield* Deferred.make<void>();
- const baseClock = yield* Clock.Clock;
- let wallTime = 0;
- const clockWithBackwardWallJump: Clock.Clock = {
- ...baseClock,
- currentTimeMillisUnsafe: () => wallTime,
- currentTimeMillis: Effect.sync(() => wallTime),
- };
-
- const install = yield* Effect.forkChild(
- runShellEnvironment({
- env,
- platform: "win32",
- handler: (command) => {
- if (command._tag !== "StandardCommand") return "";
- if (command.args.includes("-NoProfile")) {
- return envOutput({ PATH: "C:\\NoProfile\\Bin;C:\\Windows\\System32" });
- }
- profileShells.push(command.command);
- return Deferred.succeed(started, undefined).pipe(
- Effect.as(
- ChildProcessSpawner.makeHandle({
- ...makeProcess(""),
- stdout: Stream.never,
- all: Stream.never,
- exitCode: Effect.never,
- isRunning: Effect.succeed(true),
- }),
- ),
- );
- },
- }).pipe(
- Effect.tap(() => Deferred.succeed(completed, undefined)),
- Effect.provide(Logger.layer([])),
- Effect.provideService(Clock.Clock, clockWithBackwardWallJump),
- ),
- );
- yield* Deferred.await(started);
- wallTime = -60_000;
- yield* TestClock.adjust("5 seconds");
- assert.isTrue(yield* Deferred.isDone(completed), "finishes within the shared budget");
- assert.isFalse(yield* Fiber.join(install));
- assert.deepEqual(profileShells, ["pwsh.exe"]);
- assert.equal(env.PATH, "C:\\NoProfile\\Bin;C:\\Windows\\System32");
- }),
- );
-
- it.effect("falls back to Windows PowerShell when pwsh.exe is not installed", () =>
- Effect.gen(function* () {
- const env: NodeJS.ProcessEnv = { PATH: "C:\\Windows\\System32" };
- const missing = PlatformError.systemError({
- _tag: "NotFound",
- module: "ChildProcess",
- method: "spawn",
- pathOrDescriptor: "pwsh.exe",
- });
-
- const prepared = yield* runShellEnvironment({
- env,
- platform: "win32",
- handler: (command) => {
- if (command._tag !== "StandardCommand") return "";
- if (command.command === "pwsh.exe") return Effect.fail(missing);
- return command.args.includes("-NoProfile")
- ? envOutput({ PATH: "C:\\Windows\\System32" })
- : envOutput({ PATH: "C:\\Profile\\Node;C:\\Windows\\System32" });
- },
- }).pipe(Effect.provide(Logger.layer([])));
-
- assert.isTrue(prepared);
- assert.equal(env.PATH, "C:\\Profile\\Node;C:\\Windows\\System32");
- }),
- );
-
it.effect.each([false, true])(
"leaves Windows preparation incomplete when loadProfile=%s fails",
(loadProfile) =>
@@ -692,49 +605,6 @@ describe("DesktopShellEnvironment", () => {
}),
);
- it.effect("drops earlier AppImage launches' mount dirs from the search paths on linux", () =>
- Effect.gen(function* () {
- const current = "/var/tmp/.mount_cur";
- const env: NodeJS.ProcessEnv = {
- SHELL: "/bin/zsh",
- APPIMAGE: "/home/me/T3-Code.AppImage",
- APPDIR: `${current}/`,
- PATH: `${current}/usr/bin:/tmp/.mount_old/usr/bin:/usr/bin`,
- LD_LIBRARY_PATH: `/tmp/.mount_old/usr/lib:${current}/usr/lib::/opt/lib`,
- XDG_DATA_DIRS: "/tmp/.mount_old/usr/share:/var/tmp/.mount_cur2/usr/share",
- };
-
- yield* runShellEnvironment({
- env,
- platform: "linux",
- handler: () => envOutput({ PATH: "/tmp/.mount_older/usr/bin:/home/me/.local/bin" }),
- });
-
- assert.equal(env.PATH, `/home/me/.local/bin:${current}/usr/bin:/usr/bin`);
- assert.equal(env.LD_LIBRARY_PATH, `${current}/usr/lib::/opt/lib`);
- assert.equal(env.XDG_DATA_DIRS, undefined);
- }),
- );
-
- it.effect("keeps AppImage-looking search paths outside an AppImage launch", () =>
- Effect.gen(function* () {
- const env: NodeJS.ProcessEnv = {
- SHELL: "/bin/zsh",
- PATH: "/tmp/.mount_old/usr/bin:/usr/bin",
- LD_LIBRARY_PATH: "/tmp/.mount_old/usr/lib",
- };
-
- yield* runShellEnvironment({
- env,
- platform: "linux",
- handler: () => envOutput({ PATH: "/usr/bin" }),
- });
-
- assert.equal(env.PATH, "/usr/bin:/tmp/.mount_old/usr/bin");
- assert.equal(env.LD_LIBRARY_PATH, "/tmp/.mount_old/usr/lib");
- }),
- );
-
it.effect("prefers login-shell desktop session hints over inherited values on linux", () =>
Effect.gen(function* () {
const env: NodeJS.ProcessEnv = {
diff --git a/apps/desktop/src/shell/DesktopShellEnvironment.ts b/apps/desktop/src/shell/DesktopShellEnvironment.ts
index 51b4c1a9086..3fdec793236 100644
--- a/apps/desktop/src/shell/DesktopShellEnvironment.ts
+++ b/apps/desktop/src/shell/DesktopShellEnvironment.ts
@@ -3,7 +3,6 @@ import {
listLoginShellCandidates,
setWindowsPath,
} from "@t3tools/shared/shell";
-import * as Clock from "effect/Clock";
import * as Context from "effect/Context";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
@@ -119,37 +118,6 @@ const readEnvPath = (env: NodeJS.ProcessEnv): Option.Option<string> =>
const normalizeRuntimeDir = (value: string): string => value.replace(/\/+$/u, "");
-const APPIMAGE_SEARCH_PATH_ENV_NAMES = ["PATH", "LD_LIBRARY_PATH", "XDG_DATA_DIRS"] as const;
-
-// The AppImage runtime mounts each launch at `$TMPDIR/.mount_<id>` and prepends
-// it to the search paths above. A launch started from a shell that inherited an
-// earlier launch's env carries that mount too, and once it is unmounted every
-// spawn that walks PATH (git first of all) fails with ENOTCONN.
-const APPIMAGE_MOUNT_ROOT = /^(.*?\/\.mount_[^/]+)(?:\/|$)/u;
-
-const stripStaleAppImageMounts = (env: NodeJS.ProcessEnv): void => {
- if (env.APPIMAGE === undefined && env.APPDIR === undefined) return;
- const appDir = env.APPDIR === undefined ? undefined : normalizeRuntimeDir(env.APPDIR);
- for (const name of APPIMAGE_SEARCH_PATH_ENV_NAMES) {
- const value = env[name];
- if (value === undefined) continue;
- // glibc's loader also splits LD_LIBRARY_PATH on `;`.
- const segments = value.split(name === "LD_LIBRARY_PATH" ? /[:;]/u : ":");
- const kept = segments.filter((segment) => {
- const mountRoot = APPIMAGE_MOUNT_ROOT.exec(segment)?.[1];
- return mountRoot === undefined || mountRoot === appDir;
- });
- if (kept.length === segments.length) continue;
- if (kept.length === 0) {
- delete env[name];
- } else {
- // An empty segment is the current dir to the loader and to PATH lookup,
- // but a lone one joins to "", which reads as unset.
- env[name] = kept.join(":") || ":";
- }
- }
-};
-
const linuxRuntimeDirCandidates = (
env: NodeJS.ProcessEnv,
uid: number | undefined,
@@ -371,16 +339,12 @@ const readWindowsEnvironment = Effect.fn("desktop.shellEnvironment.readWindowsEn
captureWindowsEnvironmentCommand(names),
];
- const deadline =
- (yield* Clock.monotonicTimeNanos) + Duration.toNanosUnsafe(LOGIN_SHELL_TIMEOUT);
for (const command of WINDOWS_SHELL_CANDIDATES) {
- const remainingNanos = deadline - (yield* Clock.monotonicTimeNanos);
- if (remainingNanos <= 0n) break;
const output = yield* runCommandOutput({
probe: options.loadProfile ? "powershell-profile" : "powershell-no-profile",
command,
args,
- timeout: Duration.nanos(remainingNanos),
+ timeout: LOGIN_SHELL_TIMEOUT,
});
const environment = extractEnvironment(output, names);
if (Object.keys(environment).length > 0) {
@@ -459,9 +423,6 @@ const installPosixEnvironment = Effect.fn("desktop.shellEnvironment.installPosix
if (Option.isSome(mergedPath)) {
config.env.PATH = mergedPath.value;
}
- // The server, relaunch and updater all inherit process.env, so scrubbing
- // here keeps earlier AppImage launches' mounts out of every one of them.
- stripStaleAppImageMounts(config.env);
if (!config.env.SSH_AUTH_SOCK && shellEnvironment.SSH_AUTH_SOCK) {
config.env.SSH_AUTH_SOCK = shellEnvironment.SSH_AUTH_SOCK;
}
diff --git a/apps/desktop/src/snapShot/ActiveWindow.test.ts b/apps/desktop/src/snapShot/ActiveWindow.test.ts
index c1849b3eed6..ddc760cbb9d 100644
--- a/apps/desktop/src/snapShot/ActiveWindow.test.ts
+++ b/apps/desktop/src/snapShot/ActiveWindow.test.ts
@@ -28,34 +28,19 @@ function stubMacLookup(stdout: string) {
);
}
-function macLookup(
- windows: ReadonlyArray<{
- id: number;
- title: string;
- bounds: { x: number; y: number; width: number; height: number };
- alpha?: number;
- }>,
-) {
- return JSON.stringify({
- owner: {
- name: "Editor",
- processId: 123,
- path: "/Applications/Editor.app",
- bundleId: "com.example.editor",
- },
- windows: windows.map((window) => ({ ...window, alpha: window.alpha ?? 1 })),
- });
-}
-
it("parses the frontmost macOS window from the osascript lookup", async () => {
stubMacLookup(
- macLookup([
- {
- id: 42,
- title: "main.ts",
- bounds: { x: 10, y: 20, width: 800, height: 600 },
+ JSON.stringify({
+ id: 42,
+ title: "main.ts",
+ bounds: { x: 10, y: 20, width: 800, height: 600 },
+ owner: {
+ name: "Editor",
+ processId: 123,
+ path: "/Applications/Editor.app",
+ bundleId: "com.example.editor",
},
- ]) + "\n",
+ }) + "\n",
);
const window = await activeWindow("darwin");
@@ -81,15 +66,10 @@ it("parses the frontmost macOS window from the osascript lookup", async () => {
it("omits an empty macOS bundle identifier", async () => {
stubMacLookup(
JSON.stringify({
+ id: 7,
+ title: "",
+ bounds: { x: 0, y: 0, width: 1, height: 1 },
owner: { name: "cli", processId: 9, path: "", bundleId: "" },
- windows: [
- {
- id: 7,
- title: "",
- bounds: { x: 0, y: 0, width: 1, height: 1 },
- alpha: 1,
- },
- ],
}),
);
@@ -98,107 +78,12 @@ it("omits an empty macOS bundle identifier", async () => {
assert.deepEqual(window?.owner, { name: "cli", processId: 9, path: "" });
});
-it.each([
- {
- name: "transparent and untitled helpers",
- helpers: [
- {
- id: 1,
- title: "",
- bounds: { x: -1, y: -44, width: 1_680, height: 44 },
- alpha: 0,
- },
- { id: 2, title: "", bounds: { x: 0, y: 0, width: 1_680, height: 68 } },
- ],
- content: {
- id: 3,
- title: "Document",
- bounds: { x: 0, y: 0, width: 1_680, height: 1_050 },
- },
- },
- {
- name: "Chrome strips stacked above the content window",
- helpers: [
- { id: 75, title: "", bounds: { x: 0, y: 39, width: 1_800, height: 41 } },
- { id: 74, title: "", bounds: { x: 0, y: 80, width: 1_800, height: 81 } },
- { id: 1691, title: "", bounds: { x: 0, y: 39, width: 1_800, height: 158 } },
- ],
- content: {
- id: 71,
- title: "(10) Video - YouTube",
- bounds: { x: 0, y: 161, width: 1_800, height: 1_008 },
- },
- },
- {
- name: "a smaller front window's strips with a larger background window",
- helpers: [
- { id: 75, title: "", bounds: { x: 100, y: 139, width: 1_200, height: 41 } },
- { id: 74, title: "", bounds: { x: 100, y: 180, width: 1_200, height: 81 } },
- ],
- content: {
- id: 71,
- title: "Video - YouTube",
- bounds: { x: 100, y: 261, width: 1_200, height: 700 },
- },
- background: [
- { id: 80, title: "Other document", bounds: { x: 0, y: 39, width: 1_800, height: 1_130 } },
- ],
- },
-])("selects the content window behind $name", async ({ helpers, content, background = [] }) => {
- stubMacLookup(macLookup([...helpers, content, ...background]));
-
- const window = await activeWindow("darwin");
-
- assert.strictEqual(window?.id, content.id);
- assert.deepEqual(window?.bounds, content.bounds);
-});
-
-it.each([
- { name: "untitled dialog", title: "", bounds: { x: 300, y: 200, width: 400, height: 240 } },
- { name: "titled palette", title: "Palette", bounds: { x: 0, y: 0, width: 800, height: 50 } },
- { name: "offset untitled strip", title: "", bounds: { x: 100, y: 100, width: 800, height: 50 } },
- { name: "tall untitled window", title: "", bounds: { x: 0, y: 0, width: 800, height: 900 } },
-])("keeps a frontmost $name ahead of a larger document", async ({ title, bounds }) => {
- stubMacLookup(
- macLookup([
- { id: 1, title, bounds },
- { id: 2, title: "Document", bounds: { x: 0, y: 0, width: 800, height: 1_000 } },
- ]),
- );
-
- const window = await activeWindow("darwin");
-
- assert.strictEqual(window?.id, 1);
- assert.deepEqual(window?.bounds, bounds);
-});
-
-it("keeps an untitled content window ahead of a much taller background window", async () => {
- const bounds = { x: 0, y: 0, width: 800, height: 900 };
- stubMacLookup(
- macLookup([
- { id: 1, title: "", bounds },
- { id: 2, title: "Background document", bounds: { x: 0, y: 0, width: 800, height: 4_000 } },
- ]),
- );
-
- const window = await activeWindow("darwin");
-
- assert.strictEqual(window?.id, 1);
- assert.deepEqual(window?.bounds, bounds);
-});
-
it("resolves undefined when macOS has no frontmost window", async () => {
stubMacLookup("\n");
assert.isUndefined(await activeWindow("darwin"));
});
-it("resolves undefined when macOS reports no visible windows", async () => {
- stubMacLookup(macLookup([]));
-
- assert.isUndefined(await activeWindow("darwin"));
-});
-
it("composes the Windows foreground window from Win32 calls", async () => {
const api = {
getForegroundWindow: vi.fn(() => 0x1_f123_4567n),
diff --git a/apps/desktop/src/snapShot/ActiveWindow.ts b/apps/desktop/src/snapShot/ActiveWindow.ts
index 08c6cfa6ba0..f62669a39bf 100644
--- a/apps/desktop/src/snapShot/ActiveWindow.ts
+++ b/apps/desktop/src/snapShot/ActiveWindow.ts
@@ -30,32 +30,23 @@ export type ActiveWindow = {
const MAC_LOOKUP_TIMEOUT_MS = 5_000;
-const MAC_HELPER_STRIP_MAX_THICKNESS_RATIO = 0.25;
-
-const MacActiveWindowLookup = Schema.Struct({
+const MacActiveWindow = Schema.Struct({
+ id: Schema.Number,
+ title: Schema.String,
+ bounds: Schema.Struct({
+ x: Schema.Number,
+ y: Schema.Number,
+ width: Schema.Number,
+ height: Schema.Number,
+ }),
owner: Schema.Struct({
name: Schema.String,
processId: Schema.Number,
path: Schema.String,
bundleId: Schema.String,
}),
- windows: Schema.Array(
- Schema.Struct({
- id: Schema.Number,
- title: Schema.String,
- bounds: Schema.Struct({
- x: Schema.Number,
- y: Schema.Number,
- width: Schema.Number,
- height: Schema.Number,
- }),
- alpha: Schema.Number,
- }),
- ),
});
-const decodeMacActiveWindowLookup = Schema.decodeUnknownSync(
- Schema.fromJsonString(MacActiveWindowLookup),
-);
+const decodeMacActiveWindow = Schema.decodeUnknownSync(Schema.fromJsonString(MacActiveWindow));
const MAC_LOOKUP_SCRIPT = `
ObjC.import("CoreGraphics");
@@ -64,38 +55,30 @@ function run() {
const app = $.NSWorkspace.sharedWorkspace.frontmostApplication;
if (app.isNil()) return "";
const pid = app.processIdentifier;
- let ownerName = String(app.localizedName.js || "");
const list = $.CGWindowListCopyWindowInfo(
$.kCGWindowListOptionOnScreenOnly | $.kCGWindowListExcludeDesktopElements,
$.kCGNullWindowID,
);
$.CFMakeCollectable(list);
const count = $.CFArrayGetCount(list);
- const windows = [];
for (let i = 0; i < count; i++) {
const w = ObjC.castRefToObject($.CFArrayGetValueAtIndex(list, i));
if (w.objectForKey("kCGWindowOwnerPID").js !== pid) continue;
if (w.objectForKey("kCGWindowLayer").js !== 0) continue;
- if (!ownerName) {
- ownerName = String(ObjC.unwrap(w.objectForKey("kCGWindowOwnerName")) || "");
- }
const b = ObjC.deepUnwrap(w.objectForKey("kCGWindowBounds"));
- windows.push({
+ return JSON.stringify({
id: w.objectForKey("kCGWindowNumber").js,
title: String(ObjC.unwrap(w.objectForKey("kCGWindowName")) || ""),
bounds: { x: b.X, y: b.Y, width: b.Width, height: b.Height },
- alpha: w.objectForKey("kCGWindowAlpha").js,
+ owner: {
+ name: String(app.localizedName.js || ObjC.unwrap(w.objectForKey("kCGWindowOwnerName")) || ""),
+ processId: pid,
+ path: String(app.bundleURL.path.js || ""),
+ bundleId: String(app.bundleIdentifier.js || ""),
+ },
});
}
- return JSON.stringify({
- owner: {
- name: ownerName,
- processId: pid,
- path: String(app.bundleURL.path.js || ""),
- bundleId: String(app.bundleIdentifier.js || ""),
- },
- windows,
- });
+ return "";
}`;
function runMacLookup(): Promise<string> {
@@ -103,7 +86,7 @@ function runMacLookup(): Promise<string> {
NodeChildProcess.execFile(
"/usr/bin/osascript",
["-l", "JavaScript", "-e", MAC_LOOKUP_SCRIPT],
- { timeout: MAC_LOOKUP_TIMEOUT_MS, maxBuffer: 1024 * 1024 },
+ { timeout: MAC_LOOKUP_TIMEOUT_MS, maxBuffer: 64 * 1024 },
(error, stdout) => {
if (error) reject(error);
else resolve(stdout);
@@ -115,39 +98,17 @@ function runMacLookup(): Promise<string> {
async function macActiveWindow(): Promise<ActiveWindow | undefined> {
const output = (await runMacLookup()).trim();
if (!output) return undefined;
- const lookup = decodeMacActiveWindowLookup(output);
- const visible = lookup.windows.filter(
- (window) => window.alpha > 0 && window.bounds.width > 0 && window.bounds.height > 0,
- );
- // Helpers belong to the content behind them, which may not be the app's largest window.
- const window = visible.find((candidate, index) => {
- if (candidate.title.trim() !== "") return true;
- const bounds = candidate.bounds;
- return !visible.some((reference, referenceIndex) => {
- if (referenceIndex <= index) return false;
- return (
- (bounds.x === reference.bounds.x &&
- bounds.width === reference.bounds.width &&
- bounds.height <= bounds.width * MAC_HELPER_STRIP_MAX_THICKNESS_RATIO &&
- bounds.height <= reference.bounds.height * MAC_HELPER_STRIP_MAX_THICKNESS_RATIO) ||
- (bounds.y === reference.bounds.y &&
- bounds.height === reference.bounds.height &&
- bounds.width <= bounds.height * MAC_HELPER_STRIP_MAX_THICKNESS_RATIO &&
- bounds.width <= reference.bounds.width * MAC_HELPER_STRIP_MAX_THICKNESS_RATIO)
- );
- });
- });
- if (!window) return undefined;
+ const window = decodeMacActiveWindow(output);
return {
platform: "macos",
id: window.id,
title: window.title,
bounds: window.bounds,
owner: {
- name: lookup.owner.name,
- processId: lookup.owner.processId,
- path: lookup.owner.path,
- ...(lookup.owner.bundleId ? { bundleId: lookup.owner.bundleId } : {}),
+ name: window.owner.name,
+ processId: window.owner.processId,
+ path: window.owner.path,
+ ...(window.owner.bundleId ? { bundleId: window.owner.bundleId } : {}),
},
};
}
diff --git a/apps/desktop/src/updates/DesktopUpdates.test.ts b/apps/desktop/src/updates/DesktopUpdates.test.ts
index 5233f370f7e..94bfbe44c36 100644
--- a/apps/desktop/src/updates/DesktopUpdates.test.ts
+++ b/apps/desktop/src/updates/DesktopUpdates.test.ts
@@ -273,116 +273,6 @@ describe("DesktopUpdates", () => {
).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
});
- it.effect("reuses an update an earlier launch downloaded once its check finishes", () => {
- const releaseCheck = Deferred.makeUnsafe<void>();
- const harness = makeHarness({
- cachedDownloadSha512: "sha-1.2.4",
- // electron-updater reports update-available while the check is running.
- checkForUpdates: Effect.sync(() =>
- harness.emit("update-available", {
- version: "1.2.4",
- files: [{ url: "T3-Code-1.2.4.zip", sha512: "sha-1.2.4" }],
- }),
- ).pipe(Effect.andThen(Deferred.await(releaseCheck))),
- downloadUpdate: Effect.sync(() => harness.emit("update-downloaded", { version: "1.2.4" })),
- });
-
- return Effect.scoped(
- Effect.gen(function* () {
- const updates = yield* DesktopUpdates.DesktopUpdates;
- yield* updates.configure;
-
- const check = yield* Effect.forkChild(updates.check("startup"));
- yield* flushCallbacks;
- assert.equal(harness.downloadCount(), 0);
- assert.equal((yield* updates.getState).status, "available");
-
- yield* Deferred.succeed(releaseCheck, undefined);
- yield* Fiber.join(check);
- yield* flushCallbacks;
-
- assert.equal(harness.downloadCount(), 1);
- const state = yield* updates.getState;
- assert.equal(state.status, "downloaded");
- assert.equal(state.downloadedVersion, "1.2.4");
- }),
- ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
- });
-
- it.effect.each([
- { name: "a newer release", cachedDownloadSha512: "older-release" },
- { name: "an interrupted download", cachedFileExists: false },
- { name: "unfinished metadata", cachedDownloadInfo: "{" },
- ])("keeps $name click-to-download", (cache) => {
- const harness = makeHarness({ cachedDownloadSha512: "release-sha", ...cache });
-
- return Effect.scoped(
- Effect.gen(function* () {
- const updates = yield* DesktopUpdates.DesktopUpdates;
- yield* updates.configure;
- harness.emit("update-available", {
- version: "1.2.5",
- files: [{ url: "T3-Code-1.2.5.zip", sha512: "release-sha" }],
- });
- yield* flushCallbacks;
-
- assert.equal(harness.downloadCount(), 0);
- assert.equal((yield* updates.getState).status, "available");
- assert.isTrue((yield* updates.download).accepted);
- assert.equal(harness.downloadCount(), 1);
- }),
- ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
- });
-
- it.effect.each(["quitting", "newer release", "no longer available"] as const)(
- "abandons pending cache recovery after %s",
- (change) => {
- const releaseCheck = Deferred.makeUnsafe<void>();
- const harness = makeHarness({
- cachedDownloadSha512: "cached-release",
- checkForUpdates: Effect.sync(() =>
- harness.emit("update-available", {
- version: "1.2.4",
- files: [{ url: "T3-Code-1.2.4.zip", sha512: "cached-release" }],
- }),
- ).pipe(Effect.andThen(Deferred.await(releaseCheck))),
- });
-
- return Effect.scoped(
- Effect.gen(function* () {
- const updates = yield* DesktopUpdates.DesktopUpdates;
- yield* updates.configure;
- const check = yield* Effect.forkChild(updates.check("startup"));
- yield* flushCallbacks;
- assert.equal((yield* updates.getState).status, "available");
- assert.equal(harness.downloadCount(), 0);
-
- if (change === "quitting") {
- const desktop = yield* DesktopState.DesktopState;
- yield* Ref.set(desktop.quitting, true);
- } else if (change === "newer release") {
- harness.emit("update-available", {
- version: "1.2.5",
- files: [{ url: "T3-Code-1.2.5.zip", sha512: "new-release" }],
- });
- } else {
- harness.emit("update-not-available");
- }
- yield* flushCallbacks;
- yield* Deferred.succeed(releaseCheck, undefined);
- yield* Fiber.join(check);
- yield* flushCallbacks;
-
- assert.equal(harness.downloadCount(), 0);
- assert.equal(
- (yield* updates.getState).status,
- change === "no longer available" ? "up-to-date" : "available",
- );
- }),
- ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
- },
- );
-
it.effect("preserves a queued installer when the feed has no update", () => {
const harness = makeHarness();
diff --git a/apps/desktop/src/updates/DesktopUpdates.ts b/apps/desktop/src/updates/DesktopUpdates.ts
index 592d453cf60..ae3c2588fab 100644
--- a/apps/desktop/src/updates/DesktopUpdates.ts
+++ b/apps/desktop/src/updates/DesktopUpdates.ts
@@ -68,17 +68,8 @@ const UpdateInfo = Schema.Struct({
// fail the decode and block the update state transition. The shape is
// validated defensively in normalizeDesktopUpdateReleaseNotes.
releaseNotes: Schema.optional(Schema.Unknown),
- files: Schema.optional(Schema.Unknown),
});
-const ReleaseFile = Schema.Struct({ url: Schema.String, sha512: Schema.String });
-type ReleaseFile = typeof ReleaseFile.Type;
-const ReleaseFiles = Schema.Array(ReleaseFile);
-
-const CachedDownloadInfo = Schema.fromJsonString(
- Schema.Struct({ fileName: Schema.String, sha512: Schema.String }),
-);
-
const DownloadProgressInfo = Schema.Struct({
percent: Schema.Number,
});
@@ -92,8 +83,6 @@ const encodeInstallRecord = Schema.encodeEffect(DesktopUpdateInstallRecord);
const decodeAppUpdateYmlConfig = Schema.decodeUnknownEffect(AppUpdateYmlConfig);
const decodeUpdateInfo = Schema.decodeUnknownEffect(UpdateInfo);
const decodeDownloadProgressInfo = Schema.decodeUnknownEffect(DownloadProgressInfo);
-const decodeReleaseFiles = Schema.decodeUnknownOption(ReleaseFiles);
-const decodeCachedDownloadInfo = Schema.decodeUnknownEffect(CachedDownloadInfo);
const currentIsoTimestamp = DateTime.now.pipe(Effect.map(DateTime.formatIso));
@@ -346,32 +335,6 @@ function isArm64HostRunningIntelBuild(runtimeInfo: DesktopRuntimeInfo): boolean
return runtimeInfo.hostArch === "arm64" && runtimeInfo.appArch === "x64";
}
-// Match electron-updater 6.8.9's MacUpdater.filterFilesForArch and Provider.findFile
-// for T3's package feeds. Matching any artifact can trigger a different download.
-function selectUpdateFile(
- files: ReadonlyArray<ReleaseFile>,
- platform: NodeJS.Platform,
- isDebPackage: boolean,
- runtimeInfo: DesktopRuntimeInfo,
-): ReleaseFile | undefined {
- let candidates = files;
- if (platform === "darwin") {
- const isArm64File = (file: ReleaseFile) => file.url.includes("arm64");
- const preferArm64 = runtimeInfo.hostArch === "arm64" && files.some(isArm64File);
- candidates = files.filter((file) => isArm64File(file) === preferArm64);
- }
- const extension =
- platform === "darwin"
- ? ".zip"
- : platform === "win32"
- ? ".exe"
- : isDebPackage
- ? ".deb"
- : ".appimage";
- const packageFiles = candidates.filter((file) => file.url.toLowerCase().endsWith(extension));
- return packageFiles.find((file) => file.url.includes(runtimeInfo.appArch)) ?? packageFiles[0];
-}
-
/** @public Service construction is part of the canonical Effect module API. */
export const make = Effect.gen(function* () {
const config = yield* DesktopConfig.DesktopConfig;
@@ -490,15 +453,6 @@ export const make = Effect.gen(function* () {
),
);
- const awaitIdleUpdateAction = Effect.scoped(
- Effect.gen(function* () {
- const completions = yield* PubSub.subscribe(finishedUpdateActions);
- while (Option.isSome(yield* activeUpdateAction)) {
- yield* PubSub.take(completions);
- }
- }),
- );
-
const applyAutoUpdaterChannel = Effect.fn("desktop.updates.applyAutoUpdaterChannel")(function* (
channel: DesktopUpdateChannel,
) {
@@ -801,7 +755,7 @@ export const make = Effect.gen(function* () {
yield* Ref.set(installRunningBackendsRef, runningInstances);
yield* Effect.forEach(
instances,
- (instance) => instance.stop({ timeout: Duration.seconds(45) }),
+ (instance) => instance.stop({ timeout: Duration.seconds(5) }),
{ concurrency: "unbounded" },
);
yield* electronUpdater.quitAndInstall({
@@ -899,44 +853,6 @@ export const make = Effect.gen(function* () {
);
}).pipe(Effect.withSpan("desktop.updates.startPollers"));
- const cachedDownloadSha512 = Effect.gen(function* () {
- const pendingDirectory = yield* electronUpdater.pendingDownloadDirectory;
- if (Option.isNone(pendingDirectory)) return Option.none<string>();
- const info = yield* fileSystem
- .readFileString(environment.path.join(pendingDirectory.value, "update-info.json"))
- .pipe(Effect.flatMap(decodeCachedDownloadInfo));
- const fileExists = yield* fileSystem.exists(
- environment.path.join(pendingDirectory.value, info.fileName),
- );
- return fileExists ? Option.some(info.sha512) : Option.none<string>();
- }).pipe(Effect.orElseSucceed(() => Option.none<string>()));
-
- // downloadUpdate validates the cached bytes and restores install readiness.
- // Only resume the selected artifact; a cache miss would start a network download.
- const resumeCachedDownload = Effect.fn("desktop.updates.resumeCachedDownload")(function* (
- version: string,
- files: unknown,
- ) {
- const releaseFiles = decodeReleaseFiles(files);
- if (Option.isNone(releaseFiles)) return;
- const updateFile = selectUpdateFile(
- releaseFiles.value,
- environment.platform,
- isDebPackage,
- environment.runtimeInfo,
- );
- if (!updateFile) return;
- const cachedSha512 = yield* cachedDownloadSha512;
- if (Option.isNone(cachedSha512) || updateFile.sha512 !== cachedSha512.value) return;
-
- // update-available arrives while its check still holds the action reservation.
- yield* awaitIdleUpdateAction;
- if (yield* Ref.get(desktopState.quitting)) return;
- const state = yield* Ref.get(updateStateRef);
- if (state.status !== "available" || state.availableVersion !== version) return;
- yield* downloadAvailableUpdate;
- });
-
const handleUpdateAvailable = Effect.fn("desktop.updates.handleUpdateAvailable")(function* (
raw: unknown,
) {
@@ -976,9 +892,6 @@ export const make = Effect.gen(function* () {
releaseNoteGroups: releaseNotes.length,
omittedReleaseCount,
});
- if (state.downloadedVersion !== info.version) {
- yield* resumeCachedDownload(info.version, info.files);
- }
}),
),
Effect.catchCause((cause) => {
diff --git a/apps/desktop/src/updates/updatesTestHarness.ts b/apps/desktop/src/updates/updatesTestHarness.ts
index 2c016c2c4d6..1d8c21a42df 100644
--- a/apps/desktop/src/updates/updatesTestHarness.ts
+++ b/apps/desktop/src/updates/updatesTestHarness.ts
@@ -26,13 +26,6 @@ export interface UpdatesHarnessOptions {
readonly setUpdateChannelError?: DesktopAppSettings.DesktopSettingsWriteError;
readonly setDisableDifferentialDownload?: Effect.Effect<void>;
readonly downloadUpdate?: Effect.Effect<void>;
- /** sha512 of a download an earlier launch left in electron-updater's cache. */
- readonly cachedDownloadSha512?: string;
- readonly cachedDownloadInfo?: string;
- readonly cachedFileExists?: boolean;
- readonly updater?: ElectronUpdater.ElectronUpdater["Service"];
- readonly fileSystem?: FileSystem.FileSystem;
- readonly runningUnderArm64Translation?: boolean;
readonly quitAndInstall?: Effect.Effect<void, ElectronUpdater.ElectronUpdaterQuitAndInstallError>;
readonly stopBackend?: Effect.Effect<void>;
readonly startBackend?: Effect.Effect<void>;
@@ -44,8 +37,6 @@ export interface UpdatesHarnessOptions {
readonly installRecord?: string | undefined;
}
-const PENDING_DOWNLOAD_DIRECTORY = "/cache/t3code-updater/pending";
-
export function makeHarness(options: UpdatesHarnessOptions = {}) {
let checkCount = 0;
let quitAndInstallCount = 0;
@@ -74,7 +65,7 @@ export function makeHarness(options: UpdatesHarnessOptions = {}) {
}
};
- const stubUpdater = {
+ const layerUpdater = Layer.succeed(ElectronUpdater.ElectronUpdater, {
setFeedURL: (options) =>
Effect.sync(() => {
feedUrls.push(options);
@@ -93,11 +84,6 @@ export function makeHarness(options: UpdatesHarnessOptions = {}) {
fullChangelog = value;
}),
setDisableDifferentialDownload: () => options.setDisableDifferentialDownload ?? Effect.void,
- pendingDownloadDirectory: Effect.succeed(
- options.cachedDownloadSha512 === undefined
- ? Option.none()
- : Option.some(PENDING_DOWNLOAD_DIRECTORY),
- ),
checkForUpdates: Effect.sync(() => {
checkCount += 1;
}).pipe(Effect.andThen(options.checkForUpdates ?? Effect.void)),
@@ -119,11 +105,7 @@ export function makeHarness(options: UpdatesHarnessOptions = {}) {
removeListener(eventName, listener as unknown as (...args: readonly unknown[]) => void);
}),
).pipe(Effect.asVoid),
- } satisfies ElectronUpdater.ElectronUpdater["Service"];
- const layerUpdater = Layer.succeed(
- ElectronUpdater.ElectronUpdater,
- options.updater ?? stubUpdater,
- );
+ } satisfies ElectronUpdater.ElectronUpdater["Service"]);
const layerWindow = Layer.succeed(ElectronWindow.ElectronWindow, {
create: () => Effect.die("unexpected BrowserWindow creation"),
@@ -179,7 +161,7 @@ export function makeHarness(options: UpdatesHarnessOptions = {}) {
appPath: "/repo",
isPackaged: true,
resourcesPath: "/missing/resources",
- runningUnderArm64Translation: options.runningUnderArm64Translation ?? false,
+ runningUnderArm64Translation: false,
}).pipe(
Layer.provide(
Layer.mergeAll(
@@ -236,7 +218,7 @@ export function makeHarness(options: UpdatesHarnessOptions = {}) {
let previousInstallRecord = options.installRecord;
const isInstallRecord = (path: string) =>
path.endsWith(DesktopUpdates.DESKTOP_UPDATE_INSTALL_RECORD_FILE);
- const stubFileSystem = FileSystem.layerNoop({
+ const layerFileSystem = FileSystem.layerNoop({
readFileString: (path) => {
const installRecord = isInstallRecord(path)
? (installRecords.get(path) ?? previousInstallRecord)
@@ -244,28 +226,15 @@ export function makeHarness(options: UpdatesHarnessOptions = {}) {
if (installRecord !== undefined) return Effect.succeed(installRecord);
return path === "/missing/resources/package-type" && options.packageType !== undefined
? Effect.succeed(options.packageType)
- : path === `${PENDING_DOWNLOAD_DIRECTORY}/update-info.json` &&
- options.cachedDownloadSha512 !== undefined
- ? Effect.succeed(
- options.cachedDownloadInfo ??
- JSON.stringify({
- fileName: "update.zip",
- sha512: options.cachedDownloadSha512,
- }),
- )
- : Effect.fail(
- PlatformError.systemError({
- module: "FileSystem",
- method: "readFileString",
- _tag: "NotFound",
- pathOrDescriptor: path,
- }),
- );
+ : Effect.fail(
+ PlatformError.systemError({
+ module: "FileSystem",
+ method: "readFileString",
+ _tag: "NotFound",
+ pathOrDescriptor: path,
+ }),
+ );
},
- exists: (path) =>
- Effect.succeed(
- options.cachedFileExists !== false && path === `${PENDING_DOWNLOAD_DIRECTORY}/update.zip`,
- ),
makeDirectory: () => Effect.void,
writeFileString: (path, data) =>
Effect.sync(() => {
@@ -280,9 +249,6 @@ export function makeHarness(options: UpdatesHarnessOptions = {}) {
}),
});
- const layerFileSystem = options.fileSystem
- ? Layer.succeed(FileSystem.FileSystem, options.fileSystem)
- : stubFileSystem;
const layer = DesktopUpdates.layer.pipe(
Layer.provide(layerFileSystem),
Layer.provideMerge(layerUpdater),
diff --git a/apps/desktop/src/window/DesktopWindow.test.ts b/apps/desktop/src/window/DesktopWindow.test.ts
index 2746ec9338c..56206a22796 100644
--- a/apps/desktop/src/window/DesktopWindow.test.ts
+++ b/apps/desktop/src/window/DesktopWindow.test.ts
@@ -27,8 +27,6 @@ vi.mock("electron", async (importOriginal) => ({
setUserAgent: vi.fn(),
})),
},
- BrowserWindow: { getAllWindows: () => [], getFocusedWindow: () => null },
- app: { setBadgeCount: vi.fn() },
screen: {
getAllDisplays: vi.fn(() => [
{
@@ -38,42 +36,6 @@ vi.mock("electron", async (importOriginal) => ({
},
}));
-import * as NetService from "@t3tools/shared/Net";
-import { HttpClient } from "effect/http";
-import * as BrowserImport from "../preview/BrowserImport/BrowserImport.ts";
-import * as DesktopBackendConfiguration from "../backend/DesktopBackendConfiguration.ts";
-import * as DesktopLocalEnvironmentAuth from "../backend/DesktopLocalEnvironmentAuth.ts";
-import * as DesktopCliCommand from "../app/DesktopCliCommand.ts";
-import * as DesktopConnectionCatalogStore from "../app/DesktopConnectionCatalogStore.ts";
-import * as DesktopWebLinks from "../app/DesktopWebLinks.ts";
-import * as DesktopSshEnvironment from "../ssh/DesktopSshEnvironment.ts";
-import * as DesktopSshPasswordPrompts from "../ssh/DesktopSshPasswordPrompts.ts";
-import * as DesktopWslEnvironment from "../wsl/DesktopWslEnvironment.ts";
-import * as MacPermissions from "../permissions/MacPermissions.ts";
-
-import * as HostProcess from "@t3tools/shared/HostProcess";
-import * as Stream from "effect/Stream";
-import * as DesktopApp from "../app/DesktopApp.ts";
-import * as DesktopAppActivation from "../app/DesktopAppActivation.ts";
-import * as DesktopAppIdentity from "../app/DesktopAppIdentity.ts";
-import * as DesktopClerk from "../app/DesktopClerk.ts";
-import * as DesktopLegacyLocalStorage from "../app/DesktopLegacyLocalStorage.ts";
-import * as DesktopLifecycle from "../app/DesktopLifecycle.ts";
-import * as DesktopLinuxUrlHandler from "../app/DesktopLinuxUrlHandler.ts";
-import * as DesktopPreReadyPlatform from "../app/DesktopPreReadyPlatform.ts";
-import * as DesktopShutdown from "../app/DesktopShutdown.ts";
-import * as DesktopBackendPool from "../backend/DesktopBackendPool.ts";
-import * as ElectronDialog from "../electron/ElectronDialog.ts";
-import * as ElectronProtocol from "../electron/ElectronProtocol.ts";
-import * as ElectronSafeStorage from "../electron/ElectronSafeStorage.ts";
-import * as DesktopIpc from "../ipc/DesktopIpc.ts";
-import * as DesktopSnapShot from "../snapShot/DesktopSnapShot.ts";
-import * as DesktopShellEnvironment from "../shell/DesktopShellEnvironment.ts";
-import * as DesktopTelemetryPublisher from "../telemetry/DesktopTelemetryPublisher.ts";
-import * as DesktopUpdates from "../updates/DesktopUpdates.ts";
-import * as DesktopApplicationMenu from "./DesktopApplicationMenu.ts";
-import * as DesktopWslBackend from "../wsl/DesktopWslBackend.ts";
-
import * as DesktopAssets from "../app/DesktopAssets.ts";
import * as DesktopConfig from "../app/DesktopConfig.ts";
import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
@@ -170,7 +132,6 @@ function makeFakeBrowserWindow() {
return {
window: window as unknown as Electron.BrowserWindow,
- close: window.close,
getBounds: window.getBounds,
getNormalBounds: window.getNormalBounds,
isDestroyed: window.isDestroyed,
@@ -392,10 +353,7 @@ function layerTest(input: {
);
}
-const makeSplashScenario = (
- createOutcomes: readonly (Electron.BrowserWindow | null)[],
- settings = DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS,
-) =>
+const makeSplashScenario = (createOutcomes: readonly (Electron.BrowserWindow | null)[]) =>
Effect.gen(function* () {
const createdWindows = yield* Ref.make<Electron.BrowserWindow[]>([]);
const createCalls = yield* Ref.make(0);
@@ -461,7 +419,7 @@ const makeSplashScenario = (
} satisfies ElectronWindow.ElectronWindow["Service"];
const layer = DesktopWindow.layer.pipe(
- Layer.provideMerge(
+ Layer.provide(
Layer.mergeAll(
layerDesktopAssets,
Layer.succeed(DesktopRendererHistory.DesktopRendererHistory, {
@@ -470,7 +428,7 @@ const makeSplashScenario = (
shutdown: Effect.void,
}),
layerDesktopEnvironment,
- DesktopAppSettings.layerTest(settings),
+ DesktopAppSettings.layerTest(),
layerDesktopClientSettings,
layerDesktopServerExposure,
DesktopState.layer,
@@ -484,17 +442,11 @@ const makeSplashScenario = (
layerElectronTheme,
Layer.succeed(ElectronWindow.ElectronWindow, electronWindowShape),
Layer.mock(PreviewPasskeys.PreviewPasskeys)({
- configure: Effect.void,
bridgeEnabled: false,
installSessionHandlers: () => {},
attachGuest: () => () => {},
}),
Layer.mock(PreviewManager.PreviewManager)({
- subscribeStateChanges: () => Effect.void,
- subscribeRecordingFrames: () => Effect.void,
- subscribeRecordingInputs: () => Effect.void,
- subscribePointerEvents: () => Effect.void,
- subscribeOpenLinks: () => Effect.void,
getBrowserSession: () => Effect.succeed({} as Electron.Session),
setMainWindow: () => Effect.void,
isBrowserPartition: (partition) => partition.startsWith("persist:t3code-preview-"),
@@ -511,152 +463,6 @@ const captureOne = DesktopSnapShotId.make("11111111-1111-4111-8111-111111111111"
const captureTwo = DesktopSnapShotId.make("22222222-2222-4222-8222-222222222222");
describe("DesktopWindow", () => {
- it.effect.each([
- { mode: "native", localEnvironmentEnabled: true, wslBackendEnabled: false, wslOnly: false },
- { mode: "WSL-only", localEnvironmentEnabled: true, wslBackendEnabled: true, wslOnly: true },
- { mode: "dual", localEnvironmentEnabled: true, wslBackendEnabled: true, wslOnly: false },
- { mode: "disabled", localEnvironmentEnabled: false, wslBackendEnabled: false, wslOnly: false },
- ])("hands startup from the splash to the main window in $mode mode", (settings) =>
- Effect.gen(function* () {
- const splash = makeFakeBrowserWindow();
- const main = makeFakeBrowserWindow();
- const scenario = yield* makeSplashScenario(
- settings.localEnvironmentEnabled ? [splash.window, main.window] : [main.window],
- { ...DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS, ...settings },
- );
- const bootstrapped = yield* Deferred.make<void>();
- const windowsAtBackendStart: number[] = [];
- const primary = {
- id: DesktopBackendPool.PRIMARY_INSTANCE_ID,
- label: Effect.succeed("Primary"),
- start: Ref.get(scenario.createCalls).pipe(
- Effect.tap((count) => Effect.sync(() => windowsAtBackendStart.push(count))),
- Effect.asVoid,
- ),
- stop: () => Effect.void,
- currentConfig: Effect.succeedNone,
- snapshot: Effect.never,
- waitForReady: () => Effect.succeed(false),
- } satisfies DesktopBackendPool.DesktopBackendInstance;
- const startupLayer = Layer.mergeAll(
- // IPC registration captures these services but startup does not invoke their handlers.
- Layer.mock(BrowserImport.BrowserImport)({}),
- Layer.mock(DesktopBackendConfiguration.DesktopBackendConfiguration)({}),
- Layer.mock(DesktopLocalEnvironmentAuth.DesktopLocalEnvironmentAuth)({}),
- Layer.mock(DesktopCliCommand.DesktopCliCommand)({}),
- Layer.mock(DesktopConnectionCatalogStore.DesktopConnectionCatalogStore)({}),
- Layer.mock(DesktopWebLinks.DesktopWebLinks)({}),
- Layer.mock(DesktopSshEnvironment.DesktopSshEnvironment)({}),
- Layer.mock(DesktopSshPasswordPrompts.DesktopSshPasswordPrompts)({}),
- Layer.mock(DesktopWslEnvironment.DesktopWslEnvironment)({}),
- Layer.mock(MacPermissions.MacPermissions)({}),
- Layer.succeed(
- HttpClient.HttpClient,
- HttpClient.make(() => Effect.die("unexpected HTTP request")),
- ),
- Layer.mock(NetService.NetService)({}),
- Layer.mock(ElectronApp.ElectronApp)({
- whenReady: Effect.void,
- setPath: () => Effect.void,
- on: () => Effect.void,
- }),
- Layer.mock(DesktopAppIdentity.DesktopAppIdentity)({
- resolveUserDataPath: Effect.succeed("/unused"),
- configure: Effect.void,
- }),
- Layer.mock(DesktopLifecycle.DesktopLifecycle)({ register: Effect.void }),
- Layer.mock(DesktopClerk.DesktopClerk)({ configure: Effect.void }),
- Layer.mock(DesktopApplicationMenu.DesktopApplicationMenu)({ configure: Effect.void }),
- Layer.mock(DesktopLinuxUrlHandler.DesktopLinuxUrlHandler)({ register: Effect.void }),
- Layer.mock(DesktopShellEnvironment.DesktopShellEnvironment)({
- installIntoProcess: Effect.succeed(true),
- }),
- Layer.succeed(DesktopPreReadyPlatform.DesktopPreReadyElectronOptions, {
- linux: null,
- linuxPasswordStoreCommandLine: null,
- }),
- Layer.mock(ElectronSafeStorage.ElectronSafeStorage)({}),
- Layer.mock(ElectronProtocol.ElectronProtocol)({
- registerDesktopProtocol: () => Effect.void,
- }),
- Layer.mock(ElectronDialog.ElectronDialog)({}),
- Layer.mock(DesktopIpc.DesktopIpc)({
- handle: () => Effect.void,
- handleSync: () => Effect.void,
- }),
- Layer.mock(DesktopLegacyLocalStorage.DesktopLegacyLocalStorage)({
- load: () => Effect.void,
- }),
- Layer.mock(DesktopSnapShot.DesktopSnapShot)({ initialize: Effect.void }),
- Layer.mock(DesktopAppActivation.DesktopAppActivation)({ start: Effect.void }),
- Layer.mock(DesktopWslBackend.DesktopWslBackend)({ reconcile: Effect.void }),
- Layer.mock(DesktopBackendPool.DesktopBackendPool)({
- primary: Effect.succeed(primary),
- list: Effect.succeed([]),
- }),
- Layer.mock(DesktopServerExposure.DesktopServerExposure)({
- configureFromSettings: () =>
- Effect.succeed({
- mode: "local-only",
- advertisedHost: null,
- endpointUrl: null,
- tailscaleServeEnabled: false,
- tailscaleServePort: 443,
- }),
- backendConfig: Effect.succeed({
- port: 3773,
- bindHost: "127.0.0.1",
- httpBaseUrl: new URL("http://127.0.0.1:3773"),
- tailscaleServeEnabled: false,
- tailscaleServePort: 443,
- }),
- }),
- Layer.mock(DesktopUpdates.DesktopUpdates)({
- configure: Effect.void,
- subscribe: Effect.never,
- }),
- Layer.mock(DesktopTelemetryPublisher.DesktopTelemetryPublisher)({
- updateRequests: Stream.empty,
- updateCancellations: Stream.empty,
- updateCommits: Stream.empty,
- }),
- Layer.mock(DesktopShutdown.DesktopShutdown)({
- awaitRequest: Deferred.succeed(bootstrapped, undefined).pipe(
- Effect.andThen(Effect.never),
- ),
- markComplete: Effect.void,
- }),
- Layer.succeed(HostProcess.Platform, "darwin"),
- NodeServices.layer,
- );
- yield* Effect.gen(function* () {
- const desktopWindow = yield* DesktopWindow.DesktopWindow;
- const app = yield* DesktopApp.program.pipe(Effect.forkScoped);
- yield* Effect.raceFirst(Deferred.await(bootstrapped), Fiber.join(app));
-
- assert.deepEqual(windowsAtBackendStart, settings.localEnvironmentEnabled ? [1] : []);
- assert.equal(yield* Ref.get(scenario.createCalls), 1);
- if (settings.localEnvironmentEnabled) {
- assert.isTrue(Option.isNone(yield* Ref.get(scenario.mainWindow)));
- yield* desktopWindow.handleBackendReady(new URL("http://127.0.0.1:3773"));
- assert.equal(yield* Ref.get(scenario.createCalls), 2);
- }
- assert.deepEqual(yield* Ref.get(scenario.mainWindow), Option.some(main.window));
- assert.equal(splash.close.mock.calls.length, 0);
- const readyToShow = main.windowListeners.get("ready-to-show");
- assert.isDefined(readyToShow);
- readyToShow();
- assert.deepEqual(yield* Ref.get(scenario.revealedWindows), [main.window]);
- assert.equal(splash.close.mock.calls.length, settings.localEnvironmentEnabled ? 1 : 0);
- readyToShow();
- assert.equal(splash.close.mock.calls.length, settings.localEnvironmentEnabled ? 1 : 0);
- }).pipe(
- Effect.scoped,
- Effect.provide(Layer.mergeAll(scenario.layer, startupLayer, DesktopState.layer)),
- );
- }),
- );
-
it.effect("shows native context menus for browser guests and sign-in popups", () =>
Effect.gen(function* () {
const host = makeFakeBrowserWindow();
@@ -854,8 +660,6 @@ describe("DesktopWindow", () => {
assert.equal(yield* Ref.get(createCount), 1);
assert.equal(createdWindowOptions[0]?.width, 1100);
assert.equal(createdWindowOptions[0]?.height, 780);
- assert.equal(createdWindowOptions[0]?.minWidth, 600);
- assert.equal(createdWindowOptions[0]?.minHeight, 620);
assert.isUndefined(createdWindowOptions[0]?.x);
assert.isUndefined(createdWindowOptions[0]?.y);
assert.isTrue(createdWindowOptions[0]?.disableAutoHideCursor);
@@ -1114,7 +918,7 @@ describe("DesktopWindow", () => {
createdWindowOptions,
desktopSettings: {
...DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS,
- mainWindowBounds: { x: 120, y: 80, width: 768, height: 780 },
+ mainWindowBounds: { x: 120, y: 80, width: 1320, height: 880 },
},
});
@@ -1122,8 +926,8 @@ describe("DesktopWindow", () => {
const desktopWindow = yield* DesktopWindow.DesktopWindow;
yield* desktopWindow.handleBackendReady(new URL("http://127.0.0.1:3773"));
- assert.equal(createdWindowOptions[0]?.width, 768);
- assert.equal(createdWindowOptions[0]?.height, 780);
+ assert.equal(createdWindowOptions[0]?.width, 1320);
+ assert.equal(createdWindowOptions[0]?.height, 880);
assert.equal(createdWindowOptions[0]?.x, 120);
assert.equal(createdWindowOptions[0]?.y, 80);
}).pipe(Effect.provide(layer));
@@ -1348,14 +1152,14 @@ describe("DesktopWindow", () => {
move();
yield* TestClock.adjust(250);
- fakeWindow.getBounds.mockReturnValue({ x: 160, y: 100, width: 664, height: 780 });
+ fakeWindow.getBounds.mockReturnValue({ x: 160, y: 100, width: 1360, height: 900 });
resize();
yield* TestClock.adjust(499);
assert.deepEqual(mainWindowBoundsUpdates, []);
yield* TestClock.adjust(1);
yield* Effect.promise(() => Promise.resolve());
- assert.deepEqual(mainWindowBoundsUpdates, [{ x: 160, y: 100, width: 664, height: 780 }]);
+ assert.deepEqual(mainWindowBoundsUpdates, [{ x: 160, y: 100, width: 1360, height: 900 }]);
}).pipe(Effect.provide(layer));
}),
);
@@ -1437,7 +1241,7 @@ describe("DesktopWindow", () => {
it.effect("does not persist bounds that fail the domain schema", () =>
Effect.gen(function* () {
const fakeWindow = makeFakeBrowserWindow();
- fakeWindow.getBounds.mockReturnValue({ x: 100, y: 80, width: 599, height: 620 });
+ fakeWindow.getBounds.mockReturnValue({ x: 100.4, y: 80.2, width: 839.4, height: 619.4 });
const createCount = yield* Ref.make(0);
const mainWindow = yield* Ref.make<Option.Option<Electron.BrowserWindow>>(Option.none());
const mainWindowBoundsUpdates: DesktopAppSettings.DesktopWindowBounds[] = [];
diff --git a/apps/desktop/src/window/DesktopWindow.ts b/apps/desktop/src/window/DesktopWindow.ts
index 8a10de40983..5d14fdfdc53 100644
--- a/apps/desktop/src/window/DesktopWindow.ts
+++ b/apps/desktop/src/window/DesktopWindow.ts
@@ -176,12 +176,12 @@ export function resolveInitialMainWindowBounds(
return DesktopAppSettings.DEFAULT_MAIN_WINDOW_SIZE;
}
-function buildConnectingSplashDataUrl(shouldUseDarkColors: boolean, text: string): string {
+function buildConnectingSplashDataUrl(shouldUseDarkColors: boolean): string {
const background = getInitialWindowBackgroundColor(shouldUseDarkColors);
const label = shouldUseDarkColors ? "#9ca3af" : "#6b7280";
const accent = shouldUseDarkColors ? "#f8fafc" : "#1f2937";
const track = shouldUseDarkColors ? "rgba(248,250,252,0.18)" : "rgba(31,41,55,0.18)";
- 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>`;
+ 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>`;
return `data:text/html;charset=utf-8,${encodeURIComponent(html)}`;
}
@@ -315,7 +315,11 @@ export const make = Effect.gen(function* () {
}
});
- // Window lookups fall back to the first window, which may be the splash.
+ // currentMainOrFirst / focusedMainOrFirst fall back to "any first window",
+ // which during WSL-only boot is the connecting splash. The splash is never
+ // registered via setMain, so it must be treated as "no real main window" --
+ // otherwise ensureMain/activate/dispatchMenuAction latch onto it and never
+ // open (or retry) the real main.
const withoutSplash = (window: Option.Option<Electron.BrowserWindow>) =>
Ref.get(splashWindowRef).pipe(
Effect.map((splash) =>
@@ -379,8 +383,8 @@ export const make = Effect.gen(function* () {
if (yield* Ref.get(desktopState.quitting)) return Option.none();
const window = yield* electronWindow.create({
...initialBounds,
- minWidth: DesktopAppSettings.MIN_MAIN_WINDOW_SIZE.width,
- minHeight: DesktopAppSettings.MIN_MAIN_WINDOW_SIZE.height,
+ minWidth: 840,
+ minHeight: 620,
show: false,
autoHideMenuBar: true,
...(environment.platform === "darwin" ? { disableAutoHideCursor: true } : {}),
@@ -899,11 +903,6 @@ export const make = Effect.gen(function* () {
const shouldUseDarkColors = yield* electronTheme.shouldUseDarkColors;
if (yield* Ref.get(desktopState.quitting)) return;
- const settings = yield* desktopSettings.get;
- const text =
- settings.wslOnly === true && settings.wslBackendEnabled === true
- ? "Connecting to WSL…"
- : "Starting T3 Code…";
const splash = yield* electronWindow.create({
width: 360,
height: 220,
@@ -937,7 +936,7 @@ export const make = Effect.gen(function* () {
splash.show();
}
});
- void splash.loadURL(buildConnectingSplashDataUrl(shouldUseDarkColors, text));
+ void splash.loadURL(buildConnectingSplashDataUrl(shouldUseDarkColors));
yield* logWindowInfo("connecting splash shown");
}).pipe(
Effect.catch((error) =>
diff --git a/apps/web/src/components/AppSidebarLayout.tsx b/apps/web/src/components/AppSidebarLayout.tsx
index c991a900351..89d52c87b28 100644
--- a/apps/web/src/components/AppSidebarLayout.tsx
+++ b/apps/web/src/components/AppSidebarLayout.tsx
@@ -321,7 +321,6 @@ export function AppSidebarLayout({ children }: { children: ReactNode }) {
className="h-dvh! min-h-0!"
data-panel-animations={routePanelAnimationsActive ? "true" : "false"}
defaultOpen
- mobileBreakpoint={sidebarMinimumWidth + THREAD_MAIN_CONTENT_MIN_WIDTH}
style={sidebarProviderStyle}
>
<SidebarBrandWidthProbe onWidthChange={setBrandWidth} />
diff --git a/apps/web/src/components/LegacySidebar.tsx b/apps/web/src/components/LegacySidebar.tsx
index 70c7d7b0c1f..9076b9c127c 100644
--- a/apps/web/src/components/LegacySidebar.tsx
+++ b/apps/web/src/components/LegacySidebar.tsx
@@ -204,6 +204,7 @@ import {
import { sortThreads } from "../lib/threadSort";
import { SidebarChromeFooter, SidebarChromeHeader } from "./sidebar/SidebarChrome";
import { useCopyToClipboard } from "~/hooks/useCopyToClipboard";
+import { useIsMobile } from "~/hooks/useMediaQuery";
import { CommandDialogTrigger } from "./ui/command";
import { useClientSettings, updateClientSettings } from "~/hooks/useSettings";
import { primaryServerKeybindingsAtom } from "../state/server";
@@ -419,7 +420,7 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThreadRowP
environmentId: thread.environmentId,
threadId: thread.id,
});
- const { isMobile } = useSidebar();
+ const isMobile = useIsMobile();
const discoveredPorts = useThreadDiscoveredPorts({
environmentId: thread.environmentId,
threadId: thread.id,
diff --git a/apps/web/src/components/settings/ConnectionsSettings.tsx b/apps/web/src/components/settings/ConnectionsSettings.tsx
index 9f613f38665..ee0328f602f 100644
--- a/apps/web/src/components/settings/ConnectionsSettings.tsx
+++ b/apps/web/src/components/settings/ConnectionsSettings.tsx
@@ -3307,16 +3307,9 @@ export function ConnectionsSettings() {
Off
</SelectItem>
{desktopWslState.distros.length === 0 ? (
- <>
- <SelectItem hideIndicator value={BACKEND_VALUE_DEFAULT_WSL}>
- Default distro
- </SelectItem>
- {desktopWslState.distro !== null ? (
- <SelectItem hideIndicator value={desktopWslState.distro}>
- {desktopWslState.distro}
- </SelectItem>
- ) : null}
- </>
+ <SelectItem hideIndicator value={BACKEND_VALUE_DEFAULT_WSL}>
+ Default distro
+ </SelectItem>
) : (
desktopWslState.distros.map((distro) => (
<SelectItem hideIndicator key={distro.name} value={distro.name}>
diff --git a/apps/web/src/components/sidebar/SidebarChrome.tsx b/apps/web/src/components/sidebar/SidebarChrome.tsx
index c04edb1799f..e7a61f6e992 100644
--- a/apps/web/src/components/sidebar/SidebarChrome.tsx
+++ b/apps/web/src/components/sidebar/SidebarChrome.tsx
@@ -36,7 +36,6 @@ export const SidebarChromeHeader = memo(function SidebarChromeHeader({
}: {
isElectron: boolean;
}) {
- const { isMobile } = useSidebar();
const stageLabel = useEnvironmentStageLabel();
const environmentIdentificationMode = useEnvironmentIdentificationMode();
const backdropVariant = resolveSidebarStageBackdropVariant(
@@ -56,17 +55,15 @@ export const SidebarChromeHeader = memo(function SidebarChromeHeader({
)}
>
{backdropVariant ? <SidebarStageBackdrop variant={backdropVariant} /> : null}
- {isMobile ? (
- <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">
- <SidebarTrigger
- variant={backdropVariant ? "media-navigation" : "ghost"}
- className="relative top-auto translate-y-0"
- aria-label="Toggle main sidebar"
- />
- </div>
- ) : null}
+ <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">
+ <SidebarTrigger
+ variant={backdropVariant ? "media-navigation" : "ghost"}
+ className="relative top-auto translate-y-0"
+ aria-label="Toggle main sidebar"
+ />
+ </div>
<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">
- {!isMobile ? <SidebarBrand onBackdrop={backdropVariant !== null} /> : null}
+ <SidebarBrand onBackdrop={backdropVariant !== null} />
{pillLabel ? (
<div className="ml-1 flex h-7 items-center">
<Badge data-environment-identification="pill" size="sm" variant="secondary">
@@ -108,7 +105,7 @@ function SidebarBrand({ onBackdrop }: { onBackdrop: boolean }) {
<Link
aria-label="Go to threads"
className={cn(
- "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",
+ "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",
onBackdrop ? "text-white" : "text-foreground",
)}
to="/"
diff --git a/apps/web/src/components/ui/sidebar.tsx b/apps/web/src/components/ui/sidebar.tsx
index 3e44922a7b9..570e8299694 100644
--- a/apps/web/src/components/ui/sidebar.tsx
+++ b/apps/web/src/components/ui/sidebar.tsx
@@ -17,7 +17,7 @@ import {
} from "~/components/ui/sheet";
import { Tooltip, TooltipPopup, TooltipTrigger } from "~/components/ui/tooltip";
import { useResizeDrag } from "~/hooks/useResizeDrag";
-import { useMediaQuery } from "~/hooks/useMediaQuery";
+import { useIsMobile } from "~/hooks/useMediaQuery";
import { getLocalStorageItem, setLocalStorageItem } from "~/hooks/useLocalStorage";
import { resolveSidebarState, type ResponsiveSidebarState } from "./sidebarState";
import * as Schema from "effect/Schema";
@@ -96,7 +96,6 @@ function useSidebarVisibility() {
function SidebarProvider({
defaultOpen = true,
- mobileBreakpoint,
open: openProp,
onOpenChange: setOpenProp,
className,
@@ -105,17 +104,11 @@ function SidebarProvider({
...props
}: React.ComponentProps<"div"> & {
defaultOpen?: boolean;
- mobileBreakpoint?: number;
open?: boolean;
onOpenChange?: (open: boolean) => void;
}) {
- const isMobile = useMediaQuery(
- mobileBreakpoint === undefined ? "max-md" : { max: mobileBreakpoint },
- );
+ const isMobile = useIsMobile();
const [openMobile, setOpenMobile] = React.useState(false);
- if (!isMobile && openMobile) {
- setOpenMobile(false);
- }
const [mobileSheetMounted, setMobileSheetMounted] = React.useState(false);
const setMobileSheetElement = (element: HTMLDivElement | null) => {
setMobileSheetMounted(element !== null);
@@ -165,7 +158,6 @@ function SidebarProvider({
SIDEBAR_TITLEBAR_CONTROL_SIZE,
className,
)}
- data-sidebar-mobile={isMobile}
data-sidebar-state={state}
data-slot="sidebar-wrapper"
style={
@@ -306,7 +298,7 @@ function Sidebar({
<SidebarInstanceContext value={instanceContextValue}>
<div
ref={desktopSidebarRef}
- className="group peer text-sidebar-foreground"
+ className="group peer hidden text-sidebar-foreground md:block"
data-collapsible={state === "collapsed" ? collapsible : ""}
data-side={side}
data-slot="sidebar"
@@ -327,7 +319,7 @@ function Sidebar({
/>
<div
className={cn(
- "fixed inset-y-0 z-10 flex h-svh w-(--sidebar-width)",
+ "fixed inset-y-0 z-10 hidden h-svh w-(--sidebar-width) md:flex",
"[[data-panel-animations=true]_&]:transition-[left,right,width] [[data-panel-animations=true]_&]:[transition-duration:var(--panel-animation-duration)] [[data-panel-animations=true]_&]:ease-out",
side === "left"
? "left-0 group-data-[collapsible=offcanvas]:left-[calc(var(--sidebar-width)*-1)]"
diff --git a/apps/web/src/connection/desktopLocal.test.ts b/apps/web/src/connection/desktopLocal.test.ts
index e8a5496ad8a..7a31aa18209 100644
--- a/apps/web/src/connection/desktopLocal.test.ts
+++ b/apps/web/src/connection/desktopLocal.test.ts
@@ -7,7 +7,7 @@ import {
EnvironmentId,
PRIMARY_LOCAL_ENVIRONMENT_ID,
} from "@t3tools/contracts";
-import { describe, expect, it, vi } from "vite-plus/test";
+import { describe, expect, it } from "vite-plus/test";
import {
createDesktopSecondaryBootstrapsReader,
@@ -55,52 +55,7 @@ describe("desktop local connection identity", () => {
});
describe("desktop local topology reads", () => {
- it("refreshes topology asynchronously, retaining identity through unchanged reads and failures", async () => {
- const secondary: DesktopEnvironmentBootstrap = {
- id: "wsl:default",
- label: "WSL",
- runningDistro: "Ubuntu",
- httpBaseUrl: "http://127.0.0.1:4000",
- wsBaseUrl: "ws://127.0.0.1:4000",
- bootstrapToken: "bootstrap-1",
- };
- let entries = [secondary, { ...secondary, id: PRIMARY_LOCAL_ENVIRONMENT_ID }];
- let cached = entries;
- const getLocalEnvironmentBootstraps = vi.fn(() => cached);
- const readLocalEnvironmentBootstraps = vi.fn(async () => {
- cached = entries.map((entry) => ({ ...entry }));
- return cached;
- });
- const reader = createDesktopSecondaryBootstrapsReader(() => ({
- getLocalEnvironmentBootstraps,
- readLocalEnvironmentBootstraps,
- }));
-
- const connected = await reader.refresh();
- expect(connected).toEqual({ _tag: "Success", bootstraps: [secondary] });
- expect(getLocalEnvironmentBootstraps).not.toHaveBeenCalled();
- if (connected._tag !== "Success") throw new Error("expected connected topology");
-
- const unchanged = await reader.refresh();
- if (unchanged._tag !== "Success") throw new Error("expected unchanged topology");
- expect(unchanged.bootstraps).toBe(connected.bootstraps);
- expect(getLocalEnvironmentBootstraps).not.toHaveBeenCalled();
- expect(reader.readSnapshot()).toBe(connected.bootstraps);
-
- const cause = new Error("IPC unavailable");
- readLocalEnvironmentBootstraps.mockRejectedValueOnce(cause);
- expect(await reader.refresh()).toEqual({ _tag: "Failure", cause });
- expect(reader.readSnapshot()).toBe(connected.bootstraps);
-
- entries = [];
- const removed = await reader.refresh();
- expect(removed).toEqual({ _tag: "Success", bootstraps: [] });
- if (removed._tag !== "Success") throw new Error("expected empty topology");
- expect(reader.readSnapshot()).toBe(removed.bootstraps);
- expect(removed.bootstraps).not.toBe(connected.bootstraps);
- });
-
- it("reuses snapshots when polling returns fresh objects for the same topology", async () => {
+ it("reuses snapshots when polling returns fresh objects for the same topology", () => {
const secondary: DesktopEnvironmentBootstrap = {
id: "wsl:default",
label: "WSL",
@@ -115,16 +70,11 @@ describe("desktop local topology reads", () => {
}));
const connected = reader.readSnapshot();
- const refreshed = await reader.refresh();
- expect(refreshed).toEqual({ _tag: "Success", bootstraps: [secondary] });
- if (refreshed._tag !== "Success") throw new Error("expected legacy topology");
- expect(refreshed.bootstraps).toBe(connected);
expect(reader.readSnapshot()).toBe(connected);
expect(reader.readResult()).toEqual({ _tag: "Success", bootstraps: connected });
expect(reader.readSnapshot()).toBe(connected);
entries = [];
- expect(await reader.refresh()).toEqual({ _tag: "Success", bootstraps: [] });
const empty = reader.readSnapshot();
expect(empty).toEqual([]);
expect(reader.readSnapshot()).toBe(empty);
diff --git a/apps/web/src/connection/desktopLocal.ts b/apps/web/src/connection/desktopLocal.ts
index 85abb94b9bd..57f9495521c 100644
--- a/apps/web/src/connection/desktopLocal.ts
+++ b/apps/web/src/connection/desktopLocal.ts
@@ -47,7 +47,6 @@ export type DesktopSecondaryBootstrapsRead =
export interface DesktopSecondaryBootstrapsReader {
readonly readResult: () => DesktopSecondaryBootstrapsRead;
- readonly refresh: () => Promise<DesktopSecondaryBootstrapsRead>;
readonly readSnapshot: () => ReadonlyArray<DesktopEnvironmentBootstrap>;
}
@@ -56,36 +55,10 @@ export interface DesktopSecondaryBootstrapsReader {
* consumers cannot temporarily disagree with the platform's retained registrations.
*/
export function createDesktopSecondaryBootstrapsReader(
- resolveBridge: () =>
- | Pick<DesktopBridge, "getLocalEnvironmentBootstraps" | "readLocalEnvironmentBootstraps">
- | undefined,
+ resolveBridge: () => Pick<DesktopBridge, "getLocalEnvironmentBootstraps"> | undefined,
): DesktopSecondaryBootstrapsReader {
let snapshot: ReadonlyArray<DesktopEnvironmentBootstrap> = [];
- const updateSnapshot = (
- entries: ReadonlyArray<DesktopEnvironmentBootstrap>,
- ): DesktopSecondaryBootstrapsRead => {
- const next = entries.filter((entry) => entry.id !== PRIMARY_LOCAL_ENVIRONMENT_ID);
- if (
- next.length !== snapshot.length ||
- next.some((entry, index) => {
- const previous = snapshot[index];
- return (
- previous === undefined ||
- entry.id !== previous.id ||
- entry.label !== previous.label ||
- entry.runningDistro !== previous.runningDistro ||
- entry.httpBaseUrl !== previous.httpBaseUrl ||
- entry.wsBaseUrl !== previous.wsBaseUrl ||
- entry.bootstrapToken !== previous.bootstrapToken
- );
- })
- ) {
- snapshot = next;
- }
- return { _tag: "Success", bootstraps: snapshot };
- };
-
const readResult = (): DesktopSecondaryBootstrapsRead => {
const bridge = resolveBridge();
if (bridge === undefined) {
@@ -93,7 +66,27 @@ export function createDesktopSecondaryBootstrapsReader(
return { _tag: "Success", bootstraps: snapshot };
}
try {
- return updateSnapshot(bridge.getLocalEnvironmentBootstraps());
+ const next = bridge
+ .getLocalEnvironmentBootstraps()
+ .filter((entry) => entry.id !== PRIMARY_LOCAL_ENVIRONMENT_ID);
+ if (
+ next.length !== snapshot.length ||
+ next.some((entry, index) => {
+ const previous = snapshot[index];
+ return (
+ previous === undefined ||
+ entry.id !== previous.id ||
+ entry.label !== previous.label ||
+ entry.runningDistro !== previous.runningDistro ||
+ entry.httpBaseUrl !== previous.httpBaseUrl ||
+ entry.wsBaseUrl !== previous.wsBaseUrl ||
+ entry.bootstrapToken !== previous.bootstrapToken
+ );
+ })
+ ) {
+ snapshot = next;
+ }
+ return { _tag: "Success", bootstraps: snapshot };
} catch (cause) {
return { _tag: "Failure", cause };
}
@@ -101,15 +94,6 @@ export function createDesktopSecondaryBootstrapsReader(
return {
readResult,
- refresh: async () => {
- const bridge = resolveBridge();
- if (bridge?.readLocalEnvironmentBootstraps === undefined) return readResult();
- try {
- return updateSnapshot(await bridge.readLocalEnvironmentBootstraps());
- } catch (cause) {
- return { _tag: "Failure", cause };
- }
- },
readSnapshot: () => {
const result = readResult();
return result._tag === "Success" ? result.bootstraps : snapshot;
@@ -121,8 +105,8 @@ const desktopSecondaryBootstrapsReader = createDesktopSecondaryBootstrapsReader(
() => window.desktopBridge,
);
-export function readDesktopSecondaryBootstrapsResult(): Promise<DesktopSecondaryBootstrapsRead> {
- return desktopSecondaryBootstrapsReader.refresh();
+export function readDesktopSecondaryBootstrapsResult(): DesktopSecondaryBootstrapsRead {
+ return desktopSecondaryBootstrapsReader.readResult();
}
export function readDesktopSecondaryBootstraps(): ReadonlyArray<DesktopEnvironmentBootstrap> {
diff --git a/apps/web/src/connection/platform.ts b/apps/web/src/connection/platform.ts
index dbc2e0ba70f..e98cb37802b 100644
--- a/apps/web/src/connection/platform.ts
+++ b/apps/web/src/connection/platform.ts
@@ -682,7 +682,7 @@ const layerPlatformConnectionSource = Layer.effect(
}
}
- const topologyRead = yield* Effect.promise(readDesktopSecondaryBootstrapsResult);
+ const topologyRead = readDesktopSecondaryBootstrapsResult();
for (const [id, cached] of secondaryRegistrationsToRetainAfterTopologyRead(
previous,
topologyRead,
diff --git a/apps/web/src/hooks/useMediaQuery.ts b/apps/web/src/hooks/useMediaQuery.ts
index f3df1b3a4b1..ec6ee4fa511 100644
--- a/apps/web/src/hooks/useMediaQuery.ts
+++ b/apps/web/src/hooks/useMediaQuery.ts
@@ -77,3 +77,7 @@ export function useMediaQuery(query: BreakpointQuery | MediaQueryInput | (string
return useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot);
}
+
+export function useIsMobile(): boolean {
+ return useMediaQuery("max-md");
+}
diff --git a/apps/web/src/workspaceTitlebar.ts b/apps/web/src/workspaceTitlebar.ts
index 8813f9b8160..729fdfa00dc 100644
--- a/apps/web/src/workspaceTitlebar.ts
+++ b/apps/web/src/workspaceTitlebar.ts
@@ -1,2 +1,2 @@
export const COLLAPSED_SIDEBAR_TITLEBAR_INSET_CLASS =
- "[[data-sidebar-state=collapsed]_&]:pl-[var(--workspace-titlebar-content-left)] [[data-sidebar-mobile=true][data-sidebar-state=expanded]_&]:pl-[var(--workspace-titlebar-content-left)]";
+ "[[data-sidebar-state=collapsed]_&]:pl-[var(--workspace-titlebar-content-left)] max-md:[[data-sidebar-state=expanded]_&]:pl-[var(--workspace-titlebar-content-left)]";
diff --git a/docs/internals/performance-regressions.md b/docs/internals/performance-regressions.md
index 0e395564f13..059cac68bc2 100644
--- a/docs/internals/performance-regressions.md
+++ b/docs/internals/performance-regressions.md
@@ -98,10 +98,7 @@ viewport, including a small overscan region. Cached badges remain available whil
released. Local Git status reads skip divergence calculations; callers that need ahead/behind
counts keep the full status path. Cached fetch failures share the existing backoff and log only
the actual failed attempt. Unchanged desktop environment bootstrap reads retain their array
-identity so polling does not invalidate subscribers. The desktop preload keeps the synchronous
-startup snapshot, while topology polling refreshes it through asynchronous IPC. Recurring
-`sendSync` calls block the renderer behind unrelated main-process work, even when the returned
-snapshot is unchanged.
+identity so polling does not invalidate subscribers.
Local trace records and provider event logs use asynchronous, serialized file writes and rotation.
Batching synchronous appends still stalls the server event loop on slow storage, especially on
diff --git a/packages/contracts/src/ipc.ts b/packages/contracts/src/ipc.ts
index cb48058b8ca..d1f6b349397 100644
--- a/packages/contracts/src/ipc.ts
+++ b/packages/contracts/src/ipc.ts
@@ -1047,8 +1047,6 @@ export interface DesktopBridge {
*/
getSystemLocale?: () => string | null;
getLocalEnvironmentBootstraps: () => readonly DesktopEnvironmentBootstrap[];
- /** Refresh the preload snapshot without blocking the renderer on synchronous IPC. */
- readLocalEnvironmentBootstraps?: () => Promise<readonly DesktopEnvironmentBootstrap[]>;
getLocalEnvironmentEnabled?: () => boolean;
setLocalEnvironmentEnabled?: (enabled: boolean) => Promise<void>;
getLocalEnvironmentBearerToken: () => Promise<string>;