Compare commits

..
Author SHA1 Message Date
Julius Marmingeandcodex dfc32cd101 Structure cloud CLI token errors
Co-authored-by: codex <[email protected]>
2026-06-20 02:29:31 -07:00
Julius Marmingeandcodex 6c12fe1e6c Structure cloud HTTP boundary errors
Co-authored-by: codex <[email protected]>
2026-06-20 02:23:20 -07:00
Julius Marmingeandcodex 47c042422c Structure server secret store errors
Co-authored-by: codex <[email protected]>
2026-06-20 02:09:59 -07:00
Julius Marmingeandcodex 4ec16654a6 Improve server auth error context
Co-authored-by: codex <[email protected]>
2026-06-20 02:03:46 -07:00
937 changed files with 18978 additions and 87137 deletions

No files matched your search

-72
View File
@@ -1,72 +0,0 @@
---
description: Cursor Cloud environment setup and run notes for T3 Code (Cursor-specific; not for other editors/CI)
alwaysApply: true
---
# Cursor Cloud specific instructions
These notes apply only to Cursor Cloud agents (kept out of the shared `AGENTS.md` since T3 Code is
developed in many places). They cover the pre-provisioned VM environment and non-obvious run caveats.
## Toolchain
Pre-installed and wired into login shells (`~/.bashrc`/`~/.profile`): Node 24 (via nvm), the global
`vp` (Vite+) CLI, and its bundled pnpm. `vp` is the package manager + task runner for this repo
(`vp i`, `vp check`, `vp run typecheck`, `vp test`, `vp run --filter <pkg> <script>`).
- Node gotcha: the base image also ships an older Node on `/exec-daemon` that wins on `PATH` in
non-login shells. Run commands in a login shell (`bash -lc '...'`) or prepend
`$HOME/.nvm/versions/node/v24.13.1/bin` so Node 24 (`engines.node: ^24.13.1`) is used.
- `vp check` also runs the formatter (not just lint); markdown edits must be formatter-clean. Run
`vp check --fix` before committing.
## Running the web app
- `npm run dev` (from repo root) starts contracts (watch), web (Vite, port 5733), and the server
(`node --watch`, port 13773) together, auto-wiring `VITE_HTTP_URL`/`VITE_WS_URL`. Use
`npm run dev:server` / `npm run dev:web` for one side. If base ports are taken it auto-offsets to
the next free pair, so read the actual ports from stdout. Avoid production `build`/`start` in dev.
- Auth/pairing: the server is unauthenticated by default and prints a pairing URL to stdout on startup
(e.g. `http://localhost:5733/pair#token=XXXX`). Open that URL in the browser to pair before the web
UI can talk to the server. Server state (SQLite, auth, projects) lives under `~/.t3`
(`T3CODE_HOME`); multiple `npm run dev` instances bind different ports but share that same DB.
- Agent providers are external CLIs (`codex`, `claude`, `cursor-agent`, `opencode`) probed on `PATH`.
Without one installed the UI loads but no agent can run. Claude Code
(`npm i -g @anthropic-ai/claude-code`) works headlessly using `ANTHROPIC_API_KEY` from the
environment (the server forwards `process.env` to the child; no interactive `claude auth login`
needed). Provider probing runs at startup and refreshes roughly every 5 minutes — restart the dev
server to pick up a newly installed provider CLI immediately.
## Android native builds (apps/mobile)
The Android toolchain is pre-installed and wired into login shells: OpenJDK 17
(`JAVA_HOME=/usr/lib/jvm/java-17-openjdk-amd64`; the base image's default `java` is 21, so builds must
use `JAVA_HOME`), and the Android SDK at `$HOME/Android/Sdk` (`ANDROID_HOME`/`ANDROID_SDK_ROOT`) with
platform-tools, `platforms;android-36`, `build-tools;36.0.0`, `ndk;27.1.12297006`, and `cmake;3.22.1`.
Gradle auto-downloads any additional pinned SDK packages on demand.
- Generate the native project first: from `apps/mobile`,
`EXPO_NO_GIT_STATUS=1 APP_VARIANT=development npx expo prebuild --clean --platform android`
(the `android/` folder is generated, not committed). RN 0.85 defaults: compileSdk/targetSdk 36,
minSdk 24, NDK `27.1.12297006` (see `react-native/gradle/libs.versions.toml`).
- Build with Gradle from `apps/mobile/android`, e.g. `./gradlew :app:assembleDebug`. First build is
slow (Kotlin + C++/NDK codegen). Limit ABIs to speed things up, e.g.
`-PreactNativeArchitectures=arm64-v8a`. Verified working end-to-end on a native module:
`./gradlew :react-native-worklets:assembleDebug` compiles Kotlin + C++ and emits an AAR + `.so`s.
- No emulator: this VM has no `/dev/kvm` (nested virtualization), so a hardware-accelerated Android
emulator will not run. Use a physical device (`adb`) or EAS cloud builds (`vp run eas:android:*`) to
actually run the app. The full IDE GUI is unnecessary here — the SDK/NDK/Gradle toolchain that
Android Studio bundles is what is installed.
- Known blocker for the full-app `:app:assembleDebug` (pre-existing, app-level — not the environment):
`:react-native-screens:compileDebugKotlin` fails because `patches/[email protected]`
adds new codegen props (`subtitle`, `largeSubtitle`, `navigationItemStyle`,
`headerCenterBarButtonItems`, `headerToolbarItems`) to the JS spec + iOS native code but includes no
Android Kotlin setters, so the generated `ScreenStackHeaderConfigManagerInterface` is unimplemented.
The mobile README documents only iOS for local builds and routes Android through EAS. Fixing local
Android app builds requires an app/patch change (add the Android Kotlin setters), which is out of
scope for environment setup.
## Known flaky tests (unrelated to setup)
- `apps/server/src/git/GitManager.test.ts` (cross-repo PR metadata, can time out at 12s).
- `apps/server/src/provider/Layers/ProviderRegistry.test.ts` (codex binaryPath re-probe ordering).
+1 -4
View File
@@ -57,10 +57,7 @@ jobs:
with:
eas-version: latest
token: ${{ secrets.EXPO_TOKEN }}
# npm, not pnpm: this only installs eas-cli into the action's own
# tool dir, and pnpm 11 hard-fails that install on dtrace-provider's
# ignored build script (no allowBuilds config outside the repo).
packager: npm
packager: pnpm
- name: Pull preview environment variables
if: steps.expo-token.outputs.present == 'true'
-113
View File
@@ -1,113 +0,0 @@
name: Mobile EAS Production
# Production builds and OTA updates run from CI (Linux) — never from a laptop.
# Under the fingerprint runtime-version policy the fingerprint must be computed
# in the same OS/pnpm as the EAS build; a macOS `eas build` computes a different
# fingerprint (platform-specific deps + pnpm version) and errors. On this Linux
# runner, with corepack pinning pnpm 10.24 in eas.json, local == build.
on:
workflow_dispatch:
inputs:
mode:
description: "build (+ auto-submit to TestFlight) or update (OTA)"
required: true
type: choice
default: build
options:
- build
- update
platform:
description: "Target platform"
required: true
type: choice
default: ios
options:
- ios
- android
- all
message:
description: "OTA update message (mode=update only)"
required: false
type: string
jobs:
production:
name: EAS Production ${{ inputs.mode }}
runs-on: blacksmith-8vcpu-ubuntu-2404
permissions:
contents: read
env:
APP_VARIANT: production
NODE_OPTIONS: --max-old-space-size=8192
steps:
- id: expo-token
name: Check for EXPO_TOKEN
env:
EXPO_TOKEN: ${{ secrets.EXPO_TOKEN }}
run: |
if [ -n "$EXPO_TOKEN" ]; then
echo "present=true" >> "$GITHUB_OUTPUT"
else
echo "present=false" >> "$GITHUB_OUTPUT"
echo "EXPO_TOKEN is not available; skipping EAS production job."
fi
- name: Checkout
if: steps.expo-token.outputs.present == 'true'
uses: actions/checkout@v6
with:
fetch-depth: 0
- name: Setup Vite+
if: steps.expo-token.outputs.present == 'true'
uses: voidzero-dev/setup-vp@v1
with:
node-version-file: package.json
cache: true
run-install: true
- name: Expose pnpm
if: steps.expo-token.outputs.present == 'true'
run: |
pnpm_version="$(node --print "require('./package.json').packageManager.split('@').pop()")"
vp_pnpm_bin="$HOME/.vite-plus/package_manager/pnpm/$pnpm_version/pnpm/bin"
echo "$vp_pnpm_bin" >> "$GITHUB_PATH"
"$vp_pnpm_bin/pnpm" --version
- name: Setup EAS
if: steps.expo-token.outputs.present == 'true'
uses: expo/expo-github-action@v8
with:
eas-version: latest
token: ${{ secrets.EXPO_TOKEN }}
# npm, not pnpm: this only installs eas-cli into the action's own
# tool dir, and pnpm 11 hard-fails that install on dtrace-provider's
# ignored build script (no allowBuilds config outside the repo).
packager: npm
- name: Pull production environment variables
if: steps.expo-token.outputs.present == 'true'
working-directory: apps/mobile
env:
EXPO_TOKEN: ${{ secrets.EXPO_TOKEN }}
run: eas env:pull production --non-interactive
- name: Build and submit
if: steps.expo-token.outputs.present == 'true' && inputs.mode == 'build'
working-directory: apps/mobile
env:
EXPO_TOKEN: ${{ secrets.EXPO_TOKEN }}
run: eas build --platform ${{ inputs.platform }} --profile production --auto-submit --non-interactive --no-wait
- name: Publish OTA update
if: steps.expo-token.outputs.present == 'true' && inputs.mode == 'update'
working-directory: apps/mobile
env:
EXPO_TOKEN: ${{ secrets.EXPO_TOKEN }}
run: |
eas update \
--channel production \
--environment production \
--platform ${{ inputs.platform }} \
--message "${{ inputs.message || format('Production OTA ({0})', github.sha) }}" \
--non-interactive
+2 -67
View File
@@ -252,64 +252,10 @@ jobs:
echo "clerk_cli_oauth_client_id=$CLERK_CLI_OAUTH_CLIENT_ID" >> "$GITHUB_OUTPUT"
echo "relay_url=https://$relay_domain" >> "$GITHUB_OUTPUT"
# node-pty publishes no Linux prebuilt and the WSL backend runs under the
# distro's own (Linux) Node, which can't load the Windows/Electron binary. We
# build the Linux pty.node here, on Linux, and hand it to the Windows packaging
# job — the Windows artifact then ships a ready WSL backend binary with no
# cross-compiling and no first-launch compiler/node-gyp/network on the user's
# machine. node-pty is N-API, so one binary works across all WSL Node versions.
build_wsl_node_pty:
name: Build WSL node-pty (linux-x64)
needs: [preflight]
if: ${{ !failure() && !cancelled() && needs.preflight.result == 'success' }}
runs-on: blacksmith-8vcpu-ubuntu-2404
timeout-minutes: 15
steps:
- name: Checkout
uses: actions/checkout@v6
with:
ref: ${{ needs.preflight.outputs.ref }}
fetch-depth: 0
- name: Setup Vite+
uses: voidzero-dev/setup-vp@v1
with:
node-version-file: package.json
cache: true
run-install: true
- name: Build node-pty linux-x64 prebuild
shell: bash
run: |
set -euo pipefail
# Resolve node-pty from apps/server (where it's a dependency) and build
# its native binary from source for Linux. node-addon-api resolves from
# node-pty's own dependency tree, so node-gyp has everything it needs.
pty_pkg="$(node -e "console.log(require.resolve('node-pty/package.json', { paths: ['$GITHUB_WORKSPACE/apps/server'] }))")"
pty_dir="$(dirname "$pty_pkg")"
( cd "$pty_dir" && npx --yes node-gyp rebuild )
mkdir -p wsl-prebuild
cp "$pty_dir/build/Release/pty.node" wsl-prebuild/pty.node
file wsl-prebuild/pty.node
- name: Upload node-pty linux-x64 prebuild
uses: actions/upload-artifact@v7
with:
name: wsl-node-pty-x64
path: wsl-prebuild/pty.node
if-no-files-found: error
build:
name: Build ${{ matrix.label }}
# build_wsl_node_pty stays in `needs` so it runs first and its artifact is
# available to download, but only the Windows matrix entry consumes it. We
# therefore gate the job on preflight + relay (must succeed) WITHOUT requiring
# build_wsl_node_pty, so a failed Linux prebuild doesn't skip the macOS/Linux
# builds. `!cancelled()` (not `!failure()`) lets the job run even when
# build_wsl_node_pty failed; the Windows-only download step below then fails
# that single platform if the prebuild is missing.
needs: [preflight, relay_public_config, build_wsl_node_pty]
if: ${{ !cancelled() && needs.preflight.result == 'success' && needs.relay_public_config.result == 'success' }}
needs: [preflight, relay_public_config]
if: ${{ !failure() && !cancelled() && needs.preflight.result == 'success' && needs.relay_public_config.result == 'success' }}
runs-on: ${{ matrix.runner }}
timeout-minutes: 30
env:
@@ -377,13 +323,6 @@ jobs:
- name: Align package versions to release version
run: node scripts/update-release-package-versions.ts "${{ needs.preflight.outputs.version }}"
- name: Download WSL node-pty prebuild
if: matrix.platform == 'win'
uses: actions/download-artifact@v7
with:
name: wsl-node-pty-x64
path: wsl-prebuild
- name: Install Spectre-mitigated MSVC libs
if: matrix.platform == 'win'
shell: pwsh
@@ -537,10 +476,6 @@ jobs:
echo "macOS signing disabled (missing one or more Apple signing secrets)."
fi
elif [[ "${{ matrix.platform }}" == "win" ]]; then
# Bundle the Linux node-pty binary built by the build_wsl_node_pty job
# so the packaged WSL backend ships a ready binary (no first-launch
# compile). Required for a working WSL backend on Windows.
args+=(--wsl-prebuild "$GITHUB_WORKSPACE/wsl-prebuild/pty.node")
if has_all \
"$AZURE_TENANT_ID" \
"$AZURE_CLIENT_ID" \
@@ -48,9 +48,7 @@ Review changed TypeScript and directly affected call sites for the conventions b
- Define service failures with `Schema.TaggedErrorClass` and structured attributes. Derive `message` from those attributes rather than storing an unstructured message as the only data.
- `Schema.Defect()` is not a substitute for modeling a generic error: its tag, fields, or both must identify the failure structurally, and its `message` must not merely stringify an opaque cause. A semantically precise error tag may preserve a real `cause` without inventing a redundant singleton field when no additional variable context exists; still retain any real path, resource, request, or entity context available at the wrapping site.
- Capture stable, serializable domain context such as the operation or stage, resource/path or entity identifier, and normalized category/status. Map failures where that context is known instead of wrapping an entire multi-step pipeline in one generic error. Do not add a `detail` field that merely copies `cause.message` and then use it to construct the wrapper message.
- Keep direct error attributes and log annotations safe and bounded. Do not copy raw wire payloads, command arguments or output, signed URLs, credentials, query strings, fragments, selectors, or arbitrary defect text into `detail`, `reason`, `message`, or a parallel log payload. Preserve the exact underlying value only as `cause`; expose normalized categories plus lengths/counts and safe URL protocol/hostname diagnostics where useful. Logging a sanitized error must not reintroduce a removed legacy `detail` or serialized `cause` field beside it.
- When translating or wrapping a real failure, preserve the immediate underlying error itself as `cause` alongside the structural fields so the complete error chain and stack remain available. If every construction wraps a failure, `cause` should be required; make it optional only when the same error can legitimately originate without an underlying failure.
- At a translation boundary, pass through an already structured domain error when it is part of the declared target error channel. Wrap only unknown or genuinely lower-level failures. A static factory or mapper may perform this classification when it is reused and keeps the policy next to the target error type.
- Derive the wrapper's `message` exclusively from its stable structural attributes, never from `cause`, `cause.message`, or a stringified defect. Do not replace the immediate error with only `error.cause`, erase a structured upstream error into a string, or manufacture an `Error` merely to populate `cause`. Pure validation/domain errors created without an underlying failure do not need a cause.
- Do not encode the same distinction twice with both a specific error tag and a single-value `operation`, `reason`, `kind`, or `phase` literal. Choose one coherent model: use distinct error classes and omit the redundant discriminator when callers or messages treat the failures as genuinely different, or use one service-level error with a multi-value operation discriminator and a generic message derived from that operation when the failures share the same semantics.
- Treat an error message exposed through an HTTP/RPC response, persisted state, UI, or another caller-visible boundary as behavior. Preserve those messages during a structural refactor. Existing distinct caller-visible messages are evidence that the failures should normally remain distinct error tags without redundant singleton discriminators, rather than being collapsed into a generic operation error.
@@ -58,9 +56,6 @@ Review changed TypeScript and directly affected call sites for the conventions b
- Use `Schema.Union` of error classes when a shared schema, predicate, or helper type is useful.
- Export direct schema predicates such as `export const isFoo = Schema.is(Foo)`. Flag a private `Schema.is` constant wrapped by a redundant function with the same signature.
- Do not introduce a large `switch` or lookup table in an error's `message` getter to model failures that deserve separate error classes.
- Catch statically known tagged failures with `Effect.catchTags({ ... })`, including when handling only one tag. Do not use `catchIf` with a schema predicate merely to recover one or more known `_tag` variants, and do not use `catchTag`. `Effect.catch` is appropriate when the entire error channel is intentionally handled; `catchIf` remains appropriate for genuinely structural predicates such as inspecting an underlying platform error code.
- Do not add a helper whose only behavior is `(...args) => new SomeError({ ...args })`, including curried aliases used once with `mapError`. Construct the error at the failure boundary so its attributes and cause remain visible. Keep a mapper only when it performs real normalization, passes through existing domain errors, or adds reusable context/control flow.
- When a reusable error-to-error translation clearly belongs to the target error type, prefer a descriptive static factory on that error class over a detached production-side switch. Do not force a static method for one-off inline mappings.
## File layout and migrations
@@ -78,6 +73,4 @@ Review changed TypeScript and directly affected call sites for the conventions b
## Reporting
Report only concrete violations introduced or retained in the pull request's changed scope. Prefer precise inline comments on the smallest relevant line range and state the expected fix. A clear convention violation may fail the check. Do not fail for optional style preferences or unrelated legacy code.
This check defaults to failure. When there are no findings, stop immediately and make the entire final response exactly `All clear` on one line. Do not add a title, explanation, punctuation, Markdown, JSON, or trailing analysis, and do not continue reasoning after deciding the review is clean.
Report only concrete violations introduced or retained in the pull request's changed scope. Prefer precise inline comments on the smallest relevant line range and state the expected fix. A clear convention violation may fail the check. Do not fail for optional style preferences or unrelated legacy code. If there are no findings, report exactly `All clear`.
-1
View File
@@ -1 +0,0 @@
vp staged
+2 -2
View File
@@ -1,6 +1,6 @@
{
"name": "@t3tools/desktop",
"version": "0.0.28",
"version": "0.0.27",
"private": true,
"type": "module",
"main": "dist-electron/main.cjs",
@@ -31,7 +31,7 @@
"@effect/vitest": "catalog:",
"@types/node": "catalog:",
"cross-env": "^10.1.0",
"electron-builder": "26.15.6",
"electron-builder": "26.8.1",
"tailwindcss": "^4.0.0",
"vite-plus": "catalog:"
},
+20 -49
View File
@@ -100,41 +100,25 @@ function shellSingleQuote(value) {
return `'${value.replaceAll("'", "'\\''")}'`;
}
export function makeDevelopmentLauncherScript({
electronBinaryPath,
mainEntryPath,
desktopRoot,
environment,
}) {
function writeDevelopmentLauncherScript(targetBinaryPath, electronBinaryPath) {
const mainEntryPath = NodePath.join(desktopDir, "dist-electron", "main.cjs");
const envEntries = [
["VITE_DEV_SERVER_URL", environment.VITE_DEV_SERVER_URL],
["T3CODE_PORT", environment.T3CODE_PORT],
["T3CODE_HOME", environment.T3CODE_HOME],
["T3CODE_COMMIT_HASH", environment.T3CODE_COMMIT_HASH],
["T3CODE_OTLP_TRACES_URL", environment.T3CODE_OTLP_TRACES_URL],
["T3CODE_OTLP_EXPORT_INTERVAL_MS", environment.T3CODE_OTLP_EXPORT_INTERVAL_MS],
["VITE_DEV_SERVER_URL", process.env.VITE_DEV_SERVER_URL],
["T3CODE_PORT", process.env.T3CODE_PORT],
["T3CODE_HOME", process.env.T3CODE_HOME],
["T3CODE_COMMIT_HASH", process.env.T3CODE_COMMIT_HASH],
["T3CODE_OTLP_TRACES_URL", process.env.T3CODE_OTLP_TRACES_URL],
["T3CODE_OTLP_EXPORT_INTERVAL_MS", process.env.T3CODE_OTLP_EXPORT_INTERVAL_MS],
["T3CODE_DESKTOP_APP_USER_MODEL_ID", APP_BUNDLE_ID],
].filter((entry) => typeof entry[1] === "string" && entry[1].trim().length > 0);
return [
"#!/bin/sh",
...envEntries.map(
([name, value]) =>
`if [ -z "\${${name}:-}" ]; then export ${name}=${shellSingleQuote(value)}; fi`,
),
`exec ${shellSingleQuote(electronBinaryPath)} --t3code-dev-root=${shellSingleQuote(desktopRoot)} ${shellSingleQuote(mainEntryPath)} "$@"`,
"",
].join("\n");
}
function writeDevelopmentLauncherScript(targetBinaryPath, electronBinaryPath) {
NodeFS.writeFileSync(
targetBinaryPath,
makeDevelopmentLauncherScript({
electronBinaryPath,
mainEntryPath: NodePath.join(desktopDir, "dist-electron", "main.cjs"),
desktopRoot: desktopDir,
environment: process.env,
}),
[
"#!/bin/sh",
...envEntries.map(([name, value]) => `export ${name}=${shellSingleQuote(value)}`),
`exec ${shellSingleQuote(electronBinaryPath)} --t3code-dev-root=${shellSingleQuote(desktopDir)} ${shellSingleQuote(mainEntryPath)} "$@"`,
"",
].join("\n"),
);
NodeFS.chmodSync(targetBinaryPath, 0o755);
}
@@ -302,12 +286,6 @@ function buildMacLauncher(electronBinaryPath) {
currentMetadata &&
JSON.stringify(currentMetadata) === JSON.stringify(expectedMetadata)
) {
if (isDevelopment) {
// The launcher also handles protocol activations outside the dev runner,
// so refresh its fallback environment on every launch. Never let a value
// captured by an older parent app override the live dev-runner environment.
writeDevelopmentLauncherScript(targetBinaryPath, electronBinaryPath);
}
registerMacLauncherBundle(targetAppBundlePath);
return targetBinaryPath;
}
@@ -358,7 +336,10 @@ function resolveLinuxSandboxArgs(electronBinaryPath) {
}
export function resolveElectronPath() {
const electronBinaryPath = resolveElectronBinaryPath();
ensureElectronRuntime();
const require = NodeModule.createRequire(import.meta.url);
const electronBinaryPath = require("electron");
if (hostPlatform !== "darwin") {
return electronBinaryPath;
@@ -375,23 +356,13 @@ export function resolveElectronLaunchCommand(args = []) {
};
}
export function resolveElectronBinaryPath({
ensureRuntime = ensureElectronRuntime,
createRequire = NodeModule.createRequire,
moduleUrl = import.meta.url,
} = {}) {
ensureRuntime();
const require = createRequire(moduleUrl);
return require("electron");
}
export function resolveDevProtocolClient() {
if (hostPlatform !== "darwin" || !isDevelopment) {
return null;
}
const electronBinaryPath = resolveElectronBinaryPath();
const require = NodeModule.createRequire(import.meta.url);
const electronBinaryPath = require("electron");
const launcherBinaryPath = buildMacLauncher(electronBinaryPath);
return {
appBundlePath: NodePath.resolve(launcherBinaryPath, "..", "..", ".."),
@@ -1,48 +0,0 @@
import { assert, describe, it } from "vite-plus/test";
import { makeDevelopmentLauncherScript, resolveElectronBinaryPath } from "./electron-launcher.mjs";
describe("electron development launcher", () => {
it("uses captured values only as fallbacks for a live runner environment", () => {
const script = makeDevelopmentLauncherScript({
electronBinaryPath: "/repo/node_modules/electron/Electron",
mainEntryPath: "/repo/apps/desktop/dist-electron/main.cjs",
desktopRoot: "/repo/apps/desktop",
environment: {
VITE_DEV_SERVER_URL: "http://127.0.0.1:8526",
T3CODE_PORT: "16566",
T3CODE_HOME: "/tmp/t3",
},
});
assert.include(
script,
"if [ -z \"${VITE_DEV_SERVER_URL:-}\" ]; then export VITE_DEV_SERVER_URL='http://127.0.0.1:8526'; fi",
);
assert.notInclude(script, "\nexport VITE_DEV_SERVER_URL=");
assert.include(
script,
"exec '/repo/node_modules/electron/Electron' --t3code-dev-root='/repo/apps/desktop' '/repo/apps/desktop/dist-electron/main.cjs' \"$@\"",
);
});
it("repairs Electron before loading the package entrypoint", () => {
const calls = [];
const electronPath = resolveElectronBinaryPath({
ensureRuntime: () => {
calls.push("ensure");
},
createRequire: () => (specifier) => {
calls.push(`require:${specifier}`);
return "/repo/node_modules/electron/dist/Electron.app/Contents/MacOS/Electron";
},
moduleUrl: import.meta.url,
});
assert.equal(
electronPath,
"/repo/node_modules/electron/dist/Electron.app/Contents/MacOS/Electron",
);
assert.deepEqual(calls, ["ensure", "require:electron"]);
});
});
+16 -45
View File
@@ -1,8 +1,8 @@
import * as Cause from "effect/Cause";
import * as Data from "effect/Data";
import * as Effect from "effect/Effect";
import * as Option from "effect/Option";
import * as Ref from "effect/Ref";
import * as Schema from "effect/Schema";
import * as NetService from "@t3tools/shared/Net";
import * as Crypto from "effect/Crypto";
@@ -13,8 +13,7 @@ import { installDesktopIpcHandlers } from "../ipc/DesktopIpcHandlers.ts";
import * as DesktopAppIdentity from "./DesktopAppIdentity.ts";
import * as DesktopClerk from "./DesktopClerk.ts";
import * as DesktopApplicationMenu from "../window/DesktopApplicationMenu.ts";
import * as DesktopWindow from "../window/DesktopWindow.ts";
import * as DesktopBackendPool from "../backend/DesktopBackendPool.ts";
import * as DesktopBackendManager from "../backend/DesktopBackendManager.ts";
import * as DesktopEnvironment from "./DesktopEnvironment.ts";
import * as DesktopLifecycle from "./DesktopLifecycle.ts";
import * as DesktopObservability from "./DesktopObservability.ts";
@@ -24,7 +23,6 @@ import * as DesktopAppSettings from "../settings/DesktopAppSettings.ts";
import * as DesktopShellEnvironment from "../shell/DesktopShellEnvironment.ts";
import * as DesktopState from "./DesktopState.ts";
import * as DesktopUpdates from "../updates/DesktopUpdates.ts";
import * as DesktopWslBackend from "../wsl/DesktopWslBackend.ts";
const DEFAULT_DESKTOP_BACKEND_PORT = 3773;
const MAX_TCP_PORT = 65_535;
@@ -35,24 +33,22 @@ const makeDesktopRunId = Crypto.Crypto.pipe(
Effect.map((value) => value.replaceAll("-", "").slice(0, 12)),
);
export class DesktopBackendPortUnavailableError extends Schema.TaggedErrorClass<DesktopBackendPortUnavailableError>()(
class DesktopBackendPortUnavailableError extends Data.TaggedError(
"DesktopBackendPortUnavailableError",
{
startPort: Schema.Int,
maxPort: Schema.Int,
hosts: Schema.Array(Schema.String),
},
) {
override get message(): string {
)<{
readonly startPort: number;
readonly maxPort: number;
readonly hosts: readonly string[];
}> {
override get message() {
return `No desktop backend port is available on hosts ${this.hosts.join(", ")} between ${this.startPort} and ${this.maxPort}.`;
}
}
export class DesktopDevelopmentBackendPortRequiredError extends Schema.TaggedErrorClass<DesktopDevelopmentBackendPortRequiredError>()(
class DesktopDevelopmentBackendPortRequiredError extends Data.TaggedError(
"DesktopDevelopmentBackendPortRequiredError",
{},
) {
override get message(): string {
)<{}> {
override get message() {
return "T3CODE_PORT is required in desktop development.";
}
}
@@ -137,14 +133,11 @@ const fatalStartupCause = <E>(stage: string, cause: Cause.Cause<E>) =>
handleFatalStartupError(stage, Cause.pretty(cause)).pipe(Effect.andThen(Effect.failCause(cause)));
const bootstrap = Effect.gen(function* () {
const pool = yield* DesktopBackendPool.DesktopBackendPool;
const primaryBackend = yield* pool.primary;
const backendManager = yield* DesktopBackendManager.DesktopBackendManager;
const state = yield* DesktopState.DesktopState;
const environment = yield* DesktopEnvironment.DesktopEnvironment;
const desktopSettings = yield* DesktopAppSettings.DesktopAppSettings;
const serverExposure = yield* DesktopServerExposure.DesktopServerExposure;
const wslBackend = yield* DesktopWslBackend.DesktopWslBackend;
const desktopWindow = yield* DesktopWindow.DesktopWindow;
yield* logBootstrapInfo("bootstrap start");
if (environment.isDevelopment && Option.isNone(environment.configuredBackendPort)) {
@@ -198,20 +191,8 @@ const bootstrap = Effect.gen(function* () {
yield* logBootstrapInfo("bootstrap ipc handlers registered");
if (!(yield* Ref.get(state.quitting))) {
// In wsl-only mode the renderer is served by the WSL backend, which can be
// slow to cold-boot — show a "Connecting to WSL" splash immediately so the
// app feels responsive instead of presenting no window until WSL is ready.
// (Dual mode opens fast off the Windows primary, so no splash there.)
if (settings.wslOnly === true && settings.wslBackendEnabled === true) {
yield* desktopWindow.showConnectingSplash;
}
yield* primaryBackend.start;
yield* backendManager.start;
yield* logBootstrapInfo("bootstrap backend start requested");
// Bring up the WSL backend if the user previously enabled it. The
// primary is already starting; reconcile fires off the WSL register
// in parallel rather than blocking primary readiness on a possibly
// slow first wsl.exe spawn.
yield* Effect.forkScoped(wslBackend.reconcile);
}
}).pipe(Effect.withSpan("desktop.bootstrap"));
@@ -258,20 +239,10 @@ const scopedProgram = Effect.scoped(
yield* Effect.annotateCurrentSpan({ scope: "desktop", runId });
const shutdown = yield* DesktopShutdown.DesktopShutdown;
const backendManager = yield* DesktopBackendManager.DesktopBackendManager;
yield* Effect.addFinalizer(() =>
Effect.gen(function* () {
const pool = yield* DesktopBackendPool.DesktopBackendPool;
// Stop every backend in the pool, not just the primary. The
// electronApp.quit() path can race ahead of the layer-scope
// cascade, so leaving the WSL instance for its parent scope
// finalizer means it gets hard-killed by the OS instead of
// receiving SIGTERM + grace. Stops run concurrently.
const instances = yield* pool.list;
yield* Effect.forEach(instances, (instance) => instance.stop(), {
concurrency: "unbounded",
});
}).pipe(Effect.ensuring(shutdown.markComplete)),
backendManager.stop().pipe(Effect.ensuring(shutdown.markComplete)),
);
yield* startup;
@@ -1,30 +0,0 @@
import { assert, describe, it } from "@effect/vitest";
import {
DesktopBackendPortUnavailableError,
DesktopDevelopmentBackendPortRequiredError,
} from "./DesktopApp.ts";
describe("DesktopApp errors", () => {
it("preserves unavailable backend port context", () => {
const error = new DesktopBackendPortUnavailableError({
startPort: 3_773,
maxPort: 65_535,
hosts: ["127.0.0.1", "0.0.0.0", "::"],
});
assert.equal(error.startPort, 3_773);
assert.equal(error.maxPort, 65_535);
assert.deepEqual(error.hosts, ["127.0.0.1", "0.0.0.0", "::"]);
assert.equal(
error.message,
"No desktop backend port is available on hosts 127.0.0.1, 0.0.0.0, :: between 3773 and 65535.",
);
});
it("reports the required development port", () => {
const error = new DesktopDevelopmentBackendPortRequiredError();
assert.equal(error.message, "T3CODE_PORT is required in desktop development.");
});
});
@@ -4,7 +4,6 @@ import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as PlatformError from "effect/PlatformError";
import type * as Electron from "electron";
@@ -106,7 +105,6 @@ const withIdentity = <A, E, R>(
readonly calls?: ElectronAppCalls;
readonly environment?: TestEnvironmentInput;
readonly legacyPathExists?: boolean;
readonly legacyPathProbeError?: PlatformError.PlatformError;
readonly packageJson?: string;
readonly pngIconPath?: Option.Option<string>;
} = {},
@@ -123,11 +121,7 @@ const withIdentity = <A, E, R>(
Layer.provideMerge(
FileSystem.layerNoop({
exists: (path) =>
input.legacyPathProbeError
? Effect.fail(input.legacyPathProbeError)
: Effect.succeed(
input.legacyPathExists === true && path.includes("T3 Code (Alpha)"),
),
Effect.succeed(input.legacyPathExists === true && path.includes("T3 Code (Alpha)")),
readFileString: () =>
Effect.succeed(input.packageJson ?? '{"t3codeCommitHash":"abcdef1234567890"}'),
}),
@@ -153,33 +147,6 @@ describe("DesktopAppIdentity", () => {
),
);
it.effect("preserves failures while inspecting the legacy userData path", () => {
const legacyPath = "/Users/alice/Library/Application Support/T3 Code (Alpha)";
const cause = PlatformError.systemError({
_tag: "PermissionDenied",
module: "FileSystem",
method: "exists",
description: "permission denied",
pathOrDescriptor: legacyPath,
});
return withIdentity(
Effect.gen(function* () {
const identity = yield* DesktopAppIdentity.DesktopAppIdentity;
const error = yield* identity.resolveUserDataPath.pipe(Effect.flip);
assert.instanceOf(error, DesktopAppIdentity.DesktopUserDataPathResolutionError);
assert.equal(error.legacyPath, legacyPath);
assert.strictEqual(error.cause, cause);
assert.equal(
error.message,
`Failed to inspect legacy desktop user-data path at "${legacyPath}".`,
);
}),
{ legacyPathProbeError: cause },
);
});
it.effect("configures app identity from the environment commit override", () => {
const calls: ElectronAppCalls = {
setAboutPanelOptions: [],
+5 -23
View File
@@ -18,22 +18,10 @@ const AppPackageMetadata = Schema.Struct({
});
const decodeAppPackageMetadata = Schema.decodeEffect(Schema.fromJsonString(AppPackageMetadata));
export class DesktopUserDataPathResolutionError extends Schema.TaggedErrorClass<DesktopUserDataPathResolutionError>()(
"DesktopUserDataPathResolutionError",
{
legacyPath: Schema.String,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to inspect legacy desktop user-data path at "${this.legacyPath}".`;
}
}
export class DesktopAppIdentity extends Context.Service<
DesktopAppIdentity,
{
readonly resolveUserDataPath: Effect.Effect<string, DesktopUserDataPathResolutionError>;
readonly resolveUserDataPath: Effect.Effect<string>;
readonly configure: Effect.Effect<void>;
}
>()("@t3tools/desktop/app/DesktopAppIdentity") {}
@@ -45,7 +33,7 @@ const normalizeCommitHash = (value: string): Option.Option<string> => {
: Option.none();
};
export const make = Effect.gen(function* () {
const make = Effect.gen(function* () {
const assets = yield* DesktopAssets.DesktopAssets;
const electronApp = yield* ElectronApp.ElectronApp;
const environment = yield* DesktopEnvironment.DesktopEnvironment;
@@ -95,15 +83,9 @@ export const make = Effect.gen(function* () {
environment.appDataDirectory,
environment.legacyUserDataDirName,
);
const legacyPathExists = yield* fileSystem.exists(legacyPath).pipe(
Effect.mapError(
(cause) =>
new DesktopUserDataPathResolutionError({
legacyPath,
cause,
}),
),
);
const legacyPathExists = yield* fileSystem
.exists(legacyPath)
.pipe(Effect.orElseSucceed(() => false));
return legacyPathExists
? legacyPath
: environment.path.join(environment.appDataDirectory, environment.userDataDirName);
@@ -1,57 +0,0 @@
import * as NodeServices from "@effect/platform-node/NodeServices";
import { assert, describe, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as PlatformError from "effect/PlatformError";
import * as DesktopAssets from "./DesktopAssets.ts";
import * as DesktopConfig from "./DesktopConfig.ts";
import * as DesktopEnvironment from "./DesktopEnvironment.ts";
const environmentLayer = DesktopEnvironment.layer({
dirname: "/repo/apps/desktop/dist-electron",
homeDirectory: "/Users/alice",
platform: "darwin",
processArch: "arm64",
appVersion: "1.2.3",
appPath: "/Applications/T3 Code.app/Contents/Resources/app.asar",
isPackaged: true,
resourcesPath: "/Applications/T3 Code.app/Contents/Resources",
runningUnderArm64Translation: false,
}).pipe(Layer.provide(Layer.mergeAll(NodeServices.layer, DesktopConfig.layerTest({}))));
describe("DesktopAssets", () => {
it.effect("preserves the failed asset candidate and filesystem cause", () =>
Effect.gen(function* () {
const fileName = "custom.bin";
const candidatePath = "/repo/apps/desktop/resources/custom.bin";
const cause = PlatformError.systemError({
_tag: "PermissionDenied",
module: "FileSystem",
method: "exists",
pathOrDescriptor: candidatePath,
description: "private filesystem diagnostic",
});
const fileSystemLayer = FileSystem.layerNoop({
exists: (path) => (path === candidatePath ? Effect.fail(cause) : Effect.succeed(false)),
});
const assetsLayer = DesktopAssets.layer.pipe(
Layer.provide(Layer.merge(fileSystemLayer, environmentLayer)),
);
const assets = yield* DesktopAssets.DesktopAssets.pipe(Effect.provide(assetsLayer));
const error = yield* assets.resolveResourcePath(fileName).pipe(Effect.flip);
assert.instanceOf(error, DesktopAssets.DesktopAssetProbeError);
assert.equal(error.fileName, fileName);
assert.equal(error.candidatePath, candidatePath);
assert.strictEqual(error.cause, cause);
assert.equal(
error.message,
`Failed to probe desktop asset "${fileName}" at ${candidatePath}.`,
);
assert.notInclude(error.message, "private filesystem diagnostic");
}),
);
});
+8 -37
View File
@@ -3,7 +3,6 @@ import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Schema from "effect/Schema";
import * as DesktopEnvironment from "./DesktopEnvironment.ts";
@@ -13,26 +12,11 @@ export interface DesktopIconPaths {
readonly png: Option.Option<string>;
}
export class DesktopAssetProbeError extends Schema.TaggedErrorClass<DesktopAssetProbeError>()(
"DesktopAssetProbeError",
{
fileName: Schema.String,
candidatePath: Schema.String,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to probe desktop asset "${this.fileName}" at ${this.candidatePath}.`;
}
}
export class DesktopAssets extends Context.Service<
DesktopAssets,
{
readonly iconPaths: Effect.Effect<DesktopIconPaths>;
readonly resolveResourcePath: (
fileName: string,
) => Effect.Effect<Option.Option<string>, DesktopAssetProbeError>;
readonly resolveResourcePath: (fileName: string) => Effect.Effect<Option.Option<string>>;
}
>()("@t3tools/desktop/app/DesktopAssets") {}
@@ -40,20 +24,14 @@ const resolveResourcePath = Effect.fn("desktop.assets.resolveResourcePath")(func
fileName: string,
): Effect.fn.Return<
Option.Option<string>,
DesktopAssetProbeError,
never,
FileSystem.FileSystem | DesktopEnvironment.DesktopEnvironment
> {
const fileSystem = yield* FileSystem.FileSystem;
const environment = yield* DesktopEnvironment.DesktopEnvironment;
const candidates = environment.resolveResourcePathCandidates(fileName);
for (const candidate of candidates) {
const exists = yield* fileSystem
.exists(candidate)
.pipe(
Effect.mapError(
(cause) => new DesktopAssetProbeError({ fileName, candidatePath: candidate, cause }),
),
);
const exists = yield* fileSystem.exists(candidate).pipe(Effect.orElseSucceed(() => false));
if (exists) {
return Option.some(candidate);
}
@@ -65,23 +43,16 @@ const resolveIconPath = Effect.fn("desktop.assets.resolveIconPath")(function* (
ext: keyof DesktopIconPaths,
): Effect.fn.Return<
Option.Option<string>,
DesktopAssetProbeError,
never,
FileSystem.FileSystem | DesktopEnvironment.DesktopEnvironment
> {
const fileSystem = yield* FileSystem.FileSystem;
const environment = yield* DesktopEnvironment.DesktopEnvironment;
if (environment.isDevelopment && environment.platform === "darwin" && ext === "png") {
const developmentDockIconPath = environment.developmentDockIconPath;
const developmentDockIconExists = yield* fileSystem.exists(developmentDockIconPath).pipe(
Effect.mapError(
(cause) =>
new DesktopAssetProbeError({
fileName: "icon.png",
candidatePath: developmentDockIconPath,
cause,
}),
),
);
const developmentDockIconExists = yield* fileSystem
.exists(developmentDockIconPath)
.pipe(Effect.orElseSucceed(() => false));
if (developmentDockIconExists) {
return Option.some(developmentDockIconPath);
}
@@ -90,7 +61,7 @@ const resolveIconPath = Effect.fn("desktop.assets.resolveIconPath")(function* (
return yield* resolveResourcePath(`icon.${ext}`);
});
export const make = Effect.gen(function* () {
const make = Effect.gen(function* () {
const context = yield* Effect.context<
FileSystem.FileSystem | DesktopEnvironment.DesktopEnvironment
>();
@@ -0,0 +1,280 @@
import * as Context from "effect/Context";
import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Path from "effect/Path";
import * as PlatformError from "effect/PlatformError";
import * as References from "effect/References";
import * as Ref from "effect/Ref";
import * as Schema from "effect/Schema";
import * as Semaphore from "effect/Semaphore";
import * as DesktopEnvironment from "./DesktopEnvironment.ts";
export const DESKTOP_LOG_FILE_MAX_BYTES = 10 * 1024 * 1024;
export const DESKTOP_LOG_FILE_MAX_FILES = 10;
const DESKTOP_BACKEND_CHILD_LOG_FIBER_ID = "#backend-child";
interface RotatingLogFileWriter {
readonly writeBytes: (chunk: Uint8Array) => Effect.Effect<void>;
readonly writeText: (chunk: string) => Effect.Effect<void>;
}
export class DesktopBackendOutputLog extends Context.Service<
DesktopBackendOutputLog,
{
readonly writeSessionBoundary: (input: {
readonly phase: "START" | "END";
readonly details: string;
}) => Effect.Effect<void>;
readonly writeOutputChunk: (
streamName: "stdout" | "stderr",
chunk: Uint8Array,
) => Effect.Effect<void>;
}
>()("@t3tools/desktop/app/DesktopBackendOutputLog") {}
class DesktopLogFileWriterConfigurationError extends Schema.TaggedErrorClass<DesktopLogFileWriterConfigurationError>()(
"DesktopLogFileWriterConfigurationError",
{
option: Schema.Literals(["maxBytes", "maxFiles"]),
value: Schema.Number,
},
) {
override get message(): string {
return `${this.option} must be >= 1 (received ${this.value})`;
}
}
type DesktopLogFileWriterError =
| DesktopLogFileWriterConfigurationError
| PlatformError.PlatformError;
const DesktopBackendChildLogRecord = Schema.Struct({
message: Schema.String,
level: Schema.Literals(["INFO", "ERROR"]),
timestamp: Schema.String,
annotations: Schema.Record(Schema.String, Schema.Unknown),
spans: Schema.Record(Schema.String, Schema.Unknown),
fiberId: Schema.String,
});
const encodeDesktopBackendChildLogRecord = Schema.encodeEffect(
Schema.fromJsonString(DesktopBackendChildLogRecord),
);
const DesktopBackendOutputLogNoop: DesktopBackendOutputLog["Service"] = {
writeSessionBoundary: () => Effect.void,
writeOutputChunk: () => Effect.void,
};
const textEncoder = new TextEncoder();
const textDecoder = new TextDecoder();
const currentDesktopRunId = Effect.gen(function* () {
const annotations = yield* References.CurrentLogAnnotations;
const runId = annotations.runId;
return typeof runId === "string" && runId.length > 0 ? runId : "unknown";
});
const sanitizeLogValue = (value: string): string => value.replace(/\s+/g, " ").trim();
const refreshFileSize = (
fileSystem: FileSystem.FileSystem,
filePath: string,
): Effect.Effect<number, never> =>
fileSystem.stat(filePath).pipe(
Effect.map((stat) => Number(stat.size)),
Effect.orElseSucceed(() => 0),
);
const makeRotatingLogFileWriter = Effect.fn("makeRotatingLogFileWriter")(function* (input: {
readonly filePath: string;
readonly maxBytes?: number;
readonly maxFiles?: number;
}): Effect.fn.Return<
RotatingLogFileWriter,
DesktopLogFileWriterError,
FileSystem.FileSystem | Path.Path
> {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const maxBytes = input.maxBytes ?? DESKTOP_LOG_FILE_MAX_BYTES;
const maxFiles = input.maxFiles ?? DESKTOP_LOG_FILE_MAX_FILES;
const directory = path.dirname(input.filePath);
const baseName = path.basename(input.filePath);
if (maxBytes < 1) {
return yield* new DesktopLogFileWriterConfigurationError({
option: "maxBytes",
value: maxBytes,
});
}
if (maxFiles < 1) {
return yield* new DesktopLogFileWriterConfigurationError({
option: "maxFiles",
value: maxFiles,
});
}
yield* fileSystem.makeDirectory(directory, { recursive: true });
const withSuffix = (index: number) => `${input.filePath}.${index}`;
const currentSize = yield* Ref.make(yield* refreshFileSize(fileSystem, input.filePath));
const mutex = yield* Semaphore.make(1);
const pruneOverflowBackups = Effect.gen(function* () {
const entries = yield* fileSystem.readDirectory(directory).pipe(Effect.orElseSucceed(() => []));
for (const entry of entries) {
if (!entry.startsWith(`${baseName}.`)) continue;
const suffix = Number(entry.slice(baseName.length + 1));
if (!Number.isInteger(suffix) || suffix <= maxFiles) continue;
yield* fileSystem.remove(path.join(directory, entry), { force: true }).pipe(Effect.ignore);
}
});
const rotate = Effect.gen(function* () {
yield* fileSystem.remove(withSuffix(maxFiles), { force: true }).pipe(Effect.ignore);
for (let index = maxFiles - 1; index >= 1; index -= 1) {
const source = withSuffix(index);
const sourceExists = yield* fileSystem.exists(source).pipe(Effect.orElseSucceed(() => false));
if (sourceExists) {
yield* fileSystem.rename(source, withSuffix(index + 1));
}
}
const currentExists = yield* fileSystem
.exists(input.filePath)
.pipe(Effect.orElseSucceed(() => false));
if (currentExists) {
yield* fileSystem.rename(input.filePath, withSuffix(1));
}
yield* Ref.set(currentSize, 0);
}).pipe(
Effect.catch(() =>
refreshFileSize(fileSystem, input.filePath).pipe(
Effect.flatMap((size) => Ref.set(currentSize, size)),
),
),
);
const writeBytes = (chunk: Uint8Array): Effect.Effect<void> => {
if (chunk.byteLength === 0) return Effect.void;
return mutex.withPermits(1)(
Effect.gen(function* () {
const beforeSize = yield* Ref.get(currentSize);
if (beforeSize > 0 && beforeSize + chunk.byteLength > maxBytes) {
yield* rotate;
}
yield* fileSystem.writeFile(input.filePath, chunk, { flag: "a" });
const afterSize = (yield* Ref.get(currentSize)) + chunk.byteLength;
yield* Ref.set(currentSize, afterSize);
if (afterSize > maxBytes) {
yield* rotate;
}
}).pipe(
Effect.catch(() =>
refreshFileSize(fileSystem, input.filePath).pipe(
Effect.flatMap((size) => Ref.set(currentSize, size)),
),
),
),
);
};
yield* pruneOverflowBackups;
return {
writeBytes,
writeText: (chunk) => writeBytes(textEncoder.encode(chunk)),
} satisfies RotatingLogFileWriter;
});
const writeDevelopmentConsoleOutput = (
streamName: "stdout" | "stderr",
chunk: Uint8Array,
): Effect.Effect<void> =>
Effect.sync(() => {
const output = streamName === "stderr" ? process.stderr : process.stdout;
output.write(chunk);
}).pipe(Effect.ignore);
const writeBackendChildLogRecord = Effect.fn("desktop.observability.writeBackendChildLogRecord")(
function* (
logFile: RotatingLogFileWriter,
input: {
readonly message: string;
readonly level: "INFO" | "ERROR";
readonly annotations: Record<string, unknown>;
},
): Effect.fn.Return<void> {
return yield* Effect.gen(function* () {
const timestamp = DateTime.formatIso(yield* DateTime.now);
const encoded = yield* encodeDesktopBackendChildLogRecord({
message: input.message,
level: input.level,
timestamp,
annotations: input.annotations,
spans: {},
fiberId: DESKTOP_BACKEND_CHILD_LOG_FIBER_ID,
});
yield* logFile.writeText(`${encoded}\n`);
}).pipe(Effect.ignore({ log: true }));
},
);
const make = Effect.gen(function* () {
const environment = yield* DesktopEnvironment.DesktopEnvironment;
const writer = yield* makeRotatingLogFileWriter({
filePath: environment.path.join(environment.logDir, "server-child.log"),
}).pipe(Effect.option);
const service = Option.match(writer, {
onNone: () => DesktopBackendOutputLogNoop,
onSome: (logFile) =>
({
writeSessionBoundary: Effect.fn("desktop.observability.backendOutput.writeSessionBoundary")(
function* ({ phase, details }) {
const runId = yield* currentDesktopRunId;
yield* writeBackendChildLogRecord(logFile, {
message: `backend child process session ${phase.toLowerCase()}`,
level: "INFO",
annotations: {
component: "desktop-backend-child",
runId,
phase,
details: sanitizeLogValue(details),
},
});
},
),
writeOutputChunk: Effect.fn("desktop.observability.backendOutput.writeOutputChunk")(
function* (streamName, chunk) {
if (environment.isDevelopment) {
yield* writeDevelopmentConsoleOutput(streamName, chunk);
}
const runId = yield* currentDesktopRunId;
yield* writeBackendChildLogRecord(logFile, {
message: "backend child process output",
level: streamName === "stderr" ? "ERROR" : "INFO",
annotations: {
component: "desktop-backend-child",
runId,
stream: streamName,
text: textDecoder.decode(chunk),
},
});
},
),
}) satisfies DesktopBackendOutputLog["Service"],
});
return DesktopBackendOutputLog.of(service);
});
export const layer = Layer.effect(DesktopBackendOutputLog, make);
+12 -67
View File
@@ -1,8 +1,7 @@
import { assert, describe, it } from "@effect/vitest";
import * as Cause from "effect/Cause";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import { beforeEach, vi } from "vite-plus/test";
import { vi } from "vite-plus/test";
const { createClerkBridgeMock, storageAdapter, storageMock } = vi.hoisted(() => ({
createClerkBridgeMock: vi.fn(),
@@ -25,23 +24,7 @@ vi.mock("@clerk/electron/storage", () => ({
import * as DesktopClerk from "./DesktopClerk.ts";
import * as DesktopEnvironment from "./DesktopEnvironment.ts";
const makeDesktopClerkLayer = (isDevelopment = true) => {
const environment = DesktopEnvironment.DesktopEnvironment.of({
stateDir: "/tmp/t3-state",
isDevelopment,
} as unknown as DesktopEnvironment.DesktopEnvironment["Service"]);
return DesktopClerk.layer.pipe(
Layer.provide(Layer.succeed(DesktopEnvironment.DesktopEnvironment, environment)),
);
};
describe("DesktopClerk", () => {
beforeEach(() => {
createClerkBridgeMock.mockReset();
storageMock.mockReset();
});
it("derives the Clerk Frontend API hostname used by the desktop CSP", () => {
const publishableKey = `pk_test_${btoa("clerk.t3.codes$")}`;
@@ -57,9 +40,19 @@ describe("DesktopClerk", () => {
const cleanup = vi.fn();
storageMock.mockReturnValue(storageAdapter);
createClerkBridgeMock.mockReturnValue({ cleanup });
const environment = DesktopEnvironment.DesktopEnvironment.of({
stateDir: "/tmp/t3-state",
isDevelopment: true,
} as unknown as DesktopEnvironment.DesktopEnvironment["Service"]);
return Effect.gen(function* () {
yield* Effect.scoped(Layer.build(makeDesktopClerkLayer()));
yield* Effect.scoped(
Layer.build(
DesktopClerk.layer.pipe(
Layer.provide(Layer.succeed(DesktopEnvironment.DesktopEnvironment, environment)),
),
),
);
assert.deepEqual(createClerkBridgeMock.mock.calls, [
[
@@ -76,54 +69,6 @@ describe("DesktopClerk", () => {
});
});
it.effect("preserves bridge initialization failures", () => {
const cause = new Error("bridge initialization failed");
storageMock.mockReturnValue(storageAdapter);
createClerkBridgeMock.mockImplementationOnce(() => {
throw cause;
});
return Effect.gen(function* () {
const error = yield* Effect.scoped(Layer.build(makeDesktopClerkLayer())).pipe(Effect.flip);
assert.instanceOf(error, DesktopClerk.DesktopClerkBridgeInitializationError);
assert.equal(error.stateDir, "/tmp/t3-state");
assert.equal(error.isDevelopment, true);
assert.strictEqual(error.cause, cause);
assert.equal(
error.message,
'Failed to initialize the desktop Clerk bridge for state directory "/tmp/t3-state" (development: true).',
);
});
});
it.effect("preserves bridge cleanup failures", () => {
const cause = new Error("bridge cleanup failed");
storageMock.mockReturnValue(storageAdapter);
createClerkBridgeMock.mockReturnValue({
cleanup: () => {
throw cause;
},
});
return Effect.gen(function* () {
const exit = yield* Effect.exit(Effect.scoped(Layer.build(makeDesktopClerkLayer(false))));
assert.equal(exit._tag, "Failure");
if (exit._tag === "Failure") {
const error = Cause.squash(exit.cause);
assert.instanceOf(error, DesktopClerk.DesktopClerkBridgeCleanupError);
assert.equal(error.stateDir, "/tmp/t3-state");
assert.equal(error.isDevelopment, false);
assert.strictEqual(error.cause, cause);
assert.equal(
error.message,
'Failed to clean up the desktop Clerk bridge for state directory "/tmp/t3-state" (development: false).',
);
}
});
});
it.each([
{ isDevelopment: true, scheme: "t3code-dev" },
{ isDevelopment: false, scheme: "t3code" },
+3 -47
View File
@@ -4,7 +4,6 @@ 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 { clerkFrontendApiHostnameFromPublishableKey } from "@t3tools/shared/relayAuth";
@@ -15,32 +14,6 @@ import * as DesktopEnvironment from "./DesktopEnvironment.ts";
declare const __T3CODE_BUILD_CLERK_PUBLISHABLE_KEY__: string | undefined;
export class DesktopClerkBridgeInitializationError extends Schema.TaggedErrorClass<DesktopClerkBridgeInitializationError>()(
"DesktopClerkBridgeInitializationError",
{
stateDir: Schema.String,
isDevelopment: Schema.Boolean,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to initialize the desktop Clerk bridge for state directory "${this.stateDir}" (development: ${this.isDevelopment}).`;
}
}
export class DesktopClerkBridgeCleanupError extends Schema.TaggedErrorClass<DesktopClerkBridgeCleanupError>()(
"DesktopClerkBridgeCleanupError",
{
stateDir: Schema.String,
isDevelopment: Schema.Boolean,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to clean up the desktop Clerk bridge for state directory "${this.stateDir}" (development: ${this.isDevelopment}).`;
}
}
export class DesktopClerk extends Context.Service<
DesktopClerk,
{
@@ -82,28 +55,11 @@ export function createDesktopClerkBridge(stateDir: string, isDevelopment: boolea
});
}
export const make = Effect.gen(function* () {
const make = Effect.gen(function* () {
const environment = yield* DesktopEnvironment.DesktopEnvironment;
yield* Effect.acquireRelease(
Effect.try({
try: () => createDesktopClerkBridge(environment.stateDir, environment.isDevelopment),
catch: (cause) =>
new DesktopClerkBridgeInitializationError({
stateDir: environment.stateDir,
isDevelopment: environment.isDevelopment,
cause,
}),
}),
(bridge) =>
Effect.try({
try: () => bridge.cleanup(),
catch: (cause) =>
new DesktopClerkBridgeCleanupError({
stateDir: environment.stateDir,
isDevelopment: environment.isDevelopment,
cause,
}),
}).pipe(Effect.orDie),
Effect.sync(() => createDesktopClerkBridge(environment.stateDir, environment.isDevelopment)),
(bridge) => Effect.sync(() => bridge.cleanup()),
);
return DesktopClerk.of({
@@ -393,21 +393,7 @@ describe("DesktopConnectionCatalogStore", () => {
assert.isTrue(yield* store.set('{"schemaVersion":1,"targets":[]}'));
yield* Ref.set(failDecrypt, true);
const error = yield* store.get.pipe(Effect.flip);
assert.instanceOf(
error,
DesktopConnectionCatalogStore.DesktopConnectionCatalogStoreProtectionError,
);
assert.equal(error.operation, "decrypt-catalog");
assert.equal(error.catalogPath, `${baseDir}/userdata/connection-catalog.json`);
assert.instanceOf(error.cause, ElectronSafeStorage.ElectronSafeStorageDecryptError);
const decryptError = error.cause as ElectronSafeStorage.ElectronSafeStorageDecryptError;
assert.instanceOf(decryptError.cause, Error);
assert.equal(decryptError.cause.message, "invalid encrypted catalog");
assert.equal(
error.message,
`Desktop connection catalog protection failed during decrypt-catalog at ${baseDir}/userdata/connection-catalog.json.`,
);
assert.notEqual(error.message, decryptError.message);
assert.instanceOf(error, ElectronSafeStorage.ElectronSafeStorageDecryptError);
yield* Ref.set(failDecrypt, false);
assert.deepStrictEqual(yield* store.get, Option.some('{"schemaVersion":1,"targets":[]}'));
}).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
@@ -53,6 +53,8 @@ const DesktopConnectionCatalogStoreWriteOperation = Schema.Literals([
"write-temporary-file",
"replace-catalog-file",
]);
type DesktopConnectionCatalogStoreWriteOperation =
typeof DesktopConnectionCatalogStoreWriteOperation.Type;
const DesktopConnectionCatalogStoreMigrationOperation = Schema.Literals([
"read-legacy-registry",
@@ -60,12 +62,8 @@ const DesktopConnectionCatalogStoreMigrationOperation = Schema.Literals([
"encode-catalog",
"persist-catalog",
]);
const DesktopConnectionCatalogStoreProtectionOperation = Schema.Literals([
"check-encryption-availability",
"encrypt-catalog",
"decrypt-catalog",
]);
type DesktopConnectionCatalogStoreMigrationOperation =
typeof DesktopConnectionCatalogStoreMigrationOperation.Type;
export class DesktopConnectionCatalogStoreWriteError extends Schema.TaggedErrorClass<DesktopConnectionCatalogStoreWriteError>()(
"DesktopConnectionCatalogStoreWriteError",
@@ -80,6 +78,17 @@ export class DesktopConnectionCatalogStoreWriteError extends Schema.TaggedErrorC
}
}
const writeError = (
operation: DesktopConnectionCatalogStoreWriteOperation,
path: string,
cause: unknown,
): DesktopConnectionCatalogStoreWriteError =>
new DesktopConnectionCatalogStoreWriteError({
operation,
path,
cause,
});
export class DesktopConnectionCatalogStoreDecodeError extends Schema.TaggedErrorClass<DesktopConnectionCatalogStoreDecodeError>()(
"DesktopConnectionCatalogStoreDecodeError",
{
@@ -133,18 +142,18 @@ export class DesktopConnectionCatalogStoreMigrationError extends Schema.TaggedEr
}
}
export class DesktopConnectionCatalogStoreProtectionError extends Schema.TaggedErrorClass<DesktopConnectionCatalogStoreProtectionError>()(
"DesktopConnectionCatalogStoreProtectionError",
{
operation: DesktopConnectionCatalogStoreProtectionOperation,
catalogPath: Schema.String,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Desktop connection catalog protection failed during ${this.operation} at ${this.catalogPath}.`;
}
}
const migrationError = (
operation: DesktopConnectionCatalogStoreMigrationOperation,
catalogPath: string,
cause: unknown,
environmentId?: string,
): DesktopConnectionCatalogStoreMigrationError =>
new DesktopConnectionCatalogStoreMigrationError({
operation,
catalogPath,
...(environmentId === undefined ? {} : { environmentId }),
cause,
});
export class DesktopConnectionCatalogStore extends Context.Service<
DesktopConnectionCatalogStore,
@@ -155,13 +164,13 @@ export class DesktopConnectionCatalogStore extends Context.Service<
| DesktopConnectionCatalogStoreDocumentDecodeError
| DesktopConnectionCatalogStoreDecodeError
| DesktopConnectionCatalogStoreMigrationError
| DesktopConnectionCatalogStoreProtectionError
| ElectronSafeStorage.ElectronSafeStorageError
>;
readonly set: (
catalog: string,
) => Effect.Effect<
boolean,
DesktopConnectionCatalogStoreWriteError | DesktopConnectionCatalogStoreProtectionError
DesktopConnectionCatalogStoreWriteError | ElectronSafeStorage.ElectronSafeStorageError
>;
readonly clear: Effect.Effect<void>;
}
@@ -227,46 +236,20 @@ const writeDocument = Effect.fn("desktop.connectionCatalogStore.writeDocument")(
const directory = input.path.dirname(input.catalogPath);
const tempPath = `${input.catalogPath}.${process.pid}.${input.suffix}.tmp`;
const encoded = yield* encodeEncryptedConnectionCatalogDocumentJson(input.document).pipe(
Effect.mapError(
(cause) =>
new DesktopConnectionCatalogStoreWriteError({
operation: "encode-document",
path: input.catalogPath,
cause,
}),
),
);
yield* input.fileSystem.makeDirectory(directory, { recursive: true }).pipe(
Effect.mapError(
(cause) =>
new DesktopConnectionCatalogStoreWriteError({
operation: "create-directory",
path: directory,
cause,
}),
),
Effect.mapError((cause) => writeError("encode-document", input.catalogPath, cause)),
);
yield* input.fileSystem
.makeDirectory(directory, { recursive: true })
.pipe(Effect.mapError((cause) => writeError("create-directory", directory, cause)));
yield* Effect.gen(function* () {
yield* input.fileSystem.writeFileString(tempPath, `${encoded}\n`).pipe(
Effect.mapError(
(cause) =>
new DesktopConnectionCatalogStoreWriteError({
operation: "write-temporary-file",
path: tempPath,
cause,
}),
),
);
yield* input.fileSystem.rename(tempPath, input.catalogPath).pipe(
Effect.mapError(
(cause) =>
new DesktopConnectionCatalogStoreWriteError({
operation: "replace-catalog-file",
path: input.catalogPath,
cause,
}),
),
);
yield* input.fileSystem
.writeFileString(tempPath, `${encoded}\n`)
.pipe(Effect.mapError((cause) => writeError("write-temporary-file", tempPath, cause)));
yield* input.fileSystem
.rename(tempPath, input.catalogPath)
.pipe(
Effect.mapError((cause) => writeError("replace-catalog-file", input.catalogPath, cause)),
);
}).pipe(
Effect.ensuring(
input.fileSystem.remove(tempPath, { force: true }).pipe(
@@ -347,17 +330,13 @@ const migrateSavedEnvironmentRecords = Effect.fn(
wsBaseUrl: record.wsBaseUrl,
}),
);
const token = yield* savedEnvironments.getSecret(record.environmentId).pipe(
Effect.mapError(
(cause) =>
new DesktopConnectionCatalogStoreMigrationError({
operation: "read-legacy-secret",
catalogPath,
environmentId: record.environmentId,
cause,
}),
),
);
const token = yield* savedEnvironments
.getSecret(record.environmentId)
.pipe(
Effect.mapError((cause) =>
migrationError("read-legacy-secret", catalogPath, cause, record.environmentId),
),
);
if (Option.isSome(token)) {
credentials.push({
connectionId: id,
@@ -383,41 +362,13 @@ export const make = Effect.gen(function* () {
const crypto = yield* Crypto.Crypto;
const savedEnvironments = yield* DesktopSavedEnvironments.DesktopSavedEnvironments;
const catalogPath = path.join(environment.stateDir, "connection-catalog.json");
const encryptionAvailable = safeStorage.isEncryptionAvailable.pipe(
Effect.mapError(
(cause) =>
new DesktopConnectionCatalogStoreProtectionError({
operation: "check-encryption-availability",
catalogPath,
cause,
}),
),
);
const writeCatalog = Effect.fn("desktop.connectionCatalogStore.writeCatalog")(function* (
catalog: string,
) {
const encryptedCatalog = Encoding.encodeBase64(
yield* safeStorage.encryptString(catalog).pipe(
Effect.mapError(
(cause) =>
new DesktopConnectionCatalogStoreProtectionError({
operation: "encrypt-catalog",
catalogPath,
cause,
}),
),
),
);
const encryptedCatalog = Encoding.encodeBase64(yield* safeStorage.encryptString(catalog));
const suffix = (yield* crypto.randomUUIDv4.pipe(
Effect.mapError(
(cause) =>
new DesktopConnectionCatalogStoreWriteError({
operation: "create-temporary-file-name",
path: catalogPath,
cause,
}),
),
Effect.mapError((cause) => writeError("create-temporary-file-name", catalogPath, cause)),
)).replace(/-/g, "");
yield* writeDocument({
fileSystem,
@@ -429,42 +380,21 @@ export const make = Effect.gen(function* () {
});
const migrateLegacyCatalog = Effect.gen(function* () {
if (!(yield* encryptionAvailable)) {
if (!(yield* safeStorage.isEncryptionAvailable)) {
return Option.none<string>();
}
const records = yield* savedEnvironments.getRegistry.pipe(
Effect.mapError(
(cause) =>
new DesktopConnectionCatalogStoreMigrationError({
operation: "read-legacy-registry",
catalogPath,
cause,
}),
),
Effect.mapError((cause) => migrationError("read-legacy-registry", catalogPath, cause)),
);
if (records.length === 0) {
return Option.none<string>();
}
const catalog = yield* migrateSavedEnvironmentRecords(records, savedEnvironments, catalogPath);
const encoded = yield* encodeRuntimeConnectionCatalogDocumentJson(catalog).pipe(
Effect.mapError(
(cause) =>
new DesktopConnectionCatalogStoreMigrationError({
operation: "encode-catalog",
catalogPath,
cause,
}),
),
Effect.mapError((cause) => migrationError("encode-catalog", catalogPath, cause)),
);
yield* writeCatalog(encoded).pipe(
Effect.mapError(
(cause) =>
new DesktopConnectionCatalogStoreMigrationError({
operation: "persist-catalog",
catalogPath,
cause,
}),
),
Effect.mapError((cause) => migrationError("persist-catalog", catalogPath, cause)),
);
return Option.some(encoded);
});
@@ -475,27 +405,16 @@ export const make = Effect.gen(function* () {
if (Option.isNone(document)) {
return yield* migrateLegacyCatalog;
}
if (!(yield* encryptionAvailable)) {
if (!(yield* safeStorage.isEncryptionAvailable)) {
return Option.none<string>();
}
const decrypted = yield* decodeSecretBytes(catalogPath, document.value.encryptedCatalog).pipe(
Effect.flatMap((encryptedCatalog) =>
safeStorage.decryptString(encryptedCatalog).pipe(
Effect.mapError(
(cause) =>
new DesktopConnectionCatalogStoreProtectionError({
operation: "decrypt-catalog",
catalogPath,
cause,
}),
),
),
),
Effect.flatMap(safeStorage.decryptString),
);
return Option.some(decrypted);
}).pipe(Effect.withSpan("desktop.connectionCatalogStore.get")),
set: Effect.fn("desktop.connectionCatalogStore.set")(function* (catalog) {
if (!(yield* encryptionAvailable)) {
if (!(yield* safeStorage.isEncryptionAvailable)) {
return false;
}
yield* writeCatalog(catalog);
@@ -1,37 +0,0 @@
import { assert, describe, it } from "@effect/vitest";
import * as Cause from "effect/Cause";
import { DesktopLifecycleRelaunchError } from "./DesktopLifecycle.ts";
import { DesktopApplicationMenuActionError } from "../window/DesktopApplicationMenu.ts";
describe("desktop detached action errors", () => {
it("preserves the complete relaunch failure cause and reason", () => {
const cause = Cause.combine(
Cause.fail(new Error("shutdown failed")),
Cause.die(new Error("relaunch defect")),
);
const error = new DesktopLifecycleRelaunchError({
reason: "apply update",
cause,
});
assert.strictEqual(error.cause, cause);
assert.equal(error.reason, "apply update");
assert.equal(error.message, 'Desktop relaunch failed for reason "apply update".');
});
it("preserves the complete menu action failure cause and action", () => {
const cause = Cause.combine(
Cause.fail(new Error("window unavailable")),
Cause.die(new Error("dispatch defect")),
);
const error = new DesktopApplicationMenuActionError({
action: "open-settings",
cause,
});
assert.strictEqual(error.cause, cause);
assert.equal(error.action, "open-settings");
assert.equal(error.message, 'Desktop menu action "open-settings" failed.');
});
});
+6 -17
View File
@@ -1,8 +1,8 @@
import * as Cause from "effect/Cause";
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Ref from "effect/Ref";
import * as Schema from "effect/Schema";
import * as Scope from "effect/Scope";
import type * as Electron from "electron";
@@ -15,18 +15,6 @@ import * as ElectronTheme from "../electron/ElectronTheme.ts";
import * as DesktopState from "./DesktopState.ts";
import * as DesktopWindow from "../window/DesktopWindow.ts";
export class DesktopLifecycleRelaunchError extends Schema.TaggedErrorClass<DesktopLifecycleRelaunchError>()(
"DesktopLifecycleRelaunchError",
{
reason: Schema.String,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Desktop relaunch failed for reason "${this.reason}".`;
}
}
export type DesktopLifecycleRuntimeServices =
| DesktopEnvironment.DesktopEnvironment
| DesktopShutdown.DesktopShutdown
@@ -154,10 +142,11 @@ export const make = DesktopLifecycle.of({
});
yield* electronApp.exit(0);
}).pipe(
Effect.catchCause((cause) => {
const error = new DesktopLifecycleRelaunchError({ reason, cause });
return logLifecycleError(error.message, { error });
}),
Effect.catchCause((cause) =>
logLifecycleError("desktop relaunch failed", {
cause: Cause.pretty(cause),
}),
),
Effect.forkDetach,
Effect.asVoid,
);
@@ -125,8 +125,7 @@ describe("DesktopObservability", () => {
}).pipe(Effect.provide(environmentLayer));
yield* Effect.gen(function* () {
const factory = yield* DesktopObservability.DesktopBackendOutputLogFactory;
const outputLog = yield* factory.forInstance("primary");
const outputLog = yield* DesktopObservability.DesktopBackendOutputLog;
yield* outputLog.writeSessionBoundary({
phase: "START",
details: "pid=123 port=3773 cwd=/repo",
@@ -146,7 +145,6 @@ describe("DesktopObservability", () => {
assert.equal(boundary.level, "INFO");
assert.equal(boundary.annotations.component, "desktop-backend-child");
assert.equal(boundary.annotations.runId, "test-run");
assert.equal(boundary.annotations.instanceId, "primary");
assert.equal(boundary.annotations.phase, "START");
assert.equal(boundary.annotations.details, "pid=123 port=3773 cwd=/repo");
@@ -154,7 +152,6 @@ describe("DesktopObservability", () => {
assert.equal(output.level, "INFO");
assert.equal(output.annotations.component, "desktop-backend-child");
assert.equal(output.annotations.runId, "test-run");
assert.equal(output.annotations.instanceId, "primary");
assert.equal(output.annotations.stream, "stdout");
assert.equal(output.annotations.text, "hello server\n");
}).pipe(
+8 -376
View File
@@ -1,65 +1,20 @@
import { PRIMARY_LOCAL_ENVIRONMENT_ID } from "@t3tools/contracts";
import { makeLocalFileTracer, makeTraceSink } from "@t3tools/shared/observability";
import { parsePersistedServerObservabilitySettings } from "@t3tools/shared/serverSettings";
import * as Context from "effect/Context";
import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Logger from "effect/Logger";
import * as Option from "effect/Option";
import * as Path from "effect/Path";
import * as PlatformError from "effect/PlatformError";
import * as References from "effect/References";
import * as Ref from "effect/Ref";
import * as Schema from "effect/Schema";
import * as Scope from "effect/Scope";
import * as Semaphore from "effect/Semaphore";
import * as SynchronizedRef from "effect/SynchronizedRef";
import * as Tracer from "effect/Tracer";
import { OtlpSerialization, OtlpTracer } from "effect/unstable/observability";
import * as DesktopBackendOutputLogModule from "./DesktopBackendOutputLog.ts";
import * as DesktopEnvironment from "./DesktopEnvironment.ts";
const DESKTOP_LOG_FILE_MAX_BYTES = 10 * 1024 * 1024;
const DESKTOP_LOG_FILE_MAX_FILES = 10;
const DESKTOP_BACKEND_CHILD_LOG_FIBER_ID = "#backend-child";
const DESKTOP_TRACE_BATCH_WINDOW_MS = 200;
export interface RotatingLogFileWriter {
readonly writeBytes: (chunk: Uint8Array) => Effect.Effect<void>;
readonly writeText: (chunk: string) => Effect.Effect<void>;
}
export interface DesktopBackendOutputLogShape {
readonly writeSessionBoundary: (input: {
readonly phase: "START" | "END";
readonly details: string;
}) => Effect.Effect<void>;
readonly writeOutputChunk: (
streamName: "stdout" | "stderr",
chunk: Uint8Array,
) => Effect.Effect<void>;
}
// Factory for per-instance backend output logs. `forInstance(id)` returns
// a writer that targets a distinct rotating log file — the primary
// instance keeps `server-child.log` so the historical path stays stable
// for ops; other instances get `server-child-<sanitized-id>.log`.
//
// Writers are cached per id within a single factory instance so repeated
// `forInstance` calls (e.g. during a backend restart that re-resolves
// services) reuse the same rotating writer rather than racing each other
// on the same file.
export class DesktopBackendOutputLogFactory extends Context.Service<
DesktopBackendOutputLogFactory,
{
readonly forInstance: (id: string) => Effect.Effect<DesktopBackendOutputLogShape>;
}
>()("@t3tools/desktop/app/DesktopObservability/DesktopBackendOutputLogFactory") {}
const textEncoder = new TextEncoder();
const textDecoder = new TextDecoder();
export { DesktopBackendOutputLog } from "./DesktopBackendOutputLog.ts";
export type DesktopLogAnnotations = Record<string, unknown>;
@@ -95,166 +50,7 @@ export function makeComponentLogger(component: string): DesktopComponentLogger {
};
}
class DesktopLogFileWriterConfigurationError extends Schema.TaggedErrorClass<DesktopLogFileWriterConfigurationError>()(
"DesktopLogFileWriterConfigurationError",
{
option: Schema.Literals(["maxBytes", "maxFiles"]),
value: Schema.Number,
},
) {
override get message() {
return `${this.option} must be >= 1 (received ${this.value})`;
}
}
type DesktopLogFileWriterError =
| DesktopLogFileWriterConfigurationError
| PlatformError.PlatformError;
const sanitizeLogValue = (value: string): string => value.replace(/\s+/g, " ").trim();
const DesktopBackendChildLogRecord = Schema.Struct({
message: Schema.String,
level: Schema.Literals(["INFO", "ERROR"]),
timestamp: Schema.String,
annotations: Schema.Record(Schema.String, Schema.Unknown),
spans: Schema.Record(Schema.String, Schema.Unknown),
fiberId: Schema.String,
});
const encodeDesktopBackendChildLogRecord = Schema.encodeEffect(
Schema.fromJsonString(DesktopBackendChildLogRecord),
);
const DesktopBackendOutputLogNoop: DesktopBackendOutputLogShape = {
writeSessionBoundary: () => Effect.void,
writeOutputChunk: () => Effect.void,
};
const currentDesktopRunId = Effect.gen(function* () {
const annotations = yield* References.CurrentLogAnnotations;
const runId = annotations.runId;
return typeof runId === "string" && runId.length > 0 ? runId : "unknown";
});
const refreshFileSize = (
fileSystem: FileSystem.FileSystem,
filePath: string,
): Effect.Effect<number, never> =>
fileSystem.stat(filePath).pipe(
Effect.map((stat) => Number(stat.size)),
Effect.orElseSucceed(() => 0),
);
const makeRotatingLogFileWriter = Effect.fn("makeRotatingLogFileWriter")(function* (input: {
readonly filePath: string;
readonly maxBytes?: number;
readonly maxFiles?: number;
}): Effect.fn.Return<
RotatingLogFileWriter,
DesktopLogFileWriterError,
FileSystem.FileSystem | Path.Path
> {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const maxBytes = input.maxBytes ?? DESKTOP_LOG_FILE_MAX_BYTES;
const maxFiles = input.maxFiles ?? DESKTOP_LOG_FILE_MAX_FILES;
const directory = path.dirname(input.filePath);
const baseName = path.basename(input.filePath);
if (maxBytes < 1) {
return yield* new DesktopLogFileWriterConfigurationError({
option: "maxBytes",
value: maxBytes,
});
}
if (maxFiles < 1) {
return yield* new DesktopLogFileWriterConfigurationError({
option: "maxFiles",
value: maxFiles,
});
}
yield* fileSystem.makeDirectory(directory, { recursive: true });
const withSuffix = (index: number) => `${input.filePath}.${index}`;
const currentSize = yield* Ref.make(yield* refreshFileSize(fileSystem, input.filePath));
const mutex = yield* Semaphore.make(1);
const pruneOverflowBackups = Effect.gen(function* () {
const entries = yield* fileSystem.readDirectory(directory).pipe(Effect.orElseSucceed(() => []));
for (const entry of entries) {
if (!entry.startsWith(`${baseName}.`)) continue;
const suffix = Number(entry.slice(baseName.length + 1));
if (!Number.isInteger(suffix) || suffix <= maxFiles) continue;
yield* fileSystem.remove(path.join(directory, entry), { force: true }).pipe(Effect.ignore);
}
});
const rotate = Effect.gen(function* () {
yield* fileSystem.remove(withSuffix(maxFiles), { force: true }).pipe(Effect.ignore);
for (let index = maxFiles - 1; index >= 1; index -= 1) {
const source = withSuffix(index);
const sourceExists = yield* fileSystem.exists(source).pipe(Effect.orElseSucceed(() => false));
if (sourceExists) {
yield* fileSystem.rename(source, withSuffix(index + 1));
}
}
const currentExists = yield* fileSystem
.exists(input.filePath)
.pipe(Effect.orElseSucceed(() => false));
if (currentExists) {
yield* fileSystem.rename(input.filePath, withSuffix(1));
}
yield* Ref.set(currentSize, 0);
}).pipe(
Effect.catch(() =>
refreshFileSize(fileSystem, input.filePath).pipe(
Effect.flatMap((size) => Ref.set(currentSize, size)),
),
),
);
const writeBytes = (chunk: Uint8Array): Effect.Effect<void> => {
if (chunk.byteLength === 0) return Effect.void;
return mutex.withPermits(1)(
Effect.gen(function* () {
const beforeSize = yield* Ref.get(currentSize);
if (beforeSize > 0 && beforeSize + chunk.byteLength > maxBytes) {
yield* rotate;
}
yield* fileSystem.writeFile(input.filePath, chunk, { flag: "a" });
const afterSize = (yield* Ref.get(currentSize)) + chunk.byteLength;
yield* Ref.set(currentSize, afterSize);
if (afterSize > maxBytes) {
yield* rotate;
}
}).pipe(
Effect.catch(() =>
refreshFileSize(fileSystem, input.filePath).pipe(
Effect.flatMap((size) => Ref.set(currentSize, size)),
),
),
),
);
};
yield* pruneOverflowBackups;
return {
writeBytes,
writeText: (chunk) => writeBytes(textEncoder.encode(chunk)),
} satisfies RotatingLogFileWriter;
});
const readPersistedOtlpTracesUrl: Effect.Effect<
Option.Option<string>,
never,
FileSystem.FileSystem | DesktopEnvironment.DesktopEnvironment
> = Effect.gen(function* () {
const readPersistedOtlpTracesUrl = Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const environment = yield* DesktopEnvironment.DesktopEnvironment;
const raw = yield* fileSystem.readFileString(environment.serverSettingsPath).pipe(Effect.option);
@@ -274,170 +70,6 @@ const resolveOtlpTracesUrl = Effect.gen(function* () {
return yield* readPersistedOtlpTracesUrl;
});
const writeDevelopmentConsoleOutput = (
streamName: "stdout" | "stderr",
chunk: Uint8Array,
): Effect.Effect<void> =>
Effect.sync(() => {
const output = streamName === "stderr" ? process.stderr : process.stdout;
output.write(chunk);
}).pipe(Effect.ignore);
const writeBackendChildLogRecord = Effect.fn("desktop.observability.writeBackendChildLogRecord")(
function* (
logFile: RotatingLogFileWriter,
input: {
readonly message: string;
readonly level: "INFO" | "ERROR";
readonly annotations: Record<string, unknown>;
},
): Effect.fn.Return<void> {
return yield* Effect.gen(function* () {
const timestamp = DateTime.formatIso(yield* DateTime.now);
const encoded = yield* encodeDesktopBackendChildLogRecord({
message: input.message,
level: input.level,
timestamp,
annotations: input.annotations,
spans: {},
fiberId: DESKTOP_BACKEND_CHILD_LOG_FIBER_ID,
});
yield* logFile.writeText(`${encoded}\n`);
}).pipe(Effect.ignore({ log: true }));
},
);
const PRIMARY_BACKEND_LOG_INSTANCE_ID = PRIMARY_LOCAL_ENVIRONMENT_ID;
const sanitizeInstanceIdForFileName = (id: string): string => id.replace(/[^a-zA-Z0-9._-]+/g, "_");
const backendLogFilePathForInstance = (
environment: DesktopEnvironment.DesktopEnvironment["Service"],
id: string,
): string => {
// Primary keeps the historical "server-child.log" path so ops scripts
// and packaged-build log inspection still find it where it always lived.
if (id === PRIMARY_BACKEND_LOG_INSTANCE_ID) {
return environment.path.join(environment.logDir, "server-child.log");
}
const sanitized = sanitizeInstanceIdForFileName(id);
return environment.path.join(environment.logDir, `server-child-${sanitized}.log`);
};
// Just the IO sink. Cacheable by resolved file path so two ids that
// sanitize to the same filename share a single RotatingLogFileWriter
// (no race on currentSize tracking). Splitting the sink off from the
// per-call shape lets the shape annotate writes with the *caller's*
// id rather than whatever id created the cached writer first.
const makeBackendOutputSinkForInstance = (
environment: DesktopEnvironment.DesktopEnvironment["Service"],
id: string,
): Effect.Effect<
Option.Option<RotatingLogFileWriter>,
never,
FileSystem.FileSystem | Path.Path | Scope.Scope
> =>
makeRotatingLogFileWriter({
filePath: backendLogFilePathForInstance(environment, id),
}).pipe(Effect.option);
const makeBackendOutputLogShape = (
environment: DesktopEnvironment.DesktopEnvironment["Service"],
id: string,
sink: Option.Option<RotatingLogFileWriter>,
): DesktopBackendOutputLogShape =>
Option.match(sink, {
onNone: () => DesktopBackendOutputLogNoop,
onSome: (logFile) =>
({
writeSessionBoundary: Effect.fn("desktop.observability.backendOutput.writeSessionBoundary")(
function* ({ phase, details }) {
const runId = yield* currentDesktopRunId;
yield* writeBackendChildLogRecord(logFile, {
message: `backend child process session ${phase.toLowerCase()}`,
level: "INFO",
annotations: {
component: "desktop-backend-child",
runId,
instanceId: id,
phase,
details: sanitizeLogValue(details),
},
});
},
),
writeOutputChunk: Effect.fn("desktop.observability.backendOutput.writeOutputChunk")(
function* (streamName, chunk) {
if (environment.isDevelopment) {
yield* writeDevelopmentConsoleOutput(streamName, chunk);
}
const runId = yield* currentDesktopRunId;
yield* writeBackendChildLogRecord(logFile, {
message: "backend child process output",
level: streamName === "stderr" ? "ERROR" : "INFO",
annotations: {
component: "desktop-backend-child",
runId,
instanceId: id,
stream: streamName,
text: textDecoder.decode(chunk),
},
});
},
),
}) satisfies DesktopBackendOutputLogShape,
});
const backendOutputLogFactoryLayer = Layer.effect(
DesktopBackendOutputLogFactory,
Effect.gen(function* () {
const environment = yield* DesktopEnvironment.DesktopEnvironment;
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const factoryScope = yield* Scope.Scope;
// Per-file-path cache of the IO sink only. The per-call shape
// wraps the sink with the caller's instance id so a cache hit on
// a path collision (e.g. "wsl:default" and "wsl_default" both
// resolve to server-child-wsl_default.log) doesn't attribute the
// second caller's writes to the first caller's id. Each sink pins
// itself to the factory's scope so all log resources tear down
// together at app exit. Mutex serializes concurrent first-time
// lookups for the same file path.
const cacheRef = yield* SynchronizedRef.make<
ReadonlyMap<string, Option.Option<RotatingLogFileWriter>>
>(new Map());
const makeForId = (id: string): Effect.Effect<DesktopBackendOutputLogShape> =>
SynchronizedRef.modifyEffect(cacheRef, (cache) => {
const cacheKey = backendLogFilePathForInstance(environment, id);
const cached = cache.get(cacheKey);
if (cached !== undefined) {
return Effect.succeed([
makeBackendOutputLogShape(environment, id, cached),
cache,
] as const);
}
return makeBackendOutputSinkForInstance(environment, id).pipe(
Effect.provideService(FileSystem.FileSystem, fileSystem),
Effect.provideService(Path.Path, path),
Scope.provide(factoryScope),
Effect.map((sink) => {
const next = new Map(cache);
next.set(cacheKey, sink);
return [
makeBackendOutputLogShape(environment, id, sink),
next as ReadonlyMap<string, Option.Option<RotatingLogFileWriter>>,
] as const;
}),
);
});
return DesktopBackendOutputLogFactory.of({
forInstance: (id) => makeForId(id),
});
}),
);
const desktopLoggerLayer = Layer.mergeAll(
Logger.layer([Logger.consolePretty(), Logger.tracerLogger], { mergeWithExisting: false }),
Layer.succeed(References.MinimumLogLevel, "Info"),
@@ -450,8 +82,8 @@ const tracerLayer = Layer.unwrap(
const tracePath = environment.path.join(environment.logDir, "desktop.trace.ndjson");
const sink = yield* makeTraceSink({
filePath: tracePath,
maxBytes: DESKTOP_LOG_FILE_MAX_BYTES,
maxFiles: DESKTOP_LOG_FILE_MAX_FILES,
maxBytes: DesktopBackendOutputLogModule.DESKTOP_LOG_FILE_MAX_BYTES,
maxFiles: DesktopBackendOutputLogModule.DESKTOP_LOG_FILE_MAX_FILES,
batchWindowMs: DESKTOP_TRACE_BATCH_WINDOW_MS,
});
const delegate = Option.isNone(otlpTracesUrl)
@@ -469,8 +101,8 @@ const tracerLayer = Layer.unwrap(
});
const tracer = yield* makeLocalFileTracer({
filePath: tracePath,
maxBytes: DESKTOP_LOG_FILE_MAX_BYTES,
maxFiles: DESKTOP_LOG_FILE_MAX_FILES,
maxBytes: DesktopBackendOutputLogModule.DESKTOP_LOG_FILE_MAX_BYTES,
maxFiles: DesktopBackendOutputLogModule.DESKTOP_LOG_FILE_MAX_FILES,
batchWindowMs: DESKTOP_TRACE_BATCH_WINDOW_MS,
sink,
...(delegate ? { delegate } : {}),
@@ -481,7 +113,7 @@ const tracerLayer = Layer.unwrap(
).pipe(Layer.provideMerge(OtlpSerialization.layerJson));
export const layer = Layer.mergeAll(
backendOutputLogFactoryLayer,
DesktopBackendOutputLogModule.layer,
desktopLoggerLayer,
tracerLayer,
Layer.succeed(Tracer.MinimumTraceLevel, "Info"),
@@ -3,20 +3,12 @@ import { assert, describe, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Logger from "effect/Logger";
import * as ManagedRuntime from "effect/ManagedRuntime";
import * as Option from "effect/Option";
import * as Path from "effect/Path";
import * as PlatformError from "effect/PlatformError";
import * as Schema from "effect/Schema";
import { ChildProcessSpawner } from "effect/unstable/process";
import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
import * as DesktopBackendConfiguration from "./DesktopBackendConfiguration.ts";
import * as DesktopConfig from "../app/DesktopConfig.ts";
import * as DesktopServerExposure from "./DesktopServerExposure.ts";
import * as DesktopAppSettings from "../settings/DesktopAppSettings.ts";
import * as DesktopWslEnvironment from "../wsl/DesktopWslEnvironment.ts";
const PersistedServerObservabilitySettingsDocument = Schema.Struct({
observability: Schema.Struct({
@@ -29,10 +21,6 @@ const encodePersistedServerObservabilitySettingsDocument = Schema.encodeEffect(
Schema.fromJsonString(PersistedServerObservabilitySettingsDocument),
);
const isDesktopBackendObservabilitySettingsReadError = Schema.is(
DesktopBackendConfiguration.DesktopBackendObservabilitySettingsReadError,
);
const serverExposureLayer = Layer.succeed(DesktopServerExposure.DesktopServerExposure, {
getState: Effect.die("unexpected getState"),
backendConfig: Effect.succeed({
@@ -51,22 +39,19 @@ const serverExposureLayer = Layer.succeed(DesktopServerExposure.DesktopServerExp
function makeEnvironmentLayer(
baseDir: string,
options?: {
readonly appPath?: string;
readonly isPackaged?: boolean;
readonly devServerUrl?: string;
readonly platform?: NodeJS.Platform;
readonly resourcesPath?: string;
},
) {
return DesktopEnvironment.layer({
dirname: "/repo/apps/desktop/src",
homeDirectory: baseDir,
platform: options?.platform ?? "darwin",
platform: "darwin",
processArch: "x64",
appVersion: "1.2.3",
appPath: options?.appPath ?? "/repo",
appPath: "/repo",
isPackaged: options?.isPackaged ?? true,
resourcesPath: options?.resourcesPath ?? "/missing/resources",
resourcesPath: "/missing/resources",
runningUnderArm64Translation: false,
}).pipe(
Layer.provide(
@@ -84,14 +69,6 @@ function makeEnvironmentLayer(
);
}
const restoreEnv = (name: string, value: string | undefined) => {
if (value === undefined) {
delete process.env[name];
} else {
process.env[name] = value;
}
};
const withHarness = <A, E, R>(
effect: Effect.Effect<
A,
@@ -112,8 +89,6 @@ const withHarness = <A, E, R>(
Effect.provide(
DesktopBackendConfiguration.layer.pipe(
Layer.provideMerge(serverExposureLayer),
Layer.provideMerge(DesktopAppSettings.layerTest()),
Layer.provideMerge(DesktopWslEnvironment.layerTest()),
Layer.provideMerge(makeEnvironmentLayer(baseDir)),
),
),
@@ -121,14 +96,14 @@ const withHarness = <A, E, R>(
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer));
describe("DesktopBackendConfiguration", () => {
it.effect("resolvePrimary produces a stable scoped bootstrap token", () =>
it.effect("resolves backend start config with a stable scoped bootstrap token", () =>
withHarness(
Effect.gen(function* () {
const environment = yield* DesktopEnvironment.DesktopEnvironment;
const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
const first = yield* configuration.resolvePrimary;
const second = yield* configuration.resolvePrimary;
const first = yield* configuration.resolve;
const second = yield* configuration.resolve;
assert.equal(first.executablePath, process.execPath);
assert.equal(first.entryPath, environment.backendEntryPath);
@@ -152,167 +127,7 @@ describe("DesktopBackendConfiguration", () => {
),
);
it.effect("resolveWsl reuses the primary's bootstrap token", () =>
withHarness(
Effect.gen(function* () {
const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
const primary = yield* configuration.resolvePrimary;
const wsl = yield* configuration.resolveWsl({ port: 5000, distro: null });
assert.equal(wsl.bootstrap.desktopBootstrapToken, primary.bootstrap.desktopBootstrapToken);
}),
),
);
it.effect("resolveWsl pins a default-tracking run to the concrete default distro", () =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const baseDir = yield* fileSystem.makeTempDirectoryScoped({
prefix: "t3-desktop-backend-config-test-",
});
const entryPath = path.join(baseDir, "app.asar.unpacked/apps/server/dist/bin.mjs");
yield* fileSystem.makeDirectory(path.dirname(entryPath), { recursive: true });
yield* fileSystem.writeFileString(entryPath, "");
const observedDistros: Array<string | null> = [];
const config = yield* Effect.gen(function* () {
const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
return yield* configuration.resolveWsl({ port: 5000, distro: null });
}).pipe(
Effect.provide(
DesktopBackendConfiguration.layer.pipe(
Layer.provideMerge(serverExposureLayer),
Layer.provideMerge(DesktopAppSettings.layerTest()),
Layer.provideMerge(
DesktopWslEnvironment.layerTest({
isAvailable: true,
distros: [
{ name: "Debian", isDefault: false, version: 2 },
{ name: "Ubuntu", isDefault: true, version: 2 },
],
windowsToWslPath: (distro) => {
observedDistros.push(distro);
return Option.some("/repo/apps/server/dist/bin.mjs");
},
ensureNodePty: (distro) => {
observedDistros.push(distro);
return { ok: true, nodePath: "/usr/bin/node", resolvedPath: "/usr/bin:/bin" };
},
getDistroIp: (distro) => {
observedDistros.push(distro);
return Option.some("172.27.0.99");
},
}),
),
Layer.provideMerge(
makeEnvironmentLayer(baseDir, {
appPath: baseDir,
platform: "win32",
resourcesPath: baseDir,
}),
),
),
),
);
assert.equal(config.runningDistro, "Ubuntu");
assert.deepEqual(config.args.slice(0, 2), ["-d", "Ubuntu"]);
assert.deepEqual(observedDistros, ["Ubuntu", "Ubuntu", "Ubuntu"]);
assert.isTrue(Option.isNone(config.preflightFailure));
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
);
it.effect(
"resolveWsl preserves inherited PATH with quote-sensitive values as separate args",
() =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const baseDir = yield* fileSystem.makeTempDirectoryScoped({
prefix: "t3-desktop-backend-config-test-",
});
const entryPath = path.join(baseDir, "app.asar.unpacked/apps/server/dist/bin.mjs");
yield* fileSystem.makeDirectory(path.dirname(entryPath), { recursive: true });
yield* fileSystem.writeFileString(entryPath, "");
const nodePath = "/home/test user's/.nvm/versions/node/v22.0.0/bin/node";
const linuxEntryPath = "/tmp/t3 code's launch/entry file.mjs";
const resolvedPath = "/home/test user/bin:/opt/test's tools/bin:/usr/bin:/bin";
const devServerUrl = "http://127.0.0.1:5733/dev%20assets/?label=hello%20world";
const config = yield* Effect.gen(function* () {
const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
return yield* configuration.resolveWsl({ port: 5000, distro: "Ubuntu" });
}).pipe(
Effect.provide(
DesktopBackendConfiguration.layer.pipe(
Layer.provideMerge(serverExposureLayer),
Layer.provideMerge(DesktopAppSettings.layerTest()),
Layer.provideMerge(
DesktopWslEnvironment.layerTest({
isAvailable: true,
distros: [{ name: "Ubuntu", isDefault: true, version: 2 }],
windowsToWslPath: () => Option.some(linuxEntryPath),
ensureNodePty: () => ({ ok: true, nodePath, resolvedPath }),
getDistroIp: () => Option.some("172.27.0.99"),
}),
),
Layer.provideMerge(
makeEnvironmentLayer(baseDir, {
appPath: baseDir,
devServerUrl,
isPackaged: true,
platform: "win32",
resourcesPath: baseDir,
}),
),
),
),
);
assert.equal(config.bootstrapDelivery, "stdin");
assert.deepEqual(config.args, [
"-d",
"Ubuntu",
"--exec",
"env",
"PATH=/home/test user's/.nvm/versions/node/v22.0.0/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/home/test user/bin:/opt/test's tools/bin:/usr/bin:/bin",
nodePath,
linuxEntryPath,
"--bootstrap-fd",
"0",
"--dev-url",
devServerUrl,
]);
assert.notInclude(config.args, "bash");
assert.notInclude(config.args, "/bin/sh");
assert.notInclude(config.args, "-c");
assert.isTrue(Option.isNone(config.preflightFailure));
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
);
it.effect("resolvePrimary and resolveWsl share one token under concurrent resolution", () =>
withHarness(
Effect.gen(function* () {
const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
// Resolve both before any token is cached, concurrently, so the
// generate step (a yield point) can interleave. The atomic
// get-or-create must still hand both the same token; a non-atomic
// Ref would let each generate its own and break the shared-token
// invariant.
const [primary, wsl] = yield* Effect.all(
[configuration.resolvePrimary, configuration.resolveWsl({ port: 5000, distro: null })],
{ concurrency: "unbounded" },
);
assert.equal(wsl.bootstrap.desktopBootstrapToken, primary.bootstrap.desktopBootstrapToken);
}),
),
);
it.effect("resolvePrimary surfaces persisted backend observability endpoints", () =>
it.effect("includes persisted backend observability endpoints when present", () =>
withHarness(
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
@@ -332,18 +147,18 @@ describe("DesktopBackendConfiguration", () => {
}),
);
const config = yield* configuration.resolvePrimary;
const config = yield* configuration.resolve;
assert.equal(config.bootstrap.otlpTracesUrl, "http://127.0.0.1:4318/v1/traces");
assert.equal(config.bootstrap.otlpMetricsUrl, "http://127.0.0.1:4318/v1/metrics");
}),
),
);
it.effect("resolvePrimary omits backend observability endpoints when settings are missing", () =>
it.effect("omits backend observability endpoints when settings are missing", () =>
withHarness(
Effect.gen(function* () {
const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
const config = yield* configuration.resolvePrimary;
const config = yield* configuration.resolve;
assert.isUndefined(config.bootstrap.otlpTracesUrl);
assert.isUndefined(config.bootstrap.otlpMetricsUrl);
@@ -351,66 +166,7 @@ describe("DesktopBackendConfiguration", () => {
),
);
it.effect("logs structured context when persisted observability settings cannot be read", () =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const baseDir = yield* fileSystem.makeTempDirectoryScoped({
prefix: "t3-desktop-backend-config-test-",
});
const settingsPath = path.join(baseDir, "userdata", "settings.json");
const cause = PlatformError.systemError({
_tag: "PermissionDenied",
module: "FileSystem",
method: "readFileString",
pathOrDescriptor: settingsPath,
});
const messages: Array<unknown> = [];
const logger = Logger.make(({ message }) => {
messages.push(message);
});
const failingFileSystemLayer = Layer.succeed(
FileSystem.FileSystem,
FileSystem.makeNoop({
readFileString: () => Effect.fail(cause),
}),
);
const config = yield* Effect.gen(function* () {
const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
return yield* configuration.resolvePrimary;
}).pipe(
Effect.provide(
Layer.mergeAll(
DesktopBackendConfiguration.layer.pipe(
Layer.provideMerge(serverExposureLayer),
Layer.provideMerge(DesktopAppSettings.layerTest()),
Layer.provideMerge(DesktopWslEnvironment.layerTest()),
Layer.provideMerge(makeEnvironmentLayer(baseDir)),
Layer.provideMerge(failingFileSystemLayer),
),
Logger.layer([logger], { mergeWithExisting: false }),
),
),
);
assert.isUndefined(config.bootstrap.otlpTracesUrl);
assert.isUndefined(config.bootstrap.otlpMetricsUrl);
const error = messages
.flatMap((message) => (Array.isArray(message) ? message : [message]))
.find(isDesktopBackendObservabilitySettingsReadError);
assert.isDefined(error);
assert.equal(error.settingsPath, settingsPath);
assert.equal(error.cause, cause);
assert.equal(
error.message,
`Failed to read persisted backend observability settings at ${settingsPath}.`,
);
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
);
it.effect("resolvePrimary captures backend output in dev so child logs can be persisted", () =>
it.effect("captures backend output in development so child process logs can be persisted", () =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const baseDir = yield* fileSystem.makeTempDirectoryScoped({
@@ -419,14 +175,12 @@ describe("DesktopBackendConfiguration", () => {
yield* Effect.gen(function* () {
const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
const config = yield* configuration.resolvePrimary;
const config = yield* configuration.resolve;
assert.equal(config.captureOutput, true);
}).pipe(
Effect.provide(
DesktopBackendConfiguration.layer.pipe(
Layer.provideMerge(serverExposureLayer),
Layer.provideMerge(DesktopAppSettings.layerTest()),
Layer.provideMerge(DesktopWslEnvironment.layerTest()),
Layer.provideMerge(
makeEnvironmentLayer(baseDir, {
isPackaged: false,
@@ -438,362 +192,4 @@ describe("DesktopBackendConfiguration", () => {
);
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
);
it.effect("resolveWsl preserves existing WSLENV entries when forwarding backend secrets", () =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const baseDir = yield* fileSystem.makeTempDirectoryScoped({
prefix: "t3-desktop-backend-config-test-",
});
const previousWslEnv = process.env.WSLENV;
const previousOpenAiKey = process.env.OPENAI_API_KEY;
const previousAnthropicKey = process.env.ANTHROPIC_API_KEY;
try {
process.env.WSLENV = "GOPATH/p:OPENAI_API_KEY/u:EMPTY::AZURE_DEVOPS_EXT_PAT/u";
process.env.OPENAI_API_KEY = "openai-key";
process.env.ANTHROPIC_API_KEY = "anthropic-key";
yield* Effect.gen(function* () {
const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
const config = yield* configuration.resolveWsl({ port: 5050, distro: null });
assert.equal(config.executablePath, "wsl.exe");
assert.equal(config.bootstrap.port, 5050);
// Binds to 0.0.0.0 inside WSL so the backend is reachable via
// both wslhost-forwarded localhost and the distro's eth0 IP.
assert.equal(config.bootstrap.host, "0.0.0.0");
assert.equal(config.bootstrap.tailscaleServeEnabled, false);
// httpBaseUrl uses the resolved distro IP from the test stub,
// not localhost — the renderer reaches the backend directly to
// avoid relying on wslhost forwarding.
assert.equal(config.httpBaseUrl.href, "http://172.27.0.99:5050/");
assert.equal(config.env.OPENAI_API_KEY, "openai-key");
assert.equal(config.env.ANTHROPIC_API_KEY, "anthropic-key");
// The existing WSLENV is preserved byte-for-byte (note the empty
// "::" segment survives — WSL ignores it, so we don't normalize
// it away) and ANTHROPIC_API_KEY is appended. OPENAI_API_KEY is
// already declared, so it isn't forwarded twice.
assert.equal(
config.env.WSLENV,
"GOPATH/p:OPENAI_API_KEY/u:EMPTY::AZURE_DEVOPS_EXT_PAT/u:ANTHROPIC_API_KEY",
);
}).pipe(
Effect.provide(
DesktopBackendConfiguration.layer.pipe(
Layer.provideMerge(serverExposureLayer),
Layer.provideMerge(DesktopAppSettings.layerTest()),
Layer.provideMerge(
DesktopWslEnvironment.layerTest({
isAvailable: true,
windowsToWslPath: () => Option.some("/mnt/c/repo/apps/server/src/index.ts"),
getDistroIp: () => Option.some("172.27.0.99"),
}),
),
Layer.provideMerge(makeEnvironmentLayer(baseDir, { platform: "win32" })),
),
),
);
} finally {
restoreEnv("WSLENV", previousWslEnv);
restoreEnv("OPENAI_API_KEY", previousOpenAiKey);
restoreEnv("ANTHROPIC_API_KEY", previousAnthropicKey);
}
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
);
it.effect(
"resolvePrimary falls back to the Windows primary when wsl-only but WSL is unavailable",
() =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const baseDir = yield* fileSystem.makeTempDirectoryScoped({
prefix: "t3-desktop-backend-config-test-",
});
yield* Effect.gen(function* () {
const environment = yield* DesktopEnvironment.DesktopEnvironment;
const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
const config = yield* configuration.resolvePrimary;
// wsl-only is persisted but WSL is unavailable, so the primary must
// not spawn wsl.exe (which would loop on preflight failures while the
// Connections backend control is hidden). Resolve the Windows primary.
assert.equal(config.executablePath, process.execPath);
assert.equal(config.bootstrap.t3Home, environment.baseDir);
assert.isTrue(Option.isNone(config.preflightFailure));
}).pipe(
Effect.provide(
DesktopBackendConfiguration.layer.pipe(
Layer.provideMerge(serverExposureLayer),
Layer.provideMerge(
DesktopAppSettings.layerTest({
...DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS,
wslBackendEnabled: true,
wslOnly: true,
}),
),
Layer.provideMerge(DesktopWslEnvironment.layerTest({ isAvailable: false })),
Layer.provideMerge(makeEnvironmentLayer(baseDir, { platform: "win32" })),
),
),
);
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
);
it.effect(
"resolvePrimary marks a removed persisted WSL distro as a fatal preflight failure",
() =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const baseDir = yield* fileSystem.makeTempDirectoryScoped({
prefix: "t3-desktop-backend-config-test-",
});
yield* Effect.gen(function* () {
const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
const config = yield* configuration.resolvePrimary;
const failure = Option.getOrThrow(config.preflightFailure);
assert.equal(config.executablePath, "wsl.exe");
assert.isTrue(failure.fatal);
assert.include(failure.reason, "Removed-Distro");
}).pipe(
Effect.provide(
DesktopBackendConfiguration.layer.pipe(
Layer.provideMerge(serverExposureLayer),
Layer.provideMerge(
DesktopAppSettings.layerTest({
...DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS,
wslBackendEnabled: true,
wslOnly: true,
wslDistro: "Removed-Distro",
}),
),
Layer.provideMerge(
DesktopWslEnvironment.layerTest({
isAvailable: true,
distros: [{ name: "Ubuntu", isDefault: true, version: 2 }],
}),
),
Layer.provideMerge(makeEnvironmentLayer(baseDir, { platform: "win32" })),
),
),
);
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
);
it.effect("resolveWsl keeps a transient distro-list failure retryable", () =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const baseDir = yield* fileSystem.makeTempDirectoryScoped({
prefix: "t3-desktop-backend-config-test-",
});
yield* Effect.gen(function* () {
const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
const config = yield* configuration.resolveWsl({ port: 5050, distro: "Ubuntu" });
const failure = Option.getOrThrow(config.preflightFailure);
assert.isFalse(failure.fatal);
assert.equal(failure.retryLimit, 12);
assert.include(failure.reason, "timed out");
}).pipe(
Effect.provide(
DesktopBackendConfiguration.layer.pipe(
Layer.provideMerge(serverExposureLayer),
Layer.provideMerge(DesktopAppSettings.layerTest()),
Layer.provideMerge(
DesktopWslEnvironment.layerTest({
isAvailable: true,
distroListError: new DesktopWslEnvironment.DesktopWslDistroListError({
reason: "wsl.exe --list --verbose timed out",
}),
}),
),
Layer.provideMerge(makeEnvironmentLayer(baseDir, { platform: "win32" })),
),
),
);
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
);
it.effect("resolveWsl marks a missing packaged server entry as fatal", () =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const baseDir = yield* fileSystem.makeTempDirectoryScoped({
prefix: "t3-desktop-backend-config-test-",
});
yield* Effect.gen(function* () {
const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
const config = yield* configuration.resolveWsl({ port: 5050, distro: "Ubuntu" });
const failure = Option.getOrThrow(config.preflightFailure);
assert.isTrue(failure.fatal);
assert.include(failure.reason, "missing server entry");
}).pipe(
Effect.provide(
DesktopBackendConfiguration.layer.pipe(
Layer.provideMerge(serverExposureLayer),
Layer.provideMerge(DesktopAppSettings.layerTest()),
Layer.provideMerge(
DesktopWslEnvironment.layerTest({
isAvailable: true,
distros: [{ name: "Ubuntu", isDefault: true, version: 2 }],
}),
),
Layer.provideMerge(makeEnvironmentLayer(baseDir, { platform: "win32" })),
),
),
);
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
);
it.effect("resolveWsl marks a missing selected distro as a fatal preflight failure", () =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const baseDir = yield* fileSystem.makeTempDirectoryScoped({
prefix: "t3-desktop-backend-config-test-",
});
yield* Effect.gen(function* () {
const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
const config = yield* configuration.resolveWsl({ port: 5050, distro: "Removed-Distro" });
const failure = Option.getOrThrow(config.preflightFailure);
assert.isTrue(failure.fatal);
assert.include(failure.reason, "Removed-Distro");
}).pipe(
Effect.provide(
DesktopBackendConfiguration.layer.pipe(
Layer.provideMerge(serverExposureLayer),
Layer.provideMerge(DesktopAppSettings.layerTest()),
Layer.provideMerge(
DesktopWslEnvironment.layerTest({
isAvailable: true,
distros: [{ name: "Ubuntu", isDefault: true, version: 2 }],
}),
),
Layer.provideMerge(makeEnvironmentLayer(baseDir, { platform: "win32" })),
),
),
);
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
);
it.effect("resolvePrimaryLabel reports the WSL distro when wsl-only and WSL is available", () =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const baseDir = yield* fileSystem.makeTempDirectoryScoped({
prefix: "t3-desktop-backend-config-test-",
});
yield* Effect.gen(function* () {
const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
const label = yield* configuration.resolvePrimaryLabel;
assert.equal(label, "WSL (Ubuntu)");
}).pipe(
Effect.provide(
DesktopBackendConfiguration.layer.pipe(
Layer.provideMerge(serverExposureLayer),
Layer.provideMerge(
DesktopAppSettings.layerTest({
...DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS,
wslBackendEnabled: true,
wslOnly: true,
wslDistro: "Ubuntu",
}),
),
Layer.provideMerge(DesktopWslEnvironment.layerTest({ isAvailable: true })),
Layer.provideMerge(makeEnvironmentLayer(baseDir, { platform: "win32" })),
),
),
);
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
);
it.effect("resolvePrimaryLabel reports the local environment on non-Windows platforms", () =>
withHarness(
Effect.gen(function* () {
const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
const label = yield* configuration.resolvePrimaryLabel;
assert.equal(label, "Local environment");
}),
),
);
it.effect("resolvePrimaryLabel reports Windows when wsl-only but WSL is unavailable", () =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const baseDir = yield* fileSystem.makeTempDirectoryScoped({
prefix: "t3-desktop-backend-config-test-",
});
yield* Effect.gen(function* () {
const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
// Mirrors the resolvePrimary fall-back: the label must follow the
// backend that actually resolves, not the persisted preference, so the
// env switcher can't show "WSL" for a Windows backend.
const label = yield* configuration.resolvePrimaryLabel;
assert.equal(label, "Windows");
}).pipe(
Effect.provide(
DesktopBackendConfiguration.layer.pipe(
Layer.provideMerge(serverExposureLayer),
Layer.provideMerge(
DesktopAppSettings.layerTest({
...DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS,
wslBackendEnabled: true,
wslOnly: true,
wslDistro: "Ubuntu",
}),
),
Layer.provideMerge(DesktopWslEnvironment.layerTest({ isAvailable: false })),
Layer.provideMerge(makeEnvironmentLayer(baseDir, { platform: "win32" })),
),
),
);
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
);
it("resolvePrimaryLabel is runSync-safe against the real WSL availability probe", async () => {
// getLocalEnvironmentBootstraps is a sync IPC method: it resolves the
// primary instance's lazy label through Effect.runSync. The label chains
// to wslEnvironment.isAvailable, whose real layer probes the filesystem.
// That probe must run once at layer build and expose a resolved value, not
// a live async effect — otherwise runSync throws in the handler. Build the
// real WSL layer (not the sync test stub) and resolve the label with a
// top-level runSync, exactly as the handler does.
// oxlint-disable-next-line t3code/no-manual-effect-runtime-in-tests -- This test intentionally replicates the sync IPC handler's runSync path to catch a regression to async-only resolution; it.effect would mask it.
const runtime = ManagedRuntime.make(
DesktopBackendConfiguration.layer.pipe(
Layer.provideMerge(serverExposureLayer),
Layer.provideMerge(DesktopAppSettings.layerTest()),
Layer.provideMerge(DesktopWslEnvironment.layer),
// isAvailable on win32 only touches the filesystem, never the spawner,
// so a die-stub is enough to satisfy the layer's deps.
Layer.provideMerge(
Layer.succeed(
ChildProcessSpawner.ChildProcessSpawner,
ChildProcessSpawner.make(() =>
Effect.die("spawner should not be used while probing WSL availability"),
),
),
),
Layer.provideMerge(makeEnvironmentLayer("/tmp/t3-wsl-isavailable", { platform: "win32" })),
Layer.provide(NodeServices.layer),
),
);
try {
const configuration = await runtime.runPromise(
DesktopBackendConfiguration.DesktopBackendConfiguration,
);
// oxlint-disable-next-line t3code/no-manual-effect-runtime-in-tests -- Same reason: this is the synchronous resolution the IPC handler performs.
const label = Effect.runSync(configuration.resolvePrimaryLabel);
assert.equal(typeof label, "string");
} finally {
await runtime.dispose();
}
});
});
@@ -1,5 +1,3 @@
import * as NodeOS from "node:os";
import { parsePersistedServerObservabilitySettings } from "@t3tools/shared/serverSettings";
import * as Context from "effect/Context";
import * as Crypto from "effect/Crypto";
@@ -9,57 +7,20 @@ import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as PlatformError from "effect/PlatformError";
import * as Schema from "effect/Schema";
import * as SynchronizedRef from "effect/SynchronizedRef";
import serverPackageJson from "../../../server/package.json" with { type: "json" };
import * as Ref from "effect/Ref";
import * as DesktopBackendManager from "./DesktopBackendManager.ts";
import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
import * as DesktopObservability from "../app/DesktopObservability.ts";
import * as DesktopServerExposure from "./DesktopServerExposure.ts";
import * as DesktopAppSettings from "../settings/DesktopAppSettings.ts";
import * as DesktopWslEnvironment from "../wsl/DesktopWslEnvironment.ts";
export class DesktopBackendObservabilitySettingsReadError extends Schema.TaggedErrorClass<DesktopBackendObservabilitySettingsReadError>()(
"DesktopBackendObservabilitySettingsReadError",
{
settingsPath: Schema.String,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to read persisted backend observability settings at ${this.settingsPath}.`;
}
}
export class DesktopBackendConfiguration extends Context.Service<
DesktopBackendConfiguration,
{
// Build the Windows-native primary backend's start config. Reads the
// primary's port/host/exposure from DesktopServerExposure. Can fail
// with PlatformError because bootstrap token generation now uses
// crypto.randomBytes under the hood (post Effect 4 migration).
readonly resolvePrimary: Effect.Effect<
readonly resolve: Effect.Effect<
DesktopBackendManager.DesktopBackendStartConfig,
PlatformError.PlatformError
>;
// Build a WSL backend start config for the given distro on the given
// port. The WSL backend is always loopback-only (the primary owns LAN
// exposure when the user opts in), so this takes the port directly and
// hardcodes 127.0.0.1. Distro=null means "WSL default distro" and is
// forwarded to wsl.exe with no -d flag.
readonly resolveWsl: (input: {
readonly port: number;
readonly distro: string | null;
}) => Effect.Effect<
DesktopBackendManager.DesktopBackendStartConfig,
PlatformError.PlatformError
>;
// The renderer-facing label for the primary instance, derived from the
// same decision resolvePrimary makes (including the WSL-availability
// fall-back to Windows), so the env switcher can't show "WSL" for a
// backend that actually resolved to Windows.
readonly resolvePrimaryLabel: Effect.Effect<string>;
}
>()("@t3tools/desktop/backend/DesktopBackendConfiguration") {}
@@ -86,76 +47,28 @@ const DESKTOP_BACKEND_ENV_NAMES = [
"T3CODE_TAILSCALE_SERVE_PORT",
] as const;
// Sensitive env vars that the WSL backend needs but Windows process.env won't
// forward across the wsl.exe boundary without WSLENV. The dev-server URL is
// handled separately via a `--dev-url` CLI flag because WSLENV translation of
// URL-shaped values (colons / slashes) is unreliable.
const WSL_FORWARDED_ENV_NAMES = ["OPENAI_API_KEY", "ANTHROPIC_API_KEY"] as const;
const WSL_SERVER_SYSTEM_PATH = "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin";
const backendChildEnvPatch = (): Record<string, string | undefined> =>
Object.fromEntries(DESKTOP_BACKEND_ENV_NAMES.map((name) => [name, undefined]));
const getWslEnvEntryName = (entry: string): string => {
const slashIndex = entry.indexOf("/");
return slashIndex === -1 ? entry : entry.slice(0, slashIndex);
};
const mergeWslEnv = (
existingWslEnv: string | undefined,
forwardedEnvNames: ReadonlyArray<string>,
): string | undefined => {
const existing = existingWslEnv?.trim() ?? "";
// Names already declared, so we don't forward a duplicate. We parse the
// existing value only for this membership test — the string itself is
// preserved verbatim below rather than re-serialized.
const seenNames = new Set(
existing
.split(":")
.map((entry) => getWslEnvEntryName(entry.trim()))
.filter((name) => name.length > 0),
);
const additions = forwardedEnvNames.filter((name) => !seenNames.has(name));
// Preserve the user's WSLENV exactly as Windows handed it to us — empty
// "::" segments and duplicate entries are harmless no-ops to WSL and not
// ours to normalize — and only append the secrets we need to forward
// across the wsl.exe boundary.
const parts = [existing, ...additions].filter((part) => part.length > 0);
return parts.length > 0 ? parts.join(":") : undefined;
};
const logBackendObservabilitySettingsReadFailure = (
settingsPath: string,
cause: PlatformError.PlatformError,
) => {
const error = new DesktopBackendObservabilitySettingsReadError({ settingsPath, cause });
return Effect.logWarning(error).pipe(
Effect.annotateLogs({
component: "desktop-backend-configuration",
error,
}),
);
};
const { logWarning: logBackendConfigurationWarning } = DesktopObservability.makeComponentLogger(
"desktop-backend-configuration",
);
const readPersistedBackendObservabilitySettings = Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const environment = yield* DesktopEnvironment.DesktopEnvironment;
const raw = yield* fileSystem.readFileString(environment.serverSettingsPath).pipe(
Effect.map(Option.some),
Effect.catchTags({
PlatformError: (cause) =>
cause.reason._tag === "NotFound"
? Effect.succeed(Option.none())
: logBackendObservabilitySettingsReadFailure(environment.serverSettingsPath, cause).pipe(
Effect.as(Option.none()),
),
}),
);
const exists = yield* fileSystem
.exists(environment.serverSettingsPath)
.pipe(Effect.orElseSucceed(() => false));
if (!exists) {
return emptyBackendObservabilitySettings;
}
const raw = yield* fileSystem.readFileString(environment.serverSettingsPath).pipe(Effect.option);
if (Option.isNone(raw)) {
yield* logBackendConfigurationWarning(
"failed to read persisted backend observability settings",
);
return emptyBackendObservabilitySettings;
}
@@ -166,168 +79,11 @@ const readPersistedBackendObservabilitySettings = Effect.gen(function* () {
};
});
interface SharedBootstrapInput {
readonly bootstrapToken: string;
readonly observabilitySettings: BackendObservabilitySettings;
}
interface WslPreflightSuccess {
readonly _tag: "Ready";
readonly runningDistro: string;
readonly linuxEntryPath: string;
// Absolute path to the node binary the preflight validated after the shared
// remote resolver repaired PATH. The launch must use this exact path so it
// doesn't fall through to a different/old node than the one node-pty was
// built against.
readonly nodePath: string;
// PATH captured from the same login shell after the shared resolver loaded
// version managers. The launch forwards this value directly without a shell.
readonly resolvedPath: string;
}
interface WslPreflightFailure {
readonly _tag: "Failed";
readonly reason: string;
// Fatal: the WSL distro is misconfigured (no node, wrong version, missing
// build tools) and retrying won't help — surface it and (wsl-only) fall back
// to Windows. Non-fatal: transient (WSL not ready yet, wslpath while it
// boots), with a bounded window for self-healing before fallback.
readonly fatal: boolean;
readonly retryLimit?: number;
}
const WSL_TRANSIENT_PREFLIGHT_RETRY_LIMIT = 12;
const runWslPreflight = Effect.fn("desktop.backendConfiguration.wslPreflight")(function* (input: {
readonly distro: string | null;
readonly windowsEntryPath: string;
readonly windowsRepoRoot: string;
readonly allowBuild: boolean;
}): Effect.fn.Return<
WslPreflightSuccess | WslPreflightFailure,
never,
DesktopWslEnvironment.DesktopWslEnvironment | FileSystem.FileSystem
> {
const wslEnv = yield* DesktopWslEnvironment.DesktopWslEnvironment;
const fileSystem = yield* FileSystem.FileSystem;
const wslAvailable = yield* wslEnv.isAvailable;
if (!wslAvailable) {
return {
_tag: "Failed",
reason: "WSL is not available on this system",
fatal: false,
} as const;
}
const distroProbe = yield* wslEnv.probeDistros.pipe(
Effect.map((distros) => ({ _tag: "Success", distros }) as const),
Effect.catch((error) => Effect.succeed({ _tag: "Failure", error } as const)),
);
if (distroProbe._tag === "Failure") {
return {
_tag: "Failed",
reason: `Unable to list WSL distributions: ${distroProbe.error.message}`,
fatal: false,
} as const;
}
const installedDistros = distroProbe.distros;
const runningDistro = input.distro
? (installedDistros.find(
(installed) => installed.name.toLowerCase() === input.distro?.toLowerCase(),
)?.name ?? null)
: (installedDistros.find((installed) => installed.isDefault)?.name ?? null);
if (runningDistro === null) {
return {
_tag: "Failed",
reason: input.distro
? `WSL distro is not installed: ${input.distro}`
: installedDistros.length === 0
? "WSL has no installed distributions"
: "WSL has no default distribution",
fatal: true,
} as const;
}
const entryExists = yield* fileSystem
.exists(input.windowsEntryPath)
.pipe(Effect.orElseSucceed(() => false));
if (!entryExists) {
return {
_tag: "Failed",
reason: `missing server entry at ${input.windowsEntryPath}`,
fatal: true,
} as const;
}
const linuxEntry = yield* wslEnv.windowsToWslPath(runningDistro, input.windowsEntryPath);
if (Option.isNone(linuxEntry)) {
return {
_tag: "Failed",
reason: `wslpath conversion failed for ${input.windowsEntryPath}`,
fatal: false,
} as const;
}
const nodePtyResult = yield* wslEnv.ensureNodePty(runningDistro, input.windowsRepoRoot, {
allowBuild: input.allowBuild,
nodeEngineRange: serverPackageJson.engines.node,
});
if (!nodePtyResult.ok) {
return {
_tag: "Failed",
reason: `WSL node-pty unavailable: ${nodePtyResult.reason}`,
fatal: nodePtyResult.fatal,
...(nodePtyResult.retryLimit === undefined ? {} : { retryLimit: nodePtyResult.retryLimit }),
} as const;
}
return {
_tag: "Ready",
runningDistro,
linuxEntryPath: linuxEntry.value,
nodePath: nodePtyResult.nodePath,
resolvedPath: nodePtyResult.resolvedPath,
} as const;
});
// True when the given IPv4 belongs to a Windows-side network
// interface. In WSL2 mirrored mode the distro's eth0 IP equals the
// host's, which is the signature we use to detect that mode and
// switch the renderer URL to loopback.
const isLocalHostIpv4 = (ip: string): boolean => {
const interfaces = NodeOS.networkInterfaces();
for (const list of Object.values(interfaces)) {
if (!list) continue;
for (const entry of list) {
// os.networkInterfaces() reports IPv4 `family` as the string "IPv4" on
// the Node build Electron ships (41 / Node 22, verified), but some Node
// builds report the numeric 4. Normalize to a string so a future runtime
// bump can't silently break mirrored-mode detection and leave the
// renderer pointed at the distro IP instead of loopback.
const family = String(entry.family);
if ((family === "IPv4" || family === "4") && entry.address === ip) return true;
}
}
return false;
};
const buildObservabilityFragment = (observabilitySettings: BackendObservabilitySettings) => ({
...Option.match(observabilitySettings.otlpTracesUrl, {
onNone: () => ({}),
onSome: (otlpTracesUrl) => ({ otlpTracesUrl }),
}),
...Option.match(observabilitySettings.otlpMetricsUrl, {
onNone: () => ({}),
onSome: (otlpMetricsUrl) => ({ otlpMetricsUrl }),
}),
});
const resolvePrimaryStartConfig = Effect.fn("desktop.backendConfiguration.resolvePrimary")(
function* (
input: SharedBootstrapInput,
): Effect.fn.Return<
const resolveBackendStartConfig = Effect.fn("desktop.backendConfiguration.resolveStartConfig")(
function* (input: {
readonly bootstrapToken: string;
readonly observabilitySettings: BackendObservabilitySettings;
}): Effect.fn.Return<
DesktopBackendManager.DesktopBackendStartConfig,
never,
DesktopEnvironment.DesktopEnvironment | DesktopServerExposure.DesktopServerExposure
@@ -336,350 +92,70 @@ const resolvePrimaryStartConfig = Effect.fn("desktop.backendConfiguration.resolv
const serverExposure = yield* DesktopServerExposure.DesktopServerExposure;
const backendExposure = yield* serverExposure.backendConfig;
const bootstrap = {
mode: "desktop" as const,
noBrowser: true,
port: backendExposure.port,
t3Home: environment.baseDir,
host: backendExposure.bindHost,
desktopBootstrapToken: input.bootstrapToken,
tailscaleServeEnabled: backendExposure.tailscaleServeEnabled,
tailscaleServePort: backendExposure.tailscaleServePort,
...buildObservabilityFragment(input.observabilitySettings),
};
return {
executablePath: process.execPath,
args: [environment.backendEntryPath, "--bootstrap-fd", "3"],
entryPath: environment.backendEntryPath,
cwd: environment.backendCwd,
env: {
...backendChildEnvPatch(),
ELECTRON_RUN_AS_NODE: "1",
},
// Primary wants process.env (PATH, dev-runner's T3CODE_HOME, etc.).
extendEnv: true,
bootstrap,
bootstrapDelivery: "fd3",
bootstrap: {
mode: "desktop",
noBrowser: true,
port: backendExposure.port,
t3Home: environment.baseDir,
host: backendExposure.bindHost,
desktopBootstrapToken: input.bootstrapToken,
tailscaleServeEnabled: backendExposure.tailscaleServeEnabled,
tailscaleServePort: backendExposure.tailscaleServePort,
...Option.match(input.observabilitySettings.otlpTracesUrl, {
onNone: () => ({}),
onSome: (otlpTracesUrl) => ({ otlpTracesUrl }),
}),
...Option.match(input.observabilitySettings.otlpMetricsUrl, {
onNone: () => ({}),
onSome: (otlpMetricsUrl) => ({ otlpMetricsUrl }),
}),
},
httpBaseUrl: backendExposure.httpBaseUrl,
captureOutput: true,
preflightFailure: Option.none(),
} satisfies DesktopBackendManager.DesktopBackendStartConfig;
};
},
);
const resolveWslStartConfig = Effect.fn("desktop.backendConfiguration.resolveWsl")(function* (
input: SharedBootstrapInput & {
readonly port: number;
readonly distro: string | null;
},
): Effect.fn.Return<
DesktopBackendManager.DesktopBackendStartConfig,
never,
| DesktopEnvironment.DesktopEnvironment
| DesktopWslEnvironment.DesktopWslEnvironment
| FileSystem.FileSystem
> {
const environment = yield* DesktopEnvironment.DesktopEnvironment;
const wslEnvironment = yield* DesktopWslEnvironment.DesktopWslEnvironment;
// Bind to 0.0.0.0 inside WSL so the backend is reachable both via
// WSL2's automatic localhost forwarding (wslhost: Windows 127.0.0.1
// -> WSL 127.0.0.1) AND via the distro's eth0 IP directly from
// Windows. wslhost forwarding is unreliable on some Windows hosts:
// the desktop's readiness probe and the renderer's saved-env-style
// fetch both saw "Failed to fetch" when the backend only bound to
// 127.0.0.1 inside WSL. Binding to 0.0.0.0 plus advertising the
// WSL IP as the renderer-visible URL avoids that dependency.
// Security-wise this is acceptable for the local-only WSL backend:
// the network it exposes on is the WSL-vEthernet network, not the
// LAN; the primary owns LAN exposure when the user opts in.
const wslBindHost = "0.0.0.0";
const bootstrap = {
mode: "desktop" as const,
noBrowser: true,
port: input.port,
// Omit t3Home so the Linux backend uses its own home dir instead of
// the Windows-side baseDir (which would be a /mnt/c path and share
// the SQLite file with the primary).
host: wslBindHost,
desktopBootstrapToken: input.bootstrapToken,
// PortSchema rejects 0, so when tailscale serve is disabled we still
// need a valid number in this slot. The backend reads tailscaleServePort
// only when tailscaleServeEnabled is true, so the actual value here is
// inert.
tailscaleServeEnabled: false,
tailscaleServePort: 443,
...buildObservabilityFragment(input.observabilitySettings),
};
// In packaged builds environment.appRoot is .../resources/app.asar — an
// archive FILE. The Windows primary reads its entry through
// ELECTRON_RUN_AS_NODE (asar-aware), but the WSL backend launches plain
// `wsl.exe -- node`, which can't read inside an asar. electron-builder unpacks
// the server bundle + node-pty (see asarUnpack in build-desktop-artifact.ts)
// to the app.asar.unpacked sibling, so point WSL there. In dev appRoot is
// already a real directory, so this is a no-op.
const wslAppRoot = environment.isPackaged
? environment.path.join(environment.resourcesPath, "app.asar.unpacked")
: environment.appRoot;
const wslEntryPath = environment.path.join(wslAppRoot, "apps/server/dist/bin.mjs");
const preflight = yield* runWslPreflight({
distro: input.distro,
windowsEntryPath: wslEntryPath,
windowsRepoRoot: wslAppRoot,
// Packaged builds ship a prebuilt Linux node-pty (built on Linux in CI and
// attached to the Windows artifact — see build-desktop-artifact.ts), so the
// WSL backend never needs a compiler, node-gyp, or network on first launch.
// Compiling from source is a dev-only convenience: a checkout has no shipped
// prebuilt, and developers have the toolchain. In packaged builds we instead
// surface a clear diagnostic if the prebuilt can't load (unsupported
// arch/distro), rather than silently dropping into a fragile runtime build.
allowBuild: !environment.isPackaged,
});
// Every operation after preflight uses the same concrete distro. In
// default-tracking mode this closes the race where the system default
// changes between probing and spawning the backend.
const runningDistro = preflight._tag === "Ready" ? preflight.runningDistro : null;
const distroForConfig = runningDistro ?? input.distro;
// Resolve the selected distro's IPv4 address. In mirrored mode the distro
// reports a host interface, so use loopback instead; a failed probe also
// falls back to loopback and preserves the previous behavior.
const distroIp = yield* wslEnvironment.getDistroIp(distroForConfig);
const usesSharedNetworkStack = Option.match(distroIp, {
onNone: () => false,
onSome: (ip) => isLocalHostIpv4(ip),
});
const rendererHost = usesSharedNetworkStack
? "127.0.0.1"
: Option.getOrElse(distroIp, () => "127.0.0.1");
const httpBaseUrl = new URL(`http://${rendererHost}:${input.port}`);
const distroArgs = distroForConfig ? ["-d", distroForConfig] : [];
const forwardedEnv: Record<string, string> = {};
const forwardedEnvNames: string[] = [];
for (const name of WSL_FORWARDED_ENV_NAMES) {
const value = process.env[name];
if (value !== undefined && value.length > 0) {
forwardedEnv[name] = value;
forwardedEnvNames.push(name);
}
}
// Build an explicit copy of process.env minus T3CODE_HOME (dev-runner
// exports the Windows-side base dir for the primary; if it leaks into
// the WSL backend the Linux side ends up sharing C:\Users\...\.t3 via
// /mnt/c, which means both backends read/write the same database and
// their env-ids collide).
const parentEnvWithoutT3Home: Record<string, string | undefined> = {};
for (const [key, value] of Object.entries(process.env)) {
if (key === "T3CODE_HOME") continue;
parentEnvWithoutT3Home[key] = value;
}
const wslEnv = mergeWslEnv(parentEnvWithoutT3Home.WSLENV, forwardedEnvNames);
const baseConfig = {
executablePath: "wsl.exe",
entryPath: wslEntryPath,
cwd: environment.backendCwd,
env: {
...parentEnvWithoutT3Home,
...backendChildEnvPatch(),
...forwardedEnv,
...(wslEnv !== undefined ? { WSLENV: wslEnv } : {}),
},
// env is already a complete process.env minus T3CODE_HOME; pass it
// verbatim instead of letting the spawner re-merge process.env on top.
extendEnv: false,
bootstrap,
bootstrapDelivery: "stdin" as const,
httpBaseUrl,
captureOutput: true,
...(runningDistro !== null ? { runningDistro } : {}),
};
// Forward the dev-server URL as an explicit CLI flag so the WSL backend's
// config resolution lands in dev/ instead of userdata/. Inheriting through
// WSLENV is unreliable in practice (URL-shaped values with colons /
// slashes get translated unpredictably depending on flags), and the
// packaged build leaves devServerUrl as None anyway.
const devUrlArgs = Option.match(environment.devServerUrl, {
onNone: () => [] as ReadonlyArray<string>,
onSome: (url) => ["--dev-url", url.href],
});
if (preflight._tag === "Failed") {
const retryLimit =
preflight.retryLimit ?? (preflight.fatal ? undefined : WSL_TRANSIENT_PREFLIGHT_RETRY_LIMIT);
return {
...baseConfig,
args: [...distroArgs, "--", "node", "--version"],
preflightFailure: Option.some({
reason: preflight.reason,
fatal: preflight.fatal,
...(retryLimit === undefined ? {} : { retryLimit }),
}),
} satisfies DesktopBackendManager.DesktopBackendStartConfig;
}
// The WSL server spawns commands its providers reference by name — `npm`/`npx`
// for provider updates, and the installed CLIs themselves (e.g. `codex`). Those
// live in the resolved Node's bin dir, which `wsl.exe -- node` does NOT put on
// the process PATH, so `npm install -g ...` fails with NotFound. Pass the
// user PATH entries captured by the login-shell preflight. Every dynamic
// value is a separate argv entry under `wsl.exe --exec`; no shell command is
// involved, so Windows cannot mangle nested quotes and stdin remains reserved
// for the bootstrap envelope.
const lastSlash = preflight.nodePath.lastIndexOf("/");
const nodeBinDir = lastSlash > 0 ? preflight.nodePath.slice(0, lastSlash) : "/usr/bin";
const launchPath = `${nodeBinDir}:${WSL_SERVER_SYSTEM_PATH}:${preflight.resolvedPath}`;
return {
...baseConfig,
args: [
...distroArgs,
"--exec",
"env",
`PATH=${launchPath}`,
preflight.nodePath,
preflight.linuxEntryPath,
"--bootstrap-fd",
"0",
...devUrlArgs,
],
preflightFailure: Option.none(),
} satisfies DesktopBackendManager.DesktopBackendStartConfig;
});
export const make = Effect.gen(function* () {
const environment = yield* DesktopEnvironment.DesktopEnvironment;
const fileSystem = yield* FileSystem.FileSystem;
const serverExposure = yield* DesktopServerExposure.DesktopServerExposure;
const wslEnvironment = yield* DesktopWslEnvironment.DesktopWslEnvironment;
const settings = yield* DesktopAppSettings.DesktopAppSettings;
const crypto = yield* Crypto.Crypto;
// SynchronizedRef (not a plain Ref) so the read-generate-write is atomic.
// crypto.randomBytes is a yield point, and resolvePrimary + resolveWsl can
// resolve concurrently; with a plain Ref both could observe None, generate
// distinct tokens, and one would overwrite the other — leaving the two
// backends holding mismatched tokens and breaking the shared-token
// invariant the renderer relies on. modifyEffect serializes the whole
// get-or-create so the first caller wins and the rest reuse its token.
const tokenRef = yield* SynchronizedRef.make(Option.none<string>());
const getOrCreateBootstrapToken = SynchronizedRef.modifyEffect(tokenRef, (current) =>
Option.match(current, {
onSome: (token) => Effect.succeed([token, current] as const),
onNone: () =>
crypto.randomBytes(24).pipe(
Effect.map((bytes) => {
const token = Encoding.encodeHex(bytes);
return [token, Option.some(token)] as const;
}),
),
}),
);
const tokenRef = yield* Ref.make(Option.none<string>());
const getOrCreateBootstrapToken = Effect.gen(function* () {
const existing = yield* Ref.get(tokenRef);
if (Option.isSome(existing)) {
return existing.value;
}
// Both resolvers share the same bootstrap token: the renderer holds a
// single token and uses it against whichever backend it's currently
// talking to. Observability settings get re-read each resolve so a
// hot-swap of the server-settings file is picked up on the next
// restart cycle without having to bounce the desktop process.
const sharedInputs = Effect.gen(function* () {
const bootstrapToken = yield* getOrCreateBootstrapToken;
const observabilitySettings = yield* readPersistedBackendObservabilitySettings.pipe(
Effect.provideService(FileSystem.FileSystem, fileSystem),
Effect.provideService(DesktopEnvironment.DesktopEnvironment, environment),
);
return { bootstrapToken, observabilitySettings } satisfies SharedBootstrapInput;
});
const buildWslPrimaryConfig = Effect.gen(function* () {
// wsl-only mode pipes the WSL backend through the same port the
// Windows primary would normally take. That way the renderer
// still loads from the local-only endpoint advertised by
// DesktopServerExposure, and primary-aware code paths (cookie
// auth, the env switcher's "primary" id) keep working without
// a parallel "secondary" registration.
const backendExposure = yield* serverExposure.backendConfig;
const persistedSettings = yield* settings.get;
const shared = yield* sharedInputs;
yield* wslEnvironment.preWarm(persistedSettings.wslDistro);
return yield* resolveWslStartConfig({
...shared,
port: backendExposure.port,
distro: persistedSettings.wslDistro,
}).pipe(
Effect.provideService(DesktopEnvironment.DesktopEnvironment, environment),
Effect.provideService(DesktopWslEnvironment.DesktopWslEnvironment, wslEnvironment),
Effect.provideService(FileSystem.FileSystem, fileSystem),
);
});
const buildWindowsPrimaryConfig = Effect.gen(function* () {
const shared = yield* sharedInputs;
return yield* resolvePrimaryStartConfig(shared).pipe(
Effect.provideService(DesktopEnvironment.DesktopEnvironment, environment),
Effect.provideService(DesktopServerExposure.DesktopServerExposure, serverExposure),
);
});
// Single source of truth for what the primary actually runs as. Both
// the start-config dispatch and the renderer-facing label derive from
// this, so they can't disagree — e.g. the label reading "WSL" while the
// config silently fell back to Windows because WSL is unavailable.
// Dispatch happens at resolve time so toggling wsl-only between restarts
// is picked up on the next start cycle (the pool's primary instance is
// created once at layer init, but configResolve fires on each restart).
const describePrimary = Effect.gen(function* () {
const persistedSettings = yield* settings.get;
const wslRequested = persistedSettings.wslOnly && persistedSettings.wslBackendEnabled;
// Only honor wsl-only when WSL is actually usable. If the user
// persisted wsl-only but WSL has since become unavailable (wsl.exe
// removed, no distro), fall back to the Windows primary instead of
// looping forever on preflight failures: the Connections backend
// control is hidden while WSL is unavailable, so a stuck WSL primary
// would otherwise leave no in-app way back to Windows.
const useWsl = wslRequested && (yield* wslEnvironment.isAvailable);
return { useWsl, wslRequested, distro: persistedSettings.wslDistro };
const token = Encoding.encodeHex(yield* crypto.randomBytes(24));
yield* Ref.set(tokenRef, Option.some(token));
return token;
});
return DesktopBackendConfiguration.of({
resolvePrimary: Effect.gen(function* () {
const { useWsl, wslRequested } = yield* describePrimary;
if (useWsl) {
return yield* buildWslPrimaryConfig;
}
if (wslRequested) {
yield* Effect.logWarning(
"WSL-only backend requested but WSL is unavailable; starting the Windows primary instead.",
);
}
return yield* buildWindowsPrimaryConfig;
}).pipe(Effect.withSpan("desktop.backendConfiguration.resolvePrimary")),
resolvePrimaryLabel: Effect.gen(function* () {
const { useWsl, distro } = yield* describePrimary;
if (!useWsl) {
return environment.platform === "win32" ? "Windows" : "Local environment";
}
return distro ? `WSL (${distro})` : "WSL";
}).pipe(Effect.withSpan("desktop.backendConfiguration.resolvePrimaryLabel")),
resolveWsl: (input) =>
Effect.gen(function* () {
const shared = yield* sharedInputs;
return yield* resolveWslStartConfig({ ...shared, ...input }).pipe(
Effect.provideService(DesktopEnvironment.DesktopEnvironment, environment),
Effect.provideService(DesktopWslEnvironment.DesktopWslEnvironment, wslEnvironment),
Effect.provideService(FileSystem.FileSystem, fileSystem),
);
resolve: Effect.gen(function* () {
const bootstrapToken = yield* getOrCreateBootstrapToken;
const observabilitySettings = yield* readPersistedBackendObservabilitySettings.pipe(
Effect.provideService(FileSystem.FileSystem, fileSystem),
Effect.provideService(DesktopEnvironment.DesktopEnvironment, environment),
);
return yield* resolveBackendStartConfig({
bootstrapToken,
observabilitySettings,
}).pipe(
Effect.withSpan("desktop.backendConfiguration.resolveWsl", {
attributes: { port: input.port, distro: input.distro ?? null },
}),
),
Effect.provideService(DesktopEnvironment.DesktopEnvironment, environment),
Effect.provideService(DesktopServerExposure.DesktopServerExposure, serverExposure),
);
}).pipe(Effect.withSpan("desktop.backendConfiguration.resolve")),
});
});
@@ -20,7 +20,10 @@ import { HttpClient, HttpClientRequest, HttpClientResponse } from "effect/unstab
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
import * as DesktopBackendManager from "./DesktopBackendManager.ts";
import * as DesktopBackendConfiguration from "./DesktopBackendConfiguration.ts";
import * as DesktopObservability from "../app/DesktopObservability.ts";
import * as DesktopState from "../app/DesktopState.ts";
import * as DesktopWindow from "../window/DesktopWindow.ts";
const decodeDesktopBackendBootstrap = Schema.decodeEffect(
Schema.fromJsonString(DesktopBackendBootstrap),
@@ -28,7 +31,6 @@ const decodeDesktopBackendBootstrap = Schema.decodeEffect(
const baseConfig: DesktopBackendManager.DesktopBackendStartConfig = {
executablePath: "/electron",
args: ["/server/bin.mjs", "--bootstrap-fd", "3"],
entryPath: "/server/bin.mjs",
cwd: "/server",
env: { ELECTRON_RUN_AS_NODE: "1" },
@@ -42,11 +44,8 @@ const baseConfig: DesktopBackendManager.DesktopBackendStartConfig = {
tailscaleServeEnabled: false,
tailscaleServePort: 443,
},
bootstrapDelivery: "fd3",
extendEnv: true,
httpBaseUrl: new URL("http://127.0.0.1:3773"),
captureOutput: true,
preflightFailure: Option.none(),
};
const configWithObservability: DesktopBackendBootstrapValue = {
@@ -102,98 +101,97 @@ function decodeBootstrap(raw: string) {
return decodeDesktopBackendBootstrap(raw);
}
interface MakeInstanceInput {
function makeManagerLayer(input: {
readonly spawnerLayer: Layer.Layer<ChildProcessSpawner.ChildProcessSpawner>;
readonly httpClientLayer?: Layer.Layer<HttpClient.HttpClient>;
readonly backendOutputLog?: Partial<DesktopObservability.DesktopBackendOutputLogShape>;
readonly onReady?: Effect.Effect<void>;
readonly onShutdown?: Effect.Effect<void>;
readonly onPreflightFailed?: (
failure: DesktopBackendManager.PreflightFailure,
) => Effect.Effect<boolean>;
readonly backendOutputLog?: Partial<DesktopObservability.DesktopBackendOutputLog["Service"]>;
readonly desktopState?: DesktopState.DesktopState["Service"];
readonly desktopWindow?: Partial<DesktopWindow.DesktopWindow["Service"]>;
readonly config?: DesktopBackendManager.DesktopBackendStartConfig;
readonly configResolve?: Effect.Effect<DesktopBackendManager.DesktopBackendStartConfig>;
}
// Helper that constructs a primary backend instance using the factory
// directly. The factory's deps (FileSystem, ChildProcessSpawner,
// HttpClient, DesktopBackendOutputLogFactory) are provided per-test via
// a scoped layer; tests yield the returned Effect inside `Effect.scoped`
// to drive the instance's lifecycle.
function makeTestInstance(input: MakeInstanceInput) {
const stubLog: DesktopObservability.DesktopBackendOutputLogShape = {
writeSessionBoundary: () => Effect.void,
writeOutputChunk: () => Effect.void,
...input.backendOutputLog,
};
const servicesLayer = Layer.mergeAll(
FileSystem.layerNoop({
exists: () => Effect.succeed(true),
}),
input.spawnerLayer,
input.httpClientLayer ?? healthyHttpClientLayer,
Layer.succeed(DesktopObservability.DesktopBackendOutputLogFactory, {
forInstance: () => Effect.succeed(stubLog),
} satisfies DesktopObservability.DesktopBackendOutputLogFactory["Service"]),
}) {
return DesktopBackendManager.layer.pipe(
Layer.provide(
Layer.mergeAll(
FileSystem.layerNoop({
exists: () => Effect.succeed(true),
}),
Layer.succeed(DesktopBackendConfiguration.DesktopBackendConfiguration, {
resolve: Effect.succeed(input.config ?? baseConfig),
}),
input.spawnerLayer,
input.httpClientLayer ?? healthyHttpClientLayer,
input.desktopState
? Layer.succeed(DesktopState.DesktopState, input.desktopState)
: DesktopState.layer,
Layer.succeed(DesktopObservability.DesktopBackendOutputLog, {
writeSessionBoundary: () => Effect.void,
writeOutputChunk: () => Effect.void,
...input.backendOutputLog,
} satisfies DesktopObservability.DesktopBackendOutputLog["Service"]),
Layer.succeed(DesktopWindow.DesktopWindow, {
createMain: Effect.die("unexpected createMain"),
ensureMain: Effect.die("unexpected ensureMain"),
revealOrCreateMain: Effect.die("unexpected revealOrCreateMain"),
activate: Effect.void,
createMainIfBackendReady: Effect.void,
handleBackendReady: Effect.void,
dispatchMenuAction: () => Effect.void,
syncAppearance: Effect.void,
...input.desktopWindow,
} satisfies DesktopWindow.DesktopWindow["Service"]),
),
),
);
const instance = DesktopBackendManager.makeBackendInstance({
id: DesktopBackendManager.PRIMARY_INSTANCE_ID,
label: Effect.succeed("Windows"),
configResolve: input.configResolve ?? Effect.succeed(input.config ?? baseConfig),
...(input.onReady ? { onReady: () => input.onReady! } : {}),
...(input.onShutdown ? { onShutdown: () => input.onShutdown! } : {}),
...(input.onPreflightFailed ? { onPreflightFailed: input.onPreflightFailed } : {}),
});
return instance.pipe(Effect.provide(servicesLayer));
}
describe("DesktopBackendManager", () => {
it.effect("spawns the backend with fd3 bootstrap JSON and reports HTTP readiness", () =>
Effect.scoped(
Effect.gen(function* () {
let spawnedCommand: ChildProcess.Command | undefined;
let bootstrapJson = "";
let readyCount = 0;
const ready = yield* Deferred.make<void>();
const exited = yield* Queue.unbounded<void>();
Effect.gen(function* () {
let spawnedCommand: ChildProcess.Command | undefined;
let bootstrapJson = "";
let readyCount = 0;
const ready = yield* Deferred.make<void>();
const exited = yield* Queue.unbounded<void>();
const spawnerLayer = Layer.succeed(
ChildProcessSpawner.ChildProcessSpawner,
ChildProcessSpawner.make((command) =>
Effect.gen(function* () {
spawnedCommand = command;
if (command._tag === "StandardCommand") {
const fd3 = command.options.additionalFds?.fd3;
if (fd3?.type === "input" && fd3.stream) {
bootstrapJson = yield* fd3.stream.pipe(Stream.decodeText(), Stream.mkString);
}
const spawnerLayer = Layer.succeed(
ChildProcessSpawner.ChildProcessSpawner,
ChildProcessSpawner.make((command) =>
Effect.gen(function* () {
spawnedCommand = command;
if (command._tag === "StandardCommand") {
const fd3 = command.options.additionalFds?.fd3;
if (fd3?.type === "input" && fd3.stream) {
bootstrapJson = yield* fd3.stream.pipe(Stream.decodeText(), Stream.mkString);
}
}
return makeProcess({
exitCode: Deferred.await(ready).pipe(Effect.as(ChildProcessSpawner.ExitCode(0))),
});
}),
),
);
return makeProcess({
exitCode: Deferred.await(ready).pipe(Effect.as(ChildProcessSpawner.ExitCode(0))),
});
}),
),
);
const instance = yield* makeTestInstance({
config: {
...baseConfig,
bootstrap: configWithObservability,
},
spawnerLayer,
onReady: Effect.sync(() => {
const managerLayer = makeManagerLayer({
config: {
...baseConfig,
bootstrap: configWithObservability,
},
spawnerLayer,
desktopWindow: {
handleBackendReady: Effect.sync(() => {
readyCount += 1;
}).pipe(Effect.andThen(Deferred.succeed(ready, void 0)), Effect.asVoid),
backendOutputLog: {
writeSessionBoundary: ({ phase }) =>
phase === "END" ? Queue.offer(exited, void 0).pipe(Effect.asVoid) : Effect.void,
},
});
}).pipe(Effect.andThen(Deferred.succeed(ready, void 0))),
},
backendOutputLog: {
writeSessionBoundary: ({ phase }) =>
phase === "END" ? Queue.offer(exited, void 0).pipe(Effect.asVoid) : Effect.void,
},
});
yield* instance.start;
yield* Effect.gen(function* () {
const manager = yield* DesktopBackendManager.DesktopBackendManager;
yield* manager.start;
yield* Queue.take(exited);
assert.equal(readyCount, 1);
@@ -216,52 +214,55 @@ describe("DesktopBackendManager", () => {
);
assert.deepEqual(yield* decodeBootstrap(bootstrapJson), configWithObservability);
}),
),
}).pipe(Effect.provide(managerLayer));
}),
);
it.effect("retries HTTP readiness before reporting the backend ready", () =>
Effect.scoped(
Effect.gen(function* () {
const requestUrls: Array<string> = [];
const statuses = [503, 200];
let readyCount = 0;
const firstRequest = yield* Deferred.make<void>();
const ready = yield* Deferred.make<void>();
const exited = yield* Queue.unbounded<void>();
Effect.gen(function* () {
const requestUrls: Array<string> = [];
const statuses = [503, 200];
let readyCount = 0;
const firstRequest = yield* Deferred.make<void>();
const ready = yield* Deferred.make<void>();
const exited = yield* Queue.unbounded<void>();
const spawnerLayer = Layer.succeed(
ChildProcessSpawner.ChildProcessSpawner,
ChildProcessSpawner.make(() =>
Effect.succeed(
makeProcess({
exitCode: Deferred.await(ready).pipe(Effect.as(ChildProcessSpawner.ExitCode(0))),
}),
),
),
);
const instance = yield* makeTestInstance({
spawnerLayer,
httpClientLayer: httpClientLayer((request) =>
Effect.gen(function* () {
const status = statuses.shift();
assert.isDefined(status);
requestUrls.push(request.url);
yield* Deferred.succeed(firstRequest, void 0);
return responseForRequest(request, status);
const spawnerLayer = Layer.succeed(
ChildProcessSpawner.ChildProcessSpawner,
ChildProcessSpawner.make(() =>
Effect.succeed(
makeProcess({
exitCode: Deferred.await(ready).pipe(Effect.as(ChildProcessSpawner.ExitCode(0))),
}),
),
onReady: Effect.sync(() => {
readyCount += 1;
}).pipe(Effect.andThen(Deferred.succeed(ready, void 0)), Effect.asVoid),
backendOutputLog: {
writeSessionBoundary: ({ phase }) =>
phase === "END" ? Queue.offer(exited, void 0).pipe(Effect.asVoid) : Effect.void,
},
});
),
);
yield* instance.start;
const managerLayer = makeManagerLayer({
spawnerLayer,
httpClientLayer: httpClientLayer((request) =>
Effect.gen(function* () {
const status = statuses.shift();
assert.isDefined(status);
requestUrls.push(request.url);
yield* Deferred.succeed(firstRequest, void 0);
return responseForRequest(request, status);
}),
),
desktopWindow: {
handleBackendReady: Effect.sync(() => {
readyCount += 1;
}).pipe(Effect.andThen(Deferred.succeed(ready, void 0))),
},
backendOutputLog: {
writeSessionBoundary: ({ phase }) =>
phase === "END" ? Queue.offer(exited, void 0).pipe(Effect.asVoid) : Effect.void,
},
});
yield* Effect.gen(function* () {
const manager = yield* DesktopBackendManager.DesktopBackendManager;
yield* manager.start;
yield* Deferred.await(firstRequest);
assert.equal(readyCount, 0);
@@ -275,136 +276,106 @@ describe("DesktopBackendManager", () => {
"http://127.0.0.1:3773/.well-known/t3/environment",
"http://127.0.0.1:3773/.well-known/t3/environment",
]);
}).pipe(Effect.provide(TestClock.layer())),
),
}).pipe(Effect.provide(Layer.merge(TestClock.layer(), managerLayer)));
}),
);
it.effect("starts the configured backend and closes the scoped process on stop", () =>
Effect.scoped(
Effect.gen(function* () {
let startCount = 0;
let closedCount = 0;
const closed = yield* Deferred.make<void>();
const startedPids = yield* Queue.unbounded<number>();
const ready = yield* Deferred.make<void>();
const backendReadyFlag = yield* Ref.make(false);
Effect.gen(function* () {
let startCount = 0;
let closedCount = 0;
const closed = yield* Deferred.make<void>();
const startedPids = yield* Queue.unbounded<number>();
const ready = yield* Deferred.make<void>();
const backendReady = yield* Ref.make(false);
const quitting = yield* Ref.make(false);
const spawnerLayer = Layer.succeed(
ChildProcessSpawner.ChildProcessSpawner,
ChildProcessSpawner.make(() =>
Effect.gen(function* () {
const scope = yield* Scope.Scope;
startCount += 1;
yield* Queue.offer(startedPids, 123);
const close = Effect.sync(() => {
closedCount += 1;
}).pipe(Effect.andThen(Deferred.succeed(closed, void 0)), Effect.asVoid);
const spawnerLayer = Layer.succeed(
ChildProcessSpawner.ChildProcessSpawner,
ChildProcessSpawner.make(() =>
Effect.gen(function* () {
const scope = yield* Scope.Scope;
startCount += 1;
yield* Queue.offer(startedPids, 123);
const close = Effect.sync(() => {
closedCount += 1;
}).pipe(Effect.andThen(Deferred.succeed(closed, void 0)), Effect.asVoid);
yield* Scope.addFinalizer(scope, close);
yield* Scope.addFinalizer(scope, close);
return makeProcess({
exitCode: Deferred.await(closed).pipe(Effect.as(ChildProcessSpawner.ExitCode(0))),
kill: () => close,
});
}),
),
);
return makeProcess({
exitCode: Deferred.await(closed).pipe(Effect.as(ChildProcessSpawner.ExitCode(0))),
kill: () => close,
});
}),
),
);
const instance = yield* makeTestInstance({
spawnerLayer,
onReady: Ref.set(backendReadyFlag, true).pipe(
Effect.andThen(Deferred.succeed(ready, void 0)),
Effect.asVoid,
),
onShutdown: Ref.set(backendReadyFlag, false),
});
assert.isTrue(Option.isNone(yield* instance.currentConfig));
const managerLayer = makeManagerLayer({
spawnerLayer,
desktopState: {
backendReady,
quitting,
},
desktopWindow: {
handleBackendReady: Deferred.succeed(ready, void 0).pipe(Effect.asVoid),
},
});
yield* instance.start;
yield* Effect.gen(function* () {
const manager = yield* DesktopBackendManager.DesktopBackendManager;
assert.isTrue(Option.isNone(yield* manager.currentConfig));
yield* manager.start;
assert.equal(yield* Queue.take(startedPids), 123);
yield* Deferred.await(ready);
assert.isTrue(yield* Ref.get(backendReadyFlag));
assert.deepEqual(yield* instance.currentConfig, Option.some(baseConfig));
assert.isTrue(yield* Ref.get(backendReady));
assert.deepEqual(yield* manager.currentConfig, Option.some(baseConfig));
const runningSnapshot = yield* instance.snapshot;
const runningSnapshot = yield* manager.snapshot;
assert.equal(runningSnapshot.ready, true);
assert.deepEqual(runningSnapshot.activePid, Option.some(123));
yield* instance.stop();
yield* manager.stop();
assert.equal(startCount, 1);
assert.equal(closedCount, 1);
const stoppedSnapshot = yield* instance.snapshot;
assert.isFalse(yield* Ref.get(backendReadyFlag));
const stoppedSnapshot = yield* manager.snapshot;
assert.isFalse(yield* Ref.get(backendReady));
assert.equal(stoppedSnapshot.desiredRunning, false);
assert.equal(stoppedSnapshot.ready, false);
assert.equal(Option.isNone(stoppedSnapshot.activePid), true);
}),
),
);
it.effect("does not notify shutdown before the first start has prior state", () =>
Effect.scoped(
Effect.gen(function* () {
let shutdownCount = 0;
const closed = yield* Deferred.make<void>();
const startedPids = yield* Queue.unbounded<number>();
const spawnerLayer = Layer.succeed(
ChildProcessSpawner.ChildProcessSpawner,
ChildProcessSpawner.make(() =>
Effect.gen(function* () {
yield* Queue.offer(startedPids, 123);
const close = Deferred.succeed(closed, void 0).pipe(Effect.asVoid);
return makeProcess({
exitCode: Deferred.await(closed).pipe(Effect.as(ChildProcessSpawner.ExitCode(0))),
kill: () => close,
});
}),
),
);
const instance = yield* makeTestInstance({
spawnerLayer,
httpClientLayer: httpClientLayer(() => Effect.never),
onShutdown: Effect.sync(() => {
shutdownCount += 1;
}),
});
yield* instance.start;
assert.equal(yield* Queue.take(startedPids), 123);
assert.equal(shutdownCount, 0);
}),
),
}).pipe(Effect.provide(managerLayer));
}),
);
it.effect("restarts an unexpectedly exited backend with the Effect clock", () =>
Effect.scoped(
Effect.gen(function* () {
const starts = yield* Queue.unbounded<number>();
let startCount = 0;
Effect.gen(function* () {
const starts = yield* Queue.unbounded<number>();
let startCount = 0;
const spawnerLayer = Layer.succeed(
ChildProcessSpawner.ChildProcessSpawner,
ChildProcessSpawner.make(() =>
Effect.sync(() => {
startCount += 1;
return makeProcess({
exitCode: Queue.offer(starts, startCount).pipe(
Effect.as(ChildProcessSpawner.ExitCode(1)),
),
});
}),
),
);
const spawnerLayer = Layer.succeed(
ChildProcessSpawner.ChildProcessSpawner,
ChildProcessSpawner.make(() =>
Effect.sync(() => {
startCount += 1;
return makeProcess({
exitCode: Queue.offer(starts, startCount).pipe(
Effect.as(ChildProcessSpawner.ExitCode(1)),
),
});
}),
),
);
const instance = yield* makeTestInstance({
spawnerLayer,
httpClientLayer: httpClientLayer(() => Effect.never),
});
const managerLayer = makeManagerLayer({
spawnerLayer,
httpClientLayer: httpClientLayer(() => Effect.never),
});
yield* instance.start;
yield* Effect.gen(function* () {
const manager = yield* DesktopBackendManager.DesktopBackendManager;
yield* manager.start;
assert.equal(yield* Queue.take(starts), 1);
@@ -417,300 +388,107 @@ describe("DesktopBackendManager", () => {
assert.equal(yield* Queue.size(starts), 0);
yield* TestClock.adjust(Duration.millis(1));
assert.equal(yield* Queue.take(starts), 3);
}).pipe(Effect.provide(TestClock.layer())),
),
);
it.effect("does not notify shutdown when a scheduled restart starts from non-ready state", () =>
Effect.scoped(
Effect.gen(function* () {
let shutdownCount = 0;
const spawnerLayer = Layer.succeed(
ChildProcessSpawner.ChildProcessSpawner,
ChildProcessSpawner.make(() => Effect.die("unexpected backend spawn")),
);
const instance = yield* makeTestInstance({
spawnerLayer,
config: {
...baseConfig,
preflightFailure: Option.some({ reason: "preflight failed", fatal: false }),
},
onShutdown: Effect.sync(() => {
shutdownCount += 1;
}),
});
yield* instance.start;
assert.equal(shutdownCount, 0);
yield* TestClock.adjust(Duration.millis(500));
assert.equal(shutdownCount, 0);
}).pipe(Effect.provide(TestClock.layer())),
),
);
it.effect("surfaces a fatal preflight failure once and stops looping after the cap", () =>
Effect.scoped(
Effect.gen(function* () {
const failures: string[] = [];
const spawnerLayer = Layer.succeed(
ChildProcessSpawner.ChildProcessSpawner,
ChildProcessSpawner.make(() => Effect.die("unexpected backend spawn")),
);
const instance = yield* makeTestInstance({
spawnerLayer,
config: {
...baseConfig,
preflightFailure: Option.some({ reason: "Node.js not found", fatal: true }),
},
onPreflightFailed: (failure) =>
Effect.sync(() => {
failures.push(failure.reason);
}).pipe(Effect.as(false)),
});
yield* instance.start;
assert.deepEqual(failures, []);
// Five fatal attempts with exponential backoff (500ms, 1s, 2s, 4s) reach
// the cap, at which point the failure is surfaced exactly once.
yield* TestClock.adjust(Duration.millis(500));
yield* TestClock.adjust(Duration.seconds(1));
yield* TestClock.adjust(Duration.seconds(2));
yield* TestClock.adjust(Duration.seconds(4));
assert.deepEqual(failures, ["Node.js not found"]);
// Past the cap the loop stops and nothing else is surfaced.
yield* TestClock.adjust(Duration.seconds(8));
yield* TestClock.adjust(Duration.seconds(30));
assert.deepEqual(failures, ["Node.js not found"]);
}).pipe(Effect.provide(TestClock.layer())),
),
);
it.effect("can be started again after a fatal preflight cap once config recovers", () =>
Effect.scoped(
Effect.gen(function* () {
const failing = yield* Ref.make(true);
const starts = yield* Queue.unbounded<number>();
const spawnerLayer = Layer.succeed(
ChildProcessSpawner.ChildProcessSpawner,
ChildProcessSpawner.make(() =>
Queue.offer(starts, 123).pipe(
Effect.as(
makeProcess({
exitCode: Effect.never,
}),
),
),
),
);
const instance = yield* makeTestInstance({
spawnerLayer,
configResolve: Ref.get(failing).pipe(
Effect.map((isFailing) =>
isFailing
? {
...baseConfig,
preflightFailure: Option.some({
reason: "Node.js not found",
fatal: true,
}),
}
: baseConfig,
),
),
});
yield* instance.start;
yield* TestClock.adjust(Duration.millis(500));
yield* TestClock.adjust(Duration.seconds(1));
yield* TestClock.adjust(Duration.seconds(2));
yield* TestClock.adjust(Duration.seconds(4));
yield* TestClock.adjust(Duration.seconds(8));
const parked = yield* instance.snapshot;
assert.equal(parked.desiredRunning, false);
assert.equal(parked.ready, false);
assert.isTrue(Option.isNone(parked.activePid));
assert.equal(parked.restartScheduled, false);
assert.equal(yield* Queue.size(starts), 0);
yield* Ref.set(failing, false);
yield* instance.start;
assert.equal(yield* Queue.take(starts), 123);
const running = yield* instance.snapshot;
assert.equal(running.desiredRunning, true);
assert.deepEqual(running.activePid, Option.some(123));
}).pipe(Effect.provide(TestClock.layer())),
),
);
it.effect("keeps retrying a transient (non-fatal) preflight failure without surfacing", () =>
Effect.scoped(
Effect.gen(function* () {
const failures: string[] = [];
const spawnerLayer = Layer.succeed(
ChildProcessSpawner.ChildProcessSpawner,
ChildProcessSpawner.make(() => Effect.die("unexpected backend spawn")),
);
const instance = yield* makeTestInstance({
spawnerLayer,
config: {
...baseConfig,
preflightFailure: Option.some({ reason: "wslpath conversion failed", fatal: false }),
},
onPreflightFailed: (failure) =>
Effect.sync(() => {
failures.push(failure.reason);
}).pipe(Effect.as(false)),
});
yield* instance.start;
// Well beyond the fatal cap's worth of time: a transient failure must
// keep retrying (self-heal) and never surface.
yield* TestClock.adjust(Duration.minutes(2));
assert.deepEqual(failures, []);
}).pipe(Effect.provide(TestClock.layer())),
),
);
it.effect("surfaces a bounded transient preflight failure after its retry limit", () =>
Effect.scoped(
Effect.gen(function* () {
const failures: string[] = [];
const spawnerLayer = Layer.succeed(
ChildProcessSpawner.ChildProcessSpawner,
ChildProcessSpawner.make(() => Effect.die("unexpected backend spawn")),
);
const instance = yield* makeTestInstance({
spawnerLayer,
config: {
...baseConfig,
preflightFailure: Option.some({
reason: "WSL toolchain probe timed out",
fatal: false,
retryLimit: 3,
}),
},
onPreflightFailed: (failure) =>
Effect.sync(() => {
failures.push(failure.reason);
}).pipe(Effect.as(false)),
});
yield* instance.start;
yield* TestClock.adjust(Duration.millis(500));
assert.deepEqual(failures, []);
yield* TestClock.adjust(Duration.seconds(1));
assert.deepEqual(failures, ["WSL toolchain probe timed out"]);
}).pipe(Effect.provide(TestClock.layer())),
),
}).pipe(Effect.provide(Layer.merge(TestClock.layer(), managerLayer)));
}),
);
it.effect("cancels a scheduled restart when start is requested manually", () =>
Effect.scoped(
Effect.gen(function* () {
const starts = yield* Queue.unbounded<number>();
const secondClosed = yield* Deferred.make<void>();
let startCount = 0;
Effect.gen(function* () {
const starts = yield* Queue.unbounded<number>();
const secondClosed = yield* Deferred.make<void>();
let startCount = 0;
const spawnerLayer = Layer.succeed(
ChildProcessSpawner.ChildProcessSpawner,
ChildProcessSpawner.make(() =>
Effect.gen(function* () {
startCount += 1;
yield* Queue.offer(starts, startCount);
const spawnerLayer = Layer.succeed(
ChildProcessSpawner.ChildProcessSpawner,
ChildProcessSpawner.make(() =>
Effect.gen(function* () {
startCount += 1;
yield* Queue.offer(starts, startCount);
if (startCount === 1) {
return makeProcess({
exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(1)),
});
}
const scope = yield* Scope.Scope;
const close = Deferred.succeed(secondClosed, void 0).pipe(Effect.asVoid);
yield* Scope.addFinalizer(scope, close);
if (startCount === 1) {
return makeProcess({
exitCode: Deferred.await(secondClosed).pipe(
Effect.as(ChildProcessSpawner.ExitCode(0)),
),
kill: () => close,
exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(1)),
});
}),
),
);
}
const instance = yield* makeTestInstance({
spawnerLayer,
httpClientLayer: httpClientLayer(() => Effect.never),
});
const scope = yield* Scope.Scope;
const close = Deferred.succeed(secondClosed, void 0).pipe(Effect.asVoid);
yield* Scope.addFinalizer(scope, close);
return makeProcess({
exitCode: Deferred.await(secondClosed).pipe(
Effect.as(ChildProcessSpawner.ExitCode(0)),
),
kill: () => close,
});
}),
),
);
yield* instance.start;
const managerLayer = makeManagerLayer({
spawnerLayer,
httpClientLayer: httpClientLayer(() => Effect.never),
});
yield* Effect.gen(function* () {
const manager = yield* DesktopBackendManager.DesktopBackendManager;
yield* manager.start;
assert.equal(yield* Queue.take(starts), 1);
yield* instance.start;
yield* manager.start;
assert.equal(yield* Queue.take(starts), 2);
yield* instance.stop();
yield* manager.stop();
yield* TestClock.adjust(Duration.millis(500));
assert.equal(yield* Queue.size(starts), 0);
}).pipe(Effect.provide(TestClock.layer())),
),
}).pipe(Effect.provide(Layer.merge(TestClock.layer(), managerLayer)));
}),
);
it.effect("does not restart after stop cancels a scheduled restart", () =>
Effect.scoped(
Effect.gen(function* () {
const starts = yield* Queue.unbounded<number>();
let startCount = 0;
Effect.gen(function* () {
const starts = yield* Queue.unbounded<number>();
let startCount = 0;
const spawnerLayer = Layer.succeed(
ChildProcessSpawner.ChildProcessSpawner,
ChildProcessSpawner.make(() =>
Effect.sync(() => {
startCount += 1;
return makeProcess({
exitCode: Queue.offer(starts, startCount).pipe(
Effect.as(ChildProcessSpawner.ExitCode(1)),
),
});
}),
),
);
const spawnerLayer = Layer.succeed(
ChildProcessSpawner.ChildProcessSpawner,
ChildProcessSpawner.make(() =>
Effect.sync(() => {
startCount += 1;
return makeProcess({
exitCode: Queue.offer(starts, startCount).pipe(
Effect.as(ChildProcessSpawner.ExitCode(1)),
),
});
}),
),
);
const instance = yield* makeTestInstance({
spawnerLayer,
httpClientLayer: httpClientLayer(() => Effect.never),
});
const managerLayer = makeManagerLayer({
spawnerLayer,
httpClientLayer: httpClientLayer(() => Effect.never),
});
yield* instance.start;
yield* Effect.gen(function* () {
const manager = yield* DesktopBackendManager.DesktopBackendManager;
yield* manager.start;
assert.equal(yield* Queue.take(starts), 1);
let restartScheduled = false;
while (!restartScheduled) {
restartScheduled = (yield* instance.snapshot).restartScheduled;
restartScheduled = (yield* manager.snapshot).restartScheduled;
if (!restartScheduled) {
yield* Effect.yieldNow;
}
}
yield* instance.stop();
yield* manager.stop();
yield* TestClock.adjust(Duration.millis(500));
assert.equal(yield* Queue.size(starts), 0);
assert.equal((yield* instance.snapshot).desiredRunning, false);
}).pipe(Effect.provide(TestClock.layer())),
),
assert.equal((yield* manager.snapshot).desiredRunning, false);
}).pipe(Effect.provide(Layer.merge(TestClock.layer(), managerLayer)));
}),
);
});
+109 -303
View File
@@ -1,35 +1,11 @@
// Per-instance backend factory. Replaces the legacy singleton
// `DesktopBackendManager` Context.Service: each call to
// `makeBackendInstance(spec)` constructs an isolated backend lifecycle —
// its own state Ref, mutex, restart loop, and active child process. The
// returned `DesktopBackendInstance` exposes start/stop/snapshot/wait
// methods that operate on that single backend.
//
// The pool layer (`DesktopBackendPool.ts`) calls this factory once per
// backend it wants to run. Today that's the Windows primary; follow-up
// commits add a second call for the WSL instance.
//
// Singleton couplings that the legacy service held inline are now
// parameterized via the spec:
// - configResolve replaces the legacy `DesktopBackendConfiguration.resolve`
// so each instance can resolve its own start config — the primary wires
// `configuration.resolvePrimary`, the WSL orchestrator wires a
// `configuration.resolveWsl({ port, distro })` closure.
// - onReady / onShutdown drive UI side effects (window auto-open,
// readiness latch) only for instances that want them — the primary's
// spec passes the window's handleBackendReady/handleBackendNotReady,
// other pool instances pass nothing.
// - log writes go through a per-instance writer that the factory
// pulls from `DesktopBackendOutputLogFactory.forInstance(spec.id)`,
// so each instance lands in its own rotating file.
import * as Brand from "effect/Brand";
import * as Cause from "effect/Cause";
import * as Context from "effect/Context";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as Exit from "effect/Exit";
import * as Fiber from "effect/Fiber";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as PlatformError from "effect/PlatformError";
import * as Ref from "effect/Ref";
@@ -39,25 +15,22 @@ import * as Schema from "effect/Schema";
import * as Semaphore from "effect/Semaphore";
import * as Scope from "effect/Scope";
import * as Stream from "effect/Stream";
import { HttpClient } from "effect/unstable/http";
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
import * as HttpClient from "effect/unstable/http/HttpClient";
import * as ChildProcess from "effect/unstable/process/ChildProcess";
import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner";
import {
DesktopBackendBootstrap,
type DesktopBackendBootstrap as DesktopBackendBootstrapValue,
PRIMARY_LOCAL_ENVIRONMENT_ID,
} from "@t3tools/contracts";
import { waitForHttpReady as waitForHttpReadyShared } from "@t3tools/shared/httpReadiness";
import * as DesktopBackendConfiguration from "./DesktopBackendConfiguration.ts";
import * as DesktopObservability from "../app/DesktopObservability.ts";
import * as DesktopState from "../app/DesktopState.ts";
import * as DesktopWindow from "../window/DesktopWindow.ts";
const INITIAL_RESTART_DELAY = Duration.millis(500);
const MAX_RESTART_DELAY = Duration.seconds(10);
// After this many consecutive fatal preflight failures, stop the silent
// restart loop and surface the reason via onPreflightFailed. Transient
// failures may instead provide their own larger retryLimit when they should
// self-heal for a while but must not leave the app connecting forever.
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);
@@ -70,37 +43,14 @@ type BackendProcessRunRequirements = BackendProcessLayerServices | Scope.Scope;
export type BackendProcessOutputStream = "stdout" | "stderr";
export type DesktopBackendBootstrapDelivery = "fd3" | "stdin";
export interface DesktopBackendStartConfig {
readonly executablePath: string;
readonly args: ReadonlyArray<string>;
readonly entryPath: string;
readonly cwd: string;
readonly env: Record<string, string | undefined>;
// When true the spawner merges the desktop process.env on top of `env`;
// when false `env` is passed verbatim. WSL mode opts out so a leaking
// T3CODE_HOME can't pin the WSL backend to /mnt/c/...\.t3.
readonly extendEnv: boolean;
readonly bootstrap: DesktopBackendBootstrapValue;
readonly bootstrapDelivery: DesktopBackendBootstrapDelivery;
readonly httpBaseUrl: URL;
readonly captureOutput: boolean;
readonly preflightFailure: Option.Option<PreflightFailure>;
// Present for a WSL run after the configured/default distro has been
// resolved to the concrete distro passed to wsl.exe.
readonly runningDistro?: string;
}
// A preflight failure records whether it is fatal. Transient failures (WSL
// cold-starting, wslpath while the VM boots) keep retrying so the backend can
// self-heal; fatal ones (no node, wrong version, missing build tools) are
// surfaced via onPreflightFailed and stop the restart loop after
// MAX_PREFLIGHT_FAILURE_ATTEMPTS.
export interface PreflightFailure {
readonly reason: string;
readonly fatal: boolean;
readonly retryLimit?: number;
}
interface BackendProcessExit {
@@ -112,10 +62,10 @@ interface BackendProcessExit {
export class BackendTimeoutError extends Schema.TaggedErrorClass<BackendTimeoutError>()(
"BackendTimeoutError",
{
url: Schema.instanceOf(URL),
url: Schema.URL,
},
) {
override get message() {
override get message(): string {
return `Timed out waiting for backend readiness at ${this.url.href}.`;
}
}
@@ -123,24 +73,24 @@ export class BackendTimeoutError extends Schema.TaggedErrorClass<BackendTimeoutE
class BackendProcessBootstrapEncodeError extends Schema.TaggedErrorClass<BackendProcessBootstrapEncodeError>()(
"BackendProcessBootstrapEncodeError",
{
entryPath: Schema.String,
detail: Schema.String,
cause: Schema.Defect(),
},
) {
override get message() {
return `Failed to encode the desktop backend bootstrap payload for ${this.entryPath}.`;
override get message(): string {
return `Failed to encode desktop backend bootstrap payload: ${this.detail}`;
}
}
class BackendProcessSpawnError extends Schema.TaggedErrorClass<BackendProcessSpawnError>()(
"BackendProcessSpawnError",
{
executablePath: Schema.String,
detail: Schema.String,
cause: Schema.Defect(),
},
) {
override get message() {
return `Failed to spawn the desktop backend process at ${this.executablePath}.`;
override get message(): string {
return `Failed to spawn desktop backend process: ${this.detail}`;
}
}
@@ -165,60 +115,18 @@ export interface DesktopBackendSnapshot {
readonly restartScheduled: boolean;
}
// Opaque identifier for one backend process inside the pool. Today only
// PRIMARY_INSTANCE_ID is registered. Follow-up commits add WSL distros
// under ids derived from the distro name (e.g. "wsl:ubuntu"). Eventually
// these map 1:1 with environment ids on the frontend; keeping them
// desktop-local for now avoids leaking the contracts dependency.
export type BackendInstanceId = string & Brand.Brand<"BackendInstanceId">;
export const BackendInstanceId = Brand.nominal<BackendInstanceId>();
export class DesktopBackendManager extends Context.Service<
DesktopBackendManager,
{
readonly start: Effect.Effect<void>;
readonly stop: (options?: { readonly timeout?: Duration.Duration }) => Effect.Effect<void>;
readonly currentConfig: Effect.Effect<Option.Option<DesktopBackendStartConfig>>;
readonly snapshot: Effect.Effect<DesktopBackendSnapshot>;
}
>()("@t3tools/desktop/backend/DesktopBackendManager") {}
export const PRIMARY_INSTANCE_ID: BackendInstanceId = BackendInstanceId(
PRIMARY_LOCAL_ENVIRONMENT_ID,
);
// One pooled backend instance. Same lifecycle surface as the legacy
// `DesktopBackendManagerShape`; the id and label give the pool registry
// + UI something to route on.
export interface DesktopBackendInstance {
readonly id: BackendInstanceId;
readonly label: Effect.Effect<string>;
readonly start: Effect.Effect<void>;
readonly stop: (options?: { readonly timeout?: Duration.Duration }) => Effect.Effect<void>;
readonly currentConfig: Effect.Effect<Option.Option<DesktopBackendStartConfig>>;
readonly snapshot: Effect.Effect<DesktopBackendSnapshot>;
// Polls desiredRunning + the instance's own ready flag until the
// backend reports ready, or the timeout elapses. Returns true on
// ready, false on timeout. Used by the WSL backend swap to drive its
// rollback path.
readonly waitForReady: (timeout: Duration.Duration) => Effect.Effect<boolean>;
}
// Spec describing one backend instance to spawn. The configResolve
// effect is awaited each time the instance is (re)started so live
// settings changes are picked up on the next start cycle. onReady and
// onShutdown let the primary instance trigger UI side effects (window
// open, global readiness flag) without coupling the factory to those
// concerns; other instances pass them as undefined.
export interface BackendInstanceSpec {
readonly id: BackendInstanceId;
readonly label: Effect.Effect<string>;
// configResolve can now fail with PlatformError because the
// bootstrap-token closure inside DesktopBackendConfiguration uses
// crypto.randomBytes (Effect 4 beta.73 migration).
readonly configResolve: Effect.Effect<DesktopBackendStartConfig, PlatformError.PlatformError>;
// Receives the *resolved* httpBaseUrl of the run that just became
// ready. The window service uses this to decide what URL to load
// (the WSL backend reports its distro IP, the Windows backend reports
// 127.0.0.1). Splitting this off from configResolve avoids races
// between "fired onReady" and "currentConfig already advanced".
readonly onReady?: (httpBaseUrl: URL) => Effect.Effect<void>;
readonly onShutdown?: () => Effect.Effect<void>;
// Fired once when a fatal or bounded preflight failure has exhausted its
// retries. Returns true when the callback changed configuration and the
// manager should resolve once more; false stops the failed instance.
readonly onPreflightFailed?: (failure: PreflightFailure) => Effect.Effect<boolean>;
}
const { logWarning: logBackendManagerWarning, logError: logBackendManagerError } =
DesktopObservability.makeComponentLogger("desktop-backend-manager");
interface ActiveBackendRun {
readonly id: number;
@@ -233,9 +141,6 @@ interface BackendManagerState {
readonly config: Option.Option<DesktopBackendStartConfig>;
readonly active: Option.Option<ActiveBackendRun>;
readonly restartAttempt: number;
// Consecutive bounded/fatal preflight failures, reset on a clean or
// unbounded-transient preflight. restartAttempt counts all restarts.
readonly preflightFailureAttempt: number;
readonly restartFiber: Option.Option<Fiber.Fiber<void, never>>;
readonly nextRunId: number;
}
@@ -246,7 +151,6 @@ const initialState: BackendManagerState = {
config: Option.none(),
active: Option.none(),
restartAttempt: 0,
preflightFailureAttempt: 0,
restartFiber: Option.none(),
nextRunId: 1,
};
@@ -279,20 +183,23 @@ const closeRun = (
).pipe(Effect.ignore);
};
const waitForHttpReady = (
const waitForHttpReady = Effect.fn("desktop.backendManager.waitForHttpReady")(function* (
baseUrl: URL,
timeout: Duration.Duration,
): Effect.Effect<void, BackendTimeoutError, HttpClient.HttpClient> => {
): Effect.fn.Return<void, BackendTimeoutError, HttpClient.HttpClient> {
const readinessUrl = new URL(BACKEND_READINESS_PATH, baseUrl);
return waitForHttpReadyShared({
baseUrl: baseUrl.href,
path: BACKEND_READINESS_PATH,
timeoutMs: Duration.toMillis(timeout),
intervalMs: Duration.toMillis(DEFAULT_BACKEND_READINESS_INTERVAL),
probeTimeoutMs: Duration.toMillis(DEFAULT_BACKEND_READINESS_REQUEST_TIMEOUT),
makeError: () => new BackendTimeoutError({ url: readinessUrl }),
});
};
const client = (yield* HttpClient.HttpClient).pipe(
HttpClient.filterStatusOk,
HttpClient.transformResponse(Effect.timeout(DEFAULT_BACKEND_READINESS_REQUEST_TIMEOUT)),
HttpClient.retry(Schedule.spaced(DEFAULT_BACKEND_READINESS_INTERVAL)),
);
yield* client.get(readinessUrl).pipe(
Effect.asVoid,
Effect.timeout(timeout),
Effect.mapError(() => new BackendTimeoutError({ url: readinessUrl })),
);
});
function describeProcessExit(
result: Result.Result<ChildProcessSpawner.ExitCode, PlatformError.PlatformError>,
@@ -331,37 +238,46 @@ const runBackendProcess = Effect.fn("runBackendProcess")(function* (
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const bootstrapJson = yield* encodeBootstrapJson(options.bootstrap).pipe(
Effect.mapError(
(cause) => new BackendProcessBootstrapEncodeError({ entryPath: options.entryPath, cause }),
(cause) =>
new BackendProcessBootstrapEncodeError({
detail: cause.message,
cause,
}),
),
);
const onOutput = options.onOutput ?? (() => Effect.void);
const bootstrapStream = Stream.encodeText(Stream.make(`${bootstrapJson}\n`));
const command = ChildProcess.make(options.executablePath, options.args, {
cwd: options.cwd,
env: options.env,
extendEnv: options.extendEnv,
// In Electron main, process.execPath points to the Electron binary.
// Run the child in Node mode so this backend process does not become a GUI app instance.
stdin: options.bootstrapDelivery === "stdin" ? bootstrapStream : "ignore",
stdout: options.captureOutput ? "pipe" : "inherit",
stderr: options.captureOutput ? "pipe" : "inherit",
killSignal: "SIGTERM",
forceKillAfter: DEFAULT_BACKEND_TERMINATE_GRACE,
// wsl.exe drops additional file descriptors when forwarding to the Linux
// side, so the WSL spawn path delivers the bootstrap envelope via stdin
// (`--bootstrap-fd 0`) instead.
...(options.bootstrapDelivery === "fd3"
? { additionalFds: { fd3: { type: "input" as const, stream: bootstrapStream } } }
: {}),
});
const command = ChildProcess.make(
options.executablePath,
[options.entryPath, "--bootstrap-fd", "3"],
{
cwd: options.cwd,
env: options.env,
extendEnv: true,
// In Electron main, process.execPath points to the Electron binary.
// Run the child in Node mode so this backend process does not become a GUI app instance.
stdin: "ignore",
stdout: options.captureOutput ? "pipe" : "inherit",
stderr: options.captureOutput ? "pipe" : "inherit",
killSignal: "SIGTERM",
forceKillAfter: DEFAULT_BACKEND_TERMINATE_GRACE,
additionalFds: {
fd3: {
type: "input",
stream: Stream.encodeText(Stream.make(`${bootstrapJson}\n`)),
},
},
},
);
const handle = yield* spawner
.spawn(command)
.pipe(
Effect.mapError(
(cause) => new BackendProcessSpawnError({ executablePath: options.executablePath, cause }),
),
);
const handle = yield* spawner.spawn(command).pipe(
Effect.mapError(
(cause) =>
new BackendProcessSpawnError({
detail: cause.message,
cause,
}),
),
);
yield* options.onStarted?.(handle.pid) ?? Effect.void;
if (options.captureOutput) {
@@ -380,34 +296,18 @@ const runBackendProcess = Effect.fn("runBackendProcess")(function* (
return describeProcessExit(yield* Effect.result(handle.exitCode));
});
// Factory for one pooled backend instance. The returned instance owns
// its own state Ref, mutex, restart loop, and active child process;
// nothing is shared between instances created from separate
// makeBackendInstance calls. The instance shuts down automatically when
// the calling scope closes (typically the application scope).
export const makeBackendInstance = Effect.fn("makeBackendInstance")(function* (
spec: BackendInstanceSpec,
): Effect.fn.Return<
DesktopBackendInstance,
never,
| FileSystem.FileSystem
| ChildProcessSpawner.ChildProcessSpawner
| HttpClient.HttpClient
| DesktopObservability.DesktopBackendOutputLogFactory
| Scope.Scope
> {
export const make = Effect.gen(function* () {
const parentScope = yield* Scope.Scope;
const fileSystem = yield* FileSystem.FileSystem;
const backendOutputLogFactory = yield* DesktopObservability.DesktopBackendOutputLogFactory;
const backendOutputLog = yield* backendOutputLogFactory.forInstance(spec.id);
const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
const backendOutputLog = yield* DesktopObservability.DesktopBackendOutputLog;
const desktopState = yield* DesktopState.DesktopState;
const desktopWindow = yield* DesktopWindow.DesktopWindow;
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const httpClient = yield* HttpClient.HttpClient;
const state = yield* Ref.make(initialState);
const mutex = yield* Semaphore.make(1);
const { logWarning: logInstanceWarning, logError: logInstanceError } =
DesktopObservability.makeComponentLogger(`desktop-backend-instance:${spec.id}`);
const updateActiveRun = (runId: number, f: (run: ActiveBackendRun) => ActiveBackendRun) =>
Ref.update(state, withActiveRun(runId, f));
@@ -447,15 +347,10 @@ export const makeBackendInstance = Effect.fn("makeBackendInstance")(function* (
return;
}
if (current.ready) {
yield* spec.onShutdown?.() ?? Effect.void;
yield* Ref.update(state, (latest) =>
latest.ready ? { ...latest, ready: false } : latest,
);
}
const config = yield* spec.configResolve.pipe(
yield* Ref.set(desktopState.backendReady, false);
const config = yield* configuration.resolve.pipe(
Effect.tapError((error) =>
logInstanceError("failed to generate desktop backend configuration", {
logBackendManagerError("failed to generate desktop backend configuration", {
cause: error.message,
}),
),
@@ -468,84 +363,14 @@ export const makeBackendInstance = Effect.fn("makeBackendInstance")(function* (
.exists(config.value.entryPath)
.pipe(Effect.orElseSucceed(() => false));
const resetFatalPreflightCounter =
!current.desiredRunning && current.preflightFailureAttempt > 0;
yield* cancelRestart;
yield* Ref.update(state, (latest) => ({
...latest,
desiredRunning: true,
ready: false,
config: Option.some(config.value),
preflightFailureAttempt: resetFatalPreflightCounter ? 0 : latest.preflightFailureAttempt,
}));
const preflightFailure = config.value.preflightFailure;
if (Option.isSome(preflightFailure)) {
const { reason, fatal, retryLimit } = preflightFailure.value;
if (!fatal && retryLimit === undefined) {
// Transient (WSL cold-starting, wslpath while the VM boots). Keep
// retrying so the backend self-heals once WSL is ready. Reset a
// prior bounded/fatal streak because this is a different failure.
yield* Ref.update(state, (latest) =>
latest.preflightFailureAttempt === 0
? latest
: { ...latest, preflightFailureAttempt: 0 },
);
yield* scheduleRestart(reason);
return;
}
const attemptLimit = retryLimit ?? MAX_PREFLIGHT_FAILURE_ATTEMPTS;
const attempt = yield* Ref.modify(state, (latest) => {
const next = latest.preflightFailureAttempt + 1;
return [next, { ...latest, preflightFailureAttempt: next }] as const;
});
if (attempt > attemptLimit) {
// We already surfaced and asked for the Windows fallback, yet we're
// still resolving the WSL primary — the fallback didn't take (e.g.
// the settings write failed). Stop rather than loop forever.
yield* logInstanceError("backend preflight still failing after fallback; stopping", {
reason,
attempt,
});
yield* Ref.update(state, (latest) => ({
...latest,
desiredRunning: false,
ready: false,
}));
return;
}
if (attempt === attemptLimit) {
// Fatal/bounded and out of retries. Surface the reason (onPreflightFailed,
// on the primary, shows a dialog and persists Windows mode), then
// schedule one more restart so the next resolve picks up the Windows
// primary and a window can open.
yield* logInstanceError(
"backend preflight failed repeatedly; surfacing and falling back",
{ reason, attempt },
);
const shouldRestart = yield* (
spec.onPreflightFailed?.(preflightFailure.value) ?? Effect.succeed(false)
);
if (shouldRestart) {
yield* scheduleRestart(reason);
} else {
yield* Ref.update(state, (latest) => ({
...latest,
desiredRunning: false,
ready: false,
}));
}
return;
}
yield* scheduleRestart(reason);
return;
}
// Clean preflight — reset the fatal counter so a later failure gets a
// fresh allowance.
yield* Ref.update(state, (latest) =>
latest.preflightFailureAttempt === 0 ? latest : { ...latest, preflightFailureAttempt: 0 },
);
if (!entryExists) {
yield* scheduleRestart(`missing server entry at ${config.value.entryPath}`);
return;
@@ -566,7 +391,7 @@ export const makeBackendInstance = Effect.fn("makeBackendInstance")(function* (
},
]);
const finalizeRun = Effect.fn("desktop.backendInstance.finalizeRun")(function* (
const finalizeRun = Effect.fn("desktop.backendManager.finalizeRun")(function* (
reason: string,
) {
yield* mutex.withPermits(1)(
@@ -618,7 +443,7 @@ export const makeBackendInstance = Effect.fn("makeBackendInstance")(function* (
details: `pid=${pid.value} ${reason}`,
});
}
yield* spec.onShutdown?.() ?? Effect.void;
yield* Ref.set(desktopState.backendReady, false);
}
if (isCurrentRun && nextState.desiredRunning) {
@@ -630,7 +455,7 @@ export const makeBackendInstance = Effect.fn("makeBackendInstance")(function* (
const program = runBackendProcess({
...config.value,
onStarted: Effect.fn("desktop.backendInstance.onStarted")(function* (pid) {
onStarted: Effect.fn("desktop.backendManager.onStarted")(function* (pid) {
yield* updateActiveRun(runId, (run) => ({
...run,
pid: Option.some(pid),
@@ -640,7 +465,7 @@ export const makeBackendInstance = Effect.fn("makeBackendInstance")(function* (
details: `pid=${pid} port=${config.value.bootstrap.port} cwd=${config.value.cwd}`,
});
}),
onReady: Effect.fn("desktop.backendInstance.onReady")(function* () {
onReady: Effect.fn("desktop.backendManager.onReady")(function* () {
const isCurrentRun = yield* Ref.modify(state, (latest) => {
const activeRun = Option.getOrUndefined(latest.active);
if (activeRun?.id !== runId) {
@@ -660,10 +485,17 @@ export const makeBackendInstance = Effect.fn("makeBackendInstance")(function* (
return;
}
yield* spec.onReady?.(config.value.httpBaseUrl) ?? Effect.void;
yield* Ref.set(desktopState.backendReady, true);
yield* desktopWindow.handleBackendReady.pipe(
Effect.catch((error) =>
logBackendManagerError("failed to open main window after backend readiness", {
message: error.message,
}),
),
);
}),
onReadinessFailure: (error) =>
logInstanceWarning("backend readiness check failed during bootstrap", {
logBackendManagerWarning("backend readiness check failed during bootstrap", {
error: error.message,
}),
onOutput: (streamName, chunk) => backendOutputLog.writeOutputChunk(streamName, chunk),
@@ -685,9 +517,9 @@ export const makeBackendInstance = Effect.fn("makeBackendInstance")(function* (
}));
}),
),
).pipe(Effect.withSpan("desktop.backendInstance.start", { attributes: { id: spec.id } }));
).pipe(Effect.withSpan("desktop.backendManager.start"));
const scheduleRestart = Effect.fn("desktop.backendInstance.scheduleRestart")(function* (
const scheduleRestart = Effect.fn("desktop.backendManager.scheduleRestart")(function* (
reason: string,
) {
const scheduled = yield* Ref.modify(state, (latest) => {
@@ -707,8 +539,8 @@ export const makeBackendInstance = Effect.fn("makeBackendInstance")(function* (
yield* Option.match(scheduled, {
onNone: () => Effect.void,
onSome: Effect.fn("desktop.backendInstance.scheduleRestartFiber")(function* (delay) {
yield* logInstanceError("backend exited unexpectedly; restart scheduled", {
onSome: Effect.fn("desktop.backendManager.scheduleRestartFiber")(function* (delay) {
yield* logBackendManagerError("backend exited unexpectedly; restart scheduled", {
reason,
delayMs: Duration.toMillis(delay),
});
@@ -728,7 +560,7 @@ export const makeBackendInstance = Effect.fn("makeBackendInstance")(function* (
),
Effect.flatMap((shouldRestart) => (shouldRestart ? start : Effect.void)),
Effect.catchCause((cause) =>
logInstanceError("desktop backend restart fiber failed", {
logBackendManagerError("desktop backend restart fiber failed", {
cause: Cause.pretty(cause),
}),
),
@@ -747,7 +579,7 @@ export const makeBackendInstance = Effect.fn("makeBackendInstance")(function* (
});
});
const stop = Effect.fn("desktop.backendInstance.stop")(function* (options?: {
const stop = Effect.fn("desktop.backendManager.stop")(function* (options?: {
readonly timeout?: Duration.Duration;
}) {
const { active, restartFiber } = yield* mutex.withPermits(1)(
@@ -765,15 +597,7 @@ export const makeBackendInstance = Effect.fn("makeBackendInstance")(function* (
restartFiber: Option.none<Fiber.Fiber<void, never>>(),
},
]);
// Ignore failures from spec.onShutdown so a downstream throw
// can't abort the rest of stop(). Ref.modify above already
// flipped state to "no active run / no restart fiber", and the
// physical cleanup (Fiber.interrupt + closeRun) runs after the
// mutex releases. If onShutdown were allowed to propagate, both
// would be skipped and the child process + restart fiber would
// be orphaned while state claimed nothing was running — the
// next start() would then spawn a second backend on top.
yield* (spec.onShutdown?.() ?? Effect.void).pipe(Effect.ignore);
yield* Ref.set(desktopState.backendReady, false);
return result;
}),
);
@@ -788,32 +612,14 @@ export const makeBackendInstance = Effect.fn("makeBackendInstance")(function* (
});
});
const waitForReady = (timeout: Duration.Duration): Effect.Effect<boolean> =>
Effect.gen(function* () {
const current = yield* Ref.get(state);
// Return false early if an external `stop()` flipped desiredRunning off
// — no point polling for a backend that is being torn down.
if (!current.desiredRunning) return { done: true, ready: false };
return current.ready ? { done: true, ready: true } : { done: false, ready: false };
}).pipe(
Effect.repeat({
until: (status) => status.done,
schedule: Schedule.spaced(Duration.millis(100)),
}),
Effect.map((status) => status.ready),
Effect.timeoutOption(timeout),
Effect.map(Option.getOrElse(() => false)),
);
yield* Effect.addFinalizer(() => stop());
return {
id: spec.id,
label: spec.label,
return DesktopBackendManager.of({
start,
stop,
currentConfig,
snapshot,
waitForReady,
} satisfies DesktopBackendInstance;
});
});
export const layer = Layer.effect(DesktopBackendManager, make);
@@ -1,137 +0,0 @@
import { assert, describe, it } from "@effect/vitest";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Ref from "effect/Ref";
import { HttpClient } from "effect/unstable/http";
import { ChildProcessSpawner } from "effect/unstable/process";
import * as DesktopObservability from "../app/DesktopObservability.ts";
import * as DesktopAppSettings from "../settings/DesktopAppSettings.ts";
import * as ElectronDialog from "../electron/ElectronDialog.ts";
import * as DesktopWindow from "../window/DesktopWindow.ts";
import * as DesktopBackendConfiguration from "./DesktopBackendConfiguration.ts";
import * as DesktopBackendPool from "./DesktopBackendPool.ts";
import type { DesktopBackendSnapshot, DesktopBackendStartConfig } from "./DesktopBackendManager.ts";
function makeStubInstance(
id: DesktopBackendPool.BackendInstanceId,
label: string,
): DesktopBackendPool.DesktopBackendInstance {
const snapshot: DesktopBackendSnapshot = {
desiredRunning: false,
ready: false,
activePid: Option.none(),
restartAttempt: 0,
restartScheduled: false,
};
return {
id,
label: Effect.succeed(label),
start: Effect.void,
stop: () => Effect.void,
currentConfig: Effect.succeed(Option.none<DesktopBackendStartConfig>()),
snapshot: Effect.succeed(snapshot),
waitForReady: (_timeout: Duration.Duration) => Effect.succeed(false),
};
}
function makePoolLayer(
labelRef: Ref.Ref<string>,
): Layer.Layer<DesktopBackendPool.DesktopBackendPool> {
return DesktopBackendPool.layer.pipe(
Layer.provideMerge(
Layer.mergeAll(
FileSystem.layerNoop({}),
Layer.succeed(
ChildProcessSpawner.ChildProcessSpawner,
ChildProcessSpawner.make(() => Effect.die("unexpected child process spawn")),
),
Layer.succeed(
HttpClient.HttpClient,
HttpClient.make(() => Effect.die("unexpected HTTP request")),
),
Layer.succeed(DesktopObservability.DesktopBackendOutputLogFactory, {
forInstance: () =>
Effect.succeed({
writeSessionBoundary: () => Effect.void,
writeOutputChunk: () => Effect.void,
} satisfies DesktopObservability.DesktopBackendOutputLogShape),
} satisfies DesktopObservability.DesktopBackendOutputLogFactory["Service"]),
Layer.succeed(DesktopBackendConfiguration.DesktopBackendConfiguration, {
resolvePrimary: Effect.die("unexpected primary config resolve"),
resolvePrimaryLabel: Ref.get(labelRef),
resolveWsl: () => Effect.die("unexpected WSL config resolve"),
} satisfies DesktopBackendConfiguration.DesktopBackendConfiguration["Service"]),
DesktopAppSettings.layerTest(),
ElectronDialog.layer,
Layer.succeed(DesktopWindow.DesktopWindow, {
createMain: Effect.die("unexpected window create"),
ensureMain: Effect.die("unexpected window ensure"),
revealOrCreateMain: Effect.die("unexpected window reveal"),
activate: Effect.die("unexpected window activate"),
createMainIfBackendReady: Effect.die("unexpected window create"),
showConnectingSplash: Effect.void,
handleBackendReady: () => Effect.void,
handleBackendNotReady: Effect.void,
dispatchMenuAction: () => Effect.die("unexpected menu action"),
syncAppearance: Effect.void,
} satisfies DesktopWindow.DesktopWindow["Service"]),
),
),
);
}
describe("DesktopBackendPool", () => {
it.effect("layerTest exposes registered instances by id", () =>
Effect.gen(function* () {
const pool = yield* DesktopBackendPool.DesktopBackendPool;
const fetchedPrimary = yield* pool.get(DesktopBackendPool.PRIMARY_INSTANCE_ID);
const fetchedWsl = yield* pool.get(DesktopBackendPool.BackendInstanceId("wsl:ubuntu"));
const fetchedMissing = yield* pool.get(DesktopBackendPool.BackendInstanceId("missing"));
const all = yield* pool.list;
const resolvedPrimary = yield* pool.primary;
assert.equal(yield* Option.getOrThrow(fetchedPrimary).label, "Windows");
assert.equal(yield* Option.getOrThrow(fetchedWsl).label, "WSL (Ubuntu)");
assert.isTrue(Option.isNone(fetchedMissing));
assert.lengthOf(all, 2);
// First instance becomes primary in layerTest so single-instance
// stubs don't have to wire an explicit primary.
assert.equal(resolvedPrimary.id, DesktopBackendPool.PRIMARY_INSTANCE_ID);
}).pipe(
Effect.provide(
DesktopBackendPool.layerTest([
makeStubInstance(DesktopBackendPool.PRIMARY_INSTANCE_ID, "Windows"),
makeStubInstance(DesktopBackendPool.BackendInstanceId("wsl:ubuntu"), "WSL (Ubuntu)"),
]),
),
),
);
it.effect("layerTest dies when no instances are supplied", () =>
Effect.exit(
Effect.gen(function* () {
yield* DesktopBackendPool.DesktopBackendPool;
}).pipe(Effect.provide(DesktopBackendPool.layerTest([]))),
).pipe(Effect.map((exit) => assert.equal(exit._tag, "Failure"))),
);
it.effect("resolves the primary label lazily after pool layer construction", () =>
Effect.scoped(
Effect.gen(function* () {
const labelRef = yield* Ref.make("Windows");
const pool = yield* DesktopBackendPool.DesktopBackendPool.pipe(
Effect.provide(makePoolLayer(labelRef)),
);
const primary = yield* pool.primary;
yield* Ref.set(labelRef, "WSL (Ubuntu)");
assert.equal(yield* primary.label, "WSL (Ubuntu)");
}),
),
);
});
@@ -1,470 +0,0 @@
// Pool registry for multiple backend processes. This file is the entry
// point for the concurrent-Windows+WSL-backend feature; see the design
// notes below before extending it.
//
// Current state:
// - `DesktopBackendManager.ts` exposes a per-instance factory
// (`makeBackendInstance(spec)`); the pool calls it once for the
// Windows primary at startup, and `DesktopWslBackend.reconcile`
// calls it through `pool.register` to bring up the WSL instance
// when the user enables it.
// - The primary spec wires `configResolve` to
// `DesktopBackendConfiguration.resolvePrimary` and the
// `onReady`/`onShutdown` callbacks to the window service. WSL
// instances wire `configResolve: configuration.resolveWsl(...)`
// and skip onReady/onShutdown — the window only follows the primary.
// - The pool exposes `register(spec)` and `unregister(id)`. Each
// registered instance gets its own child scope, so unregister can
// stop it cleanly without tearing down the pool. The primary's id
// refuses unregister.
// - Settings: `wslBackendEnabled: boolean` + `wslDistro: string | null`.
// The legacy `wslMode: "local" | "wsl"` swap setting is migrated on
// load. IPC surface is `setWslBackendEnabled(boolean)` +
// `setWslDistro(string | null)`; both persist and then call the
// orchestrator's reconcile. No swap, no rollback, primary stays up.
// - `getLocalEnvironmentBootstraps()` (plural) returns one entry per
// pool instance currently registered with bootstrap info. The
// primary keeps the "primary" id; WSL instances are "wsl:default"
// or "wsl:<distro>".
// - `pickFolder` accepts an optional `targetEnvironmentId`. Omitting
// it gives the Windows picker — what every existing caller gets,
// and what non-WSL users see. WSL targets route to the wsl helpers.
// - Web settings UX: a plain toggle for "WSL backend" plus a distro
// picker that shows up when the toggle is on. Default-off, so
// users who never opted in see the same surface as before.
//
// Renderer-side wiring (apps/web/src/environments/local/):
// - reconcileLocalSecondaryEnvironments() runs at app boot and after
// WSL settings changes. It reads getLocalEnvironmentBootstraps(),
// skips the primary (which the existing primary/ runtime owns),
// and for every other entry POSTs the shared bootstrap token to
// /api/auth/bootstrap/bearer on that backend's URL, fetches the
// descriptor, builds a SavedEnvironmentRecord marked desktopLocal,
// writes the bearer to the secret store, and opens a connection
// through the same saved-env path remote envs use.
// - The desktopLocal marker filters records out of saved-env
// persistence, so toggling WSL off or switching distros doesn't
// pollute the user's settings file. The sidebar, CommandPalette,
// env switcher, and project-id routing all read the saved-env
// registry, so the WSL backend shows up there without any
// per-surface changes.
//
// Browser validation (2026-05-17, dev:desktop with wslBackendEnabled=true,
// wslDistro="Ubuntu"):
// - Two backends listening on distinct loopback ports
// (server.log: 13773 primary, 13774 wsl).
// - Per-instance log files: server-child.log + server-child-wsl_Ubuntu.log.
// - Distinct environment ids reported by each backend's
// /.well-known/t3/environment (Windows vs Linux platform).
// - Renderer completes the bearer-token bootstrap against the WSL
// backend (POST /api/auth/bootstrap/bearer 200), obtains a
// ws-token (POST /api/auth/ws-token 200), and holds an
// ESTABLISHED WebSocket connection to both ports (netstat).
//
// Migration history (commits):
// 1. Reshape `DesktopBackendManager` into an instance factory and route
// consumers through the pool. Pool held a single instance. (a8fc7845)
// 2. Drop `DesktopState.backendReady`. The window owns its own
// readiness latch via onReady / onShutdown callbacks. (425c7d0b)
// 3. Per-instance log routing via DesktopBackendOutputLogFactory. (563820ed)
// 4. Add register/unregister to the pool. (a0eaf560)
// 5. Wire WSL through the pool: settings rename, BackendConfiguration
// split, DesktopWslBackend orchestrator, new IPC, web compat.
// (b1622191 + 31ce3add + 627c80cb)
// 6. Widen getLocalEnvironmentBootstrap to *Bootstraps (plural). (bad66041)
// 7. pickFolder takes optional targetEnvironmentId. (5d80468d)
// 8. Settings UX: toggle + distro picker, no swap dialog. (eb5a03ea)
// 9. Register WSL backend as desktop-local saved env via
// reconcileLocalSecondaryEnvironments. (1c7e7873 + c17897bd)
// 10. CommandPalette enables file-manager picker for desktop-local
// envs, routes pickFolder by env id. (38e8477a)
import * as Context from "effect/Context";
import * as Deferred from "effect/Deferred";
import * as Effect from "effect/Effect";
import * as Exit from "effect/Exit";
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 * as SynchronizedRef from "effect/SynchronizedRef";
import * as FileSystem from "effect/FileSystem";
import { HttpClient } from "effect/unstable/http";
import { ChildProcessSpawner } from "effect/unstable/process";
import * as DesktopBackendConfiguration from "./DesktopBackendConfiguration.ts";
import * as DesktopBackendManager from "./DesktopBackendManager.ts";
import * as DesktopObservability from "../app/DesktopObservability.ts";
import * as DesktopAppSettings from "../settings/DesktopAppSettings.ts";
import * as DesktopWindow from "../window/DesktopWindow.ts";
import * as ElectronDialog from "../electron/ElectronDialog.ts";
const { logWarning: logBackendPoolWarning } =
DesktopObservability.makeComponentLogger("desktop-backend-pool");
export type BackendInstanceId = DesktopBackendManager.BackendInstanceId;
export const BackendInstanceId = DesktopBackendManager.BackendInstanceId;
export const PRIMARY_INSTANCE_ID = DesktopBackendManager.PRIMARY_INSTANCE_ID;
export type DesktopBackendInstance = DesktopBackendManager.DesktopBackendInstance;
export type BackendInstanceSpec = DesktopBackendManager.BackendInstanceSpec;
// Caller tried to register an id that's already in the pool. The pool
// refuses overwrites so two independent orchestrators racing on the
// same id surface as a typed failure instead of one silently winning.
export class DesktopBackendPoolInstanceAlreadyRegisteredError extends Schema.TaggedErrorClass<DesktopBackendPoolInstanceAlreadyRegisteredError>()(
"DesktopBackendPoolInstanceAlreadyRegisteredError",
{
id: Schema.String,
},
) {
override get message() {
return `Backend instance "${this.id}" is already registered in the pool.`;
}
}
// Primary instance is registered for the pool's lifetime. Unregister is
// a no-op for it today (no real callers), but if someone wires it up
// later it's a clear bug rather than something to "handle".
export class DesktopBackendPoolCannotUnregisterPrimaryError extends Schema.TaggedErrorClass<DesktopBackendPoolCannotUnregisterPrimaryError>()(
"DesktopBackendPoolCannotUnregisterPrimaryError",
{},
) {
override get message() {
return "Refusing to unregister the primary backend from the pool.";
}
}
export class DesktopBackendPool extends Context.Service<
DesktopBackendPool,
{
// Look up a registered instance. None when no backend with that id is
// currently registered (e.g. WSL backend disabled).
readonly get: (id: BackendInstanceId) => Effect.Effect<Option.Option<DesktopBackendInstance>>;
// Snapshot of all currently-registered instances. Order is unspecified;
// callers that need a canonical "primary first" view should sort by id.
readonly list: Effect.Effect<readonly DesktopBackendInstance[]>;
// Convenience accessor for the always-registered primary instance.
// Currently equivalent to `get(PRIMARY_INSTANCE_ID)` unwrapped, but
// exposed as a typed effect so consumers don't have to handle the
// Option for the case that's guaranteed to be present.
readonly primary: Effect.Effect<DesktopBackendInstance>;
// Build a fresh DesktopBackendInstance from `spec` and add it to the
// registry. The pool owns the instance's scope: unregister(id) or pool
// teardown closes it and runs the instance's auto-stop finalizer. The
// returned instance has not been started — callers decide when to
// start it (and can call start more than once if a retry-after-failure
// story makes sense for them).
readonly register: (
spec: BackendInstanceSpec,
) => Effect.Effect<DesktopBackendInstance, DesktopBackendPoolInstanceAlreadyRegisteredError>;
// Stop the named instance and remove it from the registry. Closing the
// instance's scope triggers its auto-stop finalizer; the registry is
// updated atomically with the scope close so subsequent get(id) calls
// observe the unregister before the underlying child process has fully
// exited.
readonly unregister: (
id: BackendInstanceId,
) => Effect.Effect<void, DesktopBackendPoolCannotUnregisterPrimaryError>;
}
>()("@t3tools/desktop/backend/DesktopBackendPool") {}
// Services required by makeBackendInstance — exported so caller
// orchestrators that build their own specs can confirm the layer graph
// satisfies them at compile time.
export type BackendInstanceFactoryRequirements =
| FileSystem.FileSystem
| ChildProcessSpawner.ChildProcessSpawner
| HttpClient.HttpClient
| DesktopObservability.DesktopBackendOutputLogFactory;
interface ActiveRegisteredInstance {
readonly _tag: "Active";
readonly instance: DesktopBackendInstance;
// None for the primary (which lives in the pool's own layer scope and
// is never unregistered); Some for instances added via register, whose
// scope unregister closes to stop them.
readonly scope: Option.Option<Scope.Closeable>;
}
interface ClosingRegisteredInstance {
readonly _tag: "Closing";
readonly done: Deferred.Deferred<void>;
}
type RegisteredInstance = ActiveRegisteredInstance | ClosingRegisteredInstance;
type RegisterAction =
| { readonly _tag: "Registered"; readonly instance: DesktopBackendInstance }
| { readonly _tag: "Wait"; readonly done: Deferred.Deferred<void> };
type UnregisterAction =
| { readonly _tag: "Absent" }
| { readonly _tag: "Wait"; readonly done: Deferred.Deferred<void> }
| { readonly _tag: "Close"; readonly entry: ActiveRegisteredInstance };
export const layer = Layer.effect(
DesktopBackendPool,
Effect.gen(function* () {
const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
const desktopWindow = yield* DesktopWindow.DesktopWindow;
const electronDialog = yield* ElectronDialog.ElectronDialog;
const appSettings = yield* DesktopAppSettings.DesktopAppSettings;
// Anchor the pool's lifetime to its layer scope so registered
// instance scopes can be forked off it. Without this, instance
// scopes are orphaned: they only close via explicit unregister()
// calls, so on app shutdown the WSL backend child process gets
// hard-killed by the OS instead of receiving the graceful
// SIGTERM + grace period the instance's stop finalizer would
// otherwise run.
const layerScope = yield* Scope.Scope;
// Capture the services needed to build any future instance from the
// pool's layer scope. register() runs `makeBackendInstance` against
// a fresh child scope but reuses these services so the instance gets
// the same FileSystem, spawner, HTTP client and log factory the
// primary instance uses.
const factoryContext = yield* Effect.context<BackendInstanceFactoryRequirements>();
// A WSL preflight failure on the primary only happens in wsl-only mode.
// Fatal configuration failures persist the Windows fallback. Bounded
// transport failures use an in-memory fallback for this launch so the app
// opens without overwriting the user's WSL preference.
const handlePrimaryPreflightFailure = Effect.fn("desktop.backendPool.primaryPreflightFailed")(
function* (failure: DesktopBackendManager.PreflightFailure) {
const { reason, fatal } = failure;
if (!fatal) {
yield* logBackendPoolWarning(
"primary WSL preflight retry window exhausted; using Windows for this launch",
{ reason },
);
yield* electronDialog.showErrorBox(
"WSL backend is still unavailable",
`${reason}\n\nT3 Code will use the Windows backend for this launch and retry WSL the next time the app starts.`,
);
yield* appSettings.applyWslWindowsFallbackInMemory;
return true;
}
yield* logBackendPoolWarning("primary WSL preflight failed; falling back to Windows", {
reason,
});
yield* electronDialog.showErrorBox(
"WSL backend couldn't start",
`${reason}\n\nFalling back to the Windows backend so T3 Code can open. Re-enable the WSL backend from Settings > Connections once the WSL distro is fixed.`,
);
// Fully disable the WSL backend — both flags, matching the "Switch to
// Windows" recovery path — so the manager's next restart re-resolves the
// primary as Windows and reconcile won't register a secondary WSL backend
// against the same broken setup. Clearing wslBackendEnabled alone would
// leave a stale wslOnly:true that silently re-traps the user in wsl-only
// mode the next time they enable WSL. If the persisted write fails, keep
// this process recoverable by applying the fallback to in-memory settings.
yield* appSettings.applyWslWindowsFallback.pipe(
Effect.catch((error) =>
logBackendPoolWarning(
"failed to persist Windows fallback after WSL preflight failure",
{
error: error.message,
},
).pipe(Effect.andThen(appSettings.applyWslWindowsFallbackInMemory)),
),
);
return true;
},
);
const primary = yield* DesktopBackendManager.makeBackendInstance({
id: DesktopBackendManager.PRIMARY_INSTANCE_ID,
// Keep this lazy. The pool layer is initialized before startup loads
// persisted desktop settings, so resolving the primary label here would
// permanently capture DEFAULT_DESKTOP_SETTINGS and mislabel WSL-only
// primaries as Windows.
label: configuration.resolvePrimaryLabel,
configResolve: configuration.resolvePrimary,
// Window creation errors propagating out of handleBackendReady must
// not block the readiness callback (that would prevent restartAttempt
// from being reset), so we absorb them here. The window service only
// logs on success, so log the failure here before swallowing it —
// otherwise a post-readiness window-open failure vanishes silently and
// is near-impossible to diagnose in production.
onReady: (httpBaseUrl) =>
desktopWindow.handleBackendReady(httpBaseUrl).pipe(
Effect.catch((error) =>
logBackendPoolWarning("failed to open main window after backend readiness", {
error: error.message,
}),
),
),
onShutdown: () => desktopWindow.handleBackendNotReady,
onPreflightFailed: handlePrimaryPreflightFailure,
});
const instancesRef = yield* SynchronizedRef.make<
ReadonlyMap<BackendInstanceId, RegisteredInstance>
>(
new Map([
[
DesktopBackendManager.PRIMARY_INSTANCE_ID,
{ _tag: "Active", instance: primary, scope: Option.none() },
],
]),
);
const register: DesktopBackendPool["Service"]["register"] = (spec) =>
Effect.suspend(() =>
SynchronizedRef.modifyEffect(
instancesRef,
(
current,
): Effect.Effect<
readonly [RegisterAction, ReadonlyMap<BackendInstanceId, RegisteredInstance>],
DesktopBackendPoolInstanceAlreadyRegisteredError
> => {
const existing = current.get(spec.id);
if (existing?._tag === "Active") {
return Effect.fail(
new DesktopBackendPoolInstanceAlreadyRegisteredError({ id: spec.id }),
);
}
if (existing?._tag === "Closing") {
return Effect.succeed([
{ _tag: "Wait", done: existing.done } as const,
current,
] as const);
}
return Effect.gen(function* () {
// Provide the captured factory services first, then the child scope
// last so instance finalizers are owned by the unregisterable scope.
const instanceScope = yield* Scope.fork(layerScope, "sequential");
const instance = yield* DesktopBackendManager.makeBackendInstance(spec).pipe(
Effect.provide(factoryContext),
Scope.provide(instanceScope),
);
const next = new Map(current);
next.set(spec.id, {
_tag: "Active",
instance,
scope: Option.some(instanceScope),
});
return [
{ _tag: "Registered", instance } as const,
next as ReadonlyMap<BackendInstanceId, RegisteredInstance>,
] as const;
});
},
).pipe(
Effect.flatMap((result) =>
result._tag === "Registered"
? Effect.succeed(result.instance)
: Deferred.await(result.done).pipe(Effect.andThen(register(spec))),
),
),
);
const unregister: DesktopBackendPool["Service"]["unregister"] = (id) =>
Effect.gen(function* () {
if (id === DesktopBackendManager.PRIMARY_INSTANCE_ID) {
return yield* new DesktopBackendPoolCannotUnregisterPrimaryError();
}
const done = yield* Deferred.make<void>();
const action = yield* SynchronizedRef.modifyEffect(
instancesRef,
(
current,
): Effect.Effect<
readonly [UnregisterAction, ReadonlyMap<BackendInstanceId, RegisteredInstance>]
> => {
const entry = current.get(id);
if (entry === undefined) {
return Effect.succeed([{ _tag: "Absent" } as const, current] as const);
}
if (entry._tag === "Closing") {
return Effect.succeed([
{ _tag: "Wait", done: entry.done } as const,
current,
] as const);
}
const next = new Map(current);
next.set(id, { _tag: "Closing", done });
return Effect.succeed([
{ _tag: "Close", entry } as const,
next as ReadonlyMap<BackendInstanceId, RegisteredInstance>,
] as const);
},
);
if (action._tag === "Absent") return;
if (action._tag === "Wait") {
yield* Deferred.await(action.done);
return;
}
const finish = SynchronizedRef.modifyEffect(instancesRef, (current) => {
const closing = current.get(id);
if (closing?._tag !== "Closing" || closing.done !== done) {
return Effect.succeed([undefined, current] as const);
}
const next = new Map(current);
next.delete(id);
return Effect.succeed([
undefined,
next as ReadonlyMap<BackendInstanceId, RegisteredInstance>,
] as const);
}).pipe(Effect.andThen(Deferred.succeed(done, undefined)), Effect.asVoid);
yield* Option.match(action.entry.scope, {
onNone: () => Effect.void,
onSome: (scope) => Scope.close(scope, Exit.void).pipe(Effect.ignore),
}).pipe(Effect.ensuring(finish));
});
return DesktopBackendPool.of({
get: (id) =>
SynchronizedRef.get(instancesRef).pipe(
Effect.map((instances) => {
const entry = instances.get(id);
return entry?._tag === "Active" ? Option.some(entry.instance) : Option.none();
}),
),
list: SynchronizedRef.get(instancesRef).pipe(
Effect.map((instances) =>
Array.from(instances.values()).flatMap((entry) =>
entry._tag === "Active" ? [entry.instance] : [],
),
),
),
primary: Effect.succeed(primary),
register,
unregister,
});
}),
);
// Test layer for unit tests that want to assert against a known pool
// composition without standing up the full manager. Each provided
// instance is registered under its own id; the first one is also
// surfaced as `primary` so callers can stub a single-instance pool.
// `register` and `unregister` are stubbed to die so tests that
// accidentally exercise pool registration fail loudly instead of
// silently noop'ing.
export const layerTest = (
instances: readonly DesktopBackendInstance[],
): Layer.Layer<DesktopBackendPool> =>
Layer.effect(
DesktopBackendPool,
Effect.gen(function* () {
if (instances.length === 0) {
return yield* Effect.die("DesktopBackendPool.layerTest requires at least one instance");
}
const byId = new Map<BackendInstanceId, DesktopBackendInstance>(
instances.map((instance) => [instance.id, instance] as const),
);
const primary = instances[0]!;
return DesktopBackendPool.of({
get: (id) => Effect.succeed(Option.fromNullishOr(byId.get(id))),
list: Effect.succeed(Array.from(byId.values())),
primary: Effect.succeed(primary),
register: () => Effect.die("DesktopBackendPool.layerTest does not support register"),
unregister: () => Effect.die("DesktopBackendPool.layerTest does not support unregister"),
});
}),
);
@@ -5,12 +5,11 @@ import * as Option from "effect/Option";
import * as Ref from "effect/Ref";
import * as HttpClient from "effect/unstable/http/HttpClient";
import * as HttpClientResponse from "effect/unstable/http/HttpClientResponse";
import { PRIMARY_LOCAL_ENVIRONMENT_ID } from "@t3tools/contracts";
import * as DesktopBackendPool from "./DesktopBackendPool.ts";
import * as DesktopBackendManager from "./DesktopBackendManager.ts";
import * as DesktopLocalEnvironmentAuth from "./DesktopLocalEnvironmentAuth.ts";
const config = {
const config: DesktopBackendManager.DesktopBackendStartConfig = {
executablePath: "/electron",
entryPath: "/server/bin.mjs",
cwd: "/server",
@@ -55,17 +54,20 @@ describe("DesktopLocalEnvironmentAuth", () => {
),
),
);
const poolLayer = Layer.succeed(DesktopBackendPool.DesktopBackendPool, {
list: Effect.succeed([
{
id: PRIMARY_LOCAL_ENVIRONMENT_ID,
label: Effect.succeed("Windows"),
currentConfig: Effect.succeed(Option.some(config)),
},
]),
} as unknown as DesktopBackendPool.DesktopBackendPool["Service"]);
const managerLayer = Layer.succeed(DesktopBackendManager.DesktopBackendManager, {
start: Effect.void,
stop: () => Effect.void,
currentConfig: Effect.succeed(Option.some(config)),
snapshot: Effect.succeed({
desiredRunning: true,
ready: true,
activePid: Option.none(),
restartAttempt: 0,
restartScheduled: false,
}),
});
const testLayer = DesktopLocalEnvironmentAuth.layer.pipe(
Layer.provide(Layer.mergeAll(poolLayer, httpClientLayer)),
Layer.provide(Layer.mergeAll(managerLayer, httpClientLayer)),
);
const [first, second] = yield* Effect.gen(function* () {
@@ -1,5 +1,4 @@
import { bootstrapRemoteBearerSession } from "@t3tools/client-runtime/authorization";
import { PRIMARY_LOCAL_ENVIRONMENT_ID } from "@t3tools/contracts";
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
@@ -9,7 +8,7 @@ import * as Schema from "effect/Schema";
import * as Semaphore from "effect/Semaphore";
import * as HttpClient from "effect/unstable/http/HttpClient";
import * as DesktopBackendPool from "./DesktopBackendPool.ts";
import * as DesktopBackendManager from "./DesktopBackendManager.ts";
export class DesktopLocalEnvironmentAuthBackendNotConfiguredError extends Schema.TaggedErrorClass<DesktopLocalEnvironmentAuthBackendNotConfiguredError>()(
"DesktopLocalEnvironmentAuthBackendNotConfiguredError",
@@ -43,7 +42,7 @@ export class DesktopLocalEnvironmentAuth extends Context.Service<
>()("@t3tools/desktop/backend/DesktopLocalEnvironmentAuth") {}
export const make = Effect.gen(function* () {
const pool = yield* DesktopBackendPool.DesktopBackendPool;
const backendManager = yield* DesktopBackendManager.DesktopBackendManager;
const httpClient = yield* HttpClient.HttpClient;
const tokenRef = yield* Ref.make(Option.none<string>());
const mutex = yield* Semaphore.make(1);
@@ -56,20 +55,14 @@ export const make = Effect.gen(function* () {
return cached.value;
}
const instances = yield* pool.list;
const primary = instances.find((instance) => instance.id === PRIMARY_LOCAL_ENVIRONMENT_ID);
const configOption = primary === undefined ? Option.none() : yield* primary.currentConfig;
const configOption = yield* backendManager.currentConfig;
if (Option.isNone(configOption)) {
return yield* new DesktopLocalEnvironmentAuthBackendNotConfiguredError();
}
const config = configOption.value;
const credential = config.bootstrap.desktopBootstrapToken;
if (!credential) {
return yield* new DesktopLocalEnvironmentAuthBackendNotConfiguredError();
}
const session = yield* bootstrapRemoteBearerSession({
httpBaseUrl: config.httpBaseUrl.href,
credential,
credential: config.bootstrap.desktopBootstrapToken,
clientMetadata: {
label: "T3 Code Desktop",
deviceType: "desktop",
@@ -1,65 +0,0 @@
import { assert, describe, it } from "@effect/vitest";
import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
import * as Cause from "effect/Cause";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import { beforeEach, vi } from "vite-plus/test";
const { networkInterfacesMock } = vi.hoisted(() => ({
networkInterfacesMock: vi.fn(),
}));
vi.mock("node:os", () => ({
networkInterfaces: networkInterfacesMock,
}));
import * as DesktopNetworkInterfaces from "./DesktopNetworkInterfaces.ts";
const TestLayer = DesktopNetworkInterfaces.layer.pipe(
Layer.provide(Layer.succeed(HostProcessPlatform, "linux")),
);
describe("DesktopNetworkInterfaces", () => {
beforeEach(() => {
networkInterfacesMock.mockReset();
});
it.effect("reads network interfaces through the service", () => {
const interfaces = {
en0: [
{
address: "192.168.1.10",
family: "IPv4",
internal: false,
},
],
};
networkInterfacesMock.mockReturnValueOnce(interfaces);
return Effect.gen(function* () {
const service = yield* DesktopNetworkInterfaces.DesktopNetworkInterfaces;
assert.strictEqual(yield* service.read, interfaces);
}).pipe(Effect.provide(TestLayer));
});
it.effect("preserves network interface read failures as structured defects", () => {
const cause = new Error("network interface probe failed");
networkInterfacesMock.mockImplementationOnce(() => {
throw cause;
});
return Effect.gen(function* () {
const service = yield* DesktopNetworkInterfaces.DesktopNetworkInterfaces;
const exit = yield* Effect.exit(service.read);
assert.equal(exit._tag, "Failure");
if (exit._tag === "Failure") {
const error = Cause.squash(exit.cause);
assert.instanceOf(error, DesktopNetworkInterfaces.DesktopNetworkInterfacesReadError);
assert.equal(error.platform, "linux");
assert.strictEqual(error.cause, cause);
assert.equal(error.message, "Failed to read desktop network interfaces on linux.");
}
}).pipe(Effect.provide(TestLayer));
});
});
@@ -1,10 +1,8 @@
import * as NodeOS from "node:os";
import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Schema from "effect/Schema";
export interface DesktopNetworkInterfaceInfo {
readonly address: string;
@@ -20,18 +18,6 @@ export type NetworkInterfaces = Readonly<
Record<string, readonly DesktopNetworkInterfaceInfo[] | undefined>
>;
export class DesktopNetworkInterfacesReadError extends Schema.TaggedErrorClass<DesktopNetworkInterfacesReadError>()(
"DesktopNetworkInterfacesReadError",
{
platform: Schema.String,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to read desktop network interfaces on ${this.platform}.`;
}
}
export class DesktopNetworkInterfaces extends Context.Service<
DesktopNetworkInterfaces,
{
@@ -39,14 +25,9 @@ export class DesktopNetworkInterfaces extends Context.Service<
}
>()("@t3tools/desktop/backend/DesktopNetworkInterfaces") {}
export const make = Effect.gen(function* () {
const platform = yield* HostProcessPlatform;
return DesktopNetworkInterfaces.of({
read: Effect.try({
try: () => NodeOS.networkInterfaces(),
catch: (cause) => new DesktopNetworkInterfacesReadError({ platform, cause }),
}).pipe(Effect.orDie),
export const make = (): DesktopNetworkInterfaces["Service"] =>
DesktopNetworkInterfaces.of({
read: Effect.sync(() => NodeOS.networkInterfaces()),
});
});
export const layer = Layer.effect(DesktopNetworkInterfaces, make);
export const layer = Layer.succeed(DesktopNetworkInterfaces, make());
@@ -91,7 +91,6 @@ function makeLayer(input: {
readonly networkInterfaces?: DesktopNetworkInterfaces.NetworkInterfaces;
readonly env?: Record<string, string | undefined>;
readonly spawnerLayer?: Layer.Layer<ChildProcessSpawner.ChildProcessSpawner>;
readonly desktopSettingsLayer?: Layer.Layer<DesktopAppSettings.DesktopAppSettings>;
}) {
const env = { T3CODE_HOME: input.baseDir, ...input.env };
const environmentLayer = makeEnvironmentLayer(input.baseDir, env);
@@ -100,7 +99,7 @@ function makeLayer(input: {
});
return DesktopServerExposure.layer.pipe(
Layer.provideMerge(input.desktopSettingsLayer ?? DesktopAppSettings.layer),
Layer.provideMerge(DesktopAppSettings.layer),
Layer.provideMerge(NodeFileSystem.layer),
Layer.provideMerge(NodeHttpClient.layerUndici),
Layer.provideMerge(input.spawnerLayer ?? mockSpawnerLayer()),
@@ -123,7 +122,6 @@ const withHarness = <A, E, R>(
>,
env: Record<string, string | undefined> = {},
spawnerLayer?: Layer.Layer<ChildProcessSpawner.ChildProcessSpawner>,
desktopSettingsLayer?: Layer.Layer<DesktopAppSettings.DesktopAppSettings>,
) =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
@@ -137,7 +135,6 @@ const withHarness = <A, E, R>(
networkInterfaces,
env,
...(spawnerLayer ? { spawnerLayer } : {}),
...(desktopSettingsLayer ? { desktopSettingsLayer } : {}),
}),
),
);
@@ -240,72 +237,6 @@ describe("DesktopServerExposure", () => {
),
);
it.effect("preserves persistence request context and the settings failure chain", () => {
const diskFailure = new Error("disk exploded");
const settingsFailure = new DesktopAppSettings.DesktopSettingsWriteError({
operation: "replace-settings-file",
path: "/tmp/desktop-settings.json",
cause: diskFailure,
});
const settingsLayer = Layer.succeed(DesktopAppSettings.DesktopAppSettings, {
get: Effect.succeed(DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS),
load: Effect.succeed(DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS),
setServerExposureMode: () => Effect.fail(settingsFailure),
setTailscaleServe: () => Effect.fail(settingsFailure),
setUpdateChannel: () => Effect.die("unexpected update channel change"),
setWslBackendEnabled: () => Effect.die("unexpected WSL backend toggle"),
setWslDistro: () => Effect.die("unexpected WSL distro change"),
setWslOnly: () => Effect.die("unexpected WSL-only toggle"),
applyWslWindowsFallback: Effect.die("unexpected WSL Windows fallback"),
applyWslWindowsFallbackInMemory: Effect.die("unexpected WSL Windows fallback"),
} satisfies DesktopAppSettings.DesktopAppSettings["Service"]);
return withHarness(
lanNetworkInterfaces,
Effect.gen(function* () {
const serverExposure = yield* DesktopServerExposure.DesktopServerExposure;
yield* serverExposure.configureFromSettings({ port: 4173 });
const modeError = yield* serverExposure.setMode("network-accessible").pipe(Effect.flip);
assert.instanceOf(
modeError,
DesktopServerExposure.DesktopServerExposureModePersistenceError,
);
assert.isTrue(DesktopServerExposure.isDesktopServerExposureSetModeError(modeError));
assert.isTrue(DesktopServerExposure.isDesktopServerExposureError(modeError));
assert.equal(modeError.mode, "network-accessible");
assert.strictEqual(modeError.cause, settingsFailure);
assert.strictEqual(modeError.cause.cause, diskFailure);
assert.equal(
modeError.message,
"Failed to persist desktop server exposure mode network-accessible.",
);
assert.notInclude(modeError.message, diskFailure.message);
const tailscaleError = yield* serverExposure
.setTailscaleServeEnabled({ enabled: true, port: 8443 })
.pipe(Effect.flip);
assert.instanceOf(
tailscaleError,
DesktopServerExposure.DesktopTailscaleServePersistenceError,
);
assert.isTrue(DesktopServerExposure.isDesktopServerExposureError(tailscaleError));
assert.equal(tailscaleError.enabled, true);
assert.equal(tailscaleError.port, 8443);
assert.strictEqual(tailscaleError.cause, settingsFailure);
assert.strictEqual(tailscaleError.cause.cause, diskFailure);
assert.equal(
tailscaleError.message,
"Failed to persist desktop Tailscale Serve settings (enabled: true, port: 8443).",
);
assert.notInclude(tailscaleError.message, diskFailure.message);
}),
{},
undefined,
settingsLayer,
);
});
it.effect("resolves advertised endpoints from the scoped runtime state", () =>
withHarness(
{ ...lanNetworkInterfaces, ...tailnetNetworkInterfaces },
@@ -2,12 +2,11 @@ import {
createAdvertisedEndpoint,
type CreateAdvertisedEndpointInput,
} from "@t3tools/shared/advertisedEndpoint";
import {
DesktopServerExposureModeSchema,
type AdvertisedEndpoint,
type AdvertisedEndpointProvider,
type DesktopServerExposureMode,
type DesktopServerExposureState,
import type {
AdvertisedEndpoint,
AdvertisedEndpointProvider,
DesktopServerExposureMode,
DesktopServerExposureState,
} from "@t3tools/contracts";
import { readTailscaleStatus } from "@t3tools/tailscale";
import * as Context from "effect/Context";
@@ -214,45 +213,23 @@ export class DesktopServerExposureNoNetworkAddressError extends Schema.TaggedErr
}
}
export class DesktopServerExposureModePersistenceError extends Schema.TaggedErrorClass<DesktopServerExposureModePersistenceError>()(
"DesktopServerExposureModePersistenceError",
export class DesktopServerExposurePersistenceError extends Schema.TaggedErrorClass<DesktopServerExposurePersistenceError>()(
"DesktopServerExposurePersistenceError",
{
mode: DesktopServerExposureModeSchema,
operation: Schema.Literals(["server-exposure-mode", "tailscale-serve"]),
cause: Schema.instanceOf(DesktopAppSettings.DesktopSettingsWriteError),
},
) {
override get message(): string {
return `Failed to persist desktop server exposure mode ${this.mode}.`;
return `Failed to persist desktop ${this.operation} settings.`;
}
}
export class DesktopTailscaleServePersistenceError extends Schema.TaggedErrorClass<DesktopTailscaleServePersistenceError>()(
"DesktopTailscaleServePersistenceError",
{
enabled: Schema.Boolean,
port: Schema.NullOr(Schema.Number),
cause: Schema.instanceOf(DesktopAppSettings.DesktopSettingsWriteError),
},
) {
override get message(): string {
return `Failed to persist desktop Tailscale Serve settings (enabled: ${this.enabled}, port: ${this.port ?? "unchanged"}).`;
}
}
export type DesktopServerExposureSetModeError =
| DesktopServerExposureNoNetworkAddressError
| DesktopServerExposurePersistenceError;
export const DesktopServerExposureSetModeError = Schema.Union([
DesktopServerExposureNoNetworkAddressError,
DesktopServerExposureModePersistenceError,
]);
export type DesktopServerExposureSetModeError = typeof DesktopServerExposureSetModeError.Type;
export const isDesktopServerExposureSetModeError = Schema.is(DesktopServerExposureSetModeError);
export const DesktopServerExposureError = Schema.Union([
DesktopServerExposureNoNetworkAddressError,
DesktopServerExposureModePersistenceError,
DesktopTailscaleServePersistenceError,
]);
export type DesktopServerExposureError = typeof DesktopServerExposureError.Type;
export const isDesktopServerExposureError = Schema.is(DesktopServerExposureError);
export type DesktopServerExposureError = DesktopServerExposureSetModeError;
export interface DesktopServerExposureBackendConfig {
readonly port: number;
@@ -281,7 +258,7 @@ export class DesktopServerExposure extends Context.Service<
readonly setTailscaleServeEnabled: (input: {
readonly enabled: boolean;
readonly port?: number;
}) => Effect.Effect<DesktopServerExposureChange, DesktopTailscaleServePersistenceError>;
}) => Effect.Effect<DesktopServerExposureChange, DesktopServerExposurePersistenceError>;
readonly getAdvertisedEndpoints: Effect.Effect<readonly AdvertisedEndpoint[]>;
}
>()("@t3tools/desktop/backend/DesktopServerExposure") {}
@@ -472,8 +449,8 @@ export const make = Effect.gen(function* () {
const change = yield* desktopSettings.setServerExposureMode(mode).pipe(
Effect.mapError(
(cause) =>
new DesktopServerExposureModePersistenceError({
mode,
new DesktopServerExposurePersistenceError({
operation: "server-exposure-mode",
cause,
}),
),
@@ -500,9 +477,8 @@ export const make = Effect.gen(function* () {
.pipe(
Effect.mapError(
(cause) =>
new DesktopTailscaleServePersistenceError({
enabled: input.enabled,
port: input.port ?? null,
new DesktopServerExposurePersistenceError({
operation: "tailscale-serve",
cause,
}),
),
@@ -100,44 +100,6 @@ describe("ElectronApp", () => {
}).pipe(Effect.provide(ElectronApp.layer)),
);
it.effect("reports which app metadata property failed", () =>
Effect.gen(function* () {
const cause = new Error("version unavailable");
getVersionMock.mockImplementationOnce(() => {
throw cause;
});
const electronApp = yield* ElectronApp.ElectronApp;
const error = yield* electronApp.metadata.pipe(Effect.flip);
assert.instanceOf(error, ElectronApp.ElectronAppMetadataReadError);
assert.strictEqual(error.property, "app-version");
assert.strictEqual(error.cause, cause);
assert.strictEqual(
error.message,
'Failed to read Electron app metadata property "app-version".',
);
}).pipe(Effect.provide(ElectronApp.layer)),
);
it.effect("preserves Electron readiness failures", () =>
Effect.gen(function* () {
const cause = new Error("ready failed");
whenReadyMock.mockRejectedValueOnce(cause);
const electronApp = yield* ElectronApp.ElectronApp;
const error = yield* electronApp.whenReady.pipe(Effect.flip);
assert.instanceOf(error, ElectronApp.ElectronAppWhenReadyError);
assert.strictEqual(error.isPackaged, true);
assert.strictEqual(error.cause, cause);
assert.strictEqual(
error.message,
"Failed to wait for the Electron app to become ready (packaged: true).",
);
}).pipe(Effect.provide(ElectronApp.layer)),
);
it.effect("scopes app event listeners", () =>
Effect.gen(function* () {
const listener = vi.fn();
+10 -60
View File
@@ -1,7 +1,6 @@
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Schema from "effect/Schema";
import * as Scope from "effect/Scope";
import * as Electron from "electron";
@@ -14,36 +13,12 @@ export interface ElectronAppMetadata {
readonly runningUnderArm64Translation: boolean;
}
export class ElectronAppMetadataReadError extends Schema.TaggedErrorClass<ElectronAppMetadataReadError>()(
"ElectronAppMetadataReadError",
{
property: Schema.Literals(["app-version", "app-path"]),
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to read Electron app metadata property "${this.property}".`;
}
}
export class ElectronAppWhenReadyError extends Schema.TaggedErrorClass<ElectronAppWhenReadyError>()(
"ElectronAppWhenReadyError",
{
isPackaged: Schema.Boolean,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to wait for the Electron app to become ready (packaged: ${this.isPackaged}).`;
}
}
export class ElectronApp extends Context.Service<
ElectronApp,
{
readonly metadata: Effect.Effect<ElectronAppMetadata, ElectronAppMetadataReadError>;
readonly metadata: Effect.Effect<ElectronAppMetadata>;
readonly name: Effect.Effect<string>;
readonly whenReady: Effect.Effect<void, ElectronAppWhenReadyError>;
readonly whenReady: Effect.Effect<void>;
readonly quit: Effect.Effect<void>;
readonly exit: (code: number) => Effect.Effect<void>;
readonly relaunch: (options: Electron.RelaunchOptions) => Effect.Effect<void>;
@@ -88,40 +63,15 @@ const addScopedAppListener = <Args extends ReadonlyArray<unknown>>(
).pipe(Effect.asVoid);
export const make = ElectronApp.of({
metadata: Effect.gen(function* () {
const appVersion = yield* Effect.try({
try: () => Electron.app.getVersion(),
catch: (cause) =>
new ElectronAppMetadataReadError({
property: "app-version",
cause,
}),
});
const appPath = yield* Effect.try({
try: () => Electron.app.getAppPath(),
catch: (cause) =>
new ElectronAppMetadataReadError({
property: "app-path",
cause,
}),
});
return {
appVersion,
appPath,
isPackaged: Electron.app.isPackaged,
resourcesPath: process.resourcesPath,
runningUnderArm64Translation: Electron.app.runningUnderARM64Translation === true,
};
}),
metadata: Effect.sync(() => ({
appVersion: Electron.app.getVersion(),
appPath: Electron.app.getAppPath(),
isPackaged: Electron.app.isPackaged,
resourcesPath: process.resourcesPath,
runningUnderArm64Translation: Electron.app.runningUnderARM64Translation === true,
})),
name: Effect.sync(() => Electron.app.name),
whenReady: Effect.gen(function* () {
const isPackaged = Electron.app.isPackaged;
yield* Effect.tryPromise({
try: () => Electron.app.whenReady(),
catch: (cause) => new ElectronAppWhenReadyError({ isPackaged, cause }),
});
}),
whenReady: Effect.promise(() => Electron.app.whenReady()).pipe(Effect.asVoid),
quit: Effect.sync(() => {
Electron.app.quit();
}),
@@ -1,5 +1,4 @@
import { assert, describe, it } from "@effect/vitest";
import * as Cause from "effect/Cause";
import * as Effect from "effect/Effect";
import * as Option from "effect/Option";
import type { BrowserWindow } from "electron";
@@ -91,116 +90,4 @@ describe("ElectronDialog", () => {
]);
}).pipe(Effect.provide(ElectronDialog.layer)),
);
it.effect("preserves folder picker request context and cause", () =>
Effect.gen(function* () {
const cause = new Error("folder picker failed");
const owner = { id: 7 } as BrowserWindow;
showOpenDialogMock.mockRejectedValue(cause);
const dialog = yield* ElectronDialog.ElectronDialog;
const error = yield* Effect.flip(
dialog.pickFolder({
owner: Option.some(owner),
defaultPath: Option.some("/workspace"),
}),
);
assert.instanceOf(error, ElectronDialog.ElectronDialogPickFolderError);
assert.isTrue(ElectronDialog.isElectronDialogError(error));
assert.strictEqual(error.ownerWindowId, 7);
assert.strictEqual(error.defaultPath, "/workspace");
assert.strictEqual(error.cause, cause);
assert.include(error.message, "window 7");
assert.include(error.message, "/workspace");
assert.notInclude(error.message, cause.message);
}).pipe(Effect.provide(ElectronDialog.layer)),
);
it.effect("preserves confirmation request context and cause", () =>
Effect.gen(function* () {
const cause = new Error("confirmation failed");
const owner = { id: 9 } as BrowserWindow;
showMessageBoxMock.mockRejectedValue(cause);
const dialog = yield* ElectronDialog.ElectronDialog;
const error = yield* Effect.flip(
dialog.confirm({
owner: Option.some(owner),
message: " Confirm removal? ",
}),
);
assert.instanceOf(error, ElectronDialog.ElectronDialogConfirmError);
assert.strictEqual(error.ownerWindowId, 9);
assert.strictEqual(error.promptLength, "Confirm removal?".length);
assert.notProperty(error, "promptMessage");
assert.strictEqual(error.cause, cause);
assert.include(error.message, "window 9");
assert.notInclude(error.message, "Confirm removal?");
assert.notInclude(error.message, cause.message);
}).pipe(Effect.provide(ElectronDialog.layer)),
);
it.effect("preserves message box request context and cause", () =>
Effect.gen(function* () {
const cause = new Error("message box failed");
showMessageBoxMock.mockRejectedValue(cause);
const dialog = yield* ElectronDialog.ElectronDialog;
const error = yield* Effect.flip(
dialog.showMessageBox({
type: "warning",
title: "Unsaved changes",
message: "Discard changes?",
detail: "This cannot be undone.",
buttons: ["Cancel", "Discard"],
}),
);
assert.instanceOf(error, ElectronDialog.ElectronDialogShowMessageBoxError);
assert.strictEqual(error.type, "warning");
assert.strictEqual(error.titleLength, "Unsaved changes".length);
assert.strictEqual(error.messageLength, "Discard changes?".length);
assert.strictEqual(error.detailLength, "This cannot be undone.".length);
assert.strictEqual(error.buttonCount, 2);
assert.notProperty(error, "title");
assert.notProperty(error, "dialogMessage");
assert.notProperty(error, "dialogDetail");
assert.notProperty(error, "buttons");
assert.strictEqual(error.cause, cause);
assert.include(error.message, "warning");
assert.notInclude(error.message, "Unsaved changes");
assert.notInclude(error.message, "Discard changes?");
assert.notInclude(error.message, "This cannot be undone.");
assert.notInclude(error.message, "Cancel");
assert.notInclude(error.message, "Discard");
assert.notInclude(error.message, cause.message);
}).pipe(Effect.provide(ElectronDialog.layer)),
);
it.effect("preserves error box request context and cause in the defect", () =>
Effect.gen(function* () {
const cause = new Error("error box failed");
showErrorBoxMock.mockImplementation(() => {
throw cause;
});
const dialog = yield* ElectronDialog.ElectronDialog;
const exit = yield* Effect.exit(dialog.showErrorBox("Startup failed", "Could not start."));
assert.isTrue(exit._tag === "Failure");
if (exit._tag === "Success") return;
const error = Cause.squash(exit.cause);
assert.instanceOf(error, ElectronDialog.ElectronDialogShowErrorBoxError);
assert.strictEqual(error.titleLength, "Startup failed".length);
assert.strictEqual(error.contentLength, "Could not start.".length);
assert.notProperty(error, "title");
assert.notProperty(error, "content");
assert.strictEqual(error.cause, cause);
assert.notInclude(error.message, "Startup failed");
assert.notInclude(error.message, "Could not start.");
assert.notInclude(error.message, cause.message);
}).pipe(Effect.provide(ElectronDialog.layer)),
);
});
+14 -129
View File
@@ -2,80 +2,11 @@ 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 Electron from "electron";
const CONFIRM_BUTTON_INDEX = 1;
export class ElectronDialogPickFolderError extends Schema.TaggedErrorClass<ElectronDialogPickFolderError>()(
"ElectronDialogPickFolderError",
{
ownerWindowId: Schema.NullOr(Schema.Number),
defaultPath: Schema.NullOr(Schema.String),
cause: Schema.Defect(),
},
) {
override get message(): string {
const owner = this.ownerWindowId === null ? "the application" : `window ${this.ownerWindowId}`;
const defaultPath = this.defaultPath === null ? "no default path" : this.defaultPath;
return `Failed to open the Electron folder picker for ${owner} with ${defaultPath}.`;
}
}
export class ElectronDialogConfirmError extends Schema.TaggedErrorClass<ElectronDialogConfirmError>()(
"ElectronDialogConfirmError",
{
ownerWindowId: Schema.NullOr(Schema.Number),
promptLength: Schema.Number,
cause: Schema.Defect(),
},
) {
override get message(): string {
const owner = this.ownerWindowId === null ? "the application" : `window ${this.ownerWindowId}`;
return `Failed to open an Electron confirmation dialog for ${owner} with a ${this.promptLength}-character prompt.`;
}
}
export class ElectronDialogShowMessageBoxError extends Schema.TaggedErrorClass<ElectronDialogShowMessageBoxError>()(
"ElectronDialogShowMessageBoxError",
{
type: Schema.NullOr(Schema.Literals(["none", "info", "error", "question", "warning"])),
titleLength: Schema.NullOr(Schema.Number),
messageLength: Schema.Number,
detailLength: Schema.NullOr(Schema.Number),
buttonCount: Schema.Number,
cause: Schema.Defect(),
},
) {
override get message(): string {
const type = this.type === null ? "untyped" : this.type;
return `Failed to show the Electron ${type} message box with ${this.buttonCount} buttons.`;
}
}
export class ElectronDialogShowErrorBoxError extends Schema.TaggedErrorClass<ElectronDialogShowErrorBoxError>()(
"ElectronDialogShowErrorBoxError",
{
titleLength: Schema.Number,
contentLength: Schema.Number,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to show the Electron error box with a ${this.titleLength}-character title and ${this.contentLength}-character content.`;
}
}
export const ElectronDialogError = Schema.Union([
ElectronDialogPickFolderError,
ElectronDialogConfirmError,
ElectronDialogShowMessageBoxError,
ElectronDialogShowErrorBoxError,
]);
export type ElectronDialogError = typeof ElectronDialogError.Type;
export const isElectronDialogError = Schema.is(ElectronDialogError);
export interface ElectronDialogPickFolderInput {
readonly owner: Option.Option<Electron.BrowserWindow>;
readonly defaultPath: Option.Option<string>;
@@ -91,24 +22,17 @@ export class ElectronDialog extends Context.Service<
{
readonly pickFolder: (
input: ElectronDialogPickFolderInput,
) => Effect.Effect<Option.Option<string>, ElectronDialogPickFolderError>;
readonly confirm: (
input: ElectronDialogConfirmInput,
) => Effect.Effect<boolean, ElectronDialogConfirmError>;
) => Effect.Effect<Option.Option<string>>;
readonly confirm: (input: ElectronDialogConfirmInput) => Effect.Effect<boolean>;
readonly showMessageBox: (
options: Electron.MessageBoxOptions,
) => Effect.Effect<Electron.MessageBoxReturnValue, ElectronDialogShowMessageBoxError>;
) => Effect.Effect<Electron.MessageBoxReturnValue>;
readonly showErrorBox: (title: string, content: string) => Effect.Effect<void>;
}
>()("@t3tools/desktop/electron/ElectronDialog") {}
export const make = ElectronDialog.of({
pickFolder: Effect.fn("desktop.electron.dialog.pickFolder")(function* (input) {
const ownerWindowId = Option.match(input.owner, {
onNone: () => null,
onSome: (owner) => owner.id,
});
const defaultPath = Option.getOrNull(input.defaultPath);
const openDialogOptions: Electron.OpenDialogOptions = Option.match(input.defaultPath, {
onNone: () => ({
properties: ["openDirectory", "createDirectory"],
@@ -118,18 +42,10 @@ export const make = ElectronDialog.of({
defaultPath,
}),
});
const result = yield* Effect.tryPromise({
try: () =>
Option.match(input.owner, {
onNone: () => Electron.dialog.showOpenDialog(openDialogOptions),
onSome: (owner) => Electron.dialog.showOpenDialog(owner, openDialogOptions),
}),
catch: (cause) =>
new ElectronDialogPickFolderError({
ownerWindowId,
defaultPath,
cause,
}),
const result = yield* Option.match(input.owner, {
onNone: () => Effect.promise(() => Electron.dialog.showOpenDialog(openDialogOptions)),
onSome: (owner) =>
Effect.promise(() => Electron.dialog.showOpenDialog(owner, openDialogOptions)),
});
if (result.canceled) {
@@ -151,48 +67,17 @@ export const make = ElectronDialog.of({
noLink: true,
message: normalizedMessage,
};
const ownerWindowId = Option.match(input.owner, {
onNone: () => null,
onSome: (owner) => owner.id,
});
const result = yield* Effect.tryPromise({
try: () =>
Option.match(input.owner, {
onNone: () => Electron.dialog.showMessageBox(options),
onSome: (owner) => Electron.dialog.showMessageBox(owner, options),
}),
catch: (cause) =>
new ElectronDialogConfirmError({
ownerWindowId,
promptLength: normalizedMessage.length,
cause,
}),
const result = yield* Option.match(input.owner, {
onNone: () => Effect.promise(() => Electron.dialog.showMessageBox(options)),
onSome: (owner) => Effect.promise(() => Electron.dialog.showMessageBox(owner, options)),
});
return result.response === CONFIRM_BUTTON_INDEX;
}),
showMessageBox: (options) =>
Effect.tryPromise({
try: () => Electron.dialog.showMessageBox(options),
catch: (cause) =>
new ElectronDialogShowMessageBoxError({
type: options.type ?? null,
titleLength: options.title?.length ?? null,
messageLength: options.message.length,
detailLength: options.detail?.length ?? null,
buttonCount: options.buttons?.length ?? 0,
cause,
}),
}),
showMessageBox: (options) => Effect.promise(() => Electron.dialog.showMessageBox(options)),
showErrorBox: (title, content) =>
Effect.try({
try: () => Electron.dialog.showErrorBox(title, content),
catch: (cause) =>
new ElectronDialogShowErrorBoxError({
titleLength: title.length,
contentLength: content.length,
cause,
}),
}).pipe(Effect.orDie),
Effect.sync(() => {
Electron.dialog.showErrorBox(title, content);
}),
});
export const layer = Layer.succeed(ElectronDialog, make);
+4 -94
View File
@@ -1,8 +1,5 @@
import { assert, describe, it } from "@effect/vitest";
import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
import * as Cause from "effect/Cause";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import type * as Electron from "electron";
import { beforeEach, vi } from "vite-plus/test";
@@ -27,10 +24,6 @@ vi.mock("electron", () => ({
import * as ElectronMenu from "./ElectronMenu.ts";
const TestLayer = ElectronMenu.layer.pipe(
Layer.provide(Layer.succeed(HostProcessPlatform, "linux")),
);
describe("ElectronMenu", () => {
beforeEach(() => {
buildFromTemplateMock.mockReset();
@@ -49,7 +42,7 @@ describe("ElectronMenu", () => {
assert.isTrue(Option.isNone(selectedItemId));
assert.equal(buildFromTemplateMock.mock.calls.length, 0);
}).pipe(Effect.provide(TestLayer)),
}).pipe(Effect.provide(ElectronMenu.layer)),
);
it.effect("resolves with the clicked leaf item id", () =>
@@ -76,7 +69,7 @@ describe("ElectronMenu", () => {
});
assert.equal(Option.getOrNull(selectedItemId), "copy");
}).pipe(Effect.provide(TestLayer)),
}).pipe(Effect.provide(ElectronMenu.layer)),
);
it.effect("resolves with none when the menu closes without a click", () =>
@@ -100,7 +93,7 @@ describe("ElectronMenu", () => {
enabled: true,
click: buildFromTemplateMock.mock.calls[0]?.[0][0].click,
});
}).pipe(Effect.provide(TestLayer)),
}).pipe(Effect.provide(ElectronMenu.layer)),
);
it.effect("defers popupTemplate side effects until the returned Effect runs", () =>
@@ -121,89 +114,6 @@ describe("ElectronMenu", () => {
assert.equal(buildFromTemplateMock.mock.calls.length, 1);
assert.equal(popupMock.mock.calls.length, 1);
}).pipe(Effect.provide(TestLayer)),
);
it.effect("preserves application-menu failures as structured defects", () =>
Effect.gen(function* () {
const cause = new Error("application menu build failed");
buildFromTemplateMock.mockImplementationOnce(() => {
throw cause;
});
const electronMenu = yield* ElectronMenu.ElectronMenu;
const exit = yield* Effect.exit(
electronMenu.setApplicationMenu([{ label: "File" }, { label: "Edit" }]),
);
assert.equal(exit._tag, "Failure");
if (exit._tag === "Failure") {
const error = Cause.squash(exit.cause);
assert.instanceOf(error, ElectronMenu.ElectronMenuOperationError);
assert.equal(error.operation, "set-application-menu");
assert.equal(error.platform, "linux");
assert.isNull(error.windowId);
assert.equal(error.itemCount, 2);
assert.strictEqual(error.cause, cause);
assert.notInclude(error.message, cause.message);
}
}).pipe(Effect.provide(TestLayer)),
);
it.effect("preserves popup-template failures with window context", () =>
Effect.gen(function* () {
const cause = new Error("popup failed");
buildFromTemplateMock.mockReturnValueOnce({
popup: () => {
throw cause;
},
});
const electronMenu = yield* ElectronMenu.ElectronMenu;
const exit = yield* Effect.exit(
electronMenu.popupTemplate({
window: { id: 41 } as Electron.BrowserWindow,
template: [{ label: "Copy" }],
}),
);
assert.equal(exit._tag, "Failure");
if (exit._tag === "Failure") {
const error = Cause.squash(exit.cause);
assert.instanceOf(error, ElectronMenu.ElectronMenuOperationError);
assert.equal(error.operation, "popup-template");
assert.equal(error.windowId, 41);
assert.equal(error.itemCount, 1);
assert.strictEqual(error.cause, cause);
}
}).pipe(Effect.provide(TestLayer)),
);
it.effect("preserves context-menu failures with normalized item context", () =>
Effect.gen(function* () {
const cause = new Error("context menu build failed");
buildFromTemplateMock.mockImplementationOnce(() => {
throw cause;
});
const electronMenu = yield* ElectronMenu.ElectronMenu;
const exit = yield* Effect.exit(
electronMenu.showContextMenu({
window: { id: 42 } as Electron.BrowserWindow,
items: [{ id: "copy", label: "Copy" }],
position: Option.none(),
}),
);
assert.equal(exit._tag, "Failure");
if (exit._tag === "Failure") {
const error = Cause.squash(exit.cause);
assert.instanceOf(error, ElectronMenu.ElectronMenuOperationError);
assert.equal(error.operation, "show-context-menu");
assert.equal(error.windowId, 42);
assert.equal(error.itemCount, 1);
assert.strictEqual(error.cause, cause);
}
}).pipe(Effect.provide(TestLayer)),
}).pipe(Effect.provide(ElectronMenu.layer)),
);
});
+24 -85
View File
@@ -4,7 +4,6 @@ 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 Electron from "electron";
@@ -24,28 +23,6 @@ export interface ElectronMenuTemplateInput {
readonly template: readonly Electron.MenuItemConstructorOptions[];
}
const ElectronMenuOperation = Schema.Literals([
"set-application-menu",
"popup-template",
"show-context-menu",
]);
export class ElectronMenuOperationError extends Schema.TaggedErrorClass<ElectronMenuOperationError>()(
"ElectronMenuOperationError",
{
operation: ElectronMenuOperation,
platform: Schema.String,
windowId: Schema.NullOr(Schema.Number),
itemCount: Schema.Number,
cause: Schema.Defect(),
},
) {
override get message(): string {
const window = this.windowId === null ? "" : ` for window ${this.windowId}`;
return `Electron menu operation ${JSON.stringify(this.operation)} failed${window} with ${this.itemCount} items on ${this.platform}.`;
}
}
export class ElectronMenu extends Context.Service<
ElectronMenu,
{
@@ -165,36 +142,16 @@ export const make = Effect.gen(function* () {
return ElectronMenu.of({
setApplicationMenu: (template) =>
Effect.try({
try: () => {
Electron.Menu.setApplicationMenu(Electron.Menu.buildFromTemplate([...template]));
},
catch: (cause) =>
new ElectronMenuOperationError({
operation: "set-application-menu",
platform,
windowId: null,
itemCount: template.length,
cause,
}),
}).pipe(Effect.orDie),
Effect.sync(() => {
Electron.Menu.setApplicationMenu(Electron.Menu.buildFromTemplate([...template]));
}),
popupTemplate: (input) =>
input.template.length === 0
? Effect.void
: Effect.try({
try: () =>
Electron.Menu.buildFromTemplate([...input.template]).popup({
window: input.window,
}),
catch: (cause) =>
new ElectronMenuOperationError({
operation: "popup-template",
platform,
windowId: input.window.id,
itemCount: input.template.length,
cause,
}),
}).pipe(Effect.orDie),
Effect.sync(() => {
if (input.template.length === 0) {
return;
}
Electron.Menu.buildFromTemplate([...input.template]).popup({ window: input.window });
}),
showContextMenu: (input) =>
Effect.callback<Option.Option<string>>((resume) => {
const normalizedItems = normalizeContextMenuItems(input.items);
@@ -212,39 +169,21 @@ export const make = Effect.gen(function* () {
resume(Effect.succeed(selectedItemId));
};
try {
const menu = Electron.Menu.buildFromTemplate(buildTemplate(normalizedItems, complete));
const popupPosition = normalizePosition(input.position);
const popupOptions = Option.match(popupPosition, {
onNone: (): Electron.PopupOptions => ({
window: input.window,
callback: () => complete(Option.none()),
}),
onSome: (position): Electron.PopupOptions => ({
window: input.window,
x: position.x,
y: position.y,
callback: () => complete(Option.none()),
}),
});
menu.popup(popupOptions);
} catch (cause) {
if (completed) {
return;
}
completed = true;
resume(
Effect.die(
new ElectronMenuOperationError({
operation: "show-context-menu",
platform,
windowId: input.window.id,
itemCount: normalizedItems.length,
cause,
}),
),
);
}
const menu = Electron.Menu.buildFromTemplate(buildTemplate(normalizedItems, complete));
const popupPosition = normalizePosition(input.position);
const popupOptions = Option.match(popupPosition, {
onNone: (): Electron.PopupOptions => ({
window: input.window,
callback: () => complete(Option.none()),
}),
onSome: (position): Electron.PopupOptions => ({
window: input.window,
x: position.x,
y: position.y,
callback: () => complete(Option.none()),
}),
});
menu.popup(popupOptions);
}),
});
});
@@ -1,5 +1,4 @@
import { assert, describe, it } from "@effect/vitest";
import * as Cause from "effect/Cause";
import * as Effect from "effect/Effect";
import { beforeEach, vi } from "vite-plus/test";
@@ -43,16 +42,7 @@ describe("ElectronProtocol", () => {
assert.isDefined(handler);
const response = yield* Effect.promise(() =>
handler!(
new Request("t3code-dev://app/api/health?verbose=1", {
headers: {
accept: "application/json",
origin: "t3code-dev://app",
referer: "t3code-dev://app/",
"sec-fetch-site": "same-origin",
},
}),
),
handler!(new Request("t3code-dev://app/api/health?verbose=1")),
);
assert.equal(yield* Effect.promise(() => response.text()), "ok");
assert.include(
@@ -79,11 +69,6 @@ describe("ElectronProtocol", () => {
["t3code-dev"],
);
assert.equal(netFetchMock.mock.calls[0]?.[0], "http://127.0.0.1:3773/api/health?verbose=1");
const forwardedHeaders = new Headers(netFetchMock.mock.calls[0]?.[1]?.headers);
assert.equal(forwardedHeaders.get("accept"), "application/json");
assert.isNull(forwardedHeaders.get("origin"));
assert.isNull(forwardedHeaders.get("referer"));
assert.isNull(forwardedHeaders.get("sec-fetch-site"));
assert.deepEqual(unhandleMock.mock.calls, [["t3code-dev"]]);
}).pipe(Effect.provide(ElectronProtocol.layer)),
);
@@ -113,88 +98,6 @@ describe("ElectronProtocol", () => {
}).pipe(Effect.provide(ElectronProtocol.layer)),
);
it.effect("retries transient renderer target failures", () =>
Effect.gen(function* () {
let handler: ((request: Request) => Promise<Response>) | undefined;
handleMock.mockImplementation((_scheme, nextHandler) => {
handler = nextHandler;
});
netFetchMock
.mockRejectedValueOnce(new Error("connect ECONNREFUSED 127.0.0.1:5733"))
.mockResolvedValueOnce(new Response("ready"));
const response = yield* Effect.scoped(
Effect.gen(function* () {
const protocol = yield* ElectronProtocol.ElectronProtocol;
yield* protocol.registerDesktopProtocol({
scheme: "t3code-dev",
targetOrigin: new URL("http://127.0.0.1:5733/"),
backendOrigin: new URL("http://127.0.0.1:3773/"),
clerkFrontendApiHostname: undefined,
});
return yield* Effect.promise(() => handler!(new Request("t3code-dev://app/")));
}),
);
assert.equal(yield* Effect.promise(() => response.text()), "ready");
assert.equal(netFetchMock.mock.calls.length, 2);
}).pipe(Effect.provide(ElectronProtocol.layer)),
);
it.effect("preserves protocol registration failures", () =>
Effect.gen(function* () {
const cause = new Error("protocol registration failed");
handleMock.mockImplementationOnce(() => {
throw cause;
});
const protocol = yield* ElectronProtocol.ElectronProtocol;
const error = yield* Effect.scoped(
protocol.registerDesktopProtocol({
scheme: "t3code-dev",
targetOrigin: new URL("http://127.0.0.1:3773/"),
backendOrigin: new URL("http://127.0.0.1:3774/"),
clerkFrontendApiHostname: undefined,
}),
).pipe(Effect.flip);
assert.instanceOf(error, ElectronProtocol.ElectronProtocolRegistrationError);
assert.equal(error.scheme, "t3code-dev");
assert.strictEqual(error.cause, cause);
assert.equal(error.message, 'Failed to register Electron protocol scheme "t3code-dev".');
}).pipe(Effect.provide(ElectronProtocol.layer)),
);
it.effect("preserves protocol unregistration failures", () =>
Effect.gen(function* () {
const cause = new Error("protocol unregistration failed");
unhandleMock.mockImplementationOnce(() => {
throw cause;
});
const protocol = yield* ElectronProtocol.ElectronProtocol;
const exit = yield* Effect.exit(
Effect.scoped(
protocol.registerDesktopProtocol({
scheme: "t3code",
targetOrigin: new URL("http://127.0.0.1:3773/"),
backendOrigin: new URL("http://127.0.0.1:3773/"),
clerkFrontendApiHostname: undefined,
}),
),
);
assert.equal(exit._tag, "Failure");
if (exit._tag === "Failure") {
const error = Cause.squash(exit.cause);
assert.instanceOf(error, ElectronProtocol.ElectronProtocolUnregistrationError);
assert.equal(error.scheme, "t3code");
assert.strictEqual(error.cause, cause);
assert.equal(error.message, 'Failed to unregister Electron protocol scheme "t3code".');
}
}).pipe(Effect.provide(ElectronProtocol.layer)),
);
it("keeps executable sources host-restricted while allowing runtime network resources", () => {
const policy = ElectronProtocol.makeDesktopContentSecurityPolicy({
scheme: "t3code",
+6 -66
View File
@@ -1,7 +1,6 @@
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as NodeTimersPromises from "node:timers/promises";
import * as Ref from "effect/Ref";
import * as Schema from "effect/Schema";
import * as Scope from "effect/Scope";
@@ -32,19 +31,7 @@ export class ElectronProtocolRegistrationError extends Schema.TaggedErrorClass<E
},
) {
override get message(): string {
return `Failed to register Electron protocol scheme "${this.scheme}".`;
}
}
export class ElectronProtocolUnregistrationError extends Schema.TaggedErrorClass<ElectronProtocolUnregistrationError>()(
"ElectronProtocolUnregistrationError",
{
scheme: Schema.String,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to unregister Electron protocol scheme "${this.scheme}".`;
return `Failed to register ${this.scheme}: protocol.`;
}
}
@@ -115,60 +102,18 @@ async function proxyRequest(
}
const targetUrl = new URL(`${requestUrl.pathname}${requestUrl.search}`, targetOrigin);
const headers = new Headers(request.headers);
const headersToRemove: string[] = [];
for (const name of headers.keys()) {
if (
name === "host" ||
name === "origin" ||
name === "referer" ||
name === "connection" ||
name === "content-length" ||
name === "accept-encoding" ||
name === "upgrade-insecure-requests" ||
name.startsWith("sec-fetch-")
) {
headersToRemove.push(name);
}
}
for (const name of headersToRemove) {
headers.delete(name);
}
const init: RequestInit = {
method: request.method,
headers,
headers: request.headers,
};
if (request.method !== "GET" && request.method !== "HEAD") {
init.body = request.body;
(init as RequestInit & { duplex: "half" }).duplex = "half";
}
const response =
request.method === "GET" || request.method === "HEAD"
? await fetchWithTransientRetry(targetUrl.toString(), init)
: await Electron.net.fetch(targetUrl.toString(), init);
const response = await Electron.net.fetch(targetUrl.toString(), init);
return withContentSecurityPolicy(response, contentSecurityPolicy);
}
const TRANSIENT_FETCH_RETRY_DELAYS_MS = [0, 50, 150] as const;
async function fetchWithTransientRetry(url: string, init: RequestInit): Promise<Response> {
let lastError: unknown;
for (const delayMs of TRANSIENT_FETCH_RETRY_DELAYS_MS) {
if (delayMs > 0) {
await NodeTimersPromises.setTimeout(delayMs);
}
try {
return await Electron.net.fetch(url, init);
} catch (error) {
lastError = error;
}
}
throw lastError;
}
export const make = Effect.gen(function* () {
const registered = yield* Ref.make(false);
@@ -188,14 +133,9 @@ export const make = Effect.gen(function* () {
catch: (cause) => new ElectronProtocolRegistrationError({ scheme: input.scheme, cause }),
}).pipe(Effect.andThen(Ref.set(registered, true))),
() =>
Effect.try({
try: () => Electron.protocol.unhandle(input.scheme),
catch: (cause) =>
new ElectronProtocolUnregistrationError({
scheme: input.scheme,
cause,
}),
}).pipe(Effect.andThen(Ref.set(registered, false)), Effect.orDie),
Effect.sync(() => {
Electron.protocol.unhandle(input.scheme);
}).pipe(Effect.andThen(Ref.set(registered, false))),
);
},
);
@@ -8,7 +8,6 @@ const { onMock, removeListenerMock, themeState } = vi.hoisted(() => ({
themeState: {
shouldUseDarkColors: true,
themeSource: "system",
setSourceError: null as unknown,
},
}));
@@ -18,9 +17,6 @@ vi.mock("electron", () => ({
return themeState.shouldUseDarkColors;
},
set themeSource(value: string) {
if (themeState.setSourceError !== null) {
throw themeState.setSourceError;
}
themeState.themeSource = value;
},
on: onMock,
@@ -36,7 +32,6 @@ describe("ElectronTheme", () => {
removeListenerMock.mockClear();
themeState.shouldUseDarkColors = true;
themeState.themeSource = "system";
themeState.setSourceError = null;
});
it.effect("scopes native theme update listeners", () =>
@@ -54,21 +49,4 @@ describe("ElectronTheme", () => {
assert.deepEqual(removeListenerMock.mock.calls, [["updated", listener]]);
}).pipe(Effect.provide(ElectronTheme.layer)),
);
it.effect("preserves the requested source and cause when setting the theme fails", () =>
Effect.gen(function* () {
const cause = new Error("theme source failed");
themeState.setSourceError = cause;
const electronTheme = yield* ElectronTheme.ElectronTheme;
const error = yield* Effect.flip(electronTheme.setSource("dark"));
assert.instanceOf(error, ElectronTheme.ElectronThemeSetSourceError);
assert.isTrue(ElectronTheme.isElectronThemeSetSourceError(error));
assert.strictEqual(error.source, "dark");
assert.strictEqual(error.cause, cause);
assert.include(error.message, "dark");
assert.notInclude(error.message, cause.message);
}).pipe(Effect.provide(ElectronTheme.layer)),
);
});
+5 -22
View File
@@ -1,31 +1,16 @@
import { DesktopThemeSchema, type DesktopTheme } from "@t3tools/contracts";
import type { DesktopTheme } from "@t3tools/contracts";
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Schema from "effect/Schema";
import * as Scope from "effect/Scope";
import * as Electron from "electron";
export class ElectronThemeSetSourceError extends Schema.TaggedErrorClass<ElectronThemeSetSourceError>()(
"ElectronThemeSetSourceError",
{
source: DesktopThemeSchema,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to set the Electron theme source to ${this.source}.`;
}
}
export const isElectronThemeSetSourceError = Schema.is(ElectronThemeSetSourceError);
export class ElectronTheme extends Context.Service<
ElectronTheme,
{
readonly shouldUseDarkColors: Effect.Effect<boolean>;
readonly setSource: (theme: DesktopTheme) => Effect.Effect<void, ElectronThemeSetSourceError>;
readonly setSource: (theme: DesktopTheme) => Effect.Effect<void>;
readonly onUpdated: (listener: () => void) => Effect.Effect<void, never, Scope.Scope>;
}
>()("@t3tools/desktop/electron/ElectronTheme") {}
@@ -33,11 +18,9 @@ export class ElectronTheme extends Context.Service<
export const make = ElectronTheme.of({
shouldUseDarkColors: Effect.sync(() => Electron.nativeTheme.shouldUseDarkColors),
setSource: (theme) =>
Effect.try({
try: () => {
Electron.nativeTheme.themeSource = theme;
},
catch: (cause) => new ElectronThemeSetSourceError({ source: theme, cause }),
Effect.suspend(() => {
Electron.nativeTheme.themeSource = theme;
return Effect.void;
}),
onUpdated: (listener) =>
Effect.acquireRelease(
@@ -1,4 +1,5 @@
import { assert, describe, it } from "@effect/vitest";
import * as Cause from "effect/Cause";
import * as Effect from "effect/Effect";
import { beforeEach, vi } from "vite-plus/test";
@@ -64,65 +65,16 @@ describe("ElectronUpdater", () => {
const cause = new Error("network unavailable");
autoUpdaterMock.checkForUpdates.mockImplementationOnce(() => Promise.reject(cause));
const updater = yield* ElectronUpdater.ElectronUpdater;
autoUpdaterMock.channel = "beta";
const error = yield* updater.checkForUpdates.pipe(Effect.flip);
const exit = yield* Effect.exit(updater.checkForUpdates);
assert.instanceOf(error, ElectronUpdater.ElectronUpdaterCheckForUpdatesError);
assert.isTrue(ElectronUpdater.isElectronUpdaterError(error));
assert.equal(error.channel, "beta");
assert.strictEqual(error.cause, cause);
assert.equal(error.message, "Electron updater failed to check for updates on channel beta.");
assert.notInclude(error.message, cause.message);
}).pipe(Effect.provide(ElectronUpdater.layer)),
);
it.effect("preserves the execution-time channel on download failures", () =>
Effect.gen(function* () {
const cause = new Error("download unavailable");
autoUpdaterMock.downloadUpdate.mockImplementationOnce(() => Promise.reject(cause));
const updater = yield* ElectronUpdater.ElectronUpdater;
autoUpdaterMock.channel = "nightly";
const error = yield* updater.downloadUpdate.pipe(Effect.flip);
assert.instanceOf(error, ElectronUpdater.ElectronUpdaterDownloadUpdateError);
assert.isTrue(ElectronUpdater.isElectronUpdaterError(error));
assert.equal(error.channel, "nightly");
assert.strictEqual(error.cause, cause);
assert.equal(
error.message,
"Electron updater failed to download the update on channel nightly.",
);
assert.notInclude(error.message, cause.message);
}).pipe(Effect.provide(ElectronUpdater.layer)),
);
it.effect("preserves quit-and-install flags and the execution-time channel", () =>
Effect.gen(function* () {
const cause = new Error("quit and install failed");
autoUpdaterMock.quitAndInstall.mockImplementationOnce(() => {
throw cause;
});
const updater = yield* ElectronUpdater.ElectronUpdater;
autoUpdaterMock.channel = "alpha";
const error = yield* updater
.quitAndInstall({ isSilent: true, isForceRunAfter: false })
.pipe(Effect.flip);
assert.instanceOf(error, ElectronUpdater.ElectronUpdaterQuitAndInstallError);
assert.isTrue(ElectronUpdater.isElectronUpdaterError(error));
assert.equal(error.channel, "alpha");
assert.equal(error.isSilent, true);
assert.equal(error.isForceRunAfter, false);
assert.strictEqual(error.cause, cause);
assert.equal(
error.message,
"Electron updater failed to quit and install the update on channel alpha (silent: true, force run after: false).",
);
assert.notInclude(error.message, cause.message);
assert.deepEqual(autoUpdaterMock.quitAndInstall.mock.calls, [[true, false]]);
assert.equal(exit._tag, "Failure");
if (exit._tag === "Failure") {
const error = Cause.squash(exit.cause);
assert.instanceOf(error, ElectronUpdater.ElectronUpdaterCheckForUpdatesError);
assert.equal(error.cause, cause);
assert.equal(error.message, "Electron updater failed to check for updates.");
}
}).pipe(Effect.provide(ElectronUpdater.layer)),
);
});
+21 -37
View File
@@ -10,41 +10,40 @@ type AutoUpdater = typeof autoUpdater;
export type ElectronUpdaterFeedUrl = Parameters<AutoUpdater["setFeedURL"]>[0];
const electronUpdaterErrorFields = {
cause: Schema.Defect(),
};
export class ElectronUpdaterCheckForUpdatesError extends Schema.TaggedErrorClass<ElectronUpdaterCheckForUpdatesError>()(
"ElectronUpdaterCheckForUpdatesError",
{
channel: Schema.NullOr(Schema.String),
cause: Schema.Defect(),
...electronUpdaterErrorFields,
},
) {
override get message(): string {
return `Electron updater failed to check for updates on channel ${this.channel ?? "default"}.`;
return "Electron updater failed to check for updates.";
}
}
export class ElectronUpdaterDownloadUpdateError extends Schema.TaggedErrorClass<ElectronUpdaterDownloadUpdateError>()(
"ElectronUpdaterDownloadUpdateError",
{
channel: Schema.NullOr(Schema.String),
cause: Schema.Defect(),
...electronUpdaterErrorFields,
},
) {
override get message(): string {
return `Electron updater failed to download the update on channel ${this.channel ?? "default"}.`;
return "Electron updater failed to download the update.";
}
}
export class ElectronUpdaterQuitAndInstallError extends Schema.TaggedErrorClass<ElectronUpdaterQuitAndInstallError>()(
"ElectronUpdaterQuitAndInstallError",
{
channel: Schema.NullOr(Schema.String),
isSilent: Schema.Boolean,
isForceRunAfter: Schema.Boolean,
cause: Schema.Defect(),
...electronUpdaterErrorFields,
},
) {
override get message(): string {
return `Electron updater failed to quit and install the update on channel ${this.channel ?? "default"} (silent: ${this.isSilent}, force run after: ${this.isForceRunAfter}).`;
return "Electron updater failed to quit and install the update.";
}
}
@@ -117,33 +116,18 @@ export const make = ElectronUpdater.of({
autoUpdater.disableDifferentialDownload = value;
return Effect.void;
}),
checkForUpdates: Effect.suspend(() => {
const channel = autoUpdater.channel;
return Effect.tryPromise({
try: () => autoUpdater.checkForUpdates(),
catch: (cause) => new ElectronUpdaterCheckForUpdatesError({ channel, cause }),
}).pipe(Effect.asVoid);
}),
downloadUpdate: Effect.suspend(() => {
const channel = autoUpdater.channel;
return Effect.tryPromise({
try: () => autoUpdater.downloadUpdate(),
catch: (cause) => new ElectronUpdaterDownloadUpdateError({ channel, cause }),
}).pipe(Effect.asVoid);
}),
checkForUpdates: Effect.tryPromise({
try: () => autoUpdater.checkForUpdates(),
catch: (cause) => new ElectronUpdaterCheckForUpdatesError({ cause }),
}).pipe(Effect.asVoid),
downloadUpdate: Effect.tryPromise({
try: () => autoUpdater.downloadUpdate(),
catch: (cause) => new ElectronUpdaterDownloadUpdateError({ cause }),
}).pipe(Effect.asVoid),
quitAndInstall: ({ isSilent, isForceRunAfter }) =>
Effect.suspend(() => {
const channel = autoUpdater.channel;
return Effect.try({
try: () => autoUpdater.quitAndInstall(isSilent, isForceRunAfter),
catch: (cause) =>
new ElectronUpdaterQuitAndInstallError({
channel,
isSilent,
isForceRunAfter,
cause,
}),
});
Effect.try({
try: () => autoUpdater.quitAndInstall(isSilent, isForceRunAfter),
catch: (cause) => new ElectronUpdaterQuitAndInstallError({ cause }),
}),
on: (eventName, listener) => {
const eventTarget = autoUpdater as unknown as {
+10 -194
View File
@@ -1,39 +1,26 @@
import { assert, describe, it } from "@effect/vitest";
import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
import * as Cause from "effect/Cause";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import type * as Electron from "electron";
import { beforeEach, vi } from "vite-plus/test";
const { appFocusMock, browserWindowMock, getAllWindowsMock, getFocusedWindowMock } = vi.hoisted(
() => ({
appFocusMock: vi.fn(),
browserWindowMock: vi.fn(function BrowserWindowMock() {}),
getAllWindowsMock: vi.fn(),
getFocusedWindowMock: vi.fn(),
}),
);
const { appFocusMock, getAllWindowsMock } = vi.hoisted(() => ({
appFocusMock: vi.fn(),
getAllWindowsMock: vi.fn(),
}));
vi.mock("electron", () => ({
app: {
focus: appFocusMock,
},
BrowserWindow: Object.assign(browserWindowMock, {
BrowserWindow: {
getAllWindows: getAllWindowsMock,
getFocusedWindow: getFocusedWindowMock,
}),
},
}));
import * as ElectronWindow from "./ElectronWindow.ts";
const TestLayer = ElectronWindow.layer.pipe(
Layer.provide(Layer.succeed(HostProcessPlatform, "linux")),
);
function makeBrowserWindow(input: { readonly id: number; readonly destroyed: boolean }) {
function makeBrowserWindow(input: { readonly destroyed: boolean }) {
return {
id: input.id,
isDestroyed: vi.fn(() => input.destroyed),
} as unknown as Electron.BrowserWindow;
}
@@ -41,78 +28,13 @@ function makeBrowserWindow(input: { readonly id: number; readonly destroyed: boo
describe("ElectronWindow", () => {
beforeEach(() => {
appFocusMock.mockReset();
browserWindowMock.mockReset();
getAllWindowsMock.mockReset();
getFocusedWindowMock.mockReset();
});
it.effect("preserves schema-safe creation context and the Electron cause", () =>
Effect.gen(function* () {
const cause = new Error("native BrowserWindow construction failed");
browserWindowMock.mockImplementationOnce(function BrowserWindowFailure() {
throw cause;
});
const options = {
title: "T3 Code",
width: 1100,
height: 780,
minWidth: 840,
minHeight: 620,
show: false,
modal: false,
frame: true,
transparent: false,
backgroundColor: "#101010",
icon: {} as Electron.NativeImage,
webPreferences: {
preload: "/tmp/preload.js",
partition: "persist:t3code-preview-test",
sandbox: true,
contextIsolation: true,
nodeIntegration: false,
webviewTag: true,
spellcheck: true,
},
} satisfies Electron.BrowserWindowConstructorOptions;
const electronWindow = yield* ElectronWindow.ElectronWindow;
const error = yield* electronWindow.create(options).pipe(Effect.flip);
assert.instanceOf(error, ElectronWindow.ElectronWindowCreateError);
assert.isTrue(ElectronWindow.isElectronWindowCreateError(error));
assert.deepEqual(error.options, {
title: "T3 Code",
width: 1100,
height: 780,
minWidth: 840,
minHeight: 620,
show: false,
modal: false,
frame: true,
transparent: false,
backgroundColor: "#101010",
webPreferences: {
preload: "/tmp/preload.js",
partition: "persist:t3code-preview-test",
sandbox: true,
contextIsolation: true,
nodeIntegration: false,
webviewTag: true,
},
});
assert.isFalse("icon" in error.options);
assert.isFalse("spellcheck" in error.options.webPreferences);
assert.strictEqual(error.cause, cause);
assert.equal(error.message, 'Failed to create Electron BrowserWindow "T3 Code" (1100x780).');
assert.notInclude(error.message, cause.message);
assert.deepEqual(browserWindowMock.mock.calls, [[options]]);
}).pipe(Effect.provide(TestLayer)),
);
it.effect("skips windows destroyed before appearance sync runs", () =>
Effect.gen(function* () {
const liveWindow = makeBrowserWindow({ id: 1, destroyed: false });
const destroyedWindow = makeBrowserWindow({ id: 2, destroyed: true });
const liveWindow = makeBrowserWindow({ destroyed: false });
const destroyedWindow = makeBrowserWindow({ destroyed: true });
getAllWindowsMock.mockReturnValue([destroyedWindow, liveWindow]);
const syncedWindows: Electron.BrowserWindow[] = [];
@@ -124,112 +46,6 @@ describe("ElectronWindow", () => {
);
assert.deepEqual(syncedWindows, [liveWindow]);
}).pipe(Effect.provide(TestLayer)),
);
it.effect("preserves window enumeration failures as structured defects", () =>
Effect.gen(function* () {
const cause = new Error("window enumeration failed");
getAllWindowsMock.mockImplementationOnce(() => {
throw cause;
});
const electronWindow = yield* ElectronWindow.ElectronWindow;
const exit = yield* Effect.exit(electronWindow.currentMainOrFirst);
assert.equal(exit._tag, "Failure");
if (exit._tag === "Failure") {
const error = Cause.squash(exit.cause);
assert.instanceOf(error, ElectronWindow.ElectronWindowOperationError);
assert.equal(error.operation, "list-windows");
assert.equal(error.platform, "linux");
assert.isNull(error.windowId);
assert.isNull(error.channel);
assert.strictEqual(error.cause, cause);
assert.notInclude(error.message, cause.message);
}
}).pipe(Effect.provide(TestLayer)),
);
it.effect("preserves reveal failures with the target window", () =>
Effect.gen(function* () {
const cause = new Error("window restore failed");
const window = {
id: 41,
isDestroyed: vi.fn(() => false),
isMinimized: vi.fn(() => true),
restore: vi.fn(() => {
throw cause;
}),
} as unknown as Electron.BrowserWindow;
const electronWindow = yield* ElectronWindow.ElectronWindow;
const exit = yield* Effect.exit(electronWindow.reveal(window));
assert.equal(exit._tag, "Failure");
if (exit._tag === "Failure") {
const error = Cause.squash(exit.cause);
assert.instanceOf(error, ElectronWindow.ElectronWindowOperationError);
assert.equal(error.operation, "reveal-window");
assert.equal(error.windowId, 41);
assert.isNull(error.channel);
assert.strictEqual(error.cause, cause);
}
}).pipe(Effect.provide(TestLayer)),
);
it.effect("preserves message delivery failures with window and channel context", () =>
Effect.gen(function* () {
const cause = new Error("renderer send failed");
const window = {
id: 42,
isDestroyed: vi.fn(() => false),
webContents: {
send: vi.fn(() => {
throw cause;
}),
},
} as unknown as Electron.BrowserWindow;
getAllWindowsMock.mockReturnValueOnce([window]);
const electronWindow = yield* ElectronWindow.ElectronWindow;
const exit = yield* Effect.exit(electronWindow.sendAll("desktop:update", { ready: true }));
assert.equal(exit._tag, "Failure");
if (exit._tag === "Failure") {
const error = Cause.squash(exit.cause);
assert.instanceOf(error, ElectronWindow.ElectronWindowOperationError);
assert.equal(error.operation, "send-window-message");
assert.equal(error.windowId, 42);
assert.equal(error.channel, "desktop:update");
assert.strictEqual(error.cause, cause);
}
}).pipe(Effect.provide(TestLayer)),
);
it.effect("preserves destroy failures with the target window", () =>
Effect.gen(function* () {
const cause = new Error("window destroy failed");
const window = {
id: 43,
destroy: vi.fn(() => {
throw cause;
}),
} as unknown as Electron.BrowserWindow;
getAllWindowsMock.mockReturnValueOnce([window]);
const electronWindow = yield* ElectronWindow.ElectronWindow;
const exit = yield* Effect.exit(electronWindow.destroyAll);
assert.equal(exit._tag, "Failure");
if (exit._tag === "Failure") {
const error = Cause.squash(exit.cause);
assert.instanceOf(error, ElectronWindow.ElectronWindowOperationError);
assert.equal(error.operation, "destroy-window");
assert.equal(error.windowId, 43);
assert.isNull(error.channel);
assert.strictEqual(error.cause, cause);
}
}).pipe(Effect.provide(TestLayer)),
}).pipe(Effect.provide(ElectronWindow.layer)),
);
});
+44 -191
View File
@@ -8,69 +8,14 @@ import * as Schema from "effect/Schema";
import * as Electron from "electron";
const ElectronWindowCreateOptions = Schema.Struct({
title: Schema.NullOr(Schema.String),
width: Schema.NullOr(Schema.Number),
height: Schema.NullOr(Schema.Number),
minWidth: Schema.NullOr(Schema.Number),
minHeight: Schema.NullOr(Schema.Number),
show: Schema.NullOr(Schema.Boolean),
modal: Schema.NullOr(Schema.Boolean),
frame: Schema.NullOr(Schema.Boolean),
transparent: Schema.NullOr(Schema.Boolean),
backgroundColor: Schema.NullOr(Schema.String),
webPreferences: Schema.Struct({
preload: Schema.NullOr(Schema.String),
partition: Schema.NullOr(Schema.String),
sandbox: Schema.NullOr(Schema.Boolean),
contextIsolation: Schema.NullOr(Schema.Boolean),
nodeIntegration: Schema.NullOr(Schema.Boolean),
webviewTag: Schema.NullOr(Schema.Boolean),
}),
});
const ElectronWindowOperation = Schema.Literals([
"list-windows",
"get-focused-window",
"inspect-window",
"reveal-window",
"send-window-message",
"destroy-window",
]);
export class ElectronWindowCreateError extends Schema.TaggedErrorClass<ElectronWindowCreateError>()(
"ElectronWindowCreateError",
{
options: ElectronWindowCreateOptions,
cause: Schema.Defect(),
},
) {
override get message(): string {
const title = this.options.title === null ? "" : ` "${this.options.title}"`;
const dimensions =
this.options.width === null || this.options.height === null
? ""
: ` (${this.options.width}x${this.options.height})`;
return `Failed to create Electron BrowserWindow${title}${dimensions}.`;
}
}
export const isElectronWindowCreateError = Schema.is(ElectronWindowCreateError);
export class ElectronWindowOperationError extends Schema.TaggedErrorClass<ElectronWindowOperationError>()(
"ElectronWindowOperationError",
{
operation: ElectronWindowOperation,
platform: Schema.String,
windowId: Schema.NullOr(Schema.Number),
channel: Schema.NullOr(Schema.String),
cause: Schema.Defect(),
},
) {
override get message(): string {
const window = this.windowId === null ? "" : ` for window ${this.windowId}`;
const channel = this.channel === null ? "" : ` on channel ${JSON.stringify(this.channel)}`;
return `Electron window operation ${JSON.stringify(this.operation)} failed${window}${channel} on ${this.platform}.`;
return "Failed to create Electron BrowserWindow.";
}
}
@@ -98,38 +43,9 @@ export const make = Effect.gen(function* () {
const platform = yield* HostProcessPlatform;
const mainWindowRef = yield* Ref.make<Option.Option<Electron.BrowserWindow>>(Option.none());
const listWindows = Effect.try({
try: () => Electron.BrowserWindow.getAllWindows(),
catch: (cause) =>
new ElectronWindowOperationError({
operation: "list-windows",
platform,
windowId: null,
channel: null,
cause,
}),
}).pipe(Effect.orDie);
const isWindowDestroyed = (window: Electron.BrowserWindow) =>
Effect.try({
try: () => window.isDestroyed(),
catch: (cause) =>
new ElectronWindowOperationError({
operation: "inspect-window",
platform,
windowId: window.id,
channel: null,
cause,
}),
}).pipe(Effect.orDie);
const liveMain = Effect.gen(function* () {
const main = yield* Ref.get(mainWindowRef);
if (Option.isNone(main) || (yield* isWindowDestroyed(main.value))) {
return Option.none<Electron.BrowserWindow>();
}
return main;
});
const liveMain = Ref.get(mainWindowRef).pipe(
Effect.map(Option.filter((value) => !value.isDestroyed())),
);
const currentMainOrFirst = Effect.gen(function* () {
const main = yield* liveMain;
@@ -137,60 +53,27 @@ export const make = Effect.gen(function* () {
return main;
}
const first = Option.fromNullishOr((yield* listWindows)[0] ?? null);
if (Option.isNone(first) || (yield* isWindowDestroyed(first.value))) {
return Option.none<Electron.BrowserWindow>();
}
return first;
return Option.fromNullishOr(Electron.BrowserWindow.getAllWindows()[0] ?? null).pipe(
Option.filter((window) => !window.isDestroyed()),
);
});
const focusedMainOrFirst = Effect.gen(function* () {
const focused = yield* Effect.try({
try: () => Option.fromNullishOr(Electron.BrowserWindow.getFocusedWindow() ?? null),
catch: (cause) =>
new ElectronWindowOperationError({
operation: "get-focused-window",
platform,
windowId: null,
channel: null,
cause,
}),
}).pipe(Effect.orDie);
if (Option.isSome(focused) && !(yield* isWindowDestroyed(focused.value))) {
return focused;
}
return yield* currentMainOrFirst;
});
const focusedMainOrFirst = Effect.sync(() =>
Option.fromNullishOr(Electron.BrowserWindow.getFocusedWindow() ?? null).pipe(
Option.filter((window) => !window.isDestroyed()),
),
).pipe(
Effect.flatMap((focused) =>
Option.isSome(focused) ? Effect.succeed(focused) : currentMainOrFirst,
),
);
return ElectronWindow.of({
create: (options) => {
const webPreferences = options.webPreferences;
const diagnosticOptions = {
title: options.title ?? null,
width: options.width ?? null,
height: options.height ?? null,
minWidth: options.minWidth ?? null,
minHeight: options.minHeight ?? null,
show: options.show ?? null,
modal: options.modal ?? null,
frame: options.frame ?? null,
transparent: options.transparent ?? null,
backgroundColor: options.backgroundColor ?? null,
webPreferences: {
preload: webPreferences?.preload ?? null,
partition: webPreferences?.partition ?? null,
sandbox: webPreferences?.sandbox ?? null,
contextIsolation: webPreferences?.contextIsolation ?? null,
nodeIntegration: webPreferences?.nodeIntegration ?? null,
webviewTag: webPreferences?.webviewTag ?? null,
},
} satisfies typeof ElectronWindowCreateOptions.Type;
return Effect.try({
create: (options) =>
Effect.try({
try: () => new Electron.BrowserWindow(options),
catch: (cause) => new ElectronWindowCreateError({ options: diagnosticOptions, cause }),
});
},
catch: (cause) => new ElectronWindowCreateError({ cause }),
}),
main: liveMain,
currentMainOrFirst,
focusedMainOrFirst,
@@ -206,75 +89,45 @@ export const make = Effect.gen(function* () {
return Option.none();
}),
reveal: (window) =>
Effect.try({
try: () => {
if (window.isDestroyed()) {
return;
}
Effect.sync(() => {
if (window.isDestroyed()) {
return;
}
if (window.isMinimized()) {
window.restore();
}
if (window.isMinimized()) {
window.restore();
}
if (!window.isVisible()) {
window.show();
}
if (!window.isVisible()) {
window.show();
}
if (platform === "darwin") {
Electron.app.focus({ steal: true });
}
if (platform === "darwin") {
Electron.app.focus({ steal: true });
}
window.focus();
},
catch: (cause) =>
new ElectronWindowOperationError({
operation: "reveal-window",
platform,
windowId: window.id,
channel: null,
cause,
}),
}).pipe(Effect.orDie),
window.focus();
}),
sendAll: (channel, ...args) =>
Effect.gen(function* () {
for (const window of yield* listWindows) {
if (yield* isWindowDestroyed(window)) {
Effect.sync(() => {
for (const window of Electron.BrowserWindow.getAllWindows()) {
if (window.isDestroyed()) {
continue;
}
yield* Effect.try({
try: () => window.webContents.send(channel, ...args),
catch: (cause) =>
new ElectronWindowOperationError({
operation: "send-window-message",
platform,
windowId: window.id,
channel,
cause,
}),
}).pipe(Effect.orDie);
window.webContents.send(channel, ...args);
}
}),
destroyAll: Effect.gen(function* () {
for (const window of yield* listWindows) {
yield* Effect.try({
try: () => window.destroy(),
catch: (cause) =>
new ElectronWindowOperationError({
operation: "destroy-window",
platform,
windowId: window.id,
channel: null,
cause,
}),
}).pipe(Effect.orDie);
destroyAll: Effect.sync(() => {
for (const window of Electron.BrowserWindow.getAllWindows()) {
window.destroy();
}
}),
syncAllAppearance: Effect.fn("desktop.electron.window.syncAllAppearance")(function* <E, R>(
sync: (window: Electron.BrowserWindow) => Effect.Effect<void, E, R>,
) {
const windows = yield* listWindows;
const windows = Electron.BrowserWindow.getAllWindows();
for (const window of windows) {
if (yield* isWindowDestroyed(window)) {
if (window.isDestroyed()) {
continue;
}
yield* sync(window);
-79
View File
@@ -1,79 +0,0 @@
import { assert, describe, it } from "@effect/vitest";
import * as Cause from "effect/Cause";
import * as Effect from "effect/Effect";
import { vi } from "vite-plus/test";
import * as DesktopIpc from "./DesktopIpc.ts";
const invokeMethod: DesktopIpc.DesktopIpcMethod<never, never> = {
channel: "desktop.test.invoke",
handler: () => Effect.void,
};
const syncMethod: DesktopIpc.DesktopSyncIpcMethod<never, never> = {
channel: "desktop.test.sync",
handler: () => Effect.void,
};
function makeIpcMain(
overrides: Partial<DesktopIpc.DesktopIpcMain> = {},
): DesktopIpc.DesktopIpcMain {
return {
removeHandler: vi.fn(),
handle: vi.fn(),
removeAllListeners: vi.fn(),
on: vi.fn(),
...overrides,
};
}
describe("DesktopIpc", () => {
it.effect("preserves invoke registration context and cause", () =>
Effect.gen(function* () {
const cause = new Error("invoke registration failed");
const ipcMain = makeIpcMain({
handle: () => {
throw cause;
},
});
const ipc = DesktopIpc.make(ipcMain);
const error = yield* Effect.flip(Effect.scoped(ipc.handle(invokeMethod)));
assert.instanceOf(error, DesktopIpc.DesktopIpcRegistrationError);
assert.isTrue(DesktopIpc.isDesktopIpcError(error));
assert.strictEqual(error.handlerKind, "invoke");
assert.strictEqual(error.channel, invokeMethod.channel);
assert.strictEqual(error.cause, cause);
assert.include(error.message, "invoke");
assert.include(error.message, invokeMethod.channel);
assert.notInclude(error.message, cause.message);
}),
);
it.effect("preserves sync unregistration context and cause in the finalizer defect", () =>
Effect.gen(function* () {
const cause = new Error("sync unregistration failed");
let removeCount = 0;
const ipcMain = makeIpcMain({
removeAllListeners: () => {
removeCount += 1;
if (removeCount === 2) throw cause;
},
});
const ipc = DesktopIpc.make(ipcMain);
const exit = yield* Effect.exit(Effect.scoped(ipc.handleSync(syncMethod)));
assert.isTrue(exit._tag === "Failure");
if (exit._tag === "Success") return;
const error = Cause.squash(exit.cause);
assert.instanceOf(error, DesktopIpc.DesktopIpcUnregistrationError);
assert.isTrue(DesktopIpc.isDesktopIpcError(error));
assert.strictEqual(error.handlerKind, "sync");
assert.strictEqual(error.channel, syncMethod.channel);
assert.strictEqual(error.cause, cause);
assert.notInclude(error.message, cause.message);
}),
);
});
+24 -78
View File
@@ -24,39 +24,6 @@ export interface DesktopIpcMain {
on(channel: string, listener: DesktopIpcSyncListener): void;
}
export class DesktopIpcRegistrationError extends Schema.TaggedErrorClass<DesktopIpcRegistrationError>()(
"DesktopIpcRegistrationError",
{
handlerKind: Schema.Literals(["invoke", "sync"]),
channel: Schema.String,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to register the ${this.handlerKind} IPC handler for ${this.channel}.`;
}
}
export class DesktopIpcUnregistrationError extends Schema.TaggedErrorClass<DesktopIpcUnregistrationError>()(
"DesktopIpcUnregistrationError",
{
handlerKind: Schema.Literals(["invoke", "sync"]),
channel: Schema.String,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to unregister the ${this.handlerKind} IPC handler for ${this.channel}.`;
}
}
export const DesktopIpcError = Schema.Union([
DesktopIpcRegistrationError,
DesktopIpcUnregistrationError,
]);
export type DesktopIpcError = typeof DesktopIpcError.Type;
export const isDesktopIpcError = Schema.is(DesktopIpcError);
export interface DesktopIpcMethod<E, R> {
readonly channel: string;
readonly handler: (raw: unknown) => Effect.Effect<unknown, E, R>;
@@ -72,10 +39,10 @@ export class DesktopIpc extends Context.Service<
{
readonly handle: <E, R>(
input: DesktopIpcMethod<E, R>,
) => Effect.Effect<void, DesktopIpcRegistrationError, R | Scope.Scope>;
) => Effect.Effect<void, never, R | Scope.Scope>;
readonly handleSync: <E, R>(
input: DesktopSyncIpcMethod<E, R>,
) => Effect.Effect<void, DesktopIpcRegistrationError, R | Scope.Scope>;
) => Effect.Effect<void, never, R | Scope.Scope>;
}
>()("@t3tools/desktop/ipc/DesktopIpc") {}
@@ -90,27 +57,18 @@ export const make = (ipcMain: DesktopIpcMain): DesktopIpc["Service"] =>
const runPromise = Effect.runPromiseWith(context);
yield* Effect.acquireRelease(
Effect.try({
try: () => {
ipcMain.removeHandler(channel);
ipcMain.handle(channel, (_event, raw) =>
runPromise(
Effect.gen(function* () {
yield* Effect.annotateCurrentSpan({ channel });
return yield* handler(raw);
}).pipe(Effect.annotateLogs({ channel }), Effect.withSpan("desktop.ipc.invoke")),
),
);
},
catch: (cause) =>
new DesktopIpcRegistrationError({ handlerKind: "invoke", channel, cause }),
Effect.sync(() => {
ipcMain.removeHandler(channel);
ipcMain.handle(channel, (_event, raw) =>
runPromise(
Effect.gen(function* () {
yield* Effect.annotateCurrentSpan({ channel });
return yield* handler(raw);
}).pipe(Effect.annotateLogs({ channel }), Effect.withSpan("desktop.ipc.invoke")),
),
);
}),
() =>
Effect.try({
try: () => ipcMain.removeHandler(channel),
catch: (cause) =>
new DesktopIpcUnregistrationError({ handlerKind: "invoke", channel, cause }),
}).pipe(Effect.orDie),
() => Effect.sync(() => ipcMain.removeHandler(channel)),
);
}),
@@ -123,30 +81,18 @@ export const make = (ipcMain: DesktopIpcMain): DesktopIpc["Service"] =>
const runSync = Effect.runSyncWith(context);
yield* Effect.acquireRelease(
Effect.try({
try: () => {
ipcMain.removeAllListeners(channel);
ipcMain.on(channel, (event) => {
event.returnValue = runSync(
Effect.gen(function* () {
yield* Effect.annotateCurrentSpan({ channel });
return yield* handler();
}).pipe(
Effect.annotateLogs({ channel }),
Effect.withSpan("desktop.ipc.invokeSync"),
),
);
});
},
catch: (cause) =>
new DesktopIpcRegistrationError({ handlerKind: "sync", channel, cause }),
Effect.sync(() => {
ipcMain.removeAllListeners(channel);
ipcMain.on(channel, (event) => {
event.returnValue = runSync(
Effect.gen(function* () {
yield* Effect.annotateCurrentSpan({ channel });
return yield* handler();
}).pipe(Effect.annotateLogs({ channel }), Effect.withSpan("desktop.ipc.invokeSync")),
);
});
}),
() =>
Effect.try({
try: () => ipcMain.removeAllListeners(channel),
catch: (cause) =>
new DesktopIpcUnregistrationError({ handlerKind: "sync", channel, cause }),
}).pipe(Effect.orDie),
() => Effect.sync(() => ipcMain.removeAllListeners(channel)),
);
}),
});
+2 -8
View File
@@ -33,22 +33,21 @@ import {
import {
confirm,
getAppBranding,
getLocalEnvironmentBootstraps,
getLocalEnvironmentBearerToken,
getLocalEnvironmentBootstrap,
openExternal,
pickFolder,
setTheme,
showContextMenu,
} from "./methods/window.ts";
import * as PreviewIpc from "./methods/preview.ts";
import { getWslState, setWslBackendEnabled, setWslDistro, setWslOnly } from "./methods/wsl.ts";
export const installDesktopIpcHandlers = Effect.fn("desktop.ipc.installHandlers")(function* () {
const ipc = yield* DesktopIpc.DesktopIpc;
yield* PreviewIpc.installPreviewEventForwarding();
yield* ipc.handleSync(getAppBranding);
yield* ipc.handleSync(getLocalEnvironmentBootstraps);
yield* ipc.handleSync(getLocalEnvironmentBootstrap);
yield* ipc.handle(getLocalEnvironmentBearerToken);
yield* ipc.handle(getClientSettings);
@@ -71,11 +70,6 @@ export const installDesktopIpcHandlers = Effect.fn("desktop.ipc.installHandlers"
yield* ipc.handle(setTailscaleServeEnabled);
yield* ipc.handle(getAdvertisedEndpoints);
yield* ipc.handle(getWslState);
yield* ipc.handle(setWslBackendEnabled);
yield* ipc.handle(setWslDistro);
yield* ipc.handle(setWslOnly);
yield* ipc.handle(pickFolder);
yield* ipc.handle(confirm);
yield* ipc.handle(setTheme);
+1 -5
View File
@@ -11,7 +11,7 @@ export const UPDATE_DOWNLOAD_CHANNEL = "desktop:update-download";
export const UPDATE_INSTALL_CHANNEL = "desktop:update-install";
export const UPDATE_CHECK_CHANNEL = "desktop:update-check";
export const GET_APP_BRANDING_CHANNEL = "desktop:get-app-branding";
export const GET_LOCAL_ENVIRONMENT_BOOTSTRAPS_CHANNEL = "desktop:get-local-environment-bootstraps";
export const GET_LOCAL_ENVIRONMENT_BOOTSTRAP_CHANNEL = "desktop:get-local-environment-bootstrap";
export const GET_LOCAL_ENVIRONMENT_BEARER_TOKEN_CHANNEL =
"desktop:get-local-environment-bearer-token";
export const GET_CLIENT_SETTINGS_CHANNEL = "desktop:get-client-settings";
@@ -32,10 +32,6 @@ export const GET_SERVER_EXPOSURE_STATE_CHANNEL = "desktop:get-server-exposure-st
export const SET_SERVER_EXPOSURE_MODE_CHANNEL = "desktop:set-server-exposure-mode";
export const SET_TAILSCALE_SERVE_ENABLED_CHANNEL = "desktop:set-tailscale-serve-enabled";
export const GET_ADVERTISED_ENDPOINTS_CHANNEL = "desktop:get-advertised-endpoints";
export const GET_WSL_STATE_CHANNEL = "desktop:get-wsl-state";
export const SET_WSL_BACKEND_ENABLED_CHANNEL = "desktop:set-wsl-backend-enabled";
export const SET_WSL_DISTRO_CHANNEL = "desktop:set-wsl-distro";
export const SET_WSL_ONLY_CHANNEL = "desktop:set-wsl-only";
export const SSH_PASSWORD_PROMPT_CANCELLED_RESULT = "ssh-password-prompt-cancelled";
export const PREVIEW_CREATE_TAB_CHANNEL = "desktop:preview-create-tab";
export const PREVIEW_CLOSE_TAB_CHANNEL = "desktop:preview-close-tab";
+18 -11
View File
@@ -19,30 +19,37 @@ import {
PreviewAutomationSnapshot,
PreviewAutomationStatus,
} from "@t3tools/contracts";
import { BrowserWindow } from "electron";
import * as Effect from "effect/Effect";
import * as Schema from "effect/Schema";
import * as NodeURL from "node:url";
import * as ElectronWindow from "../../electron/ElectronWindow.ts";
import * as PreviewManager from "../../preview/Manager.ts";
import { PREVIEW_WEBVIEW_PREFERENCES } from "../../preview/WebviewPreferences.ts";
import * as IpcChannels from "../channels.ts";
import * as DesktopIpc from "../DesktopIpc.ts";
const broadcast = (channel: string, ...args: ReadonlyArray<unknown>): void => {
for (const window of BrowserWindow.getAllWindows()) {
if (!window.isDestroyed()) {
window.webContents.send(channel, ...args);
}
}
};
export const installPreviewEventForwarding = Effect.fn(
"desktop.ipc.preview.installEventForwarding",
)(function* () {
const electronWindow = yield* ElectronWindow.ElectronWindow;
const manager = yield* PreviewManager.PreviewManager;
yield* manager.subscribeStateChanges((tabId, state) =>
electronWindow.sendAll(IpcChannels.PREVIEW_STATE_CHANGE_CHANNEL, tabId, state),
);
yield* manager.subscribeRecordingFrames((frame) =>
electronWindow.sendAll(IpcChannels.PREVIEW_RECORDING_FRAME_CHANNEL, frame),
);
yield* manager.subscribePointerEvents((event) =>
electronWindow.sendAll(IpcChannels.PREVIEW_POINTER_EVENT_CHANNEL, event),
);
yield* manager.subscribeStateChanges((tabId, state) => {
broadcast(IpcChannels.PREVIEW_STATE_CHANGE_CHANNEL, tabId, state);
});
yield* manager.subscribeRecordingFrames((frame) => {
broadcast(IpcChannels.PREVIEW_RECORDING_FRAME_CHANNEL, frame);
});
yield* manager.subscribePointerEvents((event) => {
broadcast(IpcChannels.PREVIEW_POINTER_EVENT_CHANNEL, event);
});
});
export const createTab = DesktopIpc.makeIpcMethod({
-128
View File
@@ -1,128 +0,0 @@
import { assert, describe, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as Option from "effect/Option";
import * as DesktopBackendManager from "../../backend/DesktopBackendManager.ts";
import * as DesktopBackendPool from "../../backend/DesktopBackendPool.ts";
import { getLocalEnvironmentBootstraps } from "./window.ts";
const readyWslConfig: DesktopBackendManager.DesktopBackendStartConfig = {
executablePath: "wsl.exe",
args: ["-d", "Ubuntu", "--", "node", "/app/bin.mjs"],
entryPath: "/app/bin.mjs",
cwd: "/app",
env: {},
extendEnv: false,
bootstrap: {
mode: "desktop",
noBrowser: true,
port: 3774,
host: "0.0.0.0",
desktopBootstrapToken: "bootstrap-token",
tailscaleServeEnabled: false,
tailscaleServePort: 443,
},
bootstrapDelivery: "stdin",
httpBaseUrl: new URL("http://127.0.0.1:3774"),
captureOutput: true,
preflightFailure: Option.none(),
runningDistro: "Ubuntu",
};
const defaultWslInstance: DesktopBackendManager.DesktopBackendInstance = {
id: DesktopBackendManager.BackendInstanceId("wsl:default"),
label: Effect.succeed("WSL (default distro)"),
start: Effect.void,
stop: () => Effect.void,
currentConfig: Effect.succeed(Option.some(readyWslConfig)),
snapshot: Effect.succeed({
desiredRunning: true,
ready: true,
activePid: Option.some(123),
restartAttempt: 0,
restartScheduled: false,
}),
waitForReady: () => Effect.succeed(true),
};
describe("getLocalEnvironmentBootstraps", () => {
it.effect("publishes the concrete running distro without replacing the stable instance id", () =>
Effect.gen(function* () {
const result = yield* getLocalEnvironmentBootstraps.handler();
assert.deepEqual(result, [
{
id: "wsl:default",
label: "WSL (Ubuntu)",
runningDistro: "Ubuntu",
httpBaseUrl: "http://127.0.0.1:3774/",
wsBaseUrl: "ws://127.0.0.1:3774/",
bootstrapToken: "bootstrap-token",
},
]);
}).pipe(Effect.provide(DesktopBackendPool.layerTest([defaultWslInstance]))),
);
it.effect("publishes a pending bootstrap only while a transient retry is scheduled", () => {
const retryingConfig: DesktopBackendManager.DesktopBackendStartConfig = {
...readyWslConfig,
preflightFailure: Option.some({
reason: "WSL probe timed out",
fatal: false,
retryLimit: 12,
}),
};
const retryingInstance: DesktopBackendManager.DesktopBackendInstance = {
...defaultWslInstance,
currentConfig: Effect.succeed(Option.some(retryingConfig)),
snapshot: Effect.succeed({
desiredRunning: true,
ready: false,
activePid: Option.none(),
restartAttempt: 2,
restartScheduled: true,
}),
};
return Effect.gen(function* () {
const result = yield* getLocalEnvironmentBootstraps.handler();
assert.deepEqual(result, [
{
id: "wsl:default",
label: "WSL (default distro)",
runningDistro: null,
httpBaseUrl: null,
wsBaseUrl: null,
},
]);
}).pipe(Effect.provide(DesktopBackendPool.layerTest([retryingInstance])));
});
it.effect("omits a bounded transient bootstrap after retries stop", () => {
const stoppedInstance: DesktopBackendManager.DesktopBackendInstance = {
...defaultWslInstance,
currentConfig: Effect.succeed(
Option.some({
...readyWslConfig,
preflightFailure: Option.some({
reason: "WSL probe timed out",
fatal: false,
retryLimit: 12,
}),
}),
),
snapshot: Effect.succeed({
desiredRunning: false,
ready: false,
activePid: Option.none(),
restartAttempt: 12,
restartScheduled: false,
}),
};
return Effect.gen(function* () {
const result = yield* getLocalEnvironmentBootstraps.handler();
assert.deepEqual(result, []);
}).pipe(Effect.provide(DesktopBackendPool.layerTest([stoppedInstance])));
});
});
+15 -129
View File
@@ -4,19 +4,14 @@ import {
DesktopEnvironmentBootstrapSchema,
DesktopThemeSchema,
PickFolderOptionsSchema,
PRIMARY_LOCAL_ENVIRONMENT_ID,
type DesktopEnvironmentBootstrap,
} from "@t3tools/contracts";
import * as Effect from "effect/Effect";
import * as Option from "effect/Option";
import * as Schema from "effect/Schema";
import * as DesktopBackendPool from "../../backend/DesktopBackendPool.ts";
import * as DesktopBackendManager from "../../backend/DesktopBackendManager.ts";
import * as DesktopLocalEnvironmentAuth from "../../backend/DesktopLocalEnvironmentAuth.ts";
import * as DesktopEnvironment from "../../app/DesktopEnvironment.ts";
import * as DesktopAppSettings from "../../settings/DesktopAppSettings.ts";
import * as DesktopWslBackend from "../../wsl/DesktopWslBackend.ts";
import * as DesktopWslEnvironment from "../../wsl/DesktopWslEnvironment.ts";
import * as ElectronDialog from "../../electron/ElectronDialog.ts";
import * as ElectronMenu from "../../electron/ElectronMenu.ts";
import * as ElectronShell from "../../electron/ElectronShell.ts";
@@ -24,11 +19,6 @@ import * as ElectronTheme from "../../electron/ElectronTheme.ts";
import * as ElectronWindow from "../../electron/ElectronWindow.ts";
import * as IpcChannels from "../channels.ts";
import * as DesktopIpc from "../DesktopIpc.ts";
import {
extractDistroFromUncPath,
resolveWslPickFolderDefaultPath,
wslUncPathToLinuxPath,
} from "../../wsl/wslPathParsing.ts";
const ContextMenuPosition = Schema.Struct({
x: Schema.Number,
@@ -55,79 +45,26 @@ export const getAppBranding = DesktopIpc.makeSyncIpcMethod({
}),
});
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 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;
// A secondary backend (e.g. a parallel WSL backend) that hasn't produced
// a config yet (mid-registration, before its first start cycle) or that
// is retrying a *transient* preflight failure (WSL VM still booting, a
// not-yet-built linux server entry) is not listening on a port. We
// surface it as a *pending* bootstrap (null endpoints, no token) so the
// renderer can show a "Connecting…" indicator while it retries — null
// endpoints keep the renderer from dialing the dead port, avoiding the
// needless /api/auth/bootstrap/bearer error cycles a real endpoint would
// trigger.
if (Option.isNone(config) || Option.isSome(config.value.preflightFailure)) {
// Skip the primary (same-origin, no "connecting" affordance) and skip a
// secondary whose preflight failed *fatally* (no node, wrong version,
// missing build tools): it has stopped retrying, so an indefinite
// "Connecting…" would be misleading — its error is surfaced by the
// WSL-state UI instead.
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: runningDistro === null ? yield* instance.label : `WSL (${runningDistro})`,
runningDistro,
export const getLocalEnvironmentBootstrap = DesktopIpc.makeSyncIpcMethod({
channel: IpcChannels.GET_LOCAL_ENVIRONMENT_BOOTSTRAP_CHANNEL,
result: Schema.NullOr(DesktopEnvironmentBootstrapSchema),
handler: Effect.fn("desktop.ipc.window.getLocalEnvironmentBootstrap")(function* () {
const backendManager = yield* DesktopBackendManager.DesktopBackendManager;
const config = yield* backendManager.currentConfig;
return Option.match(config, {
onNone: () => null,
onSome: ({ bootstrap, httpBaseUrl }) => ({
label: "Local environment",
httpBaseUrl: httpBaseUrl.href,
wsBaseUrl: toWebSocketBaseUrl(httpBaseUrl),
...(bootstrap.desktopBootstrapToken
? { bootstrapToken: bootstrap.desktopBootstrapToken }
: {}),
});
}
return bootstraps;
}),
});
}),
});
// Pull the distro selection out of a backend instance id like
// "wsl:ubuntu". Returns null for "wsl:default", which is the sentinel
// for "track the user's WSL default distro" and maps to the
// wslEnv-derived default at picker time.
function extractWslDistroFromEnvironmentId(envId: string): string | null {
if (!envId.startsWith(DesktopWslBackend.WSL_INSTANCE_ID_PREFIX)) {
return null;
}
const suffix = envId.slice(DesktopWslBackend.WSL_INSTANCE_ID_PREFIX.length);
return suffix === "default" || suffix.length === 0 ? null : suffix;
}
export const getLocalEnvironmentBearerToken = DesktopIpc.makeIpcMethod({
channel: IpcChannels.GET_LOCAL_ENVIRONMENT_BEARER_TOKEN_CHANNEL,
payload: Schema.Void,
@@ -146,62 +83,11 @@ export const pickFolder = DesktopIpc.makeIpcMethod({
const dialog = yield* ElectronDialog.ElectronDialog;
const electronWindow = yield* ElectronWindow.ElectronWindow;
const environment = yield* DesktopEnvironment.DesktopEnvironment;
const appSettings = yield* DesktopAppSettings.DesktopAppSettings;
const wslEnvironment = yield* DesktopWslEnvironment.DesktopWslEnvironment;
// Three picker modes:
// - targetEnvironmentId omitted: default to the primary picker. Keeps
// the historical behavior unchanged for users who never enabled the
// WSL backend, and is what unfamiliar callers should get out of the
// box.
// - targetEnvironmentId starts with "wsl:": route to the WSL picker
// using the distro encoded in the id (or the user's selected
// wslDistro when the id is the "wsl:default" sentinel).
// - anything else (incl. PRIMARY_LOCAL_ENVIRONMENT_ID): primary picker.
const targetId = options?.targetEnvironmentId;
const wslDistroFromTarget =
targetId !== undefined && targetId.startsWith(DesktopWslBackend.WSL_INSTANCE_ID_PREFIX)
? extractWslDistroFromEnvironmentId(targetId)
: null;
const useWsl =
targetId !== undefined &&
targetId !== PRIMARY_LOCAL_ENVIRONMENT_ID &&
targetId.startsWith(DesktopWslBackend.WSL_INSTANCE_ID_PREFIX);
const settings = yield* appSettings.get;
// Fall back to the persisted wslDistro when the id is the
// "wsl:default" sentinel; the orchestrator uses the same fallback
// for the actual backend.
const wslDistro = useWsl ? (wslDistroFromTarget ?? settings.wslDistro) : null;
const defaultPath = useWsl
? Option.fromNullishOr(
resolveWslPickFolderDefaultPath(
options,
{ distro: wslDistro },
yield* wslEnvironment.listDistros,
Option.getOrNull(yield* wslEnvironment.getUserHome(wslDistro)),
),
)
: environment.resolvePickFolderDefaultPath(options);
const selectedPath = yield* dialog.pickFolder({
owner: yield* electronWindow.focusedMainOrFirst,
defaultPath,
defaultPath: environment.resolvePickFolderDefaultPath(options),
});
if (Option.isNone(selectedPath)) {
return null;
}
if (!useWsl) {
return selectedPath.value;
}
const linuxUncPath = wslUncPathToLinuxPath(selectedPath.value);
if (linuxUncPath !== null) {
return linuxUncPath;
}
const converted = yield* wslEnvironment.windowsToWslPath(
extractDistroFromUncPath(selectedPath.value) ?? wslDistro,
selectedPath.value,
);
return Option.getOrElse(converted, () => selectedPath.value);
return Option.getOrNull(selectedPath);
}),
});
-274
View File
@@ -1,274 +0,0 @@
import { DesktopWslStateSchema } from "@t3tools/contracts";
import { assert, describe, it } from "@effect/vitest";
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 DesktopEnvironment from "../../app/DesktopEnvironment.ts";
import * as DesktopLifecycle from "../../app/DesktopLifecycle.ts";
import * as DesktopShutdown from "../../app/DesktopShutdown.ts";
import * as DesktopState from "../../app/DesktopState.ts";
import * as ElectronApp from "../../electron/ElectronApp.ts";
import * as ElectronTheme from "../../electron/ElectronTheme.ts";
import * as DesktopAppSettings from "../../settings/DesktopAppSettings.ts";
import * as DesktopWindow from "../../window/DesktopWindow.ts";
import * as DesktopWslBackend from "../../wsl/DesktopWslBackend.ts";
import * as DesktopWslEnvironment from "../../wsl/DesktopWslEnvironment.ts";
import { setWslBackendEnabled, setWslDistro, setWslOnly } from "./wsl.ts";
const decodeWslState = Schema.decodeUnknownEffect(DesktopWslStateSchema);
const invokeSetWslBackendEnabled = (enabled: boolean) =>
setWslBackendEnabled.handler(enabled).pipe(Effect.flatMap(decodeWslState));
const invokeSetWslDistro = (distro: string | null) =>
setWslDistro.handler(distro).pipe(Effect.flatMap(decodeWslState));
const invokeSetWslOnly = (enabled: boolean) =>
setWslOnly.handler(enabled).pipe(Effect.flatMap(decodeWslState));
function makeWslBackendLayer(input: { readonly onReconcile?: Effect.Effect<void> } = {}) {
return Layer.succeed(
DesktopWslBackend.DesktopWslBackend,
DesktopWslBackend.DesktopWslBackend.of({
reconcile: input.onReconcile ?? Effect.void,
lastPreflightError: Effect.succeed(Option.none()),
}),
);
}
function makeLifecycleLayer(relaunchReasons: Array<string>) {
return Layer.succeed(
DesktopLifecycle.DesktopLifecycle,
DesktopLifecycle.DesktopLifecycle.of({
relaunch: (reason) =>
Effect.sync(() => {
relaunchReasons.push(reason);
}),
register: Effect.void,
}),
);
}
const unusedLifecycleRuntimeLayer = Layer.mergeAll(
DesktopShutdown.layer,
DesktopState.layer,
Layer.succeed(
DesktopEnvironment.DesktopEnvironment,
DesktopEnvironment.DesktopEnvironment.of(
{} as DesktopEnvironment.DesktopEnvironment["Service"],
),
),
Layer.succeed(
DesktopWindow.DesktopWindow,
DesktopWindow.DesktopWindow.of({} as DesktopWindow.DesktopWindow["Service"]),
),
Layer.succeed(
ElectronApp.ElectronApp,
ElectronApp.ElectronApp.of({} as ElectronApp.ElectronApp["Service"]),
),
Layer.succeed(
ElectronTheme.ElectronTheme,
ElectronTheme.ElectronTheme.of({} as ElectronTheme.ElectronTheme["Service"]),
),
);
describe("WSL IPC", () => {
it.effect("stages dual-backend preferences before enabling without relaunching", () => {
const relaunchReasons: Array<string> = [];
const layer = Layer.mergeAll(
DesktopAppSettings.layerTest({
...DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS,
wslBackendEnabled: false,
wslOnly: true,
}),
DesktopWslEnvironment.layerTest({ isAvailable: true }),
makeWslBackendLayer(),
makeLifecycleLayer(relaunchReasons),
unusedLifecycleRuntimeLayer,
);
return Effect.gen(function* () {
yield* invokeSetWslOnly(false);
yield* invokeSetWslDistro("Debian");
const state = yield* invokeSetWslBackendEnabled(true);
assert.deepEqual(state, {
enabled: true,
distro: "Debian",
available: true,
wslOnly: false,
distros: [],
preflightError: null,
});
assert.deepEqual(relaunchReasons, []);
}).pipe(Effect.provide(layer));
});
it.effect("stages WSL-only preferences and relaunches only after enabling", () => {
const relaunchReasons: Array<string> = [];
const layer = Layer.mergeAll(
DesktopAppSettings.layerTest({
...DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS,
wslBackendEnabled: false,
wslOnly: false,
}),
DesktopWslEnvironment.layerTest({ isAvailable: true }),
makeWslBackendLayer(),
makeLifecycleLayer(relaunchReasons),
unusedLifecycleRuntimeLayer,
);
return Effect.gen(function* () {
const stagedMode = yield* invokeSetWslOnly(true);
assert.equal(stagedMode.enabled, false);
assert.equal(stagedMode.wslOnly, true);
assert.deepEqual(relaunchReasons, []);
yield* invokeSetWslDistro("Debian");
assert.deepEqual(relaunchReasons, []);
const state = yield* invokeSetWslBackendEnabled(true);
assert.deepEqual(state, {
enabled: true,
distro: "Debian",
available: true,
wslOnly: true,
distros: [],
preflightError: null,
});
assert.deepEqual(relaunchReasons, ["wslBackendEnabled=true"]);
}).pipe(Effect.provide(layer));
});
it.effect("relaunches when enabling the WSL backend while wsl-only is already persisted", () => {
const relaunchReasons: Array<string> = [];
let reconcileCount = 0;
const layer = Layer.mergeAll(
DesktopAppSettings.layerTest({
...DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS,
wslBackendEnabled: false,
wslOnly: true,
}),
DesktopWslEnvironment.layerTest({ isAvailable: true }),
makeWslBackendLayer({
onReconcile: Effect.sync(() => {
reconcileCount += 1;
}),
}),
makeLifecycleLayer(relaunchReasons),
unusedLifecycleRuntimeLayer,
);
return Effect.gen(function* () {
const state = yield* invokeSetWslBackendEnabled(true);
assert.deepEqual(state, {
enabled: true,
distro: null,
available: true,
wslOnly: true,
distros: [],
preflightError: null,
});
assert.equal(reconcileCount, 0);
assert.deepEqual(relaunchReasons, ["wslBackendEnabled=true"]);
}).pipe(Effect.provide(layer));
});
it.effect("reconciles in dual-backend mode without relaunching", () => {
const relaunchReasons: Array<string> = [];
let reconcileCount = 0;
const layer = Layer.mergeAll(
DesktopAppSettings.layerTest({
...DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS,
wslBackendEnabled: false,
wslOnly: false,
}),
DesktopWslEnvironment.layerTest({ isAvailable: true }),
makeWslBackendLayer({
onReconcile: Effect.sync(() => {
reconcileCount += 1;
}),
}),
makeLifecycleLayer(relaunchReasons),
unusedLifecycleRuntimeLayer,
);
return Effect.gen(function* () {
const state = yield* invokeSetWslBackendEnabled(true);
assert.equal(state.enabled, true);
assert.equal(state.wslOnly, false);
assert.equal(reconcileCount, 1);
assert.deepEqual(relaunchReasons, []);
}).pipe(Effect.provide(layer));
});
it.effect("clears wsl-only before relaunching when disabling a WSL-only backend", () => {
const relaunchReasons: Array<string> = [];
let reconcileCount = 0;
const layer = Layer.mergeAll(
DesktopAppSettings.layerTest({
...DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS,
wslBackendEnabled: true,
wslOnly: true,
}),
DesktopWslEnvironment.layerTest({ isAvailable: true }),
makeWslBackendLayer({
onReconcile: Effect.sync(() => {
reconcileCount += 1;
}),
}),
makeLifecycleLayer(relaunchReasons),
unusedLifecycleRuntimeLayer,
);
return Effect.gen(function* () {
const state = yield* invokeSetWslBackendEnabled(false);
const appSettings = yield* DesktopAppSettings.DesktopAppSettings;
const settings = yield* appSettings.get;
assert.deepEqual(state, {
enabled: false,
distro: null,
available: true,
wslOnly: false,
distros: [],
preflightError: null,
});
assert.equal(settings.wslBackendEnabled, false);
assert.equal(settings.wslOnly, false);
assert.equal(reconcileCount, 0);
assert.deepEqual(relaunchReasons, ["wslBackendEnabled=false"]);
}).pipe(Effect.provide(layer));
});
it.effect("clears dual-backend WSL without relaunching", () => {
const relaunchReasons: Array<string> = [];
let reconcileCount = 0;
const layer = Layer.mergeAll(
DesktopAppSettings.layerTest({
...DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS,
wslBackendEnabled: true,
wslOnly: false,
}),
DesktopWslEnvironment.layerTest({ isAvailable: true }),
makeWslBackendLayer({
onReconcile: Effect.sync(() => {
reconcileCount += 1;
}),
}),
makeLifecycleLayer(relaunchReasons),
unusedLifecycleRuntimeLayer,
);
return Effect.gen(function* () {
const state = yield* invokeSetWslBackendEnabled(false);
assert.equal(state.enabled, false);
assert.equal(state.wslOnly, false);
assert.equal(reconcileCount, 1);
assert.deepEqual(relaunchReasons, []);
}).pipe(Effect.provide(layer));
});
});
-122
View File
@@ -1,122 +0,0 @@
import { DesktopWslStateSchema, type DesktopWslState } from "@t3tools/contracts";
import * as Effect from "effect/Effect";
import * as Option from "effect/Option";
import * as Schema from "effect/Schema";
import * as DesktopLifecycle from "../../app/DesktopLifecycle.ts";
import * as DesktopAppSettings from "../../settings/DesktopAppSettings.ts";
import * as DesktopWslBackend from "../../wsl/DesktopWslBackend.ts";
import * as DesktopWslEnvironment from "../../wsl/DesktopWslEnvironment.ts";
import * as IpcChannels from "../channels.ts";
import { makeIpcMethod } from "../DesktopIpc.ts";
const readWslState: Effect.Effect<
DesktopWslState,
never,
| DesktopAppSettings.DesktopAppSettings
| DesktopWslEnvironment.DesktopWslEnvironment
| DesktopWslBackend.DesktopWslBackend
> = Effect.gen(function* () {
const appSettings = yield* DesktopAppSettings.DesktopAppSettings;
const wslEnvironment = yield* DesktopWslEnvironment.DesktopWslEnvironment;
const wslBackend = yield* DesktopWslBackend.DesktopWslBackend;
const settings = yield* appSettings.get;
const available = yield* wslEnvironment.isAvailable;
// 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,
distro: settings.wslDistro,
available,
wslOnly: settings.wslOnly,
distros,
// Only the dual-mode secondary records this; a wsl-only failure surfaces via
// a dialog + Windows fallback, so it stays null there.
preflightError: settings.wslOnly ? null : Option.getOrNull(preflightError),
};
});
export const getWslState = makeIpcMethod({
channel: IpcChannels.GET_WSL_STATE_CHANNEL,
payload: Schema.Void,
result: DesktopWslStateSchema,
handler: Effect.fn("desktop.ipc.wsl.getState")(function* () {
return yield* readWslState;
}),
});
export const setWslBackendEnabled = makeIpcMethod({
channel: IpcChannels.SET_WSL_BACKEND_ENABLED_CHANNEL,
payload: Schema.Boolean,
result: DesktopWslStateSchema,
handler: Effect.fn("desktop.ipc.wsl.setEnabled")(function* (enabled) {
const appSettings = yield* DesktopAppSettings.DesktopAppSettings;
const wslBackend = yield* DesktopWslBackend.DesktopWslBackend;
const lifecycle = yield* DesktopLifecycle.DesktopLifecycle;
const previousSettings = yield* appSettings.get;
const updateSettings = enabled
? appSettings.setWslBackendEnabled(true)
: appSettings.applyWslWindowsFallback;
const change = yield* updateSettings;
const settings = yield* appSettings.get;
const changedWslOnlyPrimary = enabled
? settings.wslOnly
: previousSettings.wslBackendEnabled && previousSettings.wslOnly;
if (changedWslOnlyPrimary && change.changed) {
const state = yield* readWslState;
yield* lifecycle.relaunch(`wslBackendEnabled=${enabled}`);
return state;
}
// Reconcile is idempotent and never fails; no need for a swap-style
// rollback when the WSL side has trouble coming up. With both
// backends running side by side, "WSL didn't start" is a transient
// state on one instance — the primary stays up either way.
yield* wslBackend.reconcile;
return yield* readWslState;
}),
});
export const setWslDistro = makeIpcMethod({
channel: IpcChannels.SET_WSL_DISTRO_CHANNEL,
payload: Schema.NullOr(Schema.String),
result: DesktopWslStateSchema,
handler: Effect.fn("desktop.ipc.wsl.setDistro")(function* (distro) {
const appSettings = yield* DesktopAppSettings.DesktopAppSettings;
const wslBackend = yield* DesktopWslBackend.DesktopWslBackend;
const lifecycle = yield* DesktopLifecycle.DesktopLifecycle;
const change = yield* appSettings.setWslDistro(distro);
const settings = yield* appSettings.get;
// In active wsl-only mode the pool's primary IS the WSL backend, and its
// distro is captured when that backend starts, so relaunch to replace it.
// When WSL is disabled, this only stages a preference for the next enable.
if (settings.wslBackendEnabled && settings.wslOnly && change.changed) {
const state = yield* readWslState;
yield* lifecycle.relaunch(`wslDistro=${distro ?? "default"}`);
return state;
}
yield* wslBackend.reconcile;
return yield* readWslState;
}),
});
export const setWslOnly = makeIpcMethod({
channel: IpcChannels.SET_WSL_ONLY_CHANNEL,
payload: Schema.Boolean,
result: DesktopWslStateSchema,
handler: Effect.fn("desktop.ipc.wsl.setOnly")(function* (enabled) {
// wsl-only decides which backend the pool spins up as "primary", and that
// decision is captured once at layer init. A disabled WSL backend always
// leaves Windows primary active, so mode changes can be staged without a
// relaunch and applied by the subsequent enable call.
const appSettings = yield* DesktopAppSettings.DesktopAppSettings;
const lifecycle = yield* DesktopLifecycle.DesktopLifecycle;
const change = yield* appSettings.setWslOnly(enabled);
const state = yield* readWslState;
if (state.enabled && change.changed) {
yield* lifecycle.relaunch(`wslOnly=${enabled}`);
}
return state;
}),
});
+2 -18
View File
@@ -31,7 +31,7 @@ import * as DesktopClerk from "./app/DesktopClerk.ts";
import * as DesktopApplicationMenu from "./window/DesktopApplicationMenu.ts";
import * as DesktopAssets from "./app/DesktopAssets.ts";
import * as DesktopBackendConfiguration from "./backend/DesktopBackendConfiguration.ts";
import * as DesktopBackendPool from "./backend/DesktopBackendPool.ts";
import * as DesktopBackendManager from "./backend/DesktopBackendManager.ts";
import * as DesktopLocalEnvironmentAuth from "./backend/DesktopLocalEnvironmentAuth.ts";
import * as DesktopNetworkInterfaces from "./backend/DesktopNetworkInterfaces.ts";
import * as DesktopEnvironment from "./app/DesktopEnvironment.ts";
@@ -50,8 +50,6 @@ import * as DesktopUpdates from "./updates/DesktopUpdates.ts";
import * as BrowserSession from "./preview/BrowserSession.ts";
import * as PreviewManager from "./preview/Manager.ts";
import * as DesktopWindow from "./window/DesktopWindow.ts";
import * as DesktopWslBackend from "./wsl/DesktopWslBackend.ts";
import * as DesktopWslEnvironment from "./wsl/DesktopWslEnvironment.ts";
const desktopEnvironmentLayer = Layer.unwrap(
Effect.gen(function* () {
@@ -145,25 +143,12 @@ const desktopWindowLayer = DesktopWindow.layer.pipe(
Layer.provideMerge(desktopPreviewLayer),
);
// Pool layer instantiates the backend factory once for the Windows
// primary instance and exposes it via pool.primary. Consumers go through
// the pool now; the legacy DesktopBackendManager service is gone. The
// WSL second instance gets registered later in the migration. See
// DesktopBackendPool.ts header for the full rollout plan.
const desktopBackendLayer = DesktopBackendPool.layer.pipe(
const desktopBackendLayer = DesktopBackendManager.layer.pipe(
Layer.provideMerge(DesktopAppIdentity.layer),
Layer.provideMerge(DesktopBackendConfiguration.layer),
Layer.provideMerge(DesktopWslEnvironment.layer),
Layer.provideMerge(desktopWindowLayer),
);
// WSL orchestrator hangs off the backend layer because it needs the
// pool + configuration + serverExposure; it pulls NetService and the
// foundation services through the same provideMerge chain.
const desktopWslBackendLayer = DesktopWslBackend.layer.pipe(
Layer.provideMerge(desktopBackendLayer),
);
const desktopLocalEnvironmentAuthLayer = DesktopLocalEnvironmentAuth.layer.pipe(
Layer.provideMerge(desktopBackendLayer),
);
@@ -175,7 +160,6 @@ const desktopApplicationLayer = Layer.mergeAll(
desktopSshLayer,
).pipe(
Layer.provideMerge(DesktopUpdates.layer),
Layer.provideMerge(desktopWslBackendLayer),
Layer.provideMerge(desktopLocalEnvironmentAuthLayer),
);
+5 -10
View File
@@ -35,12 +35,12 @@ contextBridge.exposeInMainWorld("desktopBridge", {
}
return result as ReturnType<DesktopBridge["getAppBranding"]>;
},
getLocalEnvironmentBootstraps: () => {
const result = ipcRenderer.sendSync(IpcChannels.GET_LOCAL_ENVIRONMENT_BOOTSTRAPS_CHANNEL);
if (!Array.isArray(result)) {
return [];
getLocalEnvironmentBootstrap: () => {
const result = ipcRenderer.sendSync(IpcChannels.GET_LOCAL_ENVIRONMENT_BOOTSTRAP_CHANNEL);
if (typeof result !== "object" || result === null) {
return null;
}
return result as ReturnType<DesktopBridge["getLocalEnvironmentBootstraps"]>;
return result as ReturnType<DesktopBridge["getLocalEnvironmentBootstrap"]>;
},
getLocalEnvironmentBearerToken: () =>
ipcRenderer.invoke(IpcChannels.GET_LOCAL_ENVIRONMENT_BEARER_TOKEN_CHANNEL),
@@ -91,11 +91,6 @@ contextBridge.exposeInMainWorld("desktopBridge", {
setTailscaleServeEnabled: (input) =>
ipcRenderer.invoke(IpcChannels.SET_TAILSCALE_SERVE_ENABLED_CHANNEL, input),
getAdvertisedEndpoints: () => ipcRenderer.invoke(IpcChannels.GET_ADVERTISED_ENDPOINTS_CHANNEL),
getWslState: () => ipcRenderer.invoke(IpcChannels.GET_WSL_STATE_CHANNEL),
setWslBackendEnabled: (enabled) =>
ipcRenderer.invoke(IpcChannels.SET_WSL_BACKEND_ENABLED_CHANNEL, enabled),
setWslDistro: (distro) => ipcRenderer.invoke(IpcChannels.SET_WSL_DISTRO_CHANNEL, distro),
setWslOnly: (enabled) => ipcRenderer.invoke(IpcChannels.SET_WSL_ONLY_CHANNEL, enabled),
pickFolder: (options) => ipcRenderer.invoke(IpcChannels.PICK_FOLDER_CHANNEL, options),
confirm: (message) => ipcRenderer.invoke(IpcChannels.CONFIRM_CHANNEL, message),
setTheme: (theme) => ipcRenderer.invoke(IpcChannels.SET_THEME_CHANNEL, theme),
@@ -1,9 +1,7 @@
import { assert, describe, it } from "@effect/vitest";
import * as NodeServices from "@effect/platform-node/NodeServices";
import * as Crypto from "effect/Crypto";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as PlatformError from "effect/PlatformError";
import { beforeEach, vi } from "vite-plus/test";
const { fromPartition, sessions } = vi.hoisted(() => ({
@@ -61,64 +59,6 @@ describe("BrowserSession", () => {
}).pipe(Effect.provide(layer)),
);
it.effect("preserves partition scope and the platform failure chain", () => {
const nativeCause = new Error("native digest failed");
const platformCause = PlatformError.systemError({
_tag: "Unknown",
module: "Crypto",
method: "digest",
cause: nativeCause,
});
const failingCryptoLayer = Layer.succeed(
Crypto.Crypto,
Crypto.make({
randomBytes: (size) => new Uint8Array(size),
digest: () => Effect.fail(platformCause),
}),
);
return Effect.gen(function* () {
const browserSessions = yield* BrowserSession.BrowserSession;
const error = yield* browserSessions.getPartition("environment-a").pipe(Effect.flip);
assert.instanceOf(error, BrowserSession.BrowserSessionPartitionDerivationError);
assert.isTrue(BrowserSession.isBrowserSessionGetSessionError(error));
assert.isTrue(BrowserSession.isBrowserSessionError(error));
assert.equal(error.scope, "environment-a");
assert.strictEqual(error.cause, platformCause);
assert.strictEqual(error.cause.reason.cause, nativeCause);
assert.equal(
error.message,
"Failed to derive a desktop preview browser partition for scope environment-a.",
);
assert.notInclude(error.message, nativeCause.message);
}).pipe(Effect.provide(BrowserSession.layer.pipe(Layer.provide(failingCryptoLayer))));
});
it.effect("preserves session scope, partition, and the Electron failure", () =>
Effect.gen(function* () {
const cause = new Error("Electron session failed");
fromPartition.mockImplementationOnce(() => {
throw cause;
});
const browserSessions = yield* BrowserSession.BrowserSession;
const partition = yield* browserSessions.getPartition("environment-b");
const error = yield* browserSessions.getSession("environment-b").pipe(Effect.flip);
assert.instanceOf(error, BrowserSession.BrowserSessionCreationError);
assert.isTrue(BrowserSession.isBrowserSessionGetSessionError(error));
assert.isTrue(BrowserSession.isBrowserSessionError(error));
assert.equal(error.scope, "environment-b");
assert.equal(error.partition, partition);
assert.strictEqual(error.cause, cause);
assert.equal(
error.message,
`Failed to create a desktop preview browser session for scope environment-b (partition ${partition}).`,
);
assert.notInclude(error.message, cause.message);
}).pipe(Effect.provide(layer)),
);
it.effect("clears storage and cache for every created session", () =>
Effect.gen(function* () {
const browserSessions = yield* BrowserSession.BrowserSession;
@@ -140,52 +80,4 @@ describe("BrowserSession", () => {
}
}).pipe(Effect.provide(layer)),
);
it.effect("correlates clear failures while still attempting every session", () =>
Effect.gen(function* () {
const browserSessions = yield* BrowserSession.BrowserSession;
yield* browserSessions.getSession("scope-a");
yield* browserSessions.getSession("scope-b");
const firstPartition = yield* browserSessions.getPartition("scope-a");
const secondPartition = yield* browserSessions.getPartition("scope-b");
const firstSession = sessions.get(firstPartition);
const secondSession = sessions.get(secondPartition);
assert.isDefined(firstSession);
assert.isDefined(secondSession);
const storageCause = new Error("storage clear failed");
secondSession.clearStorageData.mockImplementationOnce(() => Promise.reject(storageCause));
const storageError = yield* browserSessions.clearCookies().pipe(Effect.flip);
assert.instanceOf(storageError, BrowserSession.BrowserSessionStorageClearError);
assert.isTrue(BrowserSession.isBrowserSessionError(storageError));
assert.equal(storageError.partition, secondPartition);
assert.strictEqual(storageError.cause, storageCause);
assert.equal(
storageError.message,
`Failed to clear desktop preview browser storage for partition ${secondPartition}.`,
);
assert.notInclude(storageError.message, storageCause.message);
for (const browserSession of sessions.values()) {
assert.strictEqual(browserSession.clearStorageData.mock.calls.length, 1);
}
const cacheCause = new Error("cache clear failed");
firstSession.clearCache.mockImplementationOnce(() => Promise.reject(cacheCause));
const cacheError = yield* browserSessions.clearCache().pipe(Effect.flip);
assert.instanceOf(cacheError, BrowserSession.BrowserSessionCacheClearError);
assert.isTrue(BrowserSession.isBrowserSessionError(cacheError));
assert.equal(cacheError.partition, firstPartition);
assert.strictEqual(cacheError.cause, cacheCause);
assert.equal(
cacheError.message,
`Failed to clear the desktop preview browser cache for partition ${firstPartition}.`,
);
assert.notInclude(cacheError.message, cacheCause.message);
for (const browserSession of sessions.values()) {
assert.strictEqual(browserSession.clearCache.mock.calls.length, 1);
}
}).pipe(Effect.provide(layer)),
);
});
+18 -91
View File
@@ -5,87 +5,31 @@ import * as Crypto from "effect/Crypto";
import * as Effect from "effect/Effect";
import * as Encoding from "effect/Encoding";
import * as Layer from "effect/Layer";
import * as PlatformError from "effect/PlatformError";
import * as Schema from "effect/Schema";
import * as SynchronizedRef from "effect/SynchronizedRef";
const PREVIEW_PARTITION_PREFIX = "persist:t3code-preview-";
export class BrowserSessionPartitionDerivationError extends Schema.TaggedErrorClass<BrowserSessionPartitionDerivationError>()(
"BrowserSessionPartitionDerivationError",
export class BrowserSessionError extends Schema.TaggedErrorClass<BrowserSessionError>()(
"BrowserSessionError",
{
scope: Schema.String,
cause: Schema.instanceOf(PlatformError.PlatformError),
},
) {
override get message(): string {
return `Failed to derive a desktop preview browser partition for scope ${this.scope}.`;
}
}
export class BrowserSessionCreationError extends Schema.TaggedErrorClass<BrowserSessionCreationError>()(
"BrowserSessionCreationError",
{
scope: Schema.String,
partition: Schema.String,
operation: Schema.Literals(["getPartition", "getSession", "clearCookies", "clearCache"]),
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to create a desktop preview browser session for scope ${this.scope} (partition ${this.partition}).`;
return `Desktop preview browser session operation failed: ${this.operation}`;
}
}
export class BrowserSessionStorageClearError extends Schema.TaggedErrorClass<BrowserSessionStorageClearError>()(
"BrowserSessionStorageClearError",
{
partition: Schema.String,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to clear desktop preview browser storage for partition ${this.partition}.`;
}
}
export class BrowserSessionCacheClearError extends Schema.TaggedErrorClass<BrowserSessionCacheClearError>()(
"BrowserSessionCacheClearError",
{
partition: Schema.String,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to clear the desktop preview browser cache for partition ${this.partition}.`;
}
}
export const BrowserSessionGetSessionError = Schema.Union([
BrowserSessionPartitionDerivationError,
BrowserSessionCreationError,
]);
export type BrowserSessionGetSessionError = typeof BrowserSessionGetSessionError.Type;
export const isBrowserSessionGetSessionError = Schema.is(BrowserSessionGetSessionError);
export const BrowserSessionError = Schema.Union([
BrowserSessionPartitionDerivationError,
BrowserSessionCreationError,
BrowserSessionStorageClearError,
BrowserSessionCacheClearError,
]);
export type BrowserSessionError = typeof BrowserSessionError.Type;
export const isBrowserSessionError = Schema.is(BrowserSessionError);
export class BrowserSession extends Context.Service<
BrowserSession,
{
readonly getPartition: (
scope?: string,
) => Effect.Effect<string, BrowserSessionPartitionDerivationError>;
readonly getPartition: (scope?: string) => Effect.Effect<string, BrowserSessionError>;
readonly isPartition: (partition: string) => boolean;
readonly getSession: (scope?: string) => Effect.Effect<Session, BrowserSessionGetSessionError>;
readonly clearCookies: () => Effect.Effect<void, BrowserSessionStorageClearError>;
readonly clearCache: () => Effect.Effect<void, BrowserSessionCacheClearError>;
readonly getSession: (scope?: string) => Effect.Effect<Session, BrowserSessionError>;
readonly clearCookies: () => Effect.Effect<void, BrowserSessionError>;
readonly clearCache: () => Effect.Effect<void, BrowserSessionError>;
}
>()("@t3tools/desktop/preview/BrowserSession") {}
@@ -94,15 +38,11 @@ export const make = Effect.gen(function* BrowserSessionMake() {
const sessionsRef = yield* SynchronizedRef.make<ReadonlyMap<string, Session>>(new Map());
const getPartition = Effect.fn("BrowserSession.getPartition")(function* (scope = "shared") {
const digest = yield* crypto.digest("SHA-256", new TextEncoder().encode(scope)).pipe(
Effect.mapError(
(cause) =>
new BrowserSessionPartitionDerivationError({
scope,
cause,
}),
),
);
const digest = yield* crypto
.digest("SHA-256", new TextEncoder().encode(scope))
.pipe(
Effect.mapError((cause) => new BrowserSessionError({ operation: "getPartition", cause })),
);
return `${PREVIEW_PARTITION_PREFIX}${Encoding.encodeHex(digest).slice(0, 20)}`;
});
@@ -127,12 +67,7 @@ export const make = Effect.gen(function* BrowserSessionMake() {
next.set(partition, browserSession);
return [browserSession, next] as const;
},
catch: (cause) =>
new BrowserSessionCreationError({
scope,
partition,
cause,
}),
catch: (cause) => new BrowserSessionError({ operation: "getSession", cause }),
});
});
});
@@ -144,17 +79,13 @@ export const make = Effect.gen(function* BrowserSessionMake() {
clearCookies: Effect.fn("BrowserSession.clearCookies")(function* () {
const sessions = yield* SynchronizedRef.get(sessionsRef);
yield* Effect.all(
[...sessions.entries()].map(([partition, browserSession]) =>
[...sessions.values()].map((browserSession) =>
Effect.tryPromise({
try: () =>
browserSession.clearStorageData({
storages: ["cookies", "localstorage", "indexdb", "websql", "serviceworkers"],
}),
catch: (cause) =>
new BrowserSessionStorageClearError({
partition,
cause,
}),
catch: (cause) => new BrowserSessionError({ operation: "clearCookies", cause }),
}),
),
{ concurrency: "unbounded", discard: true },
@@ -163,14 +94,10 @@ export const make = Effect.gen(function* BrowserSessionMake() {
clearCache: Effect.fn("BrowserSession.clearCache")(function* () {
const sessions = yield* SynchronizedRef.get(sessionsRef);
yield* Effect.all(
[...sessions.entries()].map(([partition, browserSession]) =>
[...sessions.values()].map((browserSession) =>
Effect.tryPromise({
try: () => browserSession.clearCache(),
catch: (cause) =>
new BrowserSessionCacheClearError({
partition,
cause,
}),
catch: (cause) => new BrowserSessionError({ operation: "clearCache", cause }),
}),
),
{ concurrency: "unbounded", discard: true },
+18 -662
View File
@@ -1,43 +1,30 @@
import { it as effectIt } from "@effect/vitest";
import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
import * as Cause from "effect/Cause";
import * as Effect from "effect/Effect";
import * as Exit from "effect/Exit";
import * as FileSystem from "effect/FileSystem";
import * as Fiber from "effect/Fiber";
import * as Layer from "effect/Layer";
import * as Logger from "effect/Logger";
import * as Option from "effect/Option";
import * as Path from "effect/Path";
import * as Schema from "effect/Schema";
import type * as Scope from "effect/Scope";
import { TestClock } from "effect/testing";
import { beforeEach, describe, expect, it, vi } from "vite-plus/test";
import { beforeEach, describe, expect, vi } from "vite-plus/test";
import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
import * as ElectronWindow from "../electron/ElectronWindow.ts";
import * as BrowserSession from "./BrowserSession.ts";
import * as PreviewManager from "./Manager.ts";
const {
createFromPath,
fromId,
getFocusedWebContents,
mkdir,
showItemInFolder,
webviewSend,
writeFile,
writeImage,
} = vi.hoisted(() => ({
createFromPath: vi.fn((): { readonly isEmpty: () => boolean } => ({ isEmpty: () => false })),
fromId: vi.fn(() => null),
getFocusedWebContents: vi.fn(() => null),
mkdir: vi.fn((_path: string) => undefined),
showItemInFolder: vi.fn(),
webviewSend: vi.fn(),
writeFile: vi.fn((_path: string, _data: Uint8Array) => undefined),
writeImage: vi.fn(),
}));
const { createFromPath, fromId, mkdir, showItemInFolder, webviewSend, writeFile, writeImage } =
vi.hoisted(() => ({
createFromPath: vi.fn(() => ({ isEmpty: () => false })),
fromId: vi.fn(() => null),
mkdir: vi.fn((_path: string) => undefined),
showItemInFolder: vi.fn(),
webviewSend: vi.fn(),
writeFile: vi.fn((_path: string, _data: Uint8Array) => undefined),
writeImage: vi.fn(),
}));
vi.mock("electron", () => ({
clipboard: {
@@ -54,7 +41,6 @@ vi.mock("electron", () => ({
},
webContents: {
fromId,
getFocusedWebContents,
},
}));
@@ -92,9 +78,7 @@ const layer = PreviewManager.layer.pipe(
Layer.provideMerge(environmentLayer),
Layer.provideMerge(fileSystemLayer),
Layer.provideMerge(Path.layer),
Layer.provideMerge(Layer.succeed(HostProcessPlatform, "linux")),
);
const encodePreviewManagerError = Schema.encodeSync(PreviewManager.PreviewManagerError);
const withManager = <A>(
use: (
@@ -109,8 +93,6 @@ const withManager = <A>(
describe("PreviewManager", () => {
beforeEach(() => {
fromId.mockClear();
getFocusedWebContents.mockReset();
getFocusedWebContents.mockReturnValue(null);
mkdir.mockClear();
writeFile.mockClear();
showItemInFolder.mockClear();
@@ -146,72 +128,6 @@ describe("PreviewManager", () => {
),
);
effectIt.effect("isolates failed state listeners and continues delivery", () => {
const loggedErrors: Array<unknown> = [];
const logger = Logger.make(({ message }) => {
for (const value of Array.isArray(message) ? message : [message]) {
if (typeof value === "object" && value !== null && "cause" in value) {
loggedErrors.push(Cause.squash(value.cause as Cause.Cause<never>));
}
}
});
const deliveryError = new ElectronWindow.ElectronWindowOperationError({
operation: "send-window-message",
platform: "darwin",
windowId: 42,
channel: "preview:state-change",
cause: new Error("renderer unavailable"),
});
const delivered = vi.fn();
return withManager((manager) =>
Effect.gen(function* () {
yield* manager.subscribeStateChanges(() => Effect.die(deliveryError));
yield* manager.subscribeStateChanges((tabId, state) =>
Effect.sync(() => {
delivered(tabId, state);
}),
);
const state = yield* manager.createTab("tab_listener_failure");
expect(delivered).toHaveBeenCalledOnce();
expect(delivered).toHaveBeenCalledWith("tab_listener_failure", state);
expect(loggedErrors).toHaveLength(1);
expect(loggedErrors[0]).toBeInstanceOf(ElectronWindow.ElectronWindowOperationError);
expect(loggedErrors[0]).toMatchObject({
operation: "send-window-message",
windowId: 42,
channel: "preview:state-change",
});
}),
).pipe(
Effect.provide(
Logger.layer([logger], {
mergeWithExisting: false,
}),
),
);
});
effectIt.effect("does not swallow state listener interruption", () =>
withManager((manager) =>
Effect.gen(function* () {
const exit = yield* Effect.scoped(
Effect.gen(function* () {
yield* manager.subscribeStateChanges(() => Effect.interrupt);
return yield* Effect.exit(manager.createTab("tab_interrupted_listener"));
}),
);
expect(Exit.isFailure(exit)).toBe(true);
if (Exit.isFailure(exit)) {
expect(Cause.hasInterrupts(exit.cause)).toBe(true);
}
}),
),
);
effectIt.effect("queues navigation until the webview registers", () =>
withManager((manager) =>
Effect.gen(function* () {
@@ -264,197 +180,6 @@ describe("PreviewManager", () => {
),
);
effectIt.effect("mirrors Electron's effective zoom across registration and navigation", () =>
withManager((manager) =>
Effect.gen(function* () {
let effectiveZoom = 0.9;
let zoomReadable = true;
let url = "https://example.com";
const listeners = new Map<string, (...args: unknown[]) => void>();
const setZoomFactor = vi.fn();
fromId.mockReturnValue({
id: 42,
isDestroyed: () => false,
getType: () => "webview",
getURL: () => url,
getTitle: () => "Example",
isLoading: () => false,
getZoomFactor: () => {
if (!zoomReadable) throw new Error("zoom unavailable");
return effectiveZoom;
},
setZoomFactor,
on: vi.fn((event: string, listener: (...args: unknown[]) => void) => {
listeners.set(event, listener);
}),
off: vi.fn(),
ipc: { on: vi.fn(), off: vi.fn() },
send: webviewSend,
navigationHistory: { canGoBack: () => false, canGoForward: () => false },
setWindowOpenHandler: vi.fn(),
debugger: {
isAttached: () => false,
attach: vi.fn(),
sendCommand: vi.fn(async () => undefined),
on: vi.fn(),
off: vi.fn(),
},
} as never);
const states: PreviewManager.PreviewTabState[] = [];
yield* manager.subscribeStateChanges((_tabId, state) =>
Effect.sync(() => {
states.push(state);
}),
);
yield* manager.createTab("tab_zoom");
yield* manager.registerWebview("tab_zoom", 42);
expect(states.at(-1)?.zoomFactor).toBe(0.9);
expect(setZoomFactor).not.toHaveBeenCalled();
effectiveZoom = 1.25;
listeners.get("did-navigate")?.();
yield* Effect.yieldNow;
expect(states.at(-1)?.zoomFactor).toBe(1.25);
expect(setZoomFactor).not.toHaveBeenCalled();
zoomReadable = false;
url = "https://example.com/after-zoom-read-failed";
listeners.get("did-navigate")?.();
yield* Effect.yieldNow;
expect(states.at(-1)?.navStatus).toEqual({
kind: "Success",
url,
title: "Example",
});
expect(states.at(-1)?.zoomFactor).toBe(1.25);
const replacementSetZoomFactor = vi.fn();
fromId.mockReturnValue({
id: 43,
isDestroyed: () => false,
getType: () => "webview",
getURL: () => url,
getTitle: () => "Example",
isLoading: () => false,
getZoomFactor: () => 1,
setZoomFactor: replacementSetZoomFactor,
on: vi.fn(),
off: vi.fn(),
ipc: { on: vi.fn(), off: vi.fn() },
send: webviewSend,
navigationHistory: { canGoBack: () => false, canGoForward: () => false },
setWindowOpenHandler: vi.fn(),
debugger: {
isAttached: () => false,
attach: vi.fn(),
sendCommand: vi.fn(async () => undefined),
on: vi.fn(),
off: vi.fn(),
},
} as never);
yield* manager.registerWebview("tab_zoom", 43);
expect(replacementSetZoomFactor).toHaveBeenCalledWith(1.25);
expect(states.at(-1)?.zoomFactor).toBe(1.25);
}),
),
);
effectIt.effect("keeps a main-frame load failure visible until a retry starts", () =>
withManager((manager) =>
Effect.gen(function* () {
const url = "http://localhost:5733/";
let loading = false;
const listeners = new Map<string, (...args: unknown[]) => void>();
fromId.mockReturnValue({
id: 42,
isDestroyed: () => false,
getType: () => "webview",
getURL: () => url,
getTitle: () => "localhost:5733",
isLoading: () => loading,
getZoomFactor: () => 1,
setZoomFactor: vi.fn(),
on: vi.fn((event: string, listener: (...args: unknown[]) => void) => {
listeners.set(event, listener);
}),
off: vi.fn(),
ipc: { on: vi.fn(), off: vi.fn() },
send: webviewSend,
navigationHistory: { canGoBack: () => false, canGoForward: () => false },
setWindowOpenHandler: vi.fn(),
debugger: {
isAttached: () => false,
attach: vi.fn(),
sendCommand: vi.fn(async () => undefined),
on: vi.fn(),
off: vi.fn(),
},
} as never);
const statuses: PreviewManager.PreviewNavStatus[] = [];
yield* manager.subscribeStateChanges((_tabId, state) =>
Effect.sync(() => {
statuses.push(state.navStatus);
}),
);
yield* manager.createTab("tab_failed");
yield* manager.registerWebview("tab_failed", 42);
listeners.get("did-fail-load")?.(
{},
-105,
"ERR_NAME_NOT_RESOLVED",
"https://missing-frame.example/",
false,
);
yield* Effect.yieldNow;
expect(statuses.at(-1)?.kind).toBe("Success");
loading = true;
listeners.get("did-start-loading")?.();
yield* Effect.yieldNow;
expect(statuses.at(-1)?.kind).toBe("Loading");
loading = false;
listeners.get("did-fail-load")?.({}, -102, "ERR_CONNECTION_REFUSED", url, true);
listeners.get("did-stop-loading")?.();
listeners.get("page-title-updated")?.();
yield* Effect.yieldNow;
expect(statuses.at(-1)).toEqual({
kind: "LoadFailed",
url,
title: "localhost:5733",
code: -102,
description: "ERR_CONNECTION_REFUSED",
});
loading = true;
listeners.get("did-start-loading")?.();
yield* Effect.yieldNow;
expect(statuses.at(-1)?.kind).toBe("Loading");
loading = false;
listeners.get("did-stop-loading")?.();
yield* Effect.yieldNow;
expect(statuses.at(-1)?.kind).toBe("Success");
listeners.get("did-fail-load")?.({}, -102, "ERR_CONNECTION_REFUSED", url, true);
yield* Effect.yieldNow;
expect(statuses.at(-1)?.kind).toBe("LoadFailed");
listeners.get("did-navigate")?.();
yield* Effect.yieldNow;
expect(statuses.at(-1)?.kind).toBe("Success");
}),
),
);
effectIt.effect("captures a PNG screenshot into browser artifacts", () =>
withManager((manager) =>
Effect.gen(function* () {
@@ -512,20 +237,6 @@ describe("PreviewManager", () => {
expect(artifact.path).toMatch(
/\/browser-artifacts\/browser-screenshot-example-com-[^.]+\.png$/,
);
const captureCause = new Error("capture failed");
capturePage.mockRejectedValueOnce(captureCause);
const exit = yield* Effect.exit(manager.captureScreenshot("tab_1"));
expect(Exit.isFailure(exit)).toBe(true);
if (Exit.isSuccess(exit)) return;
const error = Option.getOrThrow(Cause.findErrorOption(exit.cause));
expect(error).toMatchObject({
_tag: "PreviewOperationError",
operation: "captureScreenshot.capturePage",
tabId: "tab_1",
webContentsId: 42,
cause: captureCause,
});
}),
),
);
@@ -591,12 +302,9 @@ describe("PreviewManager", () => {
expect(Exit.isFailure(exit)).toBe(true);
if (Exit.isSuccess(exit)) return;
const error = Option.getOrThrow(Cause.findErrorOption(exit.cause));
expect(error).toMatchObject({
_tag: "PreviewArtifactPathOutsideDirectoryError",
artifactPath: "/tmp/t3/dev/settings.json",
artifactDirectory: "/tmp/t3/dev/browser-artifacts",
expect(error.cause).toMatchObject({
message: "Preview artifact path is outside the configured artifact directory.",
});
expect("cause" in error).toBe(false);
}),
),
);
@@ -616,20 +324,8 @@ describe("PreviewManager", () => {
expect(Exit.isFailure(exit)).toBe(true);
if (Exit.isSuccess(exit)) return;
const error = Option.getOrThrow(Cause.findErrorOption(exit.cause));
expect(error).toMatchObject({
_tag: "PreviewArtifactPathOutsideDirectoryError",
artifactPath: "/tmp/t3/dev/settings.json",
artifactDirectory: "/tmp/t3/dev/browser-artifacts",
});
expect("cause" in error).toBe(false);
createFromPath.mockReturnValueOnce({ isEmpty: () => true });
const invalidImageExit = yield* Effect.exit(manager.copyArtifactToClipboard(artifactPath));
expect(Exit.isFailure(invalidImageExit)).toBe(true);
if (Exit.isSuccess(invalidImageExit)) return;
expect(Option.getOrThrow(Cause.findErrorOption(invalidImageExit.cause))).toMatchObject({
_tag: "PreviewArtifactImageLoadError",
artifactPath,
expect(error.cause).toMatchObject({
message: "Preview artifact path is outside the configured artifact directory.",
});
}),
),
@@ -684,11 +380,7 @@ describe("PreviewManager", () => {
},
} as never);
yield* manager.subscribePointerEvents((event) =>
Effect.sync(() => {
activity.push(event.phase);
}),
);
yield* manager.subscribePointerEvents((event) => activity.push(event.phase));
yield* manager.createTab("tab_1");
yield* manager.registerWebview("tab_1", 42);
const click = yield* manager
@@ -716,178 +408,6 @@ describe("PreviewManager", () => {
),
);
effectIt.effect("types in background webviews and enables native key input", () =>
withManager((manager) =>
Effect.gen(function* () {
let failKeyDown = false;
let humanInput: ((_event: unknown, signal: unknown) => void) | undefined;
const sendCommand = vi.fn(async (method: string, params?: Record<string, unknown>) => {
if (
failKeyDown &&
method === "Input.dispatchKeyEvent" &&
(params?.["type"] === "keyDown" || params?.["type"] === "rawKeyDown")
) {
throw new Error("key dispatch failed");
}
if (
method === "Input.dispatchKeyEvent" &&
(params?.["type"] === "keyDown" || params?.["type"] === "rawKeyDown")
) {
humanInput?.(
{},
{
kind: "key",
key: params["key"],
code: params["code"] ?? "Digit1",
},
);
}
return method === "Runtime.evaluate" ? { result: { value: { ok: true } } } : undefined;
});
const restoreFocus = vi.fn();
const focus = vi.fn();
getFocusedWebContents.mockReturnValue({
id: 7,
isDestroyed: () => false,
focus: restoreFocus,
} as never);
fromId.mockReturnValue({
id: 42,
isDestroyed: () => false,
getType: () => "webview",
getURL: () => "https://example.com",
getTitle: () => "Example",
isLoading: () => false,
isDevToolsOpened: () => false,
focus,
getZoomFactor: () => 1,
setZoomFactor: vi.fn(),
on: vi.fn(),
off: vi.fn(),
ipc: {
on: vi.fn((channel: string, listener: typeof humanInput) => {
if (channel === "preview:human-input") humanInput = listener;
}),
off: vi.fn(),
},
send: webviewSend,
navigationHistory: { canGoBack: () => false, canGoForward: () => false },
setWindowOpenHandler: vi.fn(),
debugger: {
isAttached: () => false,
attach: vi.fn(),
sendCommand,
on: vi.fn(),
off: vi.fn(),
},
} as never);
yield* manager.createTab("tab_input");
yield* manager.registerWebview("tab_input", 42);
yield* manager.automationType("tab_input", { text: "hello", clear: true });
yield* manager.automationType("tab_input", { text: "", clear: true });
yield* manager.automationPress("tab_input", { key: "x" });
const calls = sendCommand.mock.calls;
const methods = calls.map(([method]) => method);
const enableIndex = methods.indexOf("Input.setIgnoreInputEvents");
const focusOnIndex = calls.findIndex(
([method, params]) =>
method === "Emulation.setFocusEmulationEnabled" && params?.["enabled"] === true,
);
const keyDownIndex = calls.findIndex(
([method, params]) =>
method === "Input.dispatchKeyEvent" && params?.["type"] === "keyDown",
);
const keyUpIndex = calls.findIndex(
([method, params]) => method === "Input.dispatchKeyEvent" && params?.["type"] === "keyUp",
);
const focusOffIndex = calls.findIndex(
([method, params]) =>
method === "Emulation.setFocusEmulationEnabled" && params?.["enabled"] === false,
);
const typeEvaluation = sendCommand.mock.calls.find(
([method, params]) =>
method === "Runtime.evaluate" &&
typeof params === "object" &&
params !== null &&
"expression" in params &&
typeof params.expression === "string" &&
params.expression.includes('document.execCommand("insertText"'),
);
expect(typeEvaluation).toBeDefined();
const clearOnlyEvaluation = sendCommand.mock.calls.find(
([method, params]) =>
method === "Runtime.evaluate" &&
typeof params === "object" &&
params !== null &&
"expression" in params &&
typeof params.expression === "string" &&
params.expression.includes('const text = ""') &&
params.expression.includes("Object.getOwnPropertyDescriptor"),
);
expect(clearOnlyEvaluation).toBeDefined();
expect(methods).not.toContain("Input.insertText");
expect(enableIndex).toBeGreaterThanOrEqual(0);
expect(focus).toHaveBeenCalledOnce();
expect(restoreFocus).toHaveBeenCalledOnce();
expect(methods).toContain("Page.bringToFront");
expect(enableIndex).toBeLessThan(focusOnIndex);
expect(focusOnIndex).toBeLessThan(keyDownIndex);
expect(keyDownIndex).toBeLessThan(keyUpIndex);
expect(keyUpIndex).toBeLessThan(focusOffIndex);
expect(
calls.filter(
([method, params]) =>
method === "Input.dispatchKeyEvent" && params?.["type"] === "keyUp",
),
).toHaveLength(1);
expect(sendCommand).toHaveBeenCalledWith("Input.setIgnoreInputEvents", { ignore: false });
sendCommand.mockClear();
failKeyDown = true;
const failedPress = yield* Effect.exit(manager.automationPress("tab_input", { key: "y" }));
expect(Exit.isFailure(failedPress)).toBe(true);
expect(sendCommand).toHaveBeenCalledWith("Input.dispatchKeyEvent", {
type: "keyUp",
key: "y",
code: "KeyY",
modifiers: 0,
windowsVirtualKeyCode: 89,
location: 0,
isKeypad: false,
});
expect(sendCommand).toHaveBeenCalledWith("Emulation.setFocusEmulationEnabled", {
enabled: false,
});
expect(restoreFocus).toHaveBeenCalledTimes(2);
expect(
sendCommand.mock.calls.filter(
([method, params]) =>
method === "Input.dispatchKeyEvent" && params?.["type"] === "keyUp",
),
).toHaveLength(1);
sendCommand.mockClear();
failKeyDown = false;
yield* manager.automationPress("tab_input", { key: "!" });
expect(sendCommand).toHaveBeenCalledWith("Input.dispatchKeyEvent", {
type: "keyDown",
key: "!",
code: "Digit1",
modifiers: 0,
windowsVirtualKeyCode: 49,
location: 0,
isKeypad: false,
text: "!",
unmodifiedText: "!",
});
expect(restoreFocus).toHaveBeenCalledTimes(3);
}),
),
);
effectIt.effect("still interrupts agent control for a different human pointer event", () =>
withManager((manager) =>
Effect.gen(function* () {
@@ -946,174 +466,10 @@ describe("PreviewManager", () => {
expect(Exit.isFailure(exit)).toBe(true);
if (Exit.isSuccess(exit)) return;
const error = Option.getOrThrow(Cause.findErrorOption(exit.cause));
expect(error).toMatchObject({
_tag: "PreviewAutomationControlInterruptedError",
operation: "click",
tabId: "tab_1",
webContentsId: 42,
});
expect(error).toBeInstanceOf(Error);
if (error instanceof Error) {
expect(error.name).toBe("PreviewAutomationControlInterruptedError");
}
expect("cause" in error).toBe(false);
}),
),
);
effectIt.effect("derives evaluation detail kind and length from the same non-empty source", () =>
withManager((manager) =>
Effect.gen(function* () {
const text = "ReferenceError: fallbackDetail is not defined";
const exceptionDetails = {
text,
exception: { description: "" },
};
const sendCommand = vi.fn(async (method: string) =>
method === "Runtime.evaluate" ? { exceptionDetails } : undefined,
);
fromId.mockReturnValue({
id: 42,
isDestroyed: () => false,
getType: () => "webview",
getURL: () => "https://example.com",
getTitle: () => "Example",
isLoading: () => false,
isDevToolsOpened: () => false,
getZoomFactor: () => 1,
setZoomFactor: vi.fn(),
on: vi.fn(),
off: vi.fn(),
ipc: { on: vi.fn(), off: vi.fn() },
send: webviewSend,
navigationHistory: { canGoBack: () => false, canGoForward: () => false },
setWindowOpenHandler: vi.fn(),
debugger: {
isAttached: () => false,
attach: vi.fn(),
sendCommand,
on: vi.fn(),
off: vi.fn(),
},
} as never);
yield* manager.createTab("tab_1");
yield* manager.registerWebview("tab_1", 42);
const exit = yield* Effect.exit(
manager.automationEvaluate("tab_1", { expression: "fallbackDetail" }),
);
expect(Exit.isFailure(exit)).toBe(true);
if (Exit.isSuccess(exit)) return;
const error = Option.getOrThrow(Cause.findErrorOption(exit.cause));
expect(error).toMatchObject({
_tag: "PreviewAutomationEvaluationError",
detailKind: "exception-text",
detailLength: text.length,
cause: exceptionDetails,
expect(error.cause).toMatchObject({
name: "PreviewAutomationControlInterruptedError",
});
}),
),
);
});
describe("PreviewOperationError", () => {
it("keeps timeline detail separate from its structured message", () => {
const cause = new Error("CDP command failed with an invalid node id");
const error = new PreviewManager.PreviewOperationError({
operation: "click.DOM.resolveNode",
tabId: "tab_1",
webContentsId: 42,
cause,
});
expect(error.message).not.toContain(cause.message);
expect(PreviewManager.PreviewOperationError.toTimelineMessage(error)).toBe(cause.message);
});
});
describe("Preview automation diagnostics", () => {
it("keeps browser exception detail out of structural diagnostics", () => {
const secret = "unrelated-browser-payload-secret";
const detail = "ReferenceError: missingValue is not defined";
const cause = {
text: "Uncaught Error",
exception: { description: detail },
unsafePayload: secret,
};
const error = new PreviewManager.PreviewAutomationEvaluationError({
tabId: "tab_1",
detailKind: "exception-description",
detailLength: detail.length,
cause,
});
const encoded = encodePreviewManagerError(error);
const { cause: encodedCause, ...encodedDiagnostics } = encoded as typeof encoded & {
readonly cause?: unknown;
};
expect(error.cause).toBe(cause);
expect(encodedCause).toStrictEqual(cause);
expect(error.message).toBe("Preview JavaScript evaluation failed in tab tab_1");
expect(error.message).not.toContain(secret);
expect(JSON.stringify(encodedDiagnostics)).not.toContain(secret);
expect("detail" in error).toBe(false);
expect(PreviewManager.PreviewAutomationEvaluationError.toTimelineMessage(error)).toBe(detail);
expect(PreviewManager.PreviewAutomationEvaluationError.toTimelineMessage(error)).not.toContain(
secret,
);
});
it("retains bounded selector diagnostics without exposing selector or reason text", () => {
const selector = "role=button[name='selector-secret']";
const reason = "Unexpected token near reason-secret";
const cause = { invalidSelector: true as const, message: reason };
const error = new PreviewManager.PreviewAutomationInvalidSelectorError({
operation: "click",
tabId: "tab_1",
selectorKind: "locator",
selectorLength: selector.length,
reasonLength: reason.length,
cause,
});
const encoded = encodePreviewManagerError(error);
const { cause: encodedCause, ...encodedDiagnostics } = encoded as typeof encoded & {
readonly cause?: unknown;
};
expect(error.cause).toBe(cause);
expect(encodedCause).toStrictEqual(cause);
expect(error).toMatchObject({
selectorKind: "locator",
selectorLength: selector.length,
reasonLength: reason.length,
});
expect(error.detail).toEqual({
selectorKind: "locator",
selectorLength: selector.length,
});
expect(error.message).not.toContain("secret");
expect(JSON.stringify(encodedDiagnostics)).not.toContain("secret");
expect("selector" in error).toBe(false);
expect("reason" in error).toBe(false);
expect(PreviewManager.PreviewAutomationInvalidSelectorError.toTimelineMessage(error)).toBe(
reason,
);
});
it("does not retain a missing target locator", () => {
const selector = "[data-token='target-secret']";
const error = new PreviewManager.PreviewAutomationTargetNotFoundError({
operation: "scroll",
tabId: "tab_1",
selectorKind: "selector",
selectorLength: selector.length,
});
expect(error.message).not.toContain(selector);
expect(JSON.stringify(error)).not.toContain(selector);
expect("locator" in error).toBe(false);
});
});
File diff suppressed because it is too large. Load diff
@@ -3,14 +3,10 @@ import * as Effect from "effect/Effect";
import { describe, expect } from "vite-plus/test";
import {
extractPlaywrightInjectedRuntimeSource,
playwrightInjectedRuntimeInstallExpression,
playwrightInjectedRuntimeSource,
} from "./PlaywrightInjectedRuntime.ts";
const bundleWithSourceLiteral = (literal: string): string =>
`const source3 = ${literal};\n }\n});`;
describe("playwright injected runtime", () => {
effectIt.effect("extracts the pinned runtime from playwright-core", () =>
Effect.gen(function* () {
@@ -27,54 +23,4 @@ describe("playwright injected runtime", () => {
expect(expression).toContain('testIdAttributeName":"data-testid');
}),
);
effectIt.effect("reports a missing source marker without an artificial cause", () =>
Effect.gen(function* () {
const error = yield* Effect.flip(
extractPlaywrightInjectedRuntimeSource("const source = 'missing';", "/tmp/coreBundle.js"),
);
expect(error).toMatchObject({
_tag: "PlaywrightSourceMarkerNotFoundError",
bundlePath: "/tmp/coreBundle.js",
marker: "source3 = ",
});
expect("cause" in error).toBe(false);
}),
);
effectIt.effect("keeps source validation metadata cause-free", () =>
Effect.gen(function* () {
const error = yield* Effect.flip(
extractPlaywrightInjectedRuntimeSource(
bundleWithSourceLiteral('"short"'),
"/tmp/coreBundle.js",
),
);
expect(error).toMatchObject({
_tag: "PlaywrightSourceValidationError",
bundlePath: "/tmp/coreBundle.js",
actualType: "string",
actualLength: 5,
minimumLength: 100_000,
});
expect("cause" in error).toBe(false);
}),
);
effectIt.effect("preserves the source evaluation cause", () =>
Effect.gen(function* () {
const error = yield* Effect.flip(
extractPlaywrightInjectedRuntimeSource(bundleWithSourceLiteral("("), "/tmp/coreBundle.js"),
);
expect(error).toMatchObject({
_tag: "PlaywrightSourceEvaluationError",
bundlePath: "/tmp/coreBundle.js",
timeoutMs: 1_000,
cause: expect.objectContaining({ name: "SyntaxError" }),
});
}),
);
});
@@ -4,180 +4,69 @@ import * as NodeModule from "node:module";
import * as NodePath from "node:path";
import * as NodeVM from "node:vm";
import * as Data from "effect/Data";
import * as Effect from "effect/Effect";
import * as Schema from "effect/Schema";
const require = NodeModule.createRequire(import.meta.url);
const encodeUnknownJson = Schema.encodeUnknownEffect(Schema.UnknownFromJsonString);
const PLAYWRIGHT_PACKAGE_SPECIFIER = "playwright-core/package.json";
const PLAYWRIGHT_SOURCE_MARKER = "source3 = ";
const PLAYWRIGHT_SOURCE_TERMINATOR = ";\n }\n});";
const PLAYWRIGHT_SOURCE_MINIMUM_LENGTH = 100_000;
const PLAYWRIGHT_SOURCE_EVALUATION_TIMEOUT_MS = 1_000;
const PLAYWRIGHT_SDK_LANGUAGE = "javascript";
const PLAYWRIGHT_BROWSER_NAME = "chromium";
export class PlaywrightPackageResolveError extends Schema.TaggedErrorClass<PlaywrightPackageResolveError>()(
"PlaywrightPackageResolveError",
{
specifier: Schema.String,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to resolve Playwright package: ${this.specifier}`;
export class PlaywrightInjectedRuntimeError extends Data.TaggedError(
"PlaywrightInjectedRuntimeError",
)<{
readonly operation: string;
readonly cause: unknown;
}> {
override get message() {
return `Playwright injected runtime operation failed: ${this.operation}`;
}
}
export class PlaywrightCoreBundleReadError extends Schema.TaggedErrorClass<PlaywrightCoreBundleReadError>()(
"PlaywrightCoreBundleReadError",
{
bundlePath: Schema.String,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to read Playwright core bundle: ${this.bundlePath}`;
}
}
export class PlaywrightSourceMarkerNotFoundError extends Schema.TaggedErrorClass<PlaywrightSourceMarkerNotFoundError>()(
"PlaywrightSourceMarkerNotFoundError",
{
bundlePath: Schema.String,
marker: Schema.String,
},
) {
override get message(): string {
return `Playwright injected runtime marker ${JSON.stringify(this.marker)} was not found in ${this.bundlePath}`;
}
}
export class PlaywrightSourceTerminatorNotFoundError extends Schema.TaggedErrorClass<PlaywrightSourceTerminatorNotFoundError>()(
"PlaywrightSourceTerminatorNotFoundError",
{
bundlePath: Schema.String,
terminator: Schema.String,
},
) {
override get message(): string {
return `Playwright injected runtime terminator ${JSON.stringify(this.terminator)} was not found in ${this.bundlePath}`;
}
}
export class PlaywrightSourceEvaluationError extends Schema.TaggedErrorClass<PlaywrightSourceEvaluationError>()(
"PlaywrightSourceEvaluationError",
{
bundlePath: Schema.String,
timeoutMs: Schema.Number,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to evaluate the Playwright injected runtime literal from ${this.bundlePath} within ${this.timeoutMs}ms`;
}
}
export class PlaywrightSourceValidationError extends Schema.TaggedErrorClass<PlaywrightSourceValidationError>()(
"PlaywrightSourceValidationError",
{
bundlePath: Schema.String,
actualType: Schema.String,
actualLength: Schema.NullOr(Schema.Number),
minimumLength: Schema.Number,
},
) {
override get message(): string {
const actual =
this.actualLength === null
? this.actualType
: `${this.actualType} with ${this.actualLength} characters`;
return `Playwright injected runtime from ${this.bundlePath} was ${actual}; expected a string with at least ${this.minimumLength} characters`;
}
}
export class PlaywrightOptionsEncodeError extends Schema.TaggedErrorClass<PlaywrightOptionsEncodeError>()(
"PlaywrightOptionsEncodeError",
{
sdkLanguage: Schema.String,
browserName: Schema.String,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to encode ${this.browserName} Playwright injected runtime options for ${this.sdkLanguage}`;
}
}
export const PlaywrightInjectedRuntimeError = Schema.Union([
PlaywrightPackageResolveError,
PlaywrightCoreBundleReadError,
PlaywrightSourceMarkerNotFoundError,
PlaywrightSourceTerminatorNotFoundError,
PlaywrightSourceEvaluationError,
PlaywrightSourceValidationError,
PlaywrightOptionsEncodeError,
]);
export type PlaywrightInjectedRuntimeError = typeof PlaywrightInjectedRuntimeError.Type;
export const extractPlaywrightInjectedRuntimeSource = Effect.fn(
"PlaywrightInjectedRuntime.extractSource",
)(function* (coreBundle: string, bundlePath: string) {
const start = coreBundle.indexOf(PLAYWRIGHT_SOURCE_MARKER);
if (start < 0) {
return yield* new PlaywrightSourceMarkerNotFoundError({
bundlePath,
marker: PLAYWRIGHT_SOURCE_MARKER,
});
}
const literalStart = start + PLAYWRIGHT_SOURCE_MARKER.length;
const literalEnd = coreBundle.indexOf(PLAYWRIGHT_SOURCE_TERMINATOR, literalStart);
if (literalEnd < 0) {
return yield* new PlaywrightSourceTerminatorNotFoundError({
bundlePath,
terminator: PLAYWRIGHT_SOURCE_TERMINATOR,
});
}
const literal = coreBundle.slice(literalStart, literalEnd);
const source = yield* Effect.try({
try: () =>
NodeVM.runInNewContext(literal, Object.create(null), {
timeout: PLAYWRIGHT_SOURCE_EVALUATION_TIMEOUT_MS,
}),
catch: (cause) =>
new PlaywrightSourceEvaluationError({
bundlePath,
timeoutMs: PLAYWRIGHT_SOURCE_EVALUATION_TIMEOUT_MS,
cause,
}),
});
if (typeof source !== "string" || source.length < PLAYWRIGHT_SOURCE_MINIMUM_LENGTH) {
return yield* new PlaywrightSourceValidationError({
bundlePath,
actualType: typeof source,
actualLength: typeof source === "string" ? source.length : null,
minimumLength: PLAYWRIGHT_SOURCE_MINIMUM_LENGTH,
});
}
return source;
});
const fail = (operation: string, cause: unknown) =>
new PlaywrightInjectedRuntimeError({ operation, cause });
export const playwrightInjectedRuntimeSource = Effect.fn("PlaywrightInjectedRuntime.source")(
function* () {
const packageJsonPath = yield* Effect.try({
try: () => require.resolve(PLAYWRIGHT_PACKAGE_SPECIFIER),
catch: (cause) =>
new PlaywrightPackageResolveError({
specifier: PLAYWRIGHT_PACKAGE_SPECIFIER,
cause,
}),
try: () => require.resolve("playwright-core/package.json"),
catch: (cause) => fail("resolvePackage", cause),
});
const bundlePath = NodePath.join(NodePath.dirname(packageJsonPath), "lib/coreBundle.js");
const coreBundle = yield* Effect.tryPromise({
try: () => NodeFSP.readFile(bundlePath, "utf8"),
catch: (cause) => new PlaywrightCoreBundleReadError({ bundlePath, cause }),
try: () =>
NodeFSP.readFile(
NodePath.join(NodePath.dirname(packageJsonPath), "lib/coreBundle.js"),
"utf8",
),
catch: (cause) => fail("readCoreBundle", cause),
});
return yield* extractPlaywrightInjectedRuntimeSource(coreBundle, bundlePath);
const marker = "source3 = ";
const start = coreBundle.indexOf(marker);
if (start < 0) {
return yield* fail(
"findSourceMarker",
new Error("Playwright injected runtime marker was not found."),
);
}
const literalStart = start + marker.length;
const literalEnd = coreBundle.indexOf(";\n }\n});", literalStart);
if (literalEnd < 0) {
return yield* fail(
"findSourceTerminator",
new Error("Playwright injected runtime terminator was not found."),
);
}
const literal = coreBundle.slice(literalStart, literalEnd);
const source = yield* Effect.try({
try: () => NodeVM.runInNewContext(literal, Object.create(null), { timeout: 1_000 }),
catch: (cause) => fail("evaluateSourceLiteral", cause),
});
if (typeof source !== "string" || source.length < 100_000) {
return yield* fail(
"validateSource",
new Error("Playwright injected runtime extraction returned invalid source."),
);
}
return source;
},
);
@@ -187,23 +76,14 @@ export const playwrightInjectedRuntimeInstallExpression = Effect.fn(
const source = yield* playwrightInjectedRuntimeSource();
const options = yield* encodeUnknownJson({
isUnderTest: false,
sdkLanguage: PLAYWRIGHT_SDK_LANGUAGE,
sdkLanguage: "javascript",
testIdAttributeName: "data-testid",
stableRafCount: 1,
browserName: PLAYWRIGHT_BROWSER_NAME,
browserName: "chromium",
shouldPrependErrorPrefix: false,
isUtilityWorld: false,
customEngines: [],
}).pipe(
Effect.mapError(
(cause) =>
new PlaywrightOptionsEncodeError({
sdkLanguage: PLAYWRIGHT_SDK_LANGUAGE,
browserName: PLAYWRIGHT_BROWSER_NAME,
cause,
}),
),
);
}).pipe(Effect.mapError((cause) => fail("encodeOptions", cause)));
return `(() => {
if (globalThis.__t3PlaywrightInjected) return true;
const module = { exports: {} };
@@ -1,97 +0,0 @@
import { describe, expect, it } from "vite-plus/test";
import { makePreviewAutomationKeySequence } from "./PreviewKeyboard.ts";
describe("preview keyboard packets", () => {
it("includes the Chromium virtual key code and Enter text", () => {
expect(makePreviewAutomationKeySequence({ key: "Enter" })).toEqual({
keyDown: {
type: "keyDown",
key: "Enter",
code: "Enter",
modifiers: 0,
windowsVirtualKeyCode: 13,
location: 0,
isKeypad: false,
text: "\r",
unmodifiedText: "\r",
},
keyUp: {
type: "keyUp",
key: "Enter",
code: "Enter",
modifiers: 0,
windowsVirtualKeyCode: 13,
location: 0,
isKeypad: false,
},
signal: { kind: "key", key: "Enter", code: "Enter" },
});
});
it("dispatches printable keys as text key-down events", () => {
const sequence = makePreviewAutomationKeySequence({ key: "z" });
expect(sequence.keyDown).toMatchObject({
type: "keyDown",
key: "z",
code: "KeyZ",
windowsVirtualKeyCode: 90,
text: "z",
});
expect(sequence.keyUp).not.toHaveProperty("text");
});
it("suppresses text and uses raw key-down for shortcuts", () => {
expect(
makePreviewAutomationKeySequence({ key: "a", modifiers: ["Meta"] }, { isMac: true }).keyDown,
).toEqual({
type: "rawKeyDown",
key: "a",
code: "KeyA",
modifiers: 4,
windowsVirtualKeyCode: 65,
location: 0,
isKeypad: false,
commands: ["selectAll"],
});
});
it("maps common macOS editing shortcuts without changing other platforms", () => {
expect(
makePreviewAutomationKeySequence({ key: "z", modifiers: ["Shift", "Meta"] }, { isMac: true })
.keyDown.commands,
).toEqual(["redo"]);
expect(
makePreviewAutomationKeySequence({ key: "a", modifiers: ["Meta"] }).keyDown,
).not.toHaveProperty("commands");
});
it("resolves shifted printable keys to their browser values", () => {
const sequence = makePreviewAutomationKeySequence({ key: "1", modifiers: ["Shift"] });
expect(sequence.keyDown).toMatchObject({
key: "!",
code: "Digit1",
modifiers: 8,
windowsVirtualKeyCode: 49,
text: "!",
});
expect(sequence.signal).toEqual({ kind: "key", key: "!", code: "Digit1" });
});
it("keeps shifted key values while suppressing text for modified chords", () => {
const sequence = makePreviewAutomationKeySequence({
key: "1",
modifiers: ["Control", "Shift"],
});
expect(sequence.keyDown).toEqual({
type: "rawKeyDown",
key: "!",
code: "Digit1",
modifiers: 10,
windowsVirtualKeyCode: 49,
location: 0,
isKeypad: false,
});
expect(sequence.signal).toEqual({ kind: "key", key: "!", code: "Digit1" });
});
});
-203
View File
@@ -1,203 +0,0 @@
import type { PreviewAutomationPressInput } from "@t3tools/contracts";
interface KeyDefinition {
readonly code: string;
readonly key: string;
readonly keyCode: number;
readonly text?: string;
readonly location?: number;
readonly shiftedKey?: string;
}
export interface PreviewAutomationKeyEvent {
readonly [key: string]: unknown;
readonly type: "keyDown" | "rawKeyDown" | "keyUp";
readonly key: string;
readonly code: string;
readonly modifiers: number;
readonly windowsVirtualKeyCode: number;
readonly location: number;
readonly isKeypad: boolean;
readonly text?: string;
readonly unmodifiedText?: string;
readonly commands?: ReadonlyArray<string>;
}
export interface PreviewAutomationKeySequence {
readonly keyDown: PreviewAutomationKeyEvent;
readonly keyUp: PreviewAutomationKeyEvent;
readonly signal: {
readonly kind: "key";
readonly key: string;
readonly code: string;
};
}
const NAMED_KEYS: Readonly<Record<string, KeyDefinition>> = {
Escape: { code: "Escape", key: "Escape", keyCode: 27 },
Backspace: { code: "Backspace", key: "Backspace", keyCode: 8 },
Tab: { code: "Tab", key: "Tab", keyCode: 9 },
Enter: { code: "Enter", key: "Enter", keyCode: 13, text: "\r" },
Shift: { code: "ShiftLeft", key: "Shift", keyCode: 16, location: 1 },
Control: { code: "ControlLeft", key: "Control", keyCode: 17, location: 1 },
Alt: { code: "AltLeft", key: "Alt", keyCode: 18, location: 1 },
Meta: { code: "MetaLeft", key: "Meta", keyCode: 91, location: 1 },
CapsLock: { code: "CapsLock", key: "CapsLock", keyCode: 20 },
Space: { code: "Space", key: " ", keyCode: 32, text: " " },
PageUp: { code: "PageUp", key: "PageUp", keyCode: 33 },
PageDown: { code: "PageDown", key: "PageDown", keyCode: 34 },
End: { code: "End", key: "End", keyCode: 35 },
Home: { code: "Home", key: "Home", keyCode: 36 },
ArrowLeft: { code: "ArrowLeft", key: "ArrowLeft", keyCode: 37 },
ArrowUp: { code: "ArrowUp", key: "ArrowUp", keyCode: 38 },
ArrowRight: { code: "ArrowRight", key: "ArrowRight", keyCode: 39 },
ArrowDown: { code: "ArrowDown", key: "ArrowDown", keyCode: 40 },
Insert: { code: "Insert", key: "Insert", keyCode: 45 },
Delete: { code: "Delete", key: "Delete", keyCode: 46 },
};
const PRINTABLE_KEYS: ReadonlyArray<KeyDefinition> = [
{ code: "Backquote", key: "`", shiftedKey: "~", keyCode: 192 },
{ code: "Digit1", key: "1", shiftedKey: "!", keyCode: 49 },
{ code: "Digit2", key: "2", shiftedKey: "@", keyCode: 50 },
{ code: "Digit3", key: "3", shiftedKey: "#", keyCode: 51 },
{ code: "Digit4", key: "4", shiftedKey: "$", keyCode: 52 },
{ code: "Digit5", key: "5", shiftedKey: "%", keyCode: 53 },
{ code: "Digit6", key: "6", shiftedKey: "^", keyCode: 54 },
{ code: "Digit7", key: "7", shiftedKey: "&", keyCode: 55 },
{ code: "Digit8", key: "8", shiftedKey: "*", keyCode: 56 },
{ code: "Digit9", key: "9", shiftedKey: "(", keyCode: 57 },
{ code: "Digit0", key: "0", shiftedKey: ")", keyCode: 48 },
{ code: "Minus", key: "-", shiftedKey: "_", keyCode: 189 },
{ code: "Equal", key: "=", shiftedKey: "+", keyCode: 187 },
{ code: "Backslash", key: "\\", shiftedKey: "|", keyCode: 220 },
{ code: "BracketLeft", key: "[", shiftedKey: "{", keyCode: 219 },
{ code: "BracketRight", key: "]", shiftedKey: "}", keyCode: 221 },
{ code: "Semicolon", key: ";", shiftedKey: ":", keyCode: 186 },
{ code: "Quote", key: "'", shiftedKey: '"', keyCode: 222 },
{ code: "Comma", key: ",", shiftedKey: "<", keyCode: 188 },
{ code: "Period", key: ".", shiftedKey: ">", keyCode: 190 },
{ code: "Slash", key: "/", shiftedKey: "?", keyCode: 191 },
];
/**
* Chromium does not infer macOS editing commands from synthetic Meta chords.
* Keep the common browser editing/navigation shortcuts explicit so dispatched
* key events behave like their physical-key equivalents.
*/
const MAC_EDITING_COMMANDS: Readonly<Record<string, string>> = {
"Meta+Backspace": "deleteToBeginningOfLine",
"Meta+ArrowUp": "moveToBeginningOfDocument",
"Meta+ArrowDown": "moveToEndOfDocument",
"Meta+ArrowLeft": "moveToLeftEndOfLine",
"Meta+ArrowRight": "moveToRightEndOfLine",
"Shift+Meta+ArrowUp": "moveToBeginningOfDocumentAndModifySelection",
"Shift+Meta+ArrowDown": "moveToEndOfDocumentAndModifySelection",
"Shift+Meta+ArrowLeft": "moveToLeftEndOfLineAndModifySelection",
"Shift+Meta+ArrowRight": "moveToRightEndOfLineAndModifySelection",
"Meta+KeyA": "selectAll",
"Meta+KeyC": "copy",
"Meta+KeyX": "cut",
"Meta+KeyV": "paste",
"Meta+KeyZ": "undo",
"Shift+Meta+KeyZ": "redo",
};
const SHORTCUT_MODIFIER_ORDER = ["Shift", "Control", "Alt", "Meta"] as const;
const macEditingCommands = (
code: string,
modifiers: PreviewAutomationPressInput["modifiers"],
): ReadonlyArray<string> => {
const shortcut = [
...SHORTCUT_MODIFIER_ORDER.filter((modifier) => modifiers?.includes(modifier)),
code,
].join("+");
const command = MAC_EDITING_COMMANDS[shortcut];
return command ? [command] : [];
};
const modifierMask = (modifiers: PreviewAutomationPressInput["modifiers"]): number =>
(modifiers ?? []).reduce((value, modifier) => {
switch (modifier) {
case "Alt":
return value | 1;
case "Control":
return value | 2;
case "Meta":
return value | 4;
case "Shift":
return value | 8;
}
}, 0);
function resolveKeyDefinition(input: PreviewAutomationPressInput): KeyDefinition {
const named = NAMED_KEYS[input.key];
if (named) return named;
const functionKey = /^F([1-9]|1[0-2])$/.exec(input.key);
if (functionKey) {
const number = Number(functionKey[1]);
return { code: input.key, key: input.key, keyCode: 111 + number };
}
if (/^[a-z]$/i.test(input.key)) {
const upper = input.key.toUpperCase();
const shifted = input.modifiers?.includes("Shift") ?? false;
const key = shifted || input.key === upper ? upper : input.key;
return { code: `Key${upper}`, key, keyCode: upper.charCodeAt(0), text: key };
}
const printable = PRINTABLE_KEYS.find(
(definition) => definition.key === input.key || definition.shiftedKey === input.key,
);
if (printable) {
const shifted = input.modifiers?.includes("Shift") ?? false;
const key =
printable.shiftedKey && (shifted || input.key === printable.shiftedKey)
? printable.shiftedKey
: printable.key;
return { ...printable, key, text: key };
}
return {
code: input.key.length > 1 ? input.key : "",
key: input.key,
keyCode: 0,
...(input.key.length === 1 ? { text: input.key } : {}),
};
}
/**
* Build Chromium CDP key packets using the same required fields and down-event
* choice as Playwright's pinned Chromium keyboard implementation.
*/
export function makePreviewAutomationKeySequence(
input: PreviewAutomationPressInput,
options?: { readonly isMac?: boolean },
): PreviewAutomationKeySequence {
const definition = resolveKeyDefinition(input);
const modifiers = modifierMask(input.modifiers);
const suppressText = input.modifiers?.some((modifier) => modifier !== "Shift") ?? false;
const text = suppressText ? "" : (definition.text ?? "");
const location = definition.location ?? 0;
const commands = options?.isMac ? macEditingCommands(definition.code, input.modifiers) : [];
const shared = {
key: definition.key,
code: definition.code,
modifiers,
windowsVirtualKeyCode: definition.keyCode,
location,
isKeypad: location === 3,
};
return {
keyDown: {
type: text ? "keyDown" : "rawKeyDown",
...shared,
...(text ? { text, unmodifiedText: text } : {}),
...(commands.length > 0 ? { commands } : {}),
},
keyUp: { type: "keyUp", ...shared },
signal: { kind: "key", key: definition.key, code: definition.code },
};
}
@@ -16,10 +16,6 @@ const DesktopSettingsPatch = Schema.Struct({
tailscaleServePort: Schema.optionalKey(Schema.Number),
updateChannel: Schema.optionalKey(Schema.Literals(["latest", "nightly"])),
updateChannelConfiguredByUser: Schema.optionalKey(Schema.Boolean),
wslBackendEnabled: Schema.optionalKey(Schema.Boolean),
wslMode: Schema.optionalKey(Schema.Literals(["local", "wsl"])),
wslDistro: Schema.optionalKey(Schema.NullOr(Schema.String)),
wslOnly: Schema.optionalKey(Schema.Boolean),
});
const decodeDesktopSettingsPatch = Schema.decodeEffect(Schema.fromJsonString(DesktopSettingsPatch));
@@ -96,9 +92,6 @@ describe("DesktopSettings", () => {
tailscaleServePort: 443,
updateChannel: "nightly",
updateChannelConfiguredByUser: false,
wslBackendEnabled: false,
wslOnly: false,
wslDistro: null,
} satisfies DesktopAppSettings.DesktopSettings,
);
});
@@ -121,9 +114,6 @@ describe("DesktopSettings", () => {
tailscaleServePort: 8443,
updateChannel: "latest",
updateChannelConfiguredByUser: true,
wslBackendEnabled: false,
wslOnly: false,
wslDistro: null,
} satisfies DesktopAppSettings.DesktopSettings);
const exposure = yield* settings.setServerExposureMode("local-only");
@@ -224,9 +214,6 @@ describe("DesktopSettings", () => {
tailscaleServePort: 8443,
updateChannel: "latest",
updateChannelConfiguredByUser: false,
wslBackendEnabled: false,
wslOnly: false,
wslDistro: null,
} satisfies DesktopAppSettings.DesktopSettings);
}),
),
@@ -266,9 +253,6 @@ describe("DesktopSettings", () => {
tailscaleServePort: 443,
updateChannel: "nightly",
updateChannelConfiguredByUser: false,
wslBackendEnabled: false,
wslOnly: false,
wslDistro: null,
} satisfies DesktopAppSettings.DesktopSettings);
}),
{ appVersion: "0.0.17-nightly.20260415.1" },
@@ -291,9 +275,6 @@ describe("DesktopSettings", () => {
tailscaleServePort: 443,
updateChannel: "latest",
updateChannelConfiguredByUser: true,
wslBackendEnabled: false,
wslOnly: false,
wslDistro: null,
} satisfies DesktopAppSettings.DesktopSettings);
}),
{ appVersion: "0.0.17-nightly.20260415.1" },
@@ -315,101 +296,8 @@ describe("DesktopSettings", () => {
tailscaleServePort: 443,
updateChannel: "latest",
updateChannelConfiguredByUser: false,
wslBackendEnabled: false,
wslOnly: false,
wslDistro: null,
} satisfies DesktopAppSettings.DesktopSettings);
}),
),
);
it.effect("persists wsl backend toggle and normalizes invalid distro names", () =>
withSettings(
Effect.gen(function* () {
const settings = yield* DesktopAppSettings.DesktopAppSettings;
const enable = yield* settings.setWslBackendEnabled(true);
assert.isTrue(enable.changed);
assert.equal(enable.settings.wslBackendEnabled, true);
const distro = yield* settings.setWslDistro("Ubuntu-22.04");
assert.isTrue(distro.changed);
assert.equal(distro.settings.wslDistro, "Ubuntu-22.04");
const reloaded = yield* settings.load;
assert.equal(reloaded.wslBackendEnabled, true);
assert.equal(reloaded.wslDistro, "Ubuntu-22.04");
const reject = yield* settings.setWslDistro("bad name!");
assert.equal(reject.settings.wslDistro, null);
const noop = yield* settings.setWslDistro(null);
assert.isFalse(noop.changed);
}),
),
);
it.effect("applies WSL Windows fallback with persisted and volatile updates", () =>
withSettings(
Effect.gen(function* () {
const settings = yield* DesktopAppSettings.DesktopAppSettings;
yield* settings.setWslBackendEnabled(true);
yield* settings.setWslOnly(true);
const persistedFallback = yield* settings.applyWslWindowsFallback;
assert.isTrue(persistedFallback.changed);
assert.equal(persistedFallback.settings.wslBackendEnabled, false);
assert.equal(persistedFallback.settings.wslOnly, false);
const persistedReload = yield* settings.load;
assert.equal(persistedReload.wslBackendEnabled, false);
assert.equal(persistedReload.wslOnly, false);
yield* settings.setWslBackendEnabled(true);
yield* settings.setWslOnly(true);
const volatileFallback = yield* settings.applyWslWindowsFallbackInMemory;
assert.isTrue(volatileFallback.changed);
assert.equal(volatileFallback.settings.wslBackendEnabled, false);
assert.equal(volatileFallback.settings.wslOnly, false);
const current = yield* settings.get;
assert.equal(current.wslBackendEnabled, false);
assert.equal(current.wslOnly, false);
const diskReload = yield* settings.load;
assert.equal(diskReload.wslBackendEnabled, true);
assert.equal(diskReload.wslOnly, true);
}),
),
);
it.effect("migrates legacy wslMode=wsl to wslBackendEnabled on load", () =>
withSettings(
Effect.gen(function* () {
const settings = yield* DesktopAppSettings.DesktopAppSettings;
yield* writeSettingsPatch({
wslMode: "wsl",
wslDistro: "Ubuntu-22.04",
});
const loaded = yield* settings.load;
assert.equal(loaded.wslBackendEnabled, true);
assert.equal(loaded.wslDistro, "Ubuntu-22.04");
}),
),
);
it.effect("drops invalid persisted wsl distro values on load", () =>
withSettings(
Effect.gen(function* () {
const settings = yield* DesktopAppSettings.DesktopAppSettings;
yield* writeSettingsPatch({
wslBackendEnabled: true,
wslDistro: "bad/name",
});
const loaded = yield* settings.load;
assert.equal(loaded.wslBackendEnabled, true);
assert.equal(loaded.wslDistro, null);
}),
),
);
});
+20 -174
View File
@@ -17,7 +17,6 @@ import * as SynchronizedRef from "effect/SynchronizedRef";
import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
import { resolveDefaultDesktopUpdateChannel } from "../updates/updateChannels.ts";
import { isValidDistroName } from "../wsl/wslPathParsing.ts";
export interface DesktopSettings {
readonly serverExposureMode: DesktopServerExposureMode;
@@ -25,21 +24,6 @@ export interface DesktopSettings {
readonly tailscaleServePort: number;
readonly updateChannel: DesktopUpdateChannel;
readonly updateChannelConfiguredByUser: boolean;
// Was a "local" | "wsl" swap mode in an earlier iteration of the WSL
// integration. We now run Windows and WSL backends side by side, so the
// setting is just whether the WSL backend should be running alongside the
// primary. Persisted documents that still carry the legacy `wslMode: "wsl"`
// value are migrated to `wslBackendEnabled: true` on load.
readonly wslBackendEnabled: boolean;
readonly wslDistro: string | null;
// When true (and wslBackendEnabled is also true) the desktop runs only
// the WSL backend as the primary, and the Windows-side Node backend is
// not started. Designed for users who develop entirely inside WSL and
// don't want a second backend process running. Defaults to false so
// existing setups stay on the parallel-backends behavior. Changing
// this requires a desktop restart because the pool's primary spec is
// chosen once at layer init.
readonly wslOnly: boolean;
}
export interface DesktopSettingsChange {
@@ -55,9 +39,6 @@ export const DEFAULT_DESKTOP_SETTINGS: DesktopSettings = {
tailscaleServePort: DEFAULT_TAILSCALE_SERVE_PORT,
updateChannel: "latest",
updateChannelConfiguredByUser: false,
wslBackendEnabled: false,
wslDistro: null,
wslOnly: false,
};
const DesktopSettingsDocument = Schema.Struct({
@@ -66,13 +47,6 @@ const DesktopSettingsDocument = Schema.Struct({
tailscaleServePort: Schema.optionalKey(Schema.Number),
updateChannel: Schema.optionalKey(DesktopUpdateChannelSchema),
updateChannelConfiguredByUser: Schema.optionalKey(Schema.Boolean),
// Newer form of the WSL toggle. `wslMode` is still accepted on load so
// existing on-disk settings keep working; on the next persist we write the
// new boolean and the legacy key drops out.
wslBackendEnabled: Schema.optionalKey(Schema.Boolean),
wslMode: Schema.optionalKey(Schema.Literals(["local", "wsl"])),
wslDistro: Schema.optionalKey(Schema.NullOr(Schema.String)),
wslOnly: Schema.optionalKey(Schema.Boolean),
});
type DesktopSettingsDocument = typeof DesktopSettingsDocument.Type;
@@ -109,6 +83,12 @@ export class DesktopSettingsWriteError extends Schema.TaggedErrorClass<DesktopSe
}
}
const writeError = (
operation: DesktopSettingsWriteOperation,
path: string,
cause: unknown,
): DesktopSettingsWriteError => new DesktopSettingsWriteError({ operation, path, cause });
export class DesktopAppSettings extends Context.Service<
DesktopAppSettings,
{
@@ -124,20 +104,6 @@ export class DesktopAppSettings extends Context.Service<
readonly setUpdateChannel: (
channel: DesktopUpdateChannel,
) => Effect.Effect<DesktopSettingsChange, DesktopSettingsWriteError>;
readonly setWslBackendEnabled: (
enabled: boolean,
) => Effect.Effect<DesktopSettingsChange, DesktopSettingsWriteError>;
readonly setWslDistro: (
distro: string | null,
) => Effect.Effect<DesktopSettingsChange, DesktopSettingsWriteError>;
readonly setWslOnly: (
enabled: boolean,
) => Effect.Effect<DesktopSettingsChange, DesktopSettingsWriteError>;
readonly applyWslWindowsFallback: Effect.Effect<
DesktopSettingsChange,
DesktopSettingsWriteError
>;
readonly applyWslWindowsFallbackInMemory: Effect.Effect<DesktopSettingsChange>;
}
>()("@t3tools/desktop/settings/DesktopAppSettings") {}
@@ -154,10 +120,6 @@ function normalizeTailscaleServePort(value: unknown): number {
: DEFAULT_TAILSCALE_SERVE_PORT;
}
function normalizeWslDistro(value: unknown): string | null {
return typeof value === "string" && isValidDistroName(value) ? value : null;
}
function normalizeDesktopSettingsDocument(
parsed: DesktopSettingsDocument,
appVersion: string,
@@ -169,13 +131,6 @@ function normalizeDesktopSettingsDocument(
parsed.updateChannelConfiguredByUser === true ||
(isLegacySettings && Option.contains(parsedUpdateChannel, "nightly"));
// Newer form wins when both are present; otherwise fall back to the legacy
// `wslMode === "wsl"` signal so users coming off the swap-mode build keep
// their WSL backend enabled.
const wslBackendEnabled =
parsed.wslBackendEnabled === true ||
(parsed.wslBackendEnabled === undefined && parsed.wslMode === "wsl");
return {
serverExposureMode:
parsed.serverExposureMode === "network-accessible" ? "network-accessible" : "local-only",
@@ -185,9 +140,6 @@ function normalizeDesktopSettingsDocument(
? Option.getOrElse(parsedUpdateChannel, () => defaultSettings.updateChannel)
: defaultSettings.updateChannel,
updateChannelConfiguredByUser,
wslBackendEnabled,
wslDistro: normalizeWslDistro(parsed.wslDistro),
wslOnly: parsed.wslOnly === true,
};
}
@@ -212,15 +164,6 @@ function toDesktopSettingsDocument(
if (settings.updateChannelConfiguredByUser !== defaults.updateChannelConfiguredByUser) {
document.updateChannelConfiguredByUser = settings.updateChannelConfiguredByUser;
}
if (settings.wslBackendEnabled !== defaults.wslBackendEnabled) {
document.wslBackendEnabled = settings.wslBackendEnabled;
}
if (settings.wslDistro !== defaults.wslDistro) {
document.wslDistro = settings.wslDistro;
}
if (settings.wslOnly !== defaults.wslOnly) {
document.wslOnly = settings.wslOnly;
}
return document;
}
@@ -267,38 +210,6 @@ function setUpdateChannel(
};
}
function setWslBackendEnabled(settings: DesktopSettings, enabled: boolean): DesktopSettings {
return settings.wslBackendEnabled === enabled
? settings
: {
...settings,
wslBackendEnabled: enabled,
};
}
function setWslDistro(settings: DesktopSettings, distro: string | null): DesktopSettings {
const normalized = normalizeWslDistro(distro);
return settings.wslDistro === normalized
? settings
: {
...settings,
wslDistro: normalized,
};
}
function setWslOnly(settings: DesktopSettings, enabled: boolean): DesktopSettings {
return settings.wslOnly === enabled
? settings
: {
...settings,
wslOnly: enabled,
};
}
function applyWslWindowsFallback(settings: DesktopSettings): DesktopSettings {
return setWslOnly(setWslBackendEnabled(settings, false), false);
}
function readSettings(
fileSystem: FileSystem.FileSystem,
settingsPath: string,
@@ -333,46 +244,18 @@ const writeSettings = Effect.fn("desktop.settings.writeSettings")(function* (inp
const tempPath = `${input.settingsPath}.${process.pid}.${input.suffix}.tmp`;
const encoded = yield* encodeDesktopSettingsJson(
toDesktopSettingsDocument(input.settings, input.defaultSettings),
).pipe(
Effect.mapError(
(cause) =>
new DesktopSettingsWriteError({
operation: "encode-document",
path: input.settingsPath,
cause,
}),
),
);
yield* input.fileSystem.makeDirectory(directory, { recursive: true }).pipe(
Effect.mapError(
(cause) =>
new DesktopSettingsWriteError({
operation: "create-directory",
path: directory,
cause,
}),
),
);
yield* input.fileSystem.writeFileString(tempPath, `${encoded}\n`).pipe(
Effect.mapError(
(cause) =>
new DesktopSettingsWriteError({
operation: "write-temporary-file",
path: tempPath,
cause,
}),
),
);
yield* input.fileSystem.rename(tempPath, input.settingsPath).pipe(
Effect.mapError(
(cause) =>
new DesktopSettingsWriteError({
operation: "replace-settings-file",
path: input.settingsPath,
cause,
}),
),
);
).pipe(Effect.mapError((cause) => writeError("encode-document", input.settingsPath, cause)));
yield* input.fileSystem
.makeDirectory(directory, { recursive: true })
.pipe(Effect.mapError((cause) => writeError("create-directory", directory, cause)));
yield* input.fileSystem
.writeFileString(tempPath, `${encoded}\n`)
.pipe(Effect.mapError((cause) => writeError("write-temporary-file", tempPath, cause)));
yield* input.fileSystem
.rename(tempPath, input.settingsPath)
.pipe(
Effect.mapError((cause) => writeError("replace-settings-file", input.settingsPath, cause)),
);
});
export const make = Effect.gen(function* () {
@@ -382,12 +265,6 @@ export const make = Effect.gen(function* () {
const crypto = yield* Crypto.Crypto;
const settingsRef = yield* SynchronizedRef.make(environment.defaultDesktopSettings);
const updateInMemory = (update: (settings: DesktopSettings) => DesktopSettings) =>
SynchronizedRef.modify(settingsRef, (settings) => {
const nextSettings = update(settings);
return [settingsChange(nextSettings, nextSettings !== settings), nextSettings] as const;
});
const persist = (
update: (settings: DesktopSettings) => DesktopSettings,
): Effect.Effect<DesktopSettingsChange, DesktopSettingsWriteError> =>
@@ -399,13 +276,8 @@ export const make = Effect.gen(function* () {
return crypto.randomUUIDv4.pipe(
Effect.map((uuid) => uuid.replace(/-/g, "")),
Effect.mapError(
(cause) =>
new DesktopSettingsWriteError({
operation: "create-temporary-file-name",
path: environment.desktopSettingsPath,
cause,
}),
Effect.mapError((cause) =>
writeError("create-temporary-file-name", environment.desktopSettingsPath, cause),
),
Effect.flatMap((suffix) =>
writeSettings({
@@ -443,26 +315,6 @@ export const make = Effect.gen(function* () {
persist((settings) => setUpdateChannel(settings, channel)).pipe(
Effect.withSpan("desktop.settings.setUpdateChannel", { attributes: { channel } }),
),
setWslBackendEnabled: (enabled) =>
persist((settings) => setWslBackendEnabled(settings, enabled)).pipe(
Effect.withSpan("desktop.settings.setWslBackendEnabled", { attributes: { enabled } }),
),
setWslDistro: (distro) =>
persist((settings) => setWslDistro(settings, distro)).pipe(
Effect.withSpan("desktop.settings.setWslDistro", {
attributes: { distro: distro ?? null },
}),
),
setWslOnly: (enabled) =>
persist((settings) => setWslOnly(settings, enabled)).pipe(
Effect.withSpan("desktop.settings.setWslOnly", { attributes: { enabled } }),
),
applyWslWindowsFallback: persist(applyWslWindowsFallback).pipe(
Effect.withSpan("desktop.settings.applyWslWindowsFallback"),
),
applyWslWindowsFallbackInMemory: updateInMemory(applyWslWindowsFallback).pipe(
Effect.withSpan("desktop.settings.applyWslWindowsFallbackInMemory"),
),
});
});
@@ -492,12 +344,6 @@ export const layerTest = (initialSettings: DesktopSettings = DEFAULT_DESKTOP_SET
update((settings) => setServerExposureMode(settings, mode)),
setTailscaleServe: (input) => update((settings) => setTailscaleServe(settings, input)),
setUpdateChannel: (channel) => update((settings) => setUpdateChannel(settings, channel)),
setWslBackendEnabled: (enabled) =>
update((settings) => setWslBackendEnabled(settings, enabled)),
setWslDistro: (distro) => update((settings) => setWslDistro(settings, distro)),
setWslOnly: (enabled) => update((settings) => setWslOnly(settings, enabled)),
applyWslWindowsFallback: update(applyWslWindowsFallback),
applyWslWindowsFallbackInMemory: update(applyWslWindowsFallback),
});
}),
);
@@ -1,129 +0,0 @@
import * as NodeServices from "@effect/platform-node/NodeServices";
import { assert, describe, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Logger from "effect/Logger";
import * as Option from "effect/Option";
import * as PlatformError from "effect/PlatformError";
import * as References from "effect/References";
import * as DesktopConfig from "../app/DesktopConfig.ts";
import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
import * as DesktopClientSettings from "./DesktopClientSettings.ts";
interface LogRecord {
readonly message: unknown;
readonly annotations: Readonly<Record<string, unknown>>;
}
const baseDir = "/virtual-home";
function makeLayer(fileSystemLayer: Layer.Layer<FileSystem.FileSystem>) {
const environmentLayer = DesktopEnvironment.layer({
dirname: "/repo/apps/desktop/src",
homeDirectory: baseDir,
platform: "darwin",
processArch: "x64",
appVersion: "1.2.3",
appPath: "/repo",
isPackaged: true,
resourcesPath: "/missing/resources",
runningUnderArm64Translation: false,
}).pipe(
Layer.provide(
Layer.mergeAll(NodeServices.layer, DesktopConfig.layerTest({ T3CODE_HOME: baseDir })),
),
);
return DesktopClientSettings.layer.pipe(
Layer.provideMerge(Layer.mergeAll(environmentLayer, NodeServices.layer, fileSystemLayer)),
);
}
const readWithLogs = (fileSystemLayer: Layer.Layer<FileSystem.FileSystem>) => {
const records: Array<LogRecord> = [];
const logger = Logger.make(({ fiber, message }) => {
records.push({
message,
annotations: { ...fiber.getRef(References.CurrentLogAnnotations) },
});
});
return Effect.gen(function* () {
const environment = yield* DesktopEnvironment.DesktopEnvironment;
const settings = yield* DesktopClientSettings.DesktopClientSettings;
return {
result: yield* settings.get,
settingsPath: environment.clientSettingsPath,
records,
};
}).pipe(
Effect.provide(
Layer.mergeAll(
makeLayer(fileSystemLayer),
Logger.layer([logger], { mergeWithExisting: false }),
),
),
);
};
describe("DesktopClientSettings diagnostics", () => {
it.effect("treats a missing settings file as expected without warning", () =>
Effect.gen(function* () {
const result = yield* readWithLogs(FileSystem.layerNoop({}));
assert.isTrue(Option.isNone(result.result));
assert.deepEqual(result.records, []);
}),
);
it.effect("logs non-missing filesystem failures with the settings path", () => {
const permissionError = PlatformError.systemError({
_tag: "PermissionDenied",
module: "FileSystem",
method: "readFileString",
pathOrDescriptor: `${baseDir}/userdata/client-settings.json`,
});
return Effect.gen(function* () {
const result = yield* readWithLogs(
FileSystem.layerNoop({
readFileString: () => Effect.fail(permissionError),
}),
);
assert.isTrue(Option.isNone(result.result));
assert.equal(result.records.length, 1);
assert.deepEqual(result.records[0]?.message, [
"Could not read desktop client settings.",
permissionError,
]);
assert.equal(result.records[0]?.annotations.settingsPath, result.settingsPath);
});
});
it.effect("logs malformed settings documents with the settings path", () =>
Effect.gen(function* () {
const result = yield* readWithLogs(
FileSystem.layerNoop({
readFileString: () => Effect.succeed("{not-json"),
}),
);
assert.isTrue(Option.isNone(result.result));
assert.equal(result.records.length, 1);
const message = result.records[0]?.message;
if (!Array.isArray(message)) {
return assert.fail("expected structured warning arguments");
}
assert.equal(message[0], "Could not decode desktop client settings.");
const schemaError = message[1];
if (schemaError === null || typeof schemaError !== "object") {
return assert.fail("expected the schema error in the warning");
}
assert.equal("_tag" in schemaError ? schemaError._tag : undefined, "SchemaError");
assert.equal(result.records[0]?.annotations.settingsPath, result.settingsPath);
}),
);
});
@@ -5,7 +5,6 @@ import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as PlatformError from "effect/PlatformError";
import * as Schema from "effect/Schema";
import * as DesktopConfig from "../app/DesktopConfig.ts";
@@ -18,6 +17,7 @@ const clientSettings: ClientSettings = {
confirmThreadDelete: false,
dismissedProviderUpdateNotificationKeys: [],
diffIgnoreWhitespace: true,
diffWordWrap: true,
favorites: [],
providerModelPreferences: {},
sidebarProjectGroupingMode: "repository_path",
@@ -28,7 +28,6 @@ const clientSettings: ClientSettings = {
sidebarThreadSortOrder: "created_at",
sidebarThreadPreviewCount: 6,
timestampFormat: "24-hour",
wordWrap: true,
};
const decodeClientSettingsJson = Schema.decodeEffect(Schema.fromJsonString(ClientSettingsSchema));
@@ -118,13 +117,11 @@ describe("DesktopClientSettings", () => {
assert.instanceOf(error, DesktopClientSettings.DesktopClientSettingsWriteError);
assert.equal(error.operation, "replace-settings-file");
assert.equal(error.path, environment.clientSettingsPath);
assert.instanceOf(error.cause, PlatformError.PlatformError);
assert.isString(error.cause.stack);
assert.exists(error.cause);
assert.equal(
error.message,
`Desktop client settings write failed during replace-settings-file at ${environment.clientSettingsPath}.`,
);
assert.notInclude(error.message, error.cause.message);
}),
),
);
@@ -25,9 +25,7 @@ const decodeClientSettingsJsonValue = Schema.decodeEffect(ClientSettingsJson);
const decodeClientSettingsJson = (raw: string): Effect.Effect<ClientSettings, Schema.SchemaError> =>
decodeLegacyClientSettingsDocumentJson(raw).pipe(
Effect.map((document) => document.settings),
Effect.catchTags({
SchemaError: () => decodeClientSettingsJsonValue(raw),
}),
Effect.catch(() => decodeClientSettingsJsonValue(raw)),
);
const encodeClientSettingsJson = Schema.encodeEffect(ClientSettingsJson);
@@ -38,6 +36,7 @@ const DesktopClientSettingsWriteOperation = Schema.Literals([
"write-temporary-file",
"replace-settings-file",
]);
type DesktopClientSettingsWriteOperation = typeof DesktopClientSettingsWriteOperation.Type;
export class DesktopClientSettingsWriteError extends Schema.TaggedErrorClass<DesktopClientSettingsWriteError>()(
"DesktopClientSettingsWriteError",
@@ -52,6 +51,13 @@ export class DesktopClientSettingsWriteError extends Schema.TaggedErrorClass<Des
}
}
const writeError = (
operation: DesktopClientSettingsWriteOperation,
path: string,
cause: unknown,
): DesktopClientSettingsWriteError =>
new DesktopClientSettingsWriteError({ operation, path, cause });
export class DesktopClientSettings extends Context.Service<
DesktopClientSettings,
{
@@ -67,29 +73,14 @@ const readClientSettings = (
settingsPath: string,
): Effect.Effect<Option.Option<ClientSettings>> =>
fileSystem.readFileString(settingsPath).pipe(
Effect.map(Option.some),
Effect.catchTags({
PlatformError: (cause) =>
cause.reason._tag === "NotFound"
? Effect.succeed(Option.none<string>())
: Effect.logWarning("Could not read desktop client settings.", cause).pipe(
Effect.annotateLogs({ settingsPath }),
Effect.as(Option.none<string>()),
),
}),
Effect.option,
Effect.flatMap(
Option.match({
onNone: () => Effect.succeed(Option.none<ClientSettings>()),
onSome: (raw) =>
decodeClientSettingsJson(raw).pipe(
Effect.map((settings) => Option.some(settings)),
Effect.catchTags({
SchemaError: (cause) =>
Effect.logWarning("Could not decode desktop client settings.", cause).pipe(
Effect.annotateLogs({ settingsPath }),
Effect.as(Option.none<ClientSettings>()),
),
}),
Effect.orElseSucceed(() => Option.none<ClientSettings>()),
),
}),
),
@@ -105,45 +96,19 @@ const writeClientSettings = Effect.fnUntraced(function* (input: {
const directory = input.path.dirname(input.settingsPath);
const tempPath = `${input.settingsPath}.${process.pid}.${input.suffix}.tmp`;
const encoded = yield* encodeClientSettingsJson(input.settings).pipe(
Effect.mapError(
(cause) =>
new DesktopClientSettingsWriteError({
operation: "encode-document",
path: input.settingsPath,
cause,
}),
),
);
yield* input.fileSystem.makeDirectory(directory, { recursive: true }).pipe(
Effect.mapError(
(cause) =>
new DesktopClientSettingsWriteError({
operation: "create-directory",
path: directory,
cause,
}),
),
);
yield* input.fileSystem.writeFileString(tempPath, `${encoded}\n`).pipe(
Effect.mapError(
(cause) =>
new DesktopClientSettingsWriteError({
operation: "write-temporary-file",
path: tempPath,
cause,
}),
),
);
yield* input.fileSystem.rename(tempPath, input.settingsPath).pipe(
Effect.mapError(
(cause) =>
new DesktopClientSettingsWriteError({
operation: "replace-settings-file",
path: input.settingsPath,
cause,
}),
),
Effect.mapError((cause) => writeError("encode-document", input.settingsPath, cause)),
);
yield* input.fileSystem
.makeDirectory(directory, { recursive: true })
.pipe(Effect.mapError((cause) => writeError("create-directory", directory, cause)));
yield* input.fileSystem
.writeFileString(tempPath, `${encoded}\n`)
.pipe(Effect.mapError((cause) => writeError("write-temporary-file", tempPath, cause)));
yield* input.fileSystem
.rename(tempPath, input.settingsPath)
.pipe(
Effect.mapError((cause) => writeError("replace-settings-file", input.settingsPath, cause)),
);
});
export const make = Effect.gen(function* () {
@@ -159,13 +124,8 @@ export const make = Effect.gen(function* () {
set: (settings) =>
crypto.randomUUIDv4.pipe(
Effect.map((uuid) => uuid.replace(/-/g, "")),
Effect.mapError(
(cause) =>
new DesktopClientSettingsWriteError({
operation: "create-temporary-file-name",
path: environment.clientSettingsPath,
cause,
}),
Effect.mapError((cause) =>
writeError("create-temporary-file-name", environment.clientSettingsPath, cause),
),
Effect.flatMap((suffix) =>
writeClientSettings({
@@ -271,11 +271,10 @@ describe("DesktopSavedEnvironments", () => {
),
);
it.effect("adds saved-environment context to safe storage availability failures", () => {
it.effect("surfaces typed safe storage availability failures", () => {
const cause = new Error("safe storage unavailable");
return withSavedEnvironments(
Effect.gen(function* () {
const environment = yield* DesktopEnvironment.DesktopEnvironment;
const savedEnvironments = yield* DesktopSavedEnvironments.DesktopSavedEnvironments;
yield* savedEnvironments.setRegistry([savedRegistryRecord]);
@@ -286,22 +285,8 @@ describe("DesktopSavedEnvironments", () => {
})
.pipe(Effect.flip);
assert.instanceOf(
error,
DesktopSavedEnvironments.DesktopSavedEnvironmentSecretProtectionError,
);
assert.equal(error.operation, "check-encryption-availability");
assert.equal(error.environmentId, savedRegistryRecord.environmentId);
assert.equal(error.registryPath, environment.savedEnvironmentRegistryPath);
assert.instanceOf(error.cause, ElectronSafeStorage.ElectronSafeStorageAvailabilityError);
const availabilityError =
error.cause as ElectronSafeStorage.ElectronSafeStorageAvailabilityError;
assert.strictEqual(availabilityError.cause, cause);
assert.equal(
error.message,
`Desktop saved-environment secret protection failed during check-encryption-availability for environment ${savedRegistryRecord.environmentId} at ${environment.savedEnvironmentRegistryPath}.`,
);
assert.notEqual(error.message, availabilityError.message);
assert.instanceOf(error, ElectronSafeStorage.ElectronSafeStorageAvailabilityError);
assert.equal(error.cause, cause);
}),
{ availabilityError: cause },
);
@@ -77,12 +77,7 @@ const DesktopSavedEnvironmentsWriteOperation = Schema.Literals([
"write-temporary-file",
"replace-registry-file",
]);
const DesktopSavedEnvironmentSecretProtectionOperation = Schema.Literals([
"check-encryption-availability",
"encrypt-secret",
"decrypt-secret",
]);
type DesktopSavedEnvironmentsWriteOperation = typeof DesktopSavedEnvironmentsWriteOperation.Type;
export class DesktopSavedEnvironmentsWriteError extends Schema.TaggedErrorClass<DesktopSavedEnvironmentsWriteError>()(
"DesktopSavedEnvironmentsWriteError",
@@ -97,6 +92,17 @@ export class DesktopSavedEnvironmentsWriteError extends Schema.TaggedErrorClass<
}
}
const writeError = (
operation: DesktopSavedEnvironmentsWriteOperation,
path: string,
cause: unknown,
): DesktopSavedEnvironmentsWriteError =>
new DesktopSavedEnvironmentsWriteError({
operation,
path,
cause,
});
export class DesktopSavedEnvironmentsReadError extends Schema.TaggedErrorClass<DesktopSavedEnvironmentsReadError>()(
"DesktopSavedEnvironmentsReadError",
{
@@ -135,20 +141,6 @@ export class DesktopSavedEnvironmentSecretDecodeError extends Schema.TaggedError
}
}
export class DesktopSavedEnvironmentSecretProtectionError extends Schema.TaggedErrorClass<DesktopSavedEnvironmentSecretProtectionError>()(
"DesktopSavedEnvironmentSecretProtectionError",
{
operation: DesktopSavedEnvironmentSecretProtectionOperation,
environmentId: Schema.String,
registryPath: Schema.String,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Desktop saved-environment secret protection failed during ${this.operation} for environment ${this.environmentId} at ${this.registryPath}.`;
}
}
export type DesktopSavedEnvironmentsReadRegistryError =
| DesktopSavedEnvironmentsReadError
| DesktopSavedEnvironmentsDocumentDecodeError;
@@ -160,11 +152,11 @@ export type DesktopSavedEnvironmentsMutationError =
export type DesktopSavedEnvironmentsGetSecretError =
| DesktopSavedEnvironmentsReadRegistryError
| DesktopSavedEnvironmentSecretDecodeError
| DesktopSavedEnvironmentSecretProtectionError;
| ElectronSafeStorage.ElectronSafeStorageError;
export type DesktopSavedEnvironmentsSetSecretError =
| DesktopSavedEnvironmentsMutationError
| DesktopSavedEnvironmentSecretProtectionError;
| ElectronSafeStorage.ElectronSafeStorageError;
export class DesktopSavedEnvironments extends Context.Service<
DesktopSavedEnvironments,
@@ -284,45 +276,19 @@ const writeRegistryDocument = Effect.fn("desktop.savedEnvironments.writeRegistry
const directory = input.path.dirname(input.registryPath);
const tempPath = `${input.registryPath}.${process.pid}.${input.suffix}.tmp`;
const encoded = yield* encodeSavedEnvironmentRegistryDocumentJson(input.document).pipe(
Effect.mapError(
(cause) =>
new DesktopSavedEnvironmentsWriteError({
operation: "encode-registry",
path: input.registryPath,
cause,
}),
),
);
yield* input.fileSystem.makeDirectory(directory, { recursive: true }).pipe(
Effect.mapError(
(cause) =>
new DesktopSavedEnvironmentsWriteError({
operation: "create-directory",
path: directory,
cause,
}),
),
);
yield* input.fileSystem.writeFileString(tempPath, `${encoded}\n`).pipe(
Effect.mapError(
(cause) =>
new DesktopSavedEnvironmentsWriteError({
operation: "write-temporary-file",
path: tempPath,
cause,
}),
),
);
yield* input.fileSystem.rename(tempPath, input.registryPath).pipe(
Effect.mapError(
(cause) =>
new DesktopSavedEnvironmentsWriteError({
operation: "replace-registry-file",
path: input.registryPath,
cause,
}),
),
Effect.mapError((cause) => writeError("encode-registry", input.registryPath, cause)),
);
yield* input.fileSystem
.makeDirectory(directory, { recursive: true })
.pipe(Effect.mapError((cause) => writeError("create-directory", directory, cause)));
yield* input.fileSystem
.writeFileString(tempPath, `${encoded}\n`)
.pipe(Effect.mapError((cause) => writeError("write-temporary-file", tempPath, cause)));
yield* input.fileSystem
.rename(tempPath, input.registryPath)
.pipe(
Effect.mapError((cause) => writeError("replace-registry-file", input.registryPath, cause)),
);
},
);
@@ -375,13 +341,8 @@ export const make = Effect.gen(function* () {
const writeDocument = (document: SavedEnvironmentRegistryDocument) =>
crypto.randomUUIDv4.pipe(
Effect.map((uuid) => uuid.replace(/-/g, "")),
Effect.mapError(
(cause) =>
new DesktopSavedEnvironmentsWriteError({
operation: "create-temporary-file-name",
path: environment.savedEnvironmentRegistryPath,
cause,
}),
Effect.mapError((cause) =>
writeError("create-temporary-file-name", environment.savedEnvironmentRegistryPath, cause),
),
Effect.flatMap((suffix) =>
writeRegistryDocument({
@@ -435,21 +396,7 @@ export const make = Effect.gen(function* () {
document.records.find((record) => record.environmentId === environmentId)
?.encryptedBearerToken,
);
if (Option.isNone(encoded)) {
return Option.none<string>();
}
const encryptionAvailable = yield* safeStorage.isEncryptionAvailable.pipe(
Effect.mapError(
(cause) =>
new DesktopSavedEnvironmentSecretProtectionError({
operation: "check-encryption-availability",
environmentId,
registryPath: environment.savedEnvironmentRegistryPath,
cause,
}),
),
);
if (!encryptionAvailable) {
if (Option.isNone(encoded) || !(yield* safeStorage.isEncryptionAvailable)) {
return Option.none<string>();
}
@@ -458,19 +405,7 @@ export const make = Effect.gen(function* () {
environment.savedEnvironmentRegistryPath,
encoded.value,
);
return Option.some(
yield* safeStorage.decryptString(secretBytes).pipe(
Effect.mapError(
(cause) =>
new DesktopSavedEnvironmentSecretProtectionError({
operation: "decrypt-secret",
environmentId,
registryPath: environment.savedEnvironmentRegistryPath,
cause,
}),
),
),
);
return Option.some(yield* safeStorage.decryptString(secretBytes));
}),
setSecret: Effect.fn("desktop.savedEnvironments.setSecret")(function* (input) {
const { environmentId, secret } = input;
@@ -480,34 +415,11 @@ export const make = Effect.gen(function* () {
environment.savedEnvironmentRegistryPath,
);
const encryptionAvailable = yield* safeStorage.isEncryptionAvailable.pipe(
Effect.mapError(
(cause) =>
new DesktopSavedEnvironmentSecretProtectionError({
operation: "check-encryption-availability",
environmentId,
registryPath: environment.savedEnvironmentRegistryPath,
cause,
}),
),
);
if (!encryptionAvailable) {
if (!(yield* safeStorage.isEncryptionAvailable)) {
return false;
}
const encryptedBearerToken = Encoding.encodeBase64(
yield* safeStorage.encryptString(secret).pipe(
Effect.mapError(
(cause) =>
new DesktopSavedEnvironmentSecretProtectionError({
operation: "encrypt-secret",
environmentId,
registryPath: environment.savedEnvironmentRegistryPath,
cause,
}),
),
),
);
const encryptedBearerToken = Encoding.encodeBase64(yield* safeStorage.encryptString(secret));
let found = false;
const nextDocument: SavedEnvironmentRegistryDocument = {
version: document.version,
@@ -1,23 +1,15 @@
import { assert, describe, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Logger from "effect/Logger";
import * as PlatformError from "effect/PlatformError";
import * as Schema from "effect/Schema";
import * as Sink from "effect/Sink";
import * as Stream from "effect/Stream";
import * as ChildProcess from "effect/unstable/process/ChildProcess";
import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner";
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
import * as DesktopShellEnvironment from "./DesktopShellEnvironment.ts";
const textEncoder = new TextEncoder();
const isDesktopShellEnvironmentCommandError = Schema.is(
DesktopShellEnvironment.DesktopShellEnvironmentCommandError,
);
function envOutput(values: Readonly<Record<string, string>>): string {
return Object.entries(values)
.flatMap(([name, value]) => [
@@ -67,7 +59,6 @@ function runShellEnvironment(input: {
readonly env: NodeJS.ProcessEnv;
readonly platform: NodeJS.Platform;
readonly handler: (command: ChildProcess.Command) => string;
readonly failure?: PlatformError.PlatformError;
}) {
const environmentLayer = Layer.succeed(
DesktopEnvironment.DesktopEnvironment,
@@ -77,11 +68,7 @@ function runShellEnvironment(input: {
);
const spawnerLayer = Layer.succeed(
ChildProcessSpawner.ChildProcessSpawner,
ChildProcessSpawner.make((command) =>
input.failure === undefined
? Effect.succeed(makeProcess(input.handler(command)))
: Effect.fail(input.failure),
),
ChildProcessSpawner.make((command) => Effect.succeed(makeProcess(input.handler(command)))),
);
const program = Effect.gen(function* () {
@@ -242,44 +229,4 @@ describe("DesktopShellEnvironment", () => {
);
}),
);
it.effect("logs command failures with safe probe context and the exact cause", () => {
const env: NodeJS.ProcessEnv = {
SHELL: "/bin/bash",
PATH: "/usr/bin",
};
const cause = PlatformError.systemError({
_tag: "PermissionDenied",
module: "ChildProcess",
method: "spawn",
pathOrDescriptor: "/bin/bash",
});
const messages: Array<unknown> = [];
const logger = Logger.make(({ message }) => {
messages.push(message);
});
return runShellEnvironment({
env,
platform: "linux",
handler: () => "",
failure: cause,
}).pipe(
Effect.andThen(
Effect.sync(() => {
const errors = messages
.flatMap((message) => (Array.isArray(message) ? message : [message]))
.filter(isDesktopShellEnvironmentCommandError);
assert.lengthOf(errors, 1);
assert.equal(errors[0]?.probe, "login-shell");
assert.equal(errors[0]?.executable, "bash");
assert.equal(errors[0]?.argumentCount, 2);
assert.notProperty(errors[0] ?? {}, "args");
assert.equal(errors[0]?.cause, cause);
assert.notInclude(errors[0]?.message ?? "", cause.message);
}),
),
Effect.provide(Logger.layer([logger], { mergeWithExisting: false })),
);
});
});
@@ -3,7 +3,6 @@ import * as Duration from "effect/Duration";
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 ChildProcess from "effect/unstable/process/ChildProcess";
import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner";
@@ -21,44 +20,6 @@ interface WindowsProbeOptions {
readonly loadProfile: boolean;
}
const DesktopShellEnvironmentProbe = Schema.Literals([
"login-shell",
"launchctl-path",
"powershell-profile",
"powershell-no-profile",
]);
type DesktopShellEnvironmentProbe = typeof DesktopShellEnvironmentProbe.Type;
const desktopShellEnvironmentCommandFields = {
probe: DesktopShellEnvironmentProbe,
executable: Schema.String,
argumentCount: Schema.Number,
};
export class DesktopShellEnvironmentCommandError extends Schema.TaggedErrorClass<DesktopShellEnvironmentCommandError>()(
"DesktopShellEnvironmentCommandError",
{
...desktopShellEnvironmentCommandFields,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Desktop shell environment ${this.probe} probe (${this.executable}) failed.`;
}
}
export class DesktopShellEnvironmentCommandTimeoutError extends Schema.TaggedErrorClass<DesktopShellEnvironmentCommandTimeoutError>()(
"DesktopShellEnvironmentCommandTimeoutError",
{
...desktopShellEnvironmentCommandFields,
timeoutMs: Schema.Number,
},
) {
override get message(): string {
return `Desktop shell environment ${this.probe} probe (${this.executable}) timed out after ${this.timeoutMs}ms.`;
}
}
export class DesktopShellEnvironment extends Context.Service<
DesktopShellEnvironment,
{
@@ -166,18 +127,6 @@ const knownWindowsCliDirs = (env: NodeJS.ProcessEnv): ReadonlyArray<string> => [
const startMarker = (name: string) => `__T3CODE_ENV_${name}_START__`;
const endMarker = (name: string) => `__T3CODE_ENV_${name}_END__`;
const executableName = (command: string): string => command.split(/[\\/]/u).at(-1) ?? command;
const logShellEnvironmentCommandError = (
error: DesktopShellEnvironmentCommandError | DesktopShellEnvironmentCommandTimeoutError,
) =>
Effect.logWarning(error).pipe(
Effect.annotateLogs({
component: "desktop-shell-environment",
error,
}),
);
const capturePosixEnvironmentCommand = (names: ReadonlyArray<string>) =>
names
.map((name) => {
@@ -226,14 +175,13 @@ const extractEnvironment = (output: string, names: ReadonlyArray<string>): Envir
};
const runCommandOutput = Effect.fn("desktop.shellEnvironment.runCommandOutput")(function* (input: {
readonly probe: DesktopShellEnvironmentProbe;
readonly command: string;
readonly args: ReadonlyArray<string>;
readonly timeout: Duration.Duration;
readonly shell?: boolean;
}): Effect.fn.Return<string, never, ChildProcessSpawner.ChildProcessSpawner> {
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const output = yield* spawner
return yield* spawner
.string(
ChildProcess.make(input.command, input.args, {
shell: input.shell ?? false,
@@ -245,33 +193,10 @@ const runCommandOutput = Effect.fn("desktop.shellEnvironment.runCommandOutput")(
}),
)
.pipe(
Effect.mapError(
(cause) =>
new DesktopShellEnvironmentCommandError({
probe: input.probe,
executable: executableName(input.command),
argumentCount: input.args.length,
cause,
}),
),
Effect.catchTags({
DesktopShellEnvironmentCommandError: (error) =>
logShellEnvironmentCommandError(error).pipe(Effect.as("")),
}),
Effect.timeoutOption(input.timeout),
Effect.map(Option.getOrElse(() => "")),
Effect.orElseSucceed(() => ""),
);
if (Option.isSome(output)) {
return output.value;
}
const error = new DesktopShellEnvironmentCommandTimeoutError({
probe: input.probe,
executable: executableName(input.command),
argumentCount: input.args.length,
timeoutMs: Duration.toMillis(input.timeout),
});
yield* logShellEnvironmentCommandError(error);
return "";
});
const readLoginShellEnvironment = (
@@ -281,14 +206,12 @@ const readLoginShellEnvironment = (
names.length === 0
? Effect.succeed({})
: runCommandOutput({
probe: "login-shell",
command: shell,
args: ["-ilc", capturePosixEnvironmentCommand(names)],
timeout: LOGIN_SHELL_TIMEOUT,
}).pipe(Effect.map((output) => extractEnvironment(output, names)));
const readLaunchctlPath = runCommandOutput({
probe: "launchctl-path",
command: "/bin/launchctl",
args: ["getenv", "PATH"],
timeout: LAUNCHCTL_TIMEOUT,
@@ -311,7 +234,6 @@ const readWindowsEnvironment = Effect.fn("desktop.shellEnvironment.readWindowsEn
for (const command of WINDOWS_SHELL_CANDIDATES) {
const output = yield* runCommandOutput({
probe: options.loadProfile ? "powershell-profile" : "powershell-no-profile",
command,
args,
timeout: LOGIN_SHELL_TIMEOUT,
@@ -23,7 +23,6 @@ describe("sshEnvironment", () => {
const cause = new DesktopSshPasswordPrompts.DesktopSshPromptPresentationError({
requestId: "prompt-1",
destination: "devbox",
operation: "send-prompt-request",
cause: new Error("renderer send failed"),
});
@@ -17,13 +17,7 @@ interface SentMessage {
readonly args: readonly unknown[];
}
function makeTestWindow(
options: {
readonly isDestroyedError?: unknown;
readonly isMinimizedError?: unknown;
readonly sendError?: unknown;
} = {},
) {
function makeTestWindow() {
const listeners = new Map<string, Set<() => void>>();
const sentMessages: SentMessage[] = [];
let destroyed = false;
@@ -32,18 +26,8 @@ function makeTestWindow(
let focused = false;
const window = {
isDestroyed: () => {
if (options.isDestroyedError !== undefined) {
throw options.isDestroyedError;
}
return destroyed;
},
isMinimized: () => {
if (options.isMinimizedError !== undefined) {
throw options.isMinimizedError;
}
return minimized;
},
isDestroyed: () => destroyed,
isMinimized: () => minimized,
restore: () => {
restored = true;
minimized = false;
@@ -61,11 +45,7 @@ function makeTestWindow(
},
webContents: {
send: (channel: string, ...args: readonly unknown[]) => {
const message = { channel, args };
sentMessages.push(message);
if (options.sendError !== undefined) {
throw options.sendError;
}
sentMessages.push({ channel, args });
},
},
};
@@ -75,7 +55,6 @@ function makeTestWindow(
sentMessages,
isRestored: () => restored,
isFocused: () => focused,
closedListenerCount: () => listeners.get("closed")?.size ?? 0,
close: () => {
destroyed = true;
const closedListeners = [...(listeners.get("closed") ?? [])];
@@ -128,7 +107,6 @@ describe("DesktopSshPasswordPrompts", () => {
})
.pipe(Effect.forkScoped);
yield* Effect.yieldNow;
yield* Effect.yieldNow;
assert.equal(testWindow.sentMessages.length, 1);
const sent = testWindow.sentMessages[0];
@@ -165,85 +143,4 @@ describe("DesktopSshPasswordPrompts", () => {
assert.equal(error.destination, "devbox");
}).pipe(Effect.provide(makeLayer(testWindow.window)), Effect.scoped);
});
it.effect("cleans up a prompt that fails during renderer delivery", () => {
const cause = new Error("renderer unavailable");
const testWindow = makeTestWindow({ sendError: cause });
return Effect.gen(function* () {
const prompts = yield* DesktopSshPasswordPrompts.DesktopSshPasswordPrompts;
const error = yield* prompts
.request({
destination: "devbox",
username: "julius",
prompt: "Enter the SSH password.",
attempt: 1,
})
.pipe(Effect.flip);
assert.instanceOf(error, DesktopSshPasswordPrompts.DesktopSshPromptPresentationError);
assert.equal(error.operation, "send-prompt-request");
assert.equal(error.destination, "devbox");
const requestId = error.requestId;
if (requestId === null) {
assert.fail("renderer delivery failures must retain their request id");
}
assert.equal(testWindow.closedListenerCount(), 0);
const resolveError = yield* prompts
.resolve({ requestId, password: "secret" })
.pipe(Effect.flip);
assert.instanceOf(resolveError, DesktopSshPasswordPrompts.DesktopSshPromptExpiredError);
}).pipe(Effect.provide(makeLayer(testWindow.window)), Effect.scoped);
});
it.effect("keeps a submitted password when a later presentation step fails", () => {
const testWindow = makeTestWindow({
isMinimizedError: new Error("failed to read minimized state"),
});
return Effect.gen(function* () {
const prompts = yield* DesktopSshPasswordPrompts.DesktopSshPasswordPrompts;
const requestFiber = yield* prompts
.request({
destination: "devbox",
username: "julius",
prompt: "Enter the SSH password.",
attempt: 1,
})
.pipe(Effect.forkScoped);
yield* Effect.yieldNow;
const sent = testWindow.sentMessages[0];
assert.ok(sent);
const request = sent.args[0] as { readonly requestId: string };
yield* prompts.resolve({ requestId: request.requestId, password: "secret" });
const password = yield* Fiber.join(requestFiber);
assert.equal(password, "secret");
assert.equal(testWindow.isFocused(), false);
assert.equal(testWindow.closedListenerCount(), 0);
}).pipe(Effect.provide(makeLayer(testWindow.window)), Effect.scoped);
});
it.effect("classifies a failed initial window availability check", () => {
const testWindow = makeTestWindow({ isDestroyedError: new Error("window unavailable") });
return Effect.gen(function* () {
const prompts = yield* DesktopSshPasswordPrompts.DesktopSshPasswordPrompts;
const error = yield* prompts
.request({
destination: "devbox",
username: "julius",
prompt: "Enter the SSH password.",
attempt: 1,
})
.pipe(Effect.flip);
assert.instanceOf(error, DesktopSshPasswordPrompts.DesktopSshPromptPresentationError);
assert.equal(error.operation, "check-window-before-request");
assert.equal(error.requestId, null);
assert.deepEqual(testWindow.sentMessages, []);
}).pipe(Effect.provide(makeLayer(testWindow.window)), Effect.scoped);
});
});
+35 -123
View File
@@ -20,26 +20,7 @@ const DEFAULT_SSH_PASSWORD_PROMPT_TIMEOUT_MS = 3 * 60 * 1000;
type DesktopSshPasswordPromptResolutionInput =
typeof DesktopSshPasswordPromptResolutionInputSchema.Type;
const DesktopSshPromptWindowAvailabilityStage = Schema.Literals([
"before-request",
"before-presentation",
"after-send",
"after-restore",
]);
const DesktopSshPromptPresentationOperation = Schema.Literals([
"check-window-before-request",
"check-window-before-presentation",
"register-window-close-listener",
"send-prompt-request",
"check-window-after-send",
"check-window-minimized",
"restore-window",
"check-window-after-restore",
"focus-window",
"remove-window-close-listener",
]);
type DesktopSshPromptPresentationOperation = typeof DesktopSshPromptPresentationOperation.Type;
const WINDOW_UNAVAILABLE_MESSAGE = "T3 Code window is not available for SSH authentication.";
export class DesktopSshPromptRequestIdGenerationError extends Schema.TaggedErrorClass<DesktopSshPromptRequestIdGenerationError>()(
"DesktopSshPromptRequestIdGenerationError",
@@ -57,22 +38,20 @@ export class DesktopSshPromptWindowUnavailableError extends Schema.TaggedErrorCl
"DesktopSshPromptWindowUnavailableError",
{
destination: Schema.String,
requestId: Schema.NullOr(Schema.String),
stage: DesktopSshPromptWindowAvailabilityStage,
},
) {
override get message(): string {
const request = this.requestId === null ? "before a request id was assigned" : this.requestId;
return `T3 Code window is unavailable during ${this.stage} for SSH authentication to ${this.destination} (request: ${request}).`;
return WINDOW_UNAVAILABLE_MESSAGE;
}
}
const isDesktopSshPromptWindowUnavailableError = Schema.is(DesktopSshPromptWindowUnavailableError);
export class DesktopSshPromptPresentationError extends Schema.TaggedErrorClass<DesktopSshPromptPresentationError>()(
"DesktopSshPromptPresentationError",
{
requestId: Schema.NullOr(Schema.String),
requestId: Schema.String,
destination: Schema.String,
operation: DesktopSshPromptPresentationOperation,
cause: Schema.Defect(),
},
) {
@@ -284,29 +263,9 @@ export const make = Effect.fn("desktop.sshPasswordPrompts.make")(function* (
"desktop.sshPasswordPrompts.request",
)(function* (input) {
const window = yield* electronWindow.main;
if (Option.isNone(window)) {
if (Option.isNone(window) || window.value.isDestroyed()) {
return yield* new DesktopSshPromptWindowUnavailableError({
destination: input.destination,
requestId: null,
stage: "before-request",
});
}
const unavailableBeforeRequest = yield* Effect.try({
try: () => window.value.isDestroyed(),
catch: (cause) =>
new DesktopSshPromptPresentationError({
requestId: null,
destination: input.destination,
operation: "check-window-before-request",
cause,
}),
});
if (unavailableBeforeRequest) {
return yield* new DesktopSshPromptWindowUnavailableError({
destination: input.destination,
requestId: null,
stage: "before-request",
});
}
@@ -360,25 +319,11 @@ export const make = Effect.fn("desktop.sshPasswordPrompts.make")(function* (
),
);
};
const runPresentationOperation = <A>(
operation: DesktopSshPromptPresentationOperation,
evaluate: () => A,
) =>
Effect.try({
try: evaluate,
catch: (cause) =>
new DesktopSshPromptPresentationError({
requestId,
destination: input.destination,
operation,
cause,
}),
});
const cleanup = runPresentationOperation("remove-window-close-listener", () => {
const cleanup = Effect.sync(() => {
if (!window.value.isDestroyed()) {
window.value.removeListener("closed", cancelOnWindowClosed);
}
}).pipe(Effect.orDie, Effect.ensuring(removePending(pendingRef, requestId)), Effect.asVoid);
}).pipe(Effect.andThen(removePending(pendingRef, requestId)), Effect.asVoid);
const waitForPassword = Deferred.await(deferred).pipe(
Effect.timeoutOption(Duration.millis(passwordPromptTimeoutMs)),
Effect.flatMap(
@@ -394,73 +339,40 @@ export const make = Effect.fn("desktop.sshPasswordPrompts.make")(function* (
}),
),
);
const preferSubmittedPassword = (error: DesktopSshPasswordPromptRequestError) =>
Deferred.poll(deferred).pipe(
Effect.flatMap(
Option.match({
onSome: (completion) => completion,
onNone: () =>
Ref.get(pendingRef).pipe(
Effect.flatMap((entries) =>
entries.has(requestId) ? Effect.fail(error) : Deferred.await(deferred),
),
),
}),
),
);
return yield* Effect.gen(function* () {
const unavailableBeforePresentation = yield* runPresentationOperation(
"check-window-before-presentation",
() => window.value.isDestroyed(),
);
if (unavailableBeforePresentation) {
return yield* new DesktopSshPromptWindowUnavailableError({
destination: input.destination,
requestId,
stage: "before-presentation",
});
}
yield* runPresentationOperation("register-window-close-listener", () =>
window.value.once("closed", cancelOnWindowClosed),
);
return yield* Effect.gen(function* () {
yield* runPresentationOperation("send-prompt-request", () =>
window.value.webContents.send(SSH_PASSWORD_PROMPT_CHANNEL, promptRequest),
);
yield* Effect.yieldNow;
const unavailableAfterSend = yield* runPresentationOperation(
"check-window-after-send",
() => window.value.isDestroyed(),
);
if (unavailableAfterSend) {
return yield* new DesktopSshPromptWindowUnavailableError({
return yield* Effect.try({
try: () => {
if (window.value.isDestroyed()) {
throw new DesktopSshPromptWindowUnavailableError({
destination: input.destination,
requestId,
stage: "after-send",
});
}
const minimized = yield* runPresentationOperation("check-window-minimized", () =>
window.value.isMinimized(),
);
if (minimized) {
yield* runPresentationOperation("restore-window", () => window.value.restore());
}
const unavailableAfterRestore = yield* runPresentationOperation(
"check-window-after-restore",
() => window.value.isDestroyed(),
);
if (unavailableAfterRestore) {
return yield* new DesktopSshPromptWindowUnavailableError({
window.value.once("closed", cancelOnWindowClosed);
window.value.webContents.send(SSH_PASSWORD_PROMPT_CHANNEL, promptRequest);
if (window.value.isDestroyed()) {
throw new DesktopSshPromptWindowUnavailableError({
destination: input.destination,
requestId,
stage: "after-restore",
});
}
yield* runPresentationOperation("focus-window", () => window.value.focus());
return yield* waitForPassword;
}).pipe(Effect.catch(preferSubmittedPassword));
}).pipe(Effect.ensuring(cleanup));
if (window.value.isMinimized()) {
window.value.restore();
}
if (window.value.isDestroyed()) {
throw new DesktopSshPromptWindowUnavailableError({
destination: input.destination,
});
}
window.value.focus();
},
catch: (cause) =>
isDesktopSshPromptWindowUnavailableError(cause)
? cause
: new DesktopSshPromptPresentationError({
requestId,
destination: input.destination,
cause,
}),
}).pipe(Effect.andThen(waitForPassword), Effect.ensuring(cleanup));
});
return DesktopSshPasswordPrompts.of({
+6 -271
View File
@@ -7,13 +7,10 @@ import * as Duration from "effect/Duration";
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 Option from "effect/Option";
import * as References from "effect/References";
import * as Ref from "effect/Ref";
import * as TestClock from "effect/testing/TestClock";
import * as DesktopBackendPool from "../backend/DesktopBackendPool.ts";
import * as DesktopBackendManager from "../backend/DesktopBackendManager.ts";
import * as DesktopConfig from "../app/DesktopConfig.ts";
import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
import * as ElectronUpdater from "../electron/ElectronUpdater.ts";
@@ -27,9 +24,6 @@ interface UpdatesHarnessOptions {
void,
ElectronUpdater.ElectronUpdaterCheckForUpdatesError
>;
readonly setUpdateChannelError?: DesktopAppSettings.DesktopSettingsWriteError;
readonly setDisableDifferentialDownload?: Effect.Effect<void>;
readonly stopBackend?: Effect.Effect<void>;
readonly env?: Record<string, string | undefined>;
}
@@ -73,7 +67,7 @@ function makeHarness(options: UpdatesHarnessOptions = {}) {
Effect.sync(() => {
allowDowngrade = value;
}),
setDisableDifferentialDownload: () => options.setDisableDifferentialDownload ?? Effect.void,
setDisableDifferentialDownload: () => Effect.void,
checkForUpdates: Effect.sync(() => {
checkCount += 1;
}).pipe(Effect.andThen(options.checkForUpdates ?? Effect.void)),
@@ -107,11 +101,9 @@ function makeHarness(options: UpdatesHarnessOptions = {}) {
syncAllAppearance: () => Effect.void,
} satisfies ElectronWindow.ElectronWindow["Service"]);
const stubBackendInstance: DesktopBackendPool.DesktopBackendInstance = {
id: DesktopBackendPool.PRIMARY_INSTANCE_ID,
label: Effect.succeed("Windows"),
const backendLayer = Layer.succeed(DesktopBackendManager.DesktopBackendManager, {
start: Effect.void,
stop: () => options.stopBackend ?? Effect.void,
stop: () => Effect.void,
currentConfig: Effect.succeed(Option.none()),
snapshot: Effect.succeed({
desiredRunning: false,
@@ -120,9 +112,7 @@ function makeHarness(options: UpdatesHarnessOptions = {}) {
restartAttempt: 0,
restartScheduled: false,
}),
waitForReady: () => Effect.succeed(true),
};
const backendLayer = DesktopBackendPool.layerTest([stubBackendInstance]);
});
const environmentLayer = DesktopEnvironment.layer({
dirname: "/repo/apps/desktop/src",
@@ -148,28 +138,12 @@ function makeHarness(options: UpdatesHarnessOptions = {}) {
),
);
const setUpdateChannelError = options.setUpdateChannelError;
const settingsLayer = setUpdateChannelError
? Layer.succeed(DesktopAppSettings.DesktopAppSettings, {
get: Effect.succeed(DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS),
load: Effect.succeed(DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS),
setServerExposureMode: () => Effect.die("unexpected server exposure update"),
setTailscaleServe: () => Effect.die("unexpected Tailscale Serve update"),
setUpdateChannel: () => Effect.fail(setUpdateChannelError),
setWslBackendEnabled: () => Effect.die("unexpected WSL backend toggle"),
setWslDistro: () => Effect.die("unexpected WSL distro change"),
setWslOnly: () => Effect.die("unexpected WSL-only toggle"),
applyWslWindowsFallback: Effect.die("unexpected WSL Windows fallback"),
applyWslWindowsFallbackInMemory: Effect.die("unexpected WSL Windows fallback"),
} satisfies DesktopAppSettings.DesktopAppSettings["Service"])
: DesktopAppSettings.layer;
const layer = DesktopUpdates.layer.pipe(
Layer.provideMerge(updaterLayer),
Layer.provideMerge(windowLayer),
Layer.provideMerge(backendLayer),
Layer.provideMerge(DesktopState.layer),
Layer.provideMerge(settingsLayer),
Layer.provideMerge(DesktopAppSettings.layer),
Layer.provideMerge(
DesktopConfig.layerTest({
T3CODE_HOME: `/tmp/t3-desktop-updates-test-${process.pid}`,
@@ -201,45 +175,6 @@ function makeHarness(options: UpdatesHarnessOptions = {}) {
}
describe("DesktopUpdates", () => {
it("preserves complete causes for update poller and event failures", () => {
const cause = Cause.combine(
Cause.fail(new Error("updater failed")),
Cause.die(new Error("updater defect")),
);
const pollerError = new DesktopUpdates.DesktopUpdatePollerError({
poller: "startup",
cause,
});
const eventError = new DesktopUpdates.DesktopUpdateEventHandlingError({
event: "download-progress",
cause,
});
const reportedError = new DesktopUpdates.DesktopUpdaterReportedError({
operation: "download",
cause,
});
const unexpectedActionError = new DesktopUpdates.DesktopUpdateUnexpectedActionError({
action: "install",
cause,
});
assert.strictEqual(pollerError.cause, cause);
assert.equal(pollerError.poller, "startup");
assert.equal(pollerError.message, "Desktop update startup poller failed.");
assert.strictEqual(eventError.cause, cause);
assert.equal(eventError.event, "download-progress");
assert.equal(eventError.message, "Failed to handle desktop update download-progress event.");
assert.strictEqual(reportedError.cause, cause);
assert.equal(reportedError.operation, "download");
assert.equal(reportedError.message, "Desktop updater download operation reported an error.");
assert.strictEqual(unexpectedActionError.cause, cause);
assert.equal(unexpectedActionError.action, "install");
assert.equal(
unexpectedActionError.message,
"Desktop update install action failed unexpectedly.",
);
});
it.effect("configures the updater and runs startup checks on the test clock", () => {
const harness = makeHarness();
@@ -287,178 +222,6 @@ describe("DesktopUpdates", () => {
).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
});
it.effect("keeps raw updater event failures out of update state", () => {
const harness = makeHarness();
const cause = new Error(
"request failed for https://user:[email protected]/update?token=secret",
);
return Effect.scoped(
Effect.gen(function* () {
const updates = yield* DesktopUpdates.DesktopUpdates;
yield* updates.configure;
harness.emit("error", cause);
yield* flushCallbacks;
const state = yield* updates.getState;
assert.equal(state.status, "error");
assert.equal(state.message, "Desktop updater background operation reported an error.");
assert.notInclude(state.message ?? "", "secret");
}),
).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
});
it.effect("logs bounded updater failure context without exposing the cause", () => {
const cause = new Error(
"request failed for https://user:[email protected]/update?token=secret",
);
const updaterError = new ElectronUpdater.ElectronUpdaterCheckForUpdatesError({
channel: null,
cause,
});
const harness = makeHarness({ checkForUpdates: Effect.fail(updaterError) });
const loggedAnnotations: Array<Record<string, unknown>> = [];
const logger = Logger.make(({ fiber }) => {
const annotations = fiber.getRef(References.CurrentLogAnnotations);
if (annotations.errorTag === "ElectronUpdaterCheckForUpdatesError") {
loggedAnnotations.push(annotations);
}
});
return Effect.scoped(
Effect.gen(function* () {
const updates = yield* DesktopUpdates.DesktopUpdates;
yield* updates.configure;
yield* updates.check("manual");
const state = yield* updates.getState;
const loggedAnnotation = loggedAnnotations.at(-1);
assert.isDefined(loggedAnnotation);
assert.equal(loggedAnnotation.errorTag, "ElectronUpdaterCheckForUpdatesError");
assert.isNull(loggedAnnotation.channel);
assert.notProperty(loggedAnnotation, "error");
assert.notInclude(Object.values(loggedAnnotation).map(String).join(" "), "secret");
assert.equal(
state.message,
"Electron updater failed to check for updates on channel default.",
);
assert.notInclude(state.message ?? "", "secret");
}),
).pipe(
Effect.provide(
Layer.mergeAll(
TestClock.layer(),
harness.layer,
Logger.layer([logger], { mergeWithExisting: false }),
),
),
);
});
it.effect("recovers download state after an unexpected setup failure", () => {
let disableDifferentialCalls = 0;
const harness = makeHarness({
setDisableDifferentialDownload: Effect.suspend(() => {
disableDifferentialCalls += 1;
return disableDifferentialCalls === 1
? Effect.void
: Effect.die(new Error("download setup failed"));
}),
});
return Effect.scoped(
Effect.gen(function* () {
const updates = yield* DesktopUpdates.DesktopUpdates;
yield* updates.configure;
harness.emit("update-available", { version: "1.2.4" });
yield* flushCallbacks;
const result = yield* updates.download;
assert.isTrue(result.accepted);
assert.isFalse(result.completed);
const failedState = yield* updates.getState;
assert.equal(failedState.status, "available");
assert.equal(failedState.errorContext, "download");
assert.equal(failedState.message, "Desktop update download action failed unexpectedly.");
const changedState = yield* updates.setChannel("nightly");
assert.equal(changedState.channel, "nightly");
}),
).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
});
it.effect("restores download state and permits retry after interruption", () =>
Effect.gen(function* () {
const actionStarted = yield* Deferred.make<void>();
let disableDifferentialCalls = 0;
const harness = makeHarness({
setDisableDifferentialDownload: Effect.suspend(() => {
disableDifferentialCalls += 1;
if (disableDifferentialCalls === 1) {
return Effect.void;
}
if (disableDifferentialCalls === 2) {
return Deferred.succeed(actionStarted, undefined).pipe(Effect.andThen(Effect.never));
}
return Effect.void;
}),
});
yield* Effect.scoped(
Effect.gen(function* () {
const updates = yield* DesktopUpdates.DesktopUpdates;
yield* updates.configure;
harness.emit("update-available", { version: "1.2.4" });
yield* flushCallbacks;
const downloadFiber = yield* updates.download.pipe(Effect.forkScoped);
yield* Deferred.await(actionStarted);
yield* Fiber.interrupt(downloadFiber);
const interruptedState = yield* updates.getState;
assert.equal(interruptedState.status, "available");
assert.isNull(interruptedState.message);
const retry = yield* updates.download;
assert.isTrue(retry.accepted);
assert.isTrue(retry.completed);
}),
).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
}),
);
it.effect("clears quitting state after an unexpected install setup failure", () => {
const harness = makeHarness({
stopBackend: Effect.die(new Error("backend stop failed")),
});
return Effect.scoped(
Effect.gen(function* () {
const desktopState = yield* DesktopState.DesktopState;
const updates = yield* DesktopUpdates.DesktopUpdates;
yield* updates.configure;
harness.emit("update-downloaded", { version: "1.2.4" });
yield* flushCallbacks;
const result = yield* updates.install;
assert.isTrue(result.accepted);
assert.isFalse(result.completed);
assert.isFalse(yield* Ref.get(desktopState.quitting));
const failedState = yield* updates.getState;
assert.equal(failedState.status, "downloaded");
assert.equal(failedState.errorContext, "install");
assert.equal(failedState.message, "Desktop update install action failed unexpectedly.");
const changedState = yield* updates.setChannel("nightly");
assert.equal(changedState.channel, "nightly");
}),
).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
});
it.effect("persists channel changes through the settings service", () => {
const harness = makeHarness();
@@ -521,7 +284,6 @@ describe("DesktopUpdates", () => {
const error = Cause.squash(exit.cause);
assert.instanceOf(error, DesktopUpdates.DesktopUpdateActionInProgressError);
assert.equal(error.action, "check");
assert.equal(error.requestedChannel, "nightly");
}
yield* Deferred.succeed(releaseCheck, undefined);
@@ -530,31 +292,4 @@ describe("DesktopUpdates", () => {
).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
}),
);
it.effect("preserves settings failure context when an update channel cannot be persisted", () => {
const diskFailure = new Error("disk exploded");
const settingsFailure = new DesktopAppSettings.DesktopSettingsWriteError({
operation: "replace-settings-file",
path: "/tmp/settings.json",
cause: diskFailure,
});
const harness = makeHarness({ setUpdateChannelError: settingsFailure });
return Effect.scoped(
Effect.gen(function* () {
const updates = yield* DesktopUpdates.DesktopUpdates;
yield* updates.configure;
const error = yield* updates.setChannel("nightly").pipe(Effect.flip);
assert.instanceOf(error, DesktopUpdates.DesktopUpdateChannelPersistenceError);
assert.isTrue(DesktopUpdates.isDesktopUpdateSetChannelError(error));
assert.equal(error.channel, "nightly");
assert.strictEqual(error.cause, settingsFailure);
assert.strictEqual(error.cause.cause, diskFailure);
assert.equal(error.message, "Failed to persist the nightly desktop update channel.");
assert.notInclude(error.message, diskFailure.message);
}),
).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
});
});
+60 -233
View File
@@ -1,10 +1,9 @@
import {
DesktopUpdateChannelSchema,
type DesktopRuntimeInfo,
type DesktopUpdateActionResult,
type DesktopUpdateChannel,
type DesktopUpdateCheckResult,
type DesktopUpdateState,
import type {
DesktopRuntimeInfo,
DesktopUpdateActionResult,
DesktopUpdateChannel,
DesktopUpdateCheckResult,
DesktopUpdateState,
} from "@t3tools/contracts";
import * as Cause from "effect/Cause";
import * as Context from "effect/Context";
@@ -18,7 +17,7 @@ import * as Ref from "effect/Ref";
import * as Schema from "effect/Schema";
import * as Scope from "effect/Scope";
import * as DesktopBackendPool from "../backend/DesktopBackendPool.ts";
import * as DesktopBackendManager from "../backend/DesktopBackendManager.ts";
import * as DesktopConfig from "../app/DesktopConfig.ts";
import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
import * as DesktopObservability from "../app/DesktopObservability.ts";
@@ -64,82 +63,30 @@ export class DesktopUpdateActionInProgressError extends Schema.TaggedErrorClass<
"DesktopUpdateActionInProgressError",
{
action: Schema.Literals(["check", "download", "install"]),
requestedChannel: DesktopUpdateChannelSchema,
},
) {
override get message(): string {
return `Cannot change the desktop update channel to ${this.requestedChannel} while an update ${this.action} action is in progress.`;
return `Cannot change update tracks while an update ${this.action} action is in progress.`;
}
}
export class DesktopUpdateChannelPersistenceError extends Schema.TaggedErrorClass<DesktopUpdateChannelPersistenceError>()(
"DesktopUpdateChannelPersistenceError",
export class DesktopUpdatePersistenceError extends Schema.TaggedErrorClass<DesktopUpdatePersistenceError>()(
"DesktopUpdatePersistenceError",
{
channel: DesktopUpdateChannelSchema,
cause: Schema.instanceOf(DesktopAppSettings.DesktopSettingsWriteError),
},
) {
override get message(): string {
return `Failed to persist the ${this.channel} desktop update channel.`;
}
}
export class DesktopUpdatePollerError extends Schema.TaggedErrorClass<DesktopUpdatePollerError>()(
"DesktopUpdatePollerError",
{
poller: Schema.Literals(["startup", "poll"]),
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Desktop update ${this.poller} poller failed.`;
}
}
export class DesktopUpdateEventHandlingError extends Schema.TaggedErrorClass<DesktopUpdateEventHandlingError>()(
"DesktopUpdateEventHandlingError",
{
event: Schema.Literals(["update-available", "download-progress", "update-downloaded"]),
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to handle desktop update ${this.event} event.`;
}
}
export class DesktopUpdaterReportedError extends Schema.TaggedErrorClass<DesktopUpdaterReportedError>()(
"DesktopUpdaterReportedError",
{
operation: Schema.Literals(["check", "download", "install", "background"]),
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Desktop updater ${this.operation} operation reported an error.`;
}
}
export class DesktopUpdateUnexpectedActionError extends Schema.TaggedErrorClass<DesktopUpdateUnexpectedActionError>()(
"DesktopUpdateUnexpectedActionError",
{
action: Schema.Literals(["download", "install"]),
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Desktop update ${this.action} action failed unexpectedly.`;
const detail = this.cause instanceof Error ? this.cause.message : String(this.cause);
return `Failed to persist desktop update settings: ${detail}`;
}
}
export type DesktopUpdateConfigureError = never;
export const DesktopUpdateSetChannelError = Schema.Union([
DesktopUpdateActionInProgressError,
DesktopUpdateChannelPersistenceError,
]);
export type DesktopUpdateSetChannelError = typeof DesktopUpdateSetChannelError.Type;
export const isDesktopUpdateSetChannelError = Schema.is(DesktopUpdateSetChannelError);
export type DesktopUpdateSetChannelError =
| DesktopUpdateActionInProgressError
| DesktopUpdatePersistenceError;
export class DesktopUpdates extends Context.Service<
DesktopUpdates,
@@ -241,7 +188,7 @@ function isArm64HostRunningIntelBuild(runtimeInfo: DesktopRuntimeInfo): boolean
export const make = Effect.gen(function* () {
const config = yield* DesktopConfig.DesktopConfig;
const pool = yield* DesktopBackendPool.DesktopBackendPool;
const backendManager = yield* DesktopBackendManager.DesktopBackendManager;
const desktopState = yield* DesktopState.DesktopState;
const electronUpdater = yield* ElectronUpdater.ElectronUpdater;
const electronWindow = yield* ElectronWindow.ElectronWindow;
@@ -361,21 +308,16 @@ export const make = Effect.gen(function* () {
return yield* electronUpdater.checkForUpdates.pipe(
Effect.as(true),
Effect.catchTags({
ElectronUpdaterCheckForUpdatesError: Effect.fn(
"desktop.updates.handleCheckForUpdatesFailure",
)(function* (error) {
Effect.catch(
Effect.fn("desktop.updates.handleCheckForUpdatesFailure")(function* (error) {
const failedAt = yield* currentIsoTimestamp;
yield* updateState((current) =>
reduceDesktopUpdateStateOnCheckFailure(current, error.message, failedAt),
);
yield* logUpdaterError(error.message, {
errorTag: error._tag,
channel: error.channel,
});
yield* logUpdaterError("failed to check for updates", { message: error.message });
return true;
}),
}),
),
Effect.ensuring(Ref.set(updateCheckInFlightRef, false)),
);
});
@@ -400,50 +342,19 @@ export const make = Effect.gen(function* () {
yield* electronUpdater.downloadUpdate;
return { accepted: true, completed: true };
}).pipe(
Effect.catchTags({
ElectronUpdaterDownloadUpdateError: Effect.fn("desktop.updates.handleDownloadFailure")(
function* (error) {
yield* updateState((current) =>
reduceDesktopUpdateStateOnDownloadFailure(current, error.message),
);
yield* logUpdaterError(error.message, {
errorTag: error._tag,
channel: error.channel,
});
return { accepted: true, completed: false };
},
),
}),
Effect.onInterrupt(() =>
updateState((current) => (current.status === "downloading" ? state : current)).pipe(
Effect.asVoid,
),
),
Effect.catchCause((cause) => {
if (Cause.hasInterruptsOnly(cause)) {
return Effect.failCause(cause);
}
const error = new DesktopUpdateUnexpectedActionError({ action: "download", cause });
return Effect.gen(function* () {
Effect.catch(
Effect.fn("desktop.updates.handleDownloadFailure")(function* (error) {
yield* updateState((current) =>
reduceDesktopUpdateStateOnDownloadFailure(current, error.message),
);
yield* logUpdaterError(error.message, {
errorTag: error._tag,
action: error.action,
});
yield* logUpdaterError("failed to download update", { message: error.message });
return { accepted: true, completed: false };
});
}),
}),
),
Effect.ensuring(Ref.set(updateDownloadInFlightRef, false)),
);
}).pipe(Effect.withSpan("desktop.updates.downloadAvailableUpdate"));
const resetInstallAction = Effect.all(
[Ref.set(updateInstallInFlightRef, false), Ref.set(desktopState.quitting, false)],
{ discard: true },
);
const installDownloadedUpdate = Effect.gen(function* () {
const state = yield* Ref.get(updateStateRef);
if (
@@ -458,19 +369,7 @@ export const make = Effect.gen(function* () {
yield* Ref.set(updateInstallInFlightRef, true);
return yield* Effect.gen(function* () {
// Stop every backend in the pool, not just the primary. With
// parallel WSL + Windows backends, leaving the WSL instance up
// means quitAndInstall's app.quit() exits before the pool's
// scope cascade has a chance to run its stop finalizer, so the
// WSL child gets hard-killed by the OS instead of receiving
// SIGTERM + grace. Stops run concurrently with the same 5s
// budget the primary had on its own.
const instances = yield* pool.list;
yield* Effect.forEach(
instances,
(instance) => instance.stop({ timeout: Duration.seconds(5) }),
{ concurrency: "unbounded" },
);
yield* backendManager.stop({ timeout: Duration.seconds(5) });
yield* electronWindow.destroyAll;
yield* electronUpdater.quitAndInstall({
isSilent: true,
@@ -478,38 +377,14 @@ export const make = Effect.gen(function* () {
});
return { accepted: true, completed: false };
}).pipe(
Effect.catchTags({
ElectronUpdaterQuitAndInstallError: Effect.fn("desktop.updates.handleInstallFailure")(
function* (error) {
yield* resetInstallAction;
yield* updateState((current) =>
reduceDesktopUpdateStateOnInstallFailure(current, error.message),
);
yield* logUpdaterError(error.message, {
errorTag: error._tag,
channel: error.channel,
isSilent: error.isSilent,
isForceRunAfter: error.isForceRunAfter,
});
return { accepted: true, completed: false };
},
),
}),
Effect.onInterrupt(() => resetInstallAction),
Effect.catchCause((cause) =>
Effect.gen(function* () {
if (Cause.hasInterruptsOnly(cause)) {
return yield* Effect.failCause(cause);
}
yield* resetInstallAction;
const error = new DesktopUpdateUnexpectedActionError({ action: "install", cause });
Effect.catch(
Effect.fn("desktop.updates.handleInstallFailure")(function* (error) {
yield* Ref.set(updateInstallInFlightRef, false);
yield* updateState((current) =>
reduceDesktopUpdateStateOnInstallFailure(current, error.message),
);
yield* logUpdaterError(error.message, {
errorTag: error._tag,
action: error.action,
});
yield* Ref.set(desktopState.quitting, false);
yield* logUpdaterError("failed to install update", { message: error.message });
return { accepted: true, completed: false };
}),
),
@@ -519,31 +394,17 @@ export const make = Effect.gen(function* () {
const startUpdatePollers: Effect.Effect<void, never, Scope.Scope> = Effect.gen(function* () {
yield* Effect.sleep(AUTO_UPDATE_STARTUP_DELAY).pipe(
Effect.andThen(checkForUpdates("startup")),
Effect.catchCause((cause) => {
if (Cause.hasInterruptsOnly(cause)) {
return Effect.void;
}
const error = new DesktopUpdatePollerError({ poller: "startup", cause });
return logUpdaterError(error.message, {
errorTag: error._tag,
poller: error.poller,
});
}),
Effect.catchCause((cause) =>
logUpdaterError("startup update check failed", { cause: Cause.pretty(cause) }),
),
Effect.forkScoped,
);
yield* Effect.sleep(AUTO_UPDATE_POLL_INTERVAL).pipe(
Effect.andThen(checkForUpdates("poll")),
Effect.forever,
Effect.catchCause((cause) => {
if (Cause.hasInterruptsOnly(cause)) {
return Effect.void;
}
const error = new DesktopUpdatePollerError({ poller: "poll", cause });
return logUpdaterError(error.message, {
errorTag: error._tag,
poller: error.poller,
});
}),
Effect.catchCause((cause) =>
logUpdaterError("poll update check failed", { cause: Cause.pretty(cause) }),
),
Effect.forkScoped,
);
}).pipe(Effect.withSpan("desktop.updates.startPollers"));
@@ -574,16 +435,11 @@ export const make = Effect.gen(function* () {
yield* logUpdaterInfo("update available", { version: info.version });
}),
),
Effect.catchCause((cause) => {
if (Cause.hasInterruptsOnly(cause)) {
return Effect.void;
}
const error = new DesktopUpdateEventHandlingError({ event: "update-available", cause });
return logUpdaterWarning(error.message, {
errorTag: error._tag,
event: error.event,
});
}),
Effect.catchCause((cause) =>
logUpdaterWarning("ignored malformed update-available event", {
cause: Cause.pretty(cause),
}),
),
);
});
@@ -596,23 +452,14 @@ export const make = Effect.gen(function* () {
}).pipe(Effect.withSpan("desktop.updates.handleUpdateNotAvailable"));
const handleUpdaterError = Effect.fn("desktop.updates.handleUpdaterError")(function* (
cause: unknown,
error: unknown,
) {
const activeAction = yield* activeUpdateAction;
const error = new DesktopUpdaterReportedError({
operation: Option.getOrElse(activeAction, () => "background" as const),
cause,
});
const message = error instanceof Error ? error.message : String(error);
if (yield* Ref.get(updateInstallInFlightRef)) {
yield* Ref.set(updateInstallInFlightRef, false);
yield* Ref.set(desktopState.quitting, false);
yield* updateState((current) =>
reduceDesktopUpdateStateOnInstallFailure(current, error.message),
);
yield* logUpdaterError(error.message, {
errorTag: error._tag,
operation: error.operation,
});
yield* updateState((current) => reduceDesktopUpdateStateOnInstallFailure(current, message));
yield* logUpdaterError("updater error", { message });
return;
}
@@ -622,7 +469,7 @@ export const make = Effect.gen(function* () {
yield* updateState((current) => ({
...current,
status: "error",
message: error.message,
message,
checkedAt,
downloadPercent: null,
errorContext,
@@ -630,10 +477,7 @@ export const make = Effect.gen(function* () {
}));
}
yield* logUpdaterError(error.message, {
errorTag: error._tag,
operation: error.operation,
});
yield* logUpdaterError("updater error", { message });
});
const handleDownloadProgress = Effect.fn("desktop.updates.handleDownloadProgress")(function* (
@@ -655,16 +499,11 @@ export const make = Effect.gen(function* () {
}
}),
),
Effect.catchCause((cause) => {
if (Cause.hasInterruptsOnly(cause)) {
return Effect.void;
}
const error = new DesktopUpdateEventHandlingError({ event: "download-progress", cause });
return logUpdaterWarning(error.message, {
errorTag: error._tag,
event: error.event,
});
}),
Effect.catchCause((cause) =>
logUpdaterWarning("ignored malformed download-progress event", {
cause: Cause.pretty(cause),
}),
),
);
});
@@ -679,16 +518,11 @@ export const make = Effect.gen(function* () {
yield* logUpdaterInfo("update downloaded", { version: info.version });
}),
),
Effect.catchCause((cause) => {
if (Cause.hasInterruptsOnly(cause)) {
return Effect.void;
}
const error = new DesktopUpdateEventHandlingError({ event: "update-downloaded", cause });
return logUpdaterWarning(error.message, {
errorTag: error._tag,
event: error.event,
});
}),
Effect.catchCause((cause) =>
logUpdaterWarning("ignored malformed update-downloaded event", {
cause: Cause.pretty(cause),
}),
),
);
});
@@ -764,10 +598,7 @@ export const make = Effect.gen(function* () {
yield* Effect.annotateCurrentSpan({ channel: nextChannel });
const activeAction = yield* activeUpdateAction;
if (Option.isSome(activeAction)) {
return yield* new DesktopUpdateActionInProgressError({
action: activeAction.value,
requestedChannel: nextChannel,
});
return yield* new DesktopUpdateActionInProgressError({ action: activeAction.value });
}
const state = yield* Ref.get(updateStateRef);
@@ -777,11 +608,7 @@ export const make = Effect.gen(function* () {
yield* desktopSettings
.setUpdateChannel(nextChannel)
.pipe(
Effect.mapError(
(cause) => new DesktopUpdateChannelPersistenceError({ channel: nextChannel, cause }),
),
);
.pipe(Effect.mapError((cause) => new DesktopUpdatePersistenceError({ cause })));
const enabled = yield* shouldEnableAutoUpdates;
yield* setState(createBaseUpdateState(nextChannel, enabled, environment));
@@ -73,9 +73,7 @@ const makeDesktopWindowLayer = (selectedAction: Deferred.Deferred<string>) =>
revealOrCreateMain: Effect.die("unexpected revealOrCreateMain"),
activate: Effect.void,
createMainIfBackendReady: Effect.void,
showConnectingSplash: Effect.void,
handleBackendReady: () => Effect.void,
handleBackendNotReady: Effect.void,
handleBackendReady: Effect.void,
dispatchMenuAction: (action) => Deferred.succeed(selectedAction, action).pipe(Effect.asVoid),
syncAppearance: Effect.void,
} satisfies DesktopWindow.DesktopWindow["Service"]);
@@ -1,8 +1,8 @@
import * as Cause from "effect/Cause";
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 type * as Electron from "electron";
@@ -14,18 +14,6 @@ import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
import * as DesktopUpdates from "../updates/DesktopUpdates.ts";
import * as DesktopWindow from "./DesktopWindow.ts";
export class DesktopApplicationMenuActionError extends Schema.TaggedErrorClass<DesktopApplicationMenuActionError>()(
"DesktopApplicationMenuActionError",
{
action: Schema.String,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Desktop menu action "${this.action}" failed.`;
}
}
export class DesktopApplicationMenu extends Context.Service<
DesktopApplicationMenu,
{
@@ -112,10 +100,12 @@ export const make = Effect.gen(function* () {
effect.pipe(
Effect.annotateLogs({ action }),
Effect.withSpan("desktop.menu.action"),
Effect.catchCause((cause) => {
const error = new DesktopApplicationMenuActionError({ action, cause });
return logMenuError(error.message, { error });
}),
Effect.catchCause((cause) =>
logMenuError("desktop menu action failed", {
action,
cause: Cause.pretty(cause),
}),
),
),
);
};
+2 -274
View File
@@ -4,7 +4,6 @@ import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Ref from "effect/Ref";
import * as TestClock from "effect/testing/TestClock";
import type * as Electron from "electron";
import { vi } from "vite-plus/test";
@@ -28,7 +27,6 @@ import * as ElectronMenu from "../electron/ElectronMenu.ts";
import * as ElectronShell from "../electron/ElectronShell.ts";
import * as ElectronTheme from "../electron/ElectronTheme.ts";
import * as ElectronWindow from "../electron/ElectronWindow.ts";
import { MENU_ACTION_CHANNEL } from "../ipc/channels.ts";
import * as DesktopServerExposure from "../backend/DesktopServerExposure.ts";
import * as DesktopWindow from "./DesktopWindow.ts";
import * as PreviewManager from "../preview/Manager.ts";
@@ -49,21 +47,18 @@ function makeFakeBrowserWindow() {
const webContentsListeners = new Map<string, (...args: readonly unknown[]) => void>();
const webContents = {
copyImageAt: vi.fn(),
getURL: vi.fn(() => "t3code-dev://app/"),
isLoadingMainFrame: vi.fn(() => false),
on: vi.fn((eventName: string, listener: (...args: readonly unknown[]) => void) => {
webContentsListeners.set(eventName, listener);
}),
once: vi.fn(),
openDevTools: vi.fn(),
reload: vi.fn(),
replaceMisspelling: vi.fn(),
send: vi.fn(),
setWindowOpenHandler: vi.fn(),
};
const window = {
close: vi.fn(),
focus: vi.fn(),
isDestroyed: vi.fn(() => false),
isMinimized: vi.fn(() => false),
@@ -84,8 +79,6 @@ function makeFakeBrowserWindow() {
window: window as unknown as Electron.BrowserWindow,
loadURL: window.loadURL,
openDevTools: webContents.openDevTools,
reload: webContents.reload,
send: webContents.send,
setAutoHideCursor: window.setAutoHideCursor,
webContentsListeners,
};
@@ -194,100 +187,6 @@ function makeTestLayer(input: {
);
}
// Builds a DesktopWindow over a fake ElectronWindow whose `create` returns the
// given outcomes in order (null => simulated open failure), and whose
// currentMainOrFirst mirrors the real fallback to the first live window (the
// splash, before any main is registered). Reveal targets are recorded so tests
// can assert what activation actually surfaced.
const makeSplashScenario = (createOutcomes: readonly (Electron.BrowserWindow | null)[]) =>
Effect.gen(function* () {
const createdWindows = yield* Ref.make<Electron.BrowserWindow[]>([]);
const createCalls = yield* Ref.make(0);
const mainWindow = yield* Ref.make<Option.Option<Electron.BrowserWindow>>(Option.none());
const revealedWindows = yield* Ref.make<Electron.BrowserWindow[]>([]);
const fallbackWindow = createOutcomes.find(
(window): window is Electron.BrowserWindow => window !== null,
);
const currentMainOrFirst = Effect.gen(function* () {
const registered = yield* Ref.get(mainWindow);
if (Option.isSome(registered)) {
return registered;
}
const created = yield* Ref.get(createdWindows);
return Option.fromNullishOr(created[0] ?? null);
});
const electronWindowShape = {
create: () =>
Effect.gen(function* () {
const index = yield* Ref.getAndUpdate(createCalls, (count) => count + 1);
const outcome = createOutcomes[index] ?? null;
if (outcome === null) {
return yield* new ElectronWindow.ElectronWindowCreateError({
options: {
title: null,
width: null,
height: null,
minWidth: null,
minHeight: null,
show: null,
modal: null,
frame: null,
transparent: null,
backgroundColor: null,
webPreferences: {
preload: null,
partition: null,
sandbox: null,
contextIsolation: null,
nodeIntegration: null,
webviewTag: null,
},
},
cause: new Error("simulated window-open failure"),
});
}
yield* Ref.update(createdWindows, (windows) => [...windows, outcome]);
return outcome;
}),
main: Ref.get(mainWindow),
currentMainOrFirst,
focusedMainOrFirst: currentMainOrFirst,
setMain: (window) => Ref.set(mainWindow, Option.some(window)),
clearMain: () => Ref.set(mainWindow, Option.none()),
reveal: (window) => Ref.update(revealedWindows, (windows) => [...windows, window]),
sendAll: () => Effect.void,
destroyAll: Effect.void,
syncAllAppearance: (sync) => (fallbackWindow ? sync(fallbackWindow) : Effect.void),
} satisfies ElectronWindow.ElectronWindow["Service"];
const layer = DesktopWindow.layer.pipe(
Layer.provide(
Layer.mergeAll(
desktopAssetsLayer,
desktopEnvironmentLayer,
desktopServerExposureLayer,
electronMenuLayer,
Layer.succeed(ElectronShell.ElectronShell, {
openExternal: () => Effect.succeed(true),
copyText: () => Effect.void,
} satisfies ElectronShell.ElectronShell["Service"]),
electronThemeLayer,
Layer.succeed(ElectronWindow.ElectronWindow, electronWindowShape),
Layer.mock(PreviewManager.PreviewManager)({
getBrowserSession: () => Effect.succeed({} as Electron.Session),
setMainWindow: () => Effect.void,
isBrowserPartition: (partition) => partition.startsWith("persist:t3code-preview-"),
getBrowserPartition: () => Effect.succeed("persist:t3code-preview-test"),
}),
),
),
);
return { layer, createCalls, mainWindow, revealedWindows } as const;
});
describe("DesktopWindow", () => {
it("recognizes only same-origin renderer navigations", () => {
assert.isTrue(
@@ -328,7 +227,7 @@ describe("DesktopWindow", () => {
yield* desktopWindow.activate;
assert.equal(yield* Ref.get(createCount), 0);
yield* desktopWindow.handleBackendReady(new URL("http://127.0.0.1:3773"));
yield* desktopWindow.handleBackendReady;
assert.equal(yield* Ref.get(createCount), 1);
assert.isTrue(createdWindowOptions[0]?.disableAutoHideCursor);
assert.deepEqual(fakeWindow.setAutoHideCursor.mock.calls, [[false]]);
@@ -338,73 +237,6 @@ describe("DesktopWindow", () => {
}),
);
it.effect("recovers when the development renderer is temporarily unreachable", () =>
Effect.gen(function* () {
const fakeWindow = makeFakeBrowserWindow();
const createCount = yield* Ref.make(0);
const mainWindow = yield* Ref.make<Option.Option<Electron.BrowserWindow>>(Option.none());
const layer = makeTestLayer({
window: fakeWindow.window,
createCount,
mainWindow,
});
yield* Effect.gen(function* () {
const desktopWindow = yield* DesktopWindow.DesktopWindow;
yield* desktopWindow.handleBackendReady(new URL("http://127.0.0.1:3773"));
const didFailLoad = fakeWindow.webContentsListeners.get("did-fail-load");
const didFinishLoad = fakeWindow.webContentsListeners.get("did-finish-load");
if (!didFailLoad || !didFinishLoad) {
return yield* Effect.die("renderer load listeners were not registered");
}
didFailLoad({}, -9, "ERR_UNEXPECTED", "t3code-dev://app/", true);
assert.equal(fakeWindow.loadURL.mock.calls.length, 1);
yield* TestClock.adjust(100);
assert.deepEqual(fakeWindow.loadURL.mock.calls, [
["t3code-dev://app/"],
["t3code-dev://app/"],
]);
assert.equal(fakeWindow.reload.mock.calls.length, 0);
didFailLoad({}, -9, "ERR_UNEXPECTED", "t3code-dev://app/", true);
didFinishLoad();
yield* TestClock.adjust(250);
assert.equal(fakeWindow.loadURL.mock.calls.length, 2);
assert.equal(fakeWindow.reload.mock.calls.length, 0);
}).pipe(Effect.provide(layer));
}),
);
it("retries only transient failures for the development renderer", () => {
assert.isTrue(
DesktopWindow.isRetryableDevelopmentRendererLoadFailure({
applicationUrl: "t3code-dev://app/",
errorCode: -102,
isMainFrame: true,
validatedUrl: "t3code-dev://app/",
}),
);
assert.isFalse(
DesktopWindow.isRetryableDevelopmentRendererLoadFailure({
applicationUrl: "t3code-dev://app/",
errorCode: -3,
isMainFrame: true,
validatedUrl: "t3code-dev://app/",
}),
);
assert.isFalse(
DesktopWindow.isRetryableDevelopmentRendererLoadFailure({
applicationUrl: "t3code-dev://app/",
errorCode: -102,
isMainFrame: true,
validatedUrl: "https://example.com/",
}),
);
});
it.effect("opens safe off-origin renderer navigations in the system browser", () =>
Effect.gen(function* () {
const fakeWindow = makeFakeBrowserWindow();
@@ -420,7 +252,7 @@ describe("DesktopWindow", () => {
yield* Effect.gen(function* () {
const desktopWindow = yield* DesktopWindow.DesktopWindow;
yield* desktopWindow.handleBackendReady(new URL("http://127.0.0.1:3773"));
yield* desktopWindow.handleBackendReady;
const willNavigate = fakeWindow.webContentsListeners.get("will-navigate");
if (!willNavigate) {
@@ -442,108 +274,4 @@ describe("DesktopWindow", () => {
}).pipe(Effect.provide(layer));
}),
);
it.effect(
"retries opening the real main on activate when a failed post-readiness open left only the splash",
() =>
Effect.gen(function* () {
const splash = makeFakeBrowserWindow();
const main = makeFakeBrowserWindow();
// create #1 -> splash, #2 -> fails (the pool swallows this post-readiness
// window-open error), #3 -> the real main on activate's retry.
const scenario = yield* makeSplashScenario([splash.window, null, main.window]);
yield* Effect.gen(function* () {
const desktopWindow = yield* DesktopWindow.DesktopWindow;
// 1. WSL-only boot shows the connecting splash.
yield* desktopWindow.showConnectingSplash;
assert.equal(yield* Ref.get(scenario.createCalls), 1);
// 2. Backend reports ready, but opening the real main fails. The pool
// swallows that error in production, so handleBackendReady fails
// here without a registered main window -- only the splash is open.
const readyExit = yield* Effect.exit(
desktopWindow.handleBackendReady(new URL("http://127.0.0.1:3773")),
);
assert.equal(readyExit._tag, "Failure");
assert.equal(yield* Ref.get(scenario.createCalls), 2);
assert.isTrue(Option.isNone(yield* Ref.get(scenario.mainWindow)));
// 3. Activating must not mistake the splash for the main window: it
// retries the open and brings up the real main instead of leaving
// the user stranded on "Connecting to WSL".
yield* desktopWindow.activate;
assert.equal(yield* Ref.get(scenario.createCalls), 3);
const registeredMain = yield* Ref.get(scenario.mainWindow);
assert.isTrue(Option.isSome(registeredMain));
assert.equal(Option.getOrThrow(registeredMain), main.window);
}).pipe(Effect.provide(scenario.layer));
}),
);
it.effect(
"re-reveals the connecting splash on activate while the backend is still cold-booting",
() =>
Effect.gen(function* () {
const splash = makeFakeBrowserWindow();
// Only the splash is ever created; the backend never reports ready.
const scenario = yield* makeSplashScenario([splash.window]);
yield* Effect.gen(function* () {
const desktopWindow = yield* DesktopWindow.DesktopWindow;
yield* desktopWindow.showConnectingSplash;
assert.equal(yield* Ref.get(scenario.createCalls), 1);
// Taskbar/dock activation during cold boot must bring the splash back
// rather than no-op and leave it hidden until the backend finishes.
yield* desktopWindow.activate;
assert.equal(yield* Ref.get(scenario.createCalls), 1);
assert.deepEqual(yield* Ref.get(scenario.revealedWindows), [splash.window]);
}).pipe(Effect.provide(scenario.layer));
}),
);
it.effect("does not dispatch menu actions to the splash before the backend is ready", () =>
Effect.gen(function* () {
const splash = makeFakeBrowserWindow();
const main = makeFakeBrowserWindow();
const scenario = yield* makeSplashScenario([splash.window, main.window]);
yield* Effect.gen(function* () {
const desktopWindow = yield* DesktopWindow.DesktopWindow;
yield* desktopWindow.showConnectingSplash;
yield* desktopWindow.dispatchMenuAction("open-settings");
assert.equal(yield* Ref.get(scenario.createCalls), 1);
assert.equal(splash.send.mock.calls.length, 0);
assert.equal(main.send.mock.calls.length, 0);
}).pipe(Effect.provide(scenario.layer));
}),
);
it.effect("dispatches menu actions after backend readiness when no main window exists", () =>
Effect.gen(function* () {
const splash = makeFakeBrowserWindow();
const main = makeFakeBrowserWindow();
const scenario = yield* makeSplashScenario([splash.window, null, main.window]);
yield* Effect.gen(function* () {
const desktopWindow = yield* DesktopWindow.DesktopWindow;
yield* desktopWindow.showConnectingSplash;
const readyExit = yield* Effect.exit(
desktopWindow.handleBackendReady(new URL("http://127.0.0.1:3773")),
);
assert.equal(readyExit._tag, "Failure");
yield* desktopWindow.dispatchMenuAction("open-settings");
assert.equal(yield* Ref.get(scenario.createCalls), 3);
assert.deepEqual(main.send.mock.calls, [[MENU_ACTION_CHANNEL, "open-settings"]]);
}).pipe(Effect.provide(scenario.layer));
}),
);
});
+20 -239
View File
@@ -1,6 +1,5 @@
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import * as Fiber from "effect/Fiber";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Ref from "effect/Ref";
@@ -10,6 +9,7 @@ import type * as Electron from "electron";
import * as DesktopAssets from "../app/DesktopAssets.ts";
import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
import { makeComponentLogger } from "../app/DesktopObservability.ts";
import * as DesktopState from "../app/DesktopState.ts";
import * as ElectronMenu from "../electron/ElectronMenu.ts";
import { getDesktopUrl } from "../electron/ElectronProtocol.ts";
import * as ElectronShell from "../electron/ElectronShell.ts";
@@ -22,16 +22,6 @@ const TITLEBAR_HEIGHT = 40;
const TITLEBAR_COLOR = "#01000000"; // #00000000 does not work correctly on Linux
const TITLEBAR_LIGHT_SYMBOL_COLOR = "#1f2937";
const TITLEBAR_DARK_SYMBOL_COLOR = "#f8fafc";
const DEVELOPMENT_LOAD_RETRY_DELAYS_MS = [100, 250, 500, 1_000, 2_000] as const;
const DEVELOPMENT_RETRYABLE_LOAD_ERROR_CODES = new Set([
-2, // ERR_FAILED
-7, // ERR_TIMED_OUT
-9, // ERR_UNEXPECTED (custom protocol handler rejected)
-102, // ERR_CONNECTION_REFUSED
-105, // ERR_NAME_NOT_RESOLVED
-106, // ERR_INTERNET_DISCONNECTED
-118, // ERR_CONNECTION_TIMED_OUT
]);
type WindowTitleBarOptions = Pick<
Electron.BrowserWindowConstructorOptions,
@@ -41,6 +31,7 @@ type WindowTitleBarOptions = Pick<
type DesktopWindowRuntimeServices =
| DesktopEnvironment.DesktopEnvironment
| DesktopAssets.DesktopAssets
| DesktopState.DesktopState
| ElectronMenu.ElectronMenu
| ElectronShell.ElectronShell
| ElectronTheme.ElectronTheme
@@ -59,22 +50,7 @@ export class DesktopWindow extends Context.Service<
readonly revealOrCreateMain: Effect.Effect<Electron.BrowserWindow, DesktopWindowError>;
readonly activate: Effect.Effect<void, DesktopWindowError>;
readonly createMainIfBackendReady: Effect.Effect<void, DesktopWindowError>;
// Show a lightweight "Connecting to WSL" splash window immediately (wsl-only
// mode), before the WSL backend that serves the renderer is ready. It is
// dismissed automatically once the real main window reveals.
readonly showConnectingSplash: Effect.Effect<void>;
// Marks the primary backend as ready so `createMainIfBackendReady` and the
// macOS "activate without windows" path may open the real main window. The
// renderer now always loads the local client URL (getDesktopUrl) and connects
// to the backend through the connection layer, so the reported httpBaseUrl is
// no longer used to point the window at the backend — it is kept only for the
// readiness log and to preserve the callback contract the backend pool drives.
readonly handleBackendReady: (httpBaseUrl: URL) => Effect.Effect<void, DesktopWindowError>;
// Called when the backend transitions back to "not ready" (clean stop,
// restart, crash). Clears the latch that lets `activate` auto-create a
// window so a "macOS dock click" while the backend is down doesn't
// produce a stranded window pointing at nothing.
readonly handleBackendNotReady: Effect.Effect<void>;
readonly handleBackendReady: Effect.Effect<void, DesktopWindowError>;
readonly dispatchMenuAction: (action: string) => Effect.Effect<void, DesktopWindowError>;
readonly syncAppearance: Effect.Effect<void>;
}
@@ -99,18 +75,6 @@ function getInitialWindowBackgroundColor(shouldUseDarkColors: boolean): string {
return shouldUseDarkColors ? "#0a0a0a" : "#ffffff";
}
// A self-contained "Connecting to WSL" splash, shown immediately in wsl-only
// mode while the WSL backend (which serves the renderer) cold-boots. Inlined as
// a data URL so it needs no bundled asset and no backend — pure CSS, no JS.
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">Connecting to WSL…</div></body></html>`;
return `data:text/html;charset=utf-8,${encodeURIComponent(html)}`;
}
export function isSameOriginRendererNavigation(input: {
readonly applicationUrl: string;
readonly navigationUrl: string;
@@ -122,22 +86,6 @@ export function isSameOriginRendererNavigation(input: {
}
}
export function isRetryableDevelopmentRendererLoadFailure(input: {
readonly applicationUrl: string;
readonly errorCode: number;
readonly isMainFrame: boolean;
readonly validatedUrl: string;
}): boolean {
return (
input.isMainFrame &&
DEVELOPMENT_RETRYABLE_LOAD_ERROR_CODES.has(input.errorCode) &&
isSameOriginRendererNavigation({
applicationUrl: input.applicationUrl,
navigationUrl: input.validatedUrl,
})
);
}
function getWindowTitleBarOptions(
shouldUseDarkColors: boolean,
platform: NodeJS.Platform,
@@ -202,45 +150,10 @@ export const make = Effect.gen(function* () {
const electronTheme = yield* ElectronTheme.ElectronTheme;
const electronWindow = yield* ElectronWindow.ElectronWindow;
const previewManager = yield* PreviewManager.PreviewManager;
// Window-side latch for the primary backend's readiness. Set by
// handleBackendReady (driven by the pool's onReady callback), cleared
// by handleBackendNotReady (driven by onShutdown). Only consumed by
// createMainIfBackendReady, which gates the post-readiness window
// open in development and the macOS "activate without windows" path.
const backendReadyRef = yield* Ref.make(false);
// The transient "Connecting to WSL" splash window, tracked separately so it
// is never mistaken for the real main window.
const splashWindowRef = yield* Ref.make<Option.Option<Electron.BrowserWindow>>(Option.none());
const state = yield* DesktopState.DesktopState;
const context = yield* Effect.context<DesktopWindowRuntimeServices>();
const runFork = Effect.runForkWith(context);
const runPromise = Effect.runPromiseWith(context);
const dismissConnectingSplash = Effect.gen(function* () {
const splash = yield* Ref.getAndSet(splashWindowRef, Option.none());
if (Option.isSome(splash) && !splash.value.isDestroyed()) {
splash.value.close();
}
});
// 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. That is the failure the pool's swallowed
// post-readiness window-open error would otherwise strand the user in:
// splash up, backend ready, no main, and activation only re-reveals splash.
const withoutSplash = (window: Option.Option<Electron.BrowserWindow>) =>
Ref.get(splashWindowRef).pipe(
Effect.map((splash) =>
Option.isSome(splash) && Option.isSome(window) && window.value === splash.value
? Option.none<Electron.BrowserWindow>()
: window,
),
);
const currentMainWindow = electronWindow.currentMainOrFirst.pipe(Effect.flatMap(withoutSplash));
const focusedMainWindow = electronWindow.focusedMainOrFirst.pipe(Effect.flatMap(withoutSplash));
const createWindow = Effect.fn("desktop.window.createWindow")(function* (): Effect.fn.Return<
Electron.BrowserWindow,
DesktopWindowError
@@ -364,61 +277,7 @@ export const make = Effect.gen(function* () {
event.preventDefault();
window.setTitle(environment.displayName);
});
let developmentLoadRetryIndex = 0;
let developmentLoadRetryFiber: Fiber.Fiber<void, never> | undefined;
const clearDevelopmentLoadRetry = () => {
if (developmentLoadRetryFiber === undefined) {
return;
}
const retryFiber = developmentLoadRetryFiber;
developmentLoadRetryFiber = undefined;
runFork(Fiber.interrupt(retryFiber));
};
const loadApplication = () => {
if (window.isDestroyed()) {
return;
}
void window.loadURL(applicationUrl).catch(() => undefined);
};
const scheduleDevelopmentLoadRetry = () => {
if (developmentLoadRetryFiber !== undefined || window.isDestroyed()) {
return undefined;
}
const retryIndex = Math.min(
developmentLoadRetryIndex,
DEVELOPMENT_LOAD_RETRY_DELAYS_MS.length - 1,
);
const retryInMs = DEVELOPMENT_LOAD_RETRY_DELAYS_MS[retryIndex] ?? 2_000;
developmentLoadRetryIndex += 1;
developmentLoadRetryFiber = runFork(
Effect.sleep(retryInMs).pipe(
Effect.andThen(
Effect.sync(() => {
developmentLoadRetryFiber = undefined;
if (!window.isDestroyed()) {
loadApplication();
}
}),
),
),
);
return retryInMs;
};
window.webContents.on("did-finish-load", () => {
if (
environment.isDevelopment &&
!isSameOriginRendererNavigation({
applicationUrl,
navigationUrl: window.webContents.getURL(),
})
) {
return;
}
clearDevelopmentLoadRetry();
developmentLoadRetryIndex = 0;
window.setTitle(environment.displayName);
});
window.webContents.on(
@@ -427,22 +286,11 @@ export const make = Effect.gen(function* () {
if (!isMainFrame) {
return;
}
const retryInMs =
environment.isDevelopment &&
isRetryableDevelopmentRendererLoadFailure({
applicationUrl,
errorCode,
isMainFrame,
validatedUrl: validatedURL,
})
? scheduleDevelopmentLoadRetry()
: undefined;
void runPromise(
logWindowWarning("main window failed to load", {
errorCode,
errorDescription,
url: validatedURL,
...(retryInMs === undefined ? {} : { retryInMs }),
}),
);
},
@@ -461,18 +309,17 @@ export const make = Effect.gen(function* () {
revealSubscribers.push((fire) => window.webContents.once("did-finish-load", fire));
}
bindFirstRevealTrigger(revealSubscribers, () => {
// Reveal the real window, then close the connecting splash (if any) so the
// two don't overlap and there's no blank gap between them.
void runPromise(Effect.andThen(electronWindow.reveal(window), dismissConnectingSplash));
void runPromise(electronWindow.reveal(window));
});
loadApplication();
if (environment.isDevelopment) {
void window.loadURL(applicationUrl);
window.webContents.openDevTools({ mode: "detach" });
} else {
void window.loadURL(applicationUrl);
}
window.on("closed", () => {
clearDevelopmentLoadRetry();
void runPromise(electronWindow.clearMain(Option.some(window)));
});
@@ -487,7 +334,7 @@ export const make = Effect.gen(function* () {
}).pipe(Effect.withSpan("desktop.window.createMain"));
const ensureMain = Effect.gen(function* () {
const existingWindow = yield* currentMainWindow;
const existingWindow = yield* electronWindow.currentMainOrFirst;
if (Option.isSome(existingWindow)) {
return existingWindow.value;
}
@@ -501,101 +348,35 @@ export const make = Effect.gen(function* () {
}).pipe(Effect.withSpan("desktop.window.revealOrCreateMain"));
const createMainIfBackendReady = Effect.gen(function* () {
const backendReady = yield* Ref.get(backendReadyRef);
const backendReady = yield* Ref.get(state.backendReady);
if (!backendReady) return;
const existingWindow = yield* currentMainWindow;
const existingWindow = yield* electronWindow.currentMainOrFirst;
if (Option.isSome(existingWindow)) return;
yield* createMain;
}).pipe(Effect.withSpan("desktop.window.createMainIfBackendReady"));
const showConnectingSplash = Effect.gen(function* () {
// Only when nothing is shown yet: no real window, no existing splash.
const existingSplash = yield* Ref.get(splashWindowRef);
if (Option.isSome(existingSplash)) return;
const existingWindow = yield* electronWindow.currentMainOrFirst;
if (Option.isSome(existingWindow)) return;
const shouldUseDarkColors = yield* electronTheme.shouldUseDarkColors;
const splash = yield* electronWindow.create({
width: 360,
height: 220,
resizable: false,
minimizable: false,
maximizable: false,
fullscreenable: false,
frame: false,
center: true,
show: false,
skipTaskbar: false,
backgroundColor: getInitialWindowBackgroundColor(shouldUseDarkColors),
title: environment.displayName,
webPreferences: {
contextIsolation: true,
nodeIntegration: false,
sandbox: true,
},
});
yield* Ref.set(splashWindowRef, Option.some(splash));
splash.once("closed", () => {
void runPromise(Ref.set(splashWindowRef, Option.none()));
});
splash.once("ready-to-show", () => {
if (!splash.isDestroyed()) {
splash.show();
}
});
void splash.loadURL(buildConnectingSplashDataUrl(shouldUseDarkColors));
yield* logWindowInfo("connecting splash shown");
}).pipe(
// The splash is best-effort UX — never let it fail startup.
Effect.catch((error) =>
logWindowWarning("failed to show connecting splash", { message: error.message }),
),
Effect.withSpan("desktop.window.showConnectingSplash"),
);
return DesktopWindow.of({
createMain,
ensureMain,
revealOrCreateMain,
activate: Effect.gen(function* () {
const existingWindow = yield* currentMainWindow;
const existingWindow = yield* electronWindow.currentMainOrFirst;
if (Option.isSome(existingWindow)) {
yield* electronWindow.reveal(existingWindow.value);
return;
} else {
yield* createMainIfBackendReady;
}
// No real main window yet. While the backend is still cold-booting,
// re-reveal the connecting splash so taskbar/dock activation brings it
// back instead of doing nothing. Once the backend is ready we fall
// through to (re)create the real main -- including retrying a previously
// failed open the pool swallowed -- rather than latching onto the splash.
const backendReady = yield* Ref.get(backendReadyRef);
if (!backendReady) {
const splash = yield* Ref.get(splashWindowRef);
if (Option.isSome(splash)) {
yield* electronWindow.reveal(splash.value);
return;
}
}
yield* createMainIfBackendReady;
}).pipe(Effect.withSpan("desktop.window.activate")),
createMainIfBackendReady,
showConnectingSplash,
handleBackendReady: Effect.fn("desktop.window.handleBackendReady")(function* (httpBaseUrl) {
yield* Ref.set(backendReadyRef, true);
yield* logWindowInfo("backend ready", { source: "http", url: httpBaseUrl.href });
handleBackendReady: Effect.gen(function* () {
yield* Ref.set(state.backendReady, true);
yield* logWindowInfo("backend ready", { source: "http" });
yield* createMainIfBackendReady;
}),
handleBackendNotReady: Ref.set(backendReadyRef, false).pipe(
Effect.withSpan("desktop.window.handleBackendNotReady"),
),
}).pipe(Effect.withSpan("desktop.window.handleBackendReady")),
dispatchMenuAction: Effect.fn("desktop.window.dispatchMenuAction")(function* (action) {
yield* Effect.annotateCurrentSpan({ action });
const existingWindow = yield* focusedMainWindow;
if (Option.isNone(existingWindow) && !(yield* Ref.get(backendReadyRef))) {
return;
}
const targetWindow = Option.isSome(existingWindow) ? existingWindow.value : yield* ensureMain;
const existingWindow = yield* electronWindow.focusedMainOrFirst;
const targetWindow = Option.isSome(existingWindow) ? existingWindow.value : yield* createMain;
const send = () => {
if (targetWindow.isDestroyed()) return;
@@ -1,199 +0,0 @@
import { assert, describe, it } from "@effect/vitest";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as NetService from "@t3tools/shared/Net";
import * as DesktopBackendConfiguration from "../backend/DesktopBackendConfiguration.ts";
import * as DesktopBackendPool from "../backend/DesktopBackendPool.ts";
import type {
DesktopBackendSnapshot,
DesktopBackendStartConfig,
} from "../backend/DesktopBackendManager.ts";
import * as DesktopServerExposure from "../backend/DesktopServerExposure.ts";
import * as DesktopAppSettings from "../settings/DesktopAppSettings.ts";
import * as DesktopWslEnvironment from "./DesktopWslEnvironment.ts";
import * as DesktopWslBackend from "./DesktopWslBackend.ts";
function makeStubInstance(input: {
readonly id: DesktopBackendPool.BackendInstanceId;
readonly label: string;
readonly snapshot: DesktopBackendSnapshot;
readonly start?: Effect.Effect<void>;
}): DesktopBackendPool.DesktopBackendInstance {
return {
id: input.id,
label: Effect.succeed(input.label),
start: input.start ?? Effect.void,
stop: () => Effect.void,
currentConfig: Effect.succeed(Option.none<DesktopBackendStartConfig>()),
snapshot: Effect.succeed(input.snapshot),
waitForReady: (_timeout: Duration.Duration) => Effect.succeed(false),
};
}
const idleSnapshot: DesktopBackendSnapshot = {
desiredRunning: false,
ready: false,
activePid: Option.none(),
restartAttempt: 5,
restartScheduled: false,
};
const primarySnapshot: DesktopBackendSnapshot = {
desiredRunning: true,
ready: true,
activePid: Option.some(123),
restartAttempt: 0,
restartScheduled: false,
};
const serverExposureLayer = Layer.succeed(DesktopServerExposure.DesktopServerExposure, {
getState: Effect.die("unexpected getState"),
backendConfig: Effect.succeed({
port: 3773,
bindHost: "127.0.0.1",
httpBaseUrl: new URL("http://127.0.0.1:3773"),
tailscaleServeEnabled: false,
tailscaleServePort: 443,
}),
configureFromSettings: () => Effect.die("unexpected configureFromSettings"),
setMode: () => Effect.die("unexpected setMode"),
setTailscaleServeEnabled: () => Effect.die("unexpected setTailscaleServeEnabled"),
getAdvertisedEndpoints: Effect.succeed([]),
} satisfies DesktopServerExposure.DesktopServerExposure["Service"]);
const backendConfigurationLayer = Layer.succeed(
DesktopBackendConfiguration.DesktopBackendConfiguration,
{
resolvePrimary: Effect.die("unexpected resolvePrimary"),
resolvePrimaryLabel: Effect.succeed("Windows"),
resolveWsl: () => Effect.die("unexpected resolveWsl"),
} satisfies DesktopBackendConfiguration.DesktopBackendConfiguration["Service"],
);
const netLayer = Layer.succeed(NetService.NetService, {
canListenOnHost: () => Effect.succeed(true),
isPortAvailableOnLoopback: () => Effect.succeed(true),
reserveLoopbackPort: () => Effect.succeed(41773),
findAvailablePort: (preferred) => Effect.succeed(preferred),
} satisfies NetService.NetService["Service"]);
describe("DesktopWslBackend", () => {
it.effect("clears the stored preflight error when a registered WSL backend becomes ready", () => {
let registeredSpec: DesktopBackendPool.BackendInstanceSpec | undefined;
const primary = makeStubInstance({
id: DesktopBackendPool.PRIMARY_INSTANCE_ID,
label: "Windows",
snapshot: primarySnapshot,
});
const wsl = makeStubInstance({
id: DesktopBackendPool.BackendInstanceId("wsl:Ubuntu"),
label: "WSL (Ubuntu)",
snapshot: primarySnapshot,
});
const poolLayer = Layer.succeed(DesktopBackendPool.DesktopBackendPool, {
get: (id) =>
Effect.succeed(
id === DesktopBackendPool.PRIMARY_INSTANCE_ID
? Option.some(primary)
: Option.none<DesktopBackendPool.DesktopBackendInstance>(),
),
list: Effect.succeed([primary]),
primary: Effect.succeed(primary),
register: (spec) =>
Effect.sync(() => {
registeredSpec = spec;
return wsl;
}),
unregister: () => Effect.die("unexpected unregister"),
} satisfies DesktopBackendPool.DesktopBackendPool["Service"]);
return Effect.gen(function* () {
const backend = yield* DesktopWslBackend.DesktopWslBackend;
yield* backend.reconcile;
const spec = registeredSpec;
assert.isDefined(spec);
if (spec === undefined) {
throw new Error("Expected WSL backend registration");
}
const recordFailure = spec.onPreflightFailed;
const clearFailure = spec.onReady;
assert.isDefined(recordFailure);
assert.isDefined(clearFailure);
if (recordFailure === undefined || clearFailure === undefined) {
throw new Error("Expected WSL backend callbacks");
}
assert.isFalse(yield* recordFailure({ reason: "Node.js not found", fatal: true }));
assert.deepEqual(yield* backend.lastPreflightError, Option.some("Node.js not found"));
yield* clearFailure(new URL("http://127.0.0.1:41773"));
assert.deepEqual(yield* backend.lastPreflightError, Option.none());
}).pipe(
Effect.provide(
DesktopWslBackend.layer.pipe(
Layer.provideMerge(poolLayer),
Layer.provideMerge(backendConfigurationLayer),
Layer.provideMerge(serverExposureLayer),
Layer.provideMerge(netLayer),
Layer.provideMerge(
DesktopAppSettings.layerTest({
...DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS,
wslBackendEnabled: true,
wslDistro: "Ubuntu",
wslOnly: false,
}),
),
Layer.provideMerge(DesktopWslEnvironment.layerTest({ isAvailable: true })),
),
),
);
});
it.effect("retries an unchanged WSL instance when it is idle after failed preflight", () => {
let startCount = 0;
const primary = makeStubInstance({
id: DesktopBackendPool.PRIMARY_INSTANCE_ID,
label: "Windows",
snapshot: primarySnapshot,
});
const wsl = makeStubInstance({
id: DesktopBackendPool.BackendInstanceId("wsl:Ubuntu"),
label: "WSL (Ubuntu)",
snapshot: idleSnapshot,
start: Effect.sync(() => {
startCount += 1;
}),
});
return Effect.gen(function* () {
const backend = yield* DesktopWslBackend.DesktopWslBackend;
yield* backend.reconcile;
assert.equal(startCount, 1);
}).pipe(
Effect.provide(
DesktopWslBackend.layer.pipe(
Layer.provideMerge(DesktopBackendPool.layerTest([primary, wsl])),
Layer.provideMerge(backendConfigurationLayer),
Layer.provideMerge(serverExposureLayer),
Layer.provideMerge(netLayer),
Layer.provideMerge(
DesktopAppSettings.layerTest({
...DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS,
wslBackendEnabled: true,
wslDistro: "Ubuntu",
wslOnly: false,
}),
),
Layer.provideMerge(DesktopWslEnvironment.layerTest({ isAvailable: true })),
),
),
);
});
});
-268
View File
@@ -1,268 +0,0 @@
// Orchestrator that keeps the WSL pool instance in sync with the user's
// settings. `reconcile` is the single entry point — bootstrap calls it
// once after the primary backend starts, and the wsl.ts IPC calls it
// after persisting a `wslBackendEnabled` or `wslDistro` change. The
// effect is idempotent and never fails: errors (WSL not available, port
// allocation failed, register failed) get logged and reconcile returns
// having left the pool in a consistent state (either the previous WSL
// instance is still running, or none is).
//
// The instance id encodes the desired distro selection — `wsl:default`
// when the user picked "track the WSL default" (settings.wslDistro is
// null) and `wsl:<distro>` otherwise. Changing the distro setting
// changes the id, so reconcile unregisters the old instance before
// registering the new one. The label that the frontend env switcher
// renders is derived from the same field.
//
// Port allocation: each WSL instance gets a freshly scanned port to
// avoid colliding with the primary or with a previously-registered WSL
// instance that's still tearing down. The scan only checks loopback
// (127.0.0.1) since the WSL backend is loopback-only — the primary
// owns LAN exposure when the user opts in.
import * as Cause from "effect/Cause";
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 Ref from "effect/Ref";
import * as Semaphore from "effect/Semaphore";
import * as NetService from "@t3tools/shared/Net";
import * as DesktopObservability from "../app/DesktopObservability.ts";
import * as DesktopBackendConfiguration from "../backend/DesktopBackendConfiguration.ts";
import * as DesktopBackendPool from "../backend/DesktopBackendPool.ts";
import * as DesktopServerExposure from "../backend/DesktopServerExposure.ts";
import * as DesktopAppSettings from "../settings/DesktopAppSettings.ts";
import * as DesktopWslEnvironment from "./DesktopWslEnvironment.ts";
// Exported so callers that parse pool ids (e.g. the pickFolder IPC
// handler in ipc/methods/window.ts) reference the same prefix this
// module produces. Keeping it inline in two places risks silent
// divergence if one ever gets renamed.
export const WSL_INSTANCE_ID_PREFIX = "wsl:";
const WSL_DEFAULT_DISTRO_ID = `${WSL_INSTANCE_ID_PREFIX}default`;
const MAX_TCP_PORT = 65_535;
export class DesktopWslBackend extends Context.Service<
DesktopWslBackend,
{
// Bring the pool in line with the current persisted WSL settings.
// Idempotent. Never fails (errors are logged); callers can chain it
// after persisting settings without an error-handling dance.
readonly reconcile: Effect.Effect<void>;
// Reason the dual-mode WSL secondary last failed preflight (no node, wrong
// version, missing build tools), or None. Read by the getWslState IPC so
// Connections settings can show it inline. None in wsl-only mode (that path
// surfaces via a dialog + Windows fallback).
readonly lastPreflightError: Effect.Effect<Option.Option<string>>;
}
>()("@t3tools/desktop/wsl/DesktopWslBackend") {}
const { logInfo: logWslBackendInfo, logWarning: logWslBackendWarning } =
DesktopObservability.makeComponentLogger("desktop-wsl-backend");
const resolveTargetInstanceId = (distro: string | null): DesktopBackendPool.BackendInstanceId =>
DesktopBackendPool.BackendInstanceId(
distro === null ? WSL_DEFAULT_DISTRO_ID : `${WSL_INSTANCE_ID_PREFIX}${distro}`,
);
const isWslInstanceId = (id: DesktopBackendPool.BackendInstanceId): boolean =>
id.startsWith(WSL_INSTANCE_ID_PREFIX);
const buildLabel = (distro: string | null): string =>
distro === null ? "WSL (default distro)" : `WSL (${distro})`;
// Loopback-only port scan starting one above the primary's port. The
// WSL backend is reachable via 127.0.0.1 from Windows (wslhost
// auto-forwards), so we only need to verify the IPv4 loopback can bind.
const scanForWslPort = Effect.fn("desktop.wslBackend.scanForWslPort")(function* (
startPort: number,
): Effect.fn.Return<number, NetService.NetError, NetService.NetService> {
const net = yield* NetService.NetService;
for (let port = startPort; port <= MAX_TCP_PORT; port += 1) {
if (yield* net.canListenOnHost(port, "127.0.0.1")) {
return port;
}
}
return yield* new NetService.NetError({
message: `No loopback port available for WSL backend between ${startPort} and ${MAX_TCP_PORT}.`,
});
});
export const layer = Layer.effect(
DesktopWslBackend,
Effect.gen(function* () {
const pool = yield* DesktopBackendPool.DesktopBackendPool;
const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
const serverExposure = yield* DesktopServerExposure.DesktopServerExposure;
const wslEnvironment = yield* DesktopWslEnvironment.DesktopWslEnvironment;
const appSettings = yield* DesktopAppSettings.DesktopAppSettings;
const net = yield* NetService.NetService;
// Serialize reconcile so the bootstrap fork and the IPC handlers
// (setWslBackendEnabled, setWslDistro) can't interleave. Without
// this, two reconciles could both observe "no WSL instance
// registered" between their pool reads and both call startNew
// with different distros, leaving the loser stranded.
const reconcileMutex = yield* Semaphore.make(1);
// Last fatal preflight failure from the dual-mode WSL *secondary*, surfaced
// inline in Connections settings. The primary's failure is handled by the
// pool (dialog + Windows fallback) instead; here the app stays usable on
// Windows, so we record the reason rather than interrupting. Cleared on any
// reconcile state change so it reflects the current attempt.
const preflightErrorRef = yield* Ref.make(Option.none<string>());
const findExistingWslInstance = pool.list.pipe(
Effect.map((instances) => instances.find((instance) => isWslInstanceId(instance.id))),
Effect.map(Option.fromNullishOr),
);
const stopExisting = (id: DesktopBackendPool.BackendInstanceId) =>
pool.unregister(id).pipe(
Effect.catchTags({
DesktopBackendPoolCannotUnregisterPrimaryError: (cause) =>
// Should never happen — wsl: ids are not the primary id — but
// log loudly if the logic ever drifts.
logWslBackendWarning("refusing to unregister primary as wsl instance", {
id,
error: cause.message,
}),
}),
);
const startNew = Effect.fn("desktop.wslBackend.startNew")(function* (input: {
readonly distro: string | null;
}) {
const primaryConfig = yield* serverExposure.backendConfig;
const port = yield* scanForWslPort(primaryConfig.port + 1).pipe(
Effect.provideService(NetService.NetService, net),
Effect.map((value) => Option.some(value)),
Effect.catch((error) =>
logWslBackendWarning("could not allocate port for WSL backend", {
error: error.message,
}).pipe(Effect.as(Option.none<number>())),
),
);
if (Option.isNone(port)) {
return;
}
const allocatedPort = port.value;
const targetId = resolveTargetInstanceId(input.distro);
yield* logWslBackendInfo("registering WSL backend with pool", {
id: targetId,
port: allocatedPort,
distro: input.distro ?? null,
});
const instance = yield* pool
.register({
id: targetId,
label: Effect.succeed(buildLabel(input.distro)),
configResolve: configuration.resolveWsl({ port: allocatedPort, distro: input.distro }),
// Dual-mode secondary: record a fatal preflight failure so Connections
// settings can show why the WSL backend never appeared. No dialog or
// fallback — Windows is the primary and keeps working.
onPreflightFailed: (failure) =>
Ref.set(preflightErrorRef, Option.some(failure.reason)).pipe(Effect.as(false)),
onReady: () => Ref.set(preflightErrorRef, Option.none()),
})
.pipe(
Effect.map((registered) => Option.some(registered)),
Effect.catch((error) =>
logWslBackendWarning("WSL backend already registered, skipping start", {
id: targetId,
error: error.message,
}).pipe(Effect.as(Option.none<DesktopBackendPool.DesktopBackendInstance>())),
),
);
yield* Option.match(instance, {
onNone: () => Effect.void,
onSome: (registered) => registered.start,
});
});
const reconcileBody = Effect.gen(function* () {
const settings = yield* appSettings.get;
const available = yield* wslEnvironment.isAvailable;
const existing = yield* findExistingWslInstance;
const existingId = Option.map(existing, (instance) => instance.id);
// In wsl-only mode the pool's primary IS the WSL backend (see
// DesktopBackendConfiguration.resolvePrimary), so the
// orchestrator skips registering a parallel "wsl:<distro>"
// secondary. Without this skip we'd spin up two WSL processes
// on the same distro for users who explicitly asked for one.
const shouldRun = settings.wslBackendEnabled && available && !settings.wslOnly;
const targetId = shouldRun
? Option.some(resolveTargetInstanceId(settings.wslDistro))
: Option.none<DesktopBackendPool.BackendInstanceId>();
// No-op if the desired state already matches what's registered.
if (Option.isNone(targetId) && Option.isNone(existingId)) {
return;
}
if (
Option.isSome(targetId) &&
Option.isSome(existing) &&
targetId.value === existing.value.id
) {
const existingInstance = existing.value;
const snapshot = yield* existingInstance.snapshot;
const isIdle =
!snapshot.ready && Option.isNone(snapshot.activePid) && !snapshot.restartScheduled;
if (isIdle) {
yield* logWslBackendInfo("retrying idle WSL backend", { id: existingInstance.id });
yield* Ref.set(preflightErrorRef, Option.none());
yield* existingInstance.start;
}
return;
}
// A real state change is happening (start, stop, or distro swap). Clear
// any stale secondary preflight error so it reflects this fresh attempt;
// onPreflightFailed re-sets it only if the new secondary exhausts retries.
yield* Ref.set(preflightErrorRef, Option.none());
if (Option.isSome(existingId)) {
yield* logWslBackendInfo("tearing down WSL backend", { id: existingId.value });
yield* stopExisting(existingId.value);
}
if (Option.isSome(targetId)) {
// Pre-warm the WSL VM before registering so the readiness probe
// doesn't race wsl.exe's first-spawn cold start. preWarm tolerates
// distro=null (uses the WSL default) and is bounded by its own
// timeout, so it's safe to await unconditionally here.
yield* wslEnvironment.preWarm(settings.wslDistro);
yield* startNew({ distro: settings.wslDistro });
}
});
// Top-level safety net. Every internal step today already catches
// its own failures (port allocation, register, preWarm), so the
// inferred error type is `never` and this catch is a no-op in
// steady state. It's here to enforce the file-header contract
// ("reconcile never fails; errors are logged") if a future change
// introduces an unhandled failure path — otherwise IPC callers
// like setWslBackendEnabled would surface it to the renderer as
// an opaque error.
const reconcile = reconcileMutex
.withPermits(1)(reconcileBody)
.pipe(
Effect.catchCause((cause) =>
logWslBackendWarning("reconcile failed", { cause: Cause.pretty(cause) }),
),
Effect.withSpan("desktop.wslBackend.reconcile"),
);
return DesktopWslBackend.of({
reconcile,
lastPreflightError: Ref.get(preflightErrorRef),
});
}),
);
@@ -1,237 +0,0 @@
import { describe, it } from "@effect/vitest";
import { expect } from "vite-plus/test";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as Fiber from "effect/Fiber";
import * as Layer from "effect/Layer";
import * as Sink from "effect/Sink";
import * as Stream from "effect/Stream";
import * as TestClock from "effect/testing/TestClock";
import { ChildProcessSpawner } from "effect/unstable/process";
import {
buildWslNodeEnvPreamble,
DesktopWslDistroListError,
formatMissingToolsReason,
formatNodePtyProbeFailureReason,
formatWslShellTransportFailureReason,
parseNodePath,
parseResolvedPath,
parseToolchainReport,
probeWslDistros,
} from "./DesktopWslEnvironment.ts";
const encoder = new TextEncoder();
const makeDistroListSpawner = (result: { readonly stdout?: string; readonly exitCode?: number }) =>
ChildProcessSpawner.make(() =>
Effect.succeed(
ChildProcessSpawner.makeHandle({
pid: ChildProcessSpawner.ProcessId(1),
exitCode:
result.exitCode === undefined
? Effect.never
: Effect.succeed(ChildProcessSpawner.ExitCode(result.exitCode)),
isRunning: Effect.succeed(result.exitCode === undefined),
kill: () => Effect.void,
unref: Effect.succeed(Effect.void),
stdin: Sink.drain,
stdout: Stream.make(encoder.encode(result.stdout ?? "")),
stderr: Stream.empty,
all: Stream.empty,
getInputFd: () => Sink.drain,
getOutputFd: () => Stream.empty,
}),
),
);
describe("probeWslDistros", () => {
it.effect("preserves a successful empty distro list", () =>
Effect.gen(function* () {
const distros = yield* probeWslDistros;
expect(distros).toEqual([]);
}).pipe(
Effect.provideService(
ChildProcessSpawner.ChildProcessSpawner,
makeDistroListSpawner({ stdout: "", exitCode: 0 }),
),
),
);
it.effect("fails when the distro-list command exits unsuccessfully", () =>
Effect.gen(function* () {
const error = yield* probeWslDistros.pipe(Effect.flip);
expect(error).toBeInstanceOf(DesktopWslDistroListError);
expect(error.message).toContain("exited with code 1");
}).pipe(
Effect.provideService(
ChildProcessSpawner.ChildProcessSpawner,
makeDistroListSpawner({ exitCode: 1 }),
),
),
);
it.effect("fails when the distro-list command times out", () => {
const layer = Layer.merge(
TestClock.layer(),
Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, makeDistroListSpawner({})),
);
return Effect.gen(function* () {
const fiber = yield* probeWslDistros.pipe(Effect.flip, Effect.forkScoped);
yield* Effect.yieldNow;
yield* TestClock.adjust(Duration.seconds(8));
const error = yield* Fiber.join(fiber);
expect(error).toBeInstanceOf(DesktopWslDistroListError);
expect(error.message).toContain("timed out");
}).pipe(Effect.provide(layer));
});
});
describe("formatNodePtyProbeFailureReason", () => {
it("identifies a packaged build that omitted the Linux node-pty prebuild", () => {
const reason = formatNodePtyProbeFailureReason(4);
expect(reason).toContain("packaged Linux node-pty binary was not included");
expect(reason).toContain("--wsl-prebuild");
});
it("leaves other node-pty load failures to the compatibility diagnostic", () => {
expect(formatNodePtyProbeFailureReason(1)).toBeNull();
});
});
describe("formatWslShellTransportFailureReason", () => {
it("distinguishes timeouts and spawn failures from normal shell exit codes", () => {
expect(formatWslShellTransportFailureReason("timeout")).toContain("timed out");
expect(formatWslShellTransportFailureReason("spawn")).toContain("could not start wsl.exe");
expect(formatWslShellTransportFailureReason("process")).toContain("lost communication");
expect(formatWslShellTransportFailureReason(null)).toBeNull();
});
});
describe("buildWslNodeEnvPreamble", () => {
it("passes the required Node engine range into the shared resolver", () => {
const preamble = buildWslNodeEnvPreamble("^22.16 || ^23.11 || >=24.10");
expect(preamble).toContain("T3_NODE_ENGINE_RANGE='^22.16 || ^23.11 || >=24.10'");
expect(preamble.indexOf("T3_NODE_ENGINE_RANGE=")).toBeLessThan(
preamble.lastIndexOf("ensure_remote_node_path || true"),
);
});
it("keeps the shared resolver permissive when no Node engine range is provided", () => {
expect(buildWslNodeEnvPreamble()).toContain("T3_NODE_ENGINE_RANGE=''");
});
});
describe("parseToolchainReport", () => {
it("returns no missing tools and no node version on empty output", () => {
expect(parseToolchainReport("")).toEqual({ missingTools: [], nodeVersion: null });
});
it("collects all missing: lines", () => {
const stdout = ["missing:make", "missing:g++", "nodeVersion:24.10.0"].join("\n");
expect(parseToolchainReport(stdout)).toEqual({
missingTools: ["make", "g++"],
nodeVersion: "24.10.0",
});
});
it("ignores blank lines and trims whitespace", () => {
const stdout = [" missing:python3 ", "", " nodeVersion:v22.16.0 "].join("\n");
expect(parseToolchainReport(stdout)).toEqual({
missingTools: ["python3"],
nodeVersion: "v22.16.0",
});
});
it("returns null node version when value after prefix is empty", () => {
expect(parseToolchainReport("nodeVersion:")).toEqual({
missingTools: [],
nodeVersion: null,
});
});
});
describe("parseNodePath", () => {
it("extracts the absolute node path from a nodePath: line", () => {
const stdout = "nodePath:/home/josh/.nvm/versions/node/v22.16.0/bin/node";
expect(parseNodePath(stdout)).toBe("/home/josh/.nvm/versions/node/v22.16.0/bin/node");
});
it("returns null when node was not found (empty value after prefix)", () => {
expect(parseNodePath("nodePath:")).toBeNull();
});
it("returns null when there is no nodePath line at all", () => {
expect(parseNodePath("missing:node\nnodeVersion:")).toBeNull();
});
it("ignores surrounding noise and trims whitespace", () => {
const stdout = ["some preamble noise", " nodePath:/usr/bin/node ", "trailing"].join("\n");
expect(parseNodePath(stdout)).toBe("/usr/bin/node");
});
});
describe("parseResolvedPath", () => {
it("preserves spaces and apostrophes in the resolved login-shell PATH", () => {
const resolvedPath = "/home/test user/bin:/opt/test's tools/bin:/usr/bin:/bin";
expect(parseResolvedPath(`nodePath:/usr/bin/node\nresolvedPath:${resolvedPath}\n`)).toBe(
resolvedPath,
);
});
it("accepts CRLF output without retaining the carriage return", () => {
expect(parseResolvedPath("resolvedPath:/usr/local/bin:/usr/bin\r\n")).toBe(
"/usr/local/bin:/usr/bin",
);
});
it("returns null when the resolved PATH is absent or empty", () => {
expect(parseResolvedPath("nodePath:/usr/bin/node\n")).toBeNull();
expect(parseResolvedPath("resolvedPath:\n")).toBeNull();
});
});
describe("formatMissingToolsReason", () => {
it("returns null when everything is present and node is in range", () => {
expect(
formatMissingToolsReason({ missingTools: [], nodeVersion: "24.10.0" }, "^24.10"),
).toBeNull();
});
it("returns null when range is not specified and tools are present", () => {
expect(formatMissingToolsReason({ missingTools: [], nodeVersion: "18.0.0" }, null)).toBeNull();
});
it("flags missing node first", () => {
const reason = formatMissingToolsReason(
{ missingTools: ["node", "make"], nodeVersion: null },
"^24.10",
);
expect(reason).toContain("node");
expect(reason).toContain("^24.10");
expect(reason).toContain("make");
expect(reason).toContain("nvm");
});
it("flags an out-of-range node version with the actual version surfaced", () => {
const reason = formatMissingToolsReason(
{ missingTools: [], nodeVersion: "20.0.0" },
"^24.10 || ^22.16",
);
expect(reason).toContain("node 20.0.0");
expect(reason).toContain("requires ^24.10 || ^22.16");
});
it("flags missing build tools without node when node is fine", () => {
const reason = formatMissingToolsReason(
{ missingTools: ["g++", "python3"], nodeVersion: "24.10.0" },
"^24.10",
);
expect(reason).toContain("g++");
expect(reason).toContain("python3");
expect(reason).toContain("build-essential");
expect(reason).not.toContain("nvm");
});
});
@@ -1,849 +0,0 @@
import * as Context from "effect/Context";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Path from "effect/Path";
import * as Schema from "effect/Schema";
import * as Stream from "effect/Stream";
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
import { buildRemoteNodeEnvScript } from "@t3tools/ssh/tunnel";
import { satisfiesSemverRange } from "@t3tools/shared/semver";
import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
import { parseWslDistroList, type WslDistro } from "./wslPathParsing.ts";
const PROCESS_TERMINATE_GRACE = Duration.seconds(1);
const LIST_TIMEOUT = Duration.seconds(8);
const PRE_WARM_TIMEOUT = Duration.seconds(10);
const WSLPATH_TIMEOUT = Duration.seconds(10);
const PROBE_TIMEOUT = Duration.seconds(10);
const TOOLCHAIN_TIMEOUT = Duration.seconds(10);
const BUILD_TIMEOUT = Duration.minutes(5);
const USER_HOME_TIMEOUT = Duration.seconds(5);
const TOOLCHAIN_TRANSPORT_RETRY_LIMIT = 12;
const BUILD_TRANSPORT_RETRY_LIMIT = 2;
export interface EnsureWslNodePtyOptions {
readonly allowBuild?: boolean;
readonly nodeEngineRange?: string | null;
}
export type EnsureWslNodePtyResult =
| { readonly ok: true; readonly nodePath: string; readonly resolvedPath: string }
| {
readonly ok: false;
readonly reason: string;
readonly fatal: boolean;
readonly retryLimit?: number;
};
export class DesktopWslDistroListError extends Schema.TaggedErrorClass<DesktopWslDistroListError>()(
"DesktopWslDistroListError",
{ reason: Schema.String },
) {
override get message(): string {
return this.reason;
}
}
const isDesktopWslDistroListError = Schema.is(DesktopWslDistroListError);
export class DesktopWslEnvironment extends Context.Service<
DesktopWslEnvironment,
{
readonly isAvailable: Effect.Effect<boolean>;
// Best-effort enumeration for renderer UX. Backend health checks must use
// probeDistros so a transient command failure is not mistaken for a
// successful empty installation.
readonly listDistros: Effect.Effect<readonly WslDistro[]>;
readonly probeDistros: Effect.Effect<readonly WslDistro[], DesktopWslDistroListError>;
readonly preWarm: (distro: string | null) => Effect.Effect<void>;
readonly windowsToWslPath: (
distro: string | null,
windowsPath: string,
) => Effect.Effect<Option.Option<string>>;
// Resolves the user's Linux home dir inside the chosen distro (e.g.
// "/home/josh"). Used by the folder picker to expand `~` correctly.
readonly getUserHome: (distro: string | null) => Effect.Effect<Option.Option<string>>;
// Resolves the WSL distro's IPv4 address on the WSL vEthernet adapter
// (e.g. "172.x.x.x"). The orchestrator uses this for the WSL backend's
// httpBaseUrl so the renderer can reach it without relying on wslhost's
// localhost→WSL automatic forwarding, which is flaky in practice
// (the backend can be listening for 30+ seconds before wslhost starts
// forwarding 127.0.0.1:port to WSL-side localhost).
readonly getDistroIp: (distro: string | null) => Effect.Effect<Option.Option<string>>;
readonly ensureNodePty: (
distro: string | null,
windowsRepoRoot: string,
options?: EnsureWslNodePtyOptions,
) => Effect.Effect<EnsureWslNodePtyResult>;
}
>()("@t3tools/desktop/wsl/DesktopWslEnvironment") {}
const buildDistroArgs = (distro: string | null): ReadonlyArray<string> =>
distro ? ["-d", distro] : [];
const concatChunks = (arrays: ReadonlyArray<Uint8Array>): Uint8Array => {
let totalLength = 0;
for (const arr of arrays) totalLength += arr.byteLength;
const out = new Uint8Array(totalLength);
let offset = 0;
for (const arr of arrays) {
out.set(arr, offset);
offset += arr.byteLength;
}
return out;
};
const decodeUtf8 = (bytes: Uint8Array): string => new TextDecoder("utf-8").decode(bytes);
interface ShellResult {
readonly exitCode: number;
readonly stdout: string;
readonly stderr: string;
readonly transportFailure: "timeout" | "spawn" | "process" | null;
}
const TIMEOUT_RESULT: ShellResult = {
exitCode: 124,
stdout: "",
stderr: "\n[timeout]",
transportFailure: "timeout",
};
export const formatWslShellTransportFailureReason = (
failure: ShellResult["transportFailure"],
): string | null => {
switch (failure) {
case "timeout":
return "WSL backend preflight timed out while probing for Node.js. WSL may be slow to start; retry, or check that the distro is healthy.";
case "spawn":
return "WSL backend preflight could not start wsl.exe to probe for Node.js. Check that WSL is installed and the distro is accessible.";
case "process":
return "WSL backend preflight lost communication with wsl.exe while probing for Node.js. Retry, or check that the distro is healthy.";
case null:
return null;
}
};
// Reuse the SSH remote resolver so WSL and SSH discover version-managed Node
// the same way. Passing the engine range lets the resolver fall through to
// version managers like nvm when a system node exists but is too old.
export const buildWslNodeEnvPreamble = (
nodeEngineRange?: string | null,
): string => `${buildRemoteNodeEnvScript({ nodeEngineRange: nodeEngineRange ?? null })}
ensure_remote_node_path || true
`;
// wsl.exe re-escapes args before forwarding them to the Linux side, which
// mangles quotes inside `bash -lc "<script>"`. Pipe the script via stdin to
// avoid passing it on the command line at all.
const runWslShell = (
distro: string | null,
bashScript: string,
timeout: Duration.Duration,
options: EnsureWslNodePtyOptions = {},
): Effect.Effect<ShellResult, never, ChildProcessSpawner.ChildProcessSpawner> => {
const spawner = ChildProcessSpawner.ChildProcessSpawner;
// -l picks up profile-managed PATH; the shared resolver covers supported
// version managers that non-interactive login shells can miss. -s so bash
// reads the script from stdin.
const command = ChildProcess.make(
"wsl.exe",
[...buildDistroArgs(distro), "--", "bash", "-l", "-s"],
{
stdin: Stream.encodeText(
Stream.make(`${buildWslNodeEnvPreamble(options.nodeEngineRange)}${bashScript}`),
),
stdout: "pipe",
stderr: "pipe",
killSignal: "SIGTERM",
forceKillAfter: PROCESS_TERMINATE_GRACE,
},
);
return Effect.scoped(
Effect.gen(function* () {
const spawnerService = yield* spawner;
const spawnResult = yield* spawnerService.spawn(command).pipe(
Effect.match({
onFailure: (error) => ({ _tag: "Failure", error }) as const,
onSuccess: (handle) => ({ _tag: "Success", handle }) as const,
}),
);
if (spawnResult._tag === "Failure") {
return {
exitCode: 127,
stdout: "",
stderr: `\n${spawnResult.error.message}`,
transportFailure: "spawn",
} satisfies ShellResult;
}
const handle = spawnResult.handle;
// Drain stdout and stderr concurrently so neither pipe buffer can fill
// and stall the child (node-gyp rebuild emits large output on both).
const [stdoutBytes, stderrBytes, exitCode] = yield* Effect.all(
[Stream.runCollect(handle.stdout), Stream.runCollect(handle.stderr), handle.exitCode],
{ concurrency: "unbounded" },
);
return {
exitCode: exitCode as unknown as number,
stdout: decodeUtf8(concatChunks(stdoutBytes)),
stderr: decodeUtf8(concatChunks(stderrBytes)),
transportFailure: null,
} satisfies ShellResult;
}),
).pipe(
Effect.timeoutOption(timeout),
Effect.map(Option.getOrElse((): ShellResult => TIMEOUT_RESULT)),
Effect.catch((error) =>
Effect.succeed<ShellResult>({
exitCode: 127,
stdout: "",
stderr: `\n${error.message}`,
transportFailure: "process",
}),
),
);
};
const shellQuote = (value: string): string => `'${value.replaceAll("'", "'\\''")}'`;
const NODE_PTY_PREBUILD_MISSING_EXIT_CODE = 4;
export const formatNodePtyProbeFailureReason = (exitCode: number): string | null =>
exitCode === NODE_PTY_PREBUILD_MISSING_EXIT_CODE
? "WSL support is missing from this T3 Code build: the packaged Linux node-pty binary was not included. Rebuild the Windows artifact with `--wsl-prebuild <path-to-linux-pty.node>` or install a build that includes WSL support."
: null;
const NODE_PTY_PROBE_SCRIPT = (
linuxServerDir: string,
) => `printf 'nodePath:%s\\n' "$(command -v node 2>/dev/null)"
printf 'resolvedPath:%s\\n' "$PATH"
cd ${shellQuote(linuxServerDir)} && node <<'NODE' >/dev/null 2>&1
// The server bundle externalizes its deps to node_modules, and the WSL Node
// can't read inside app.asar, so confirm those deps are unpacked on the real
// filesystem before reporting the backend healthy. "effect" is the framework
// every server module imports; resolving it validates the whole node_modules
// tree. Exit 3 marks this distinct from a node-pty problem so the caller can
// report it accurately instead of letting the server crash on
// ERR_MODULE_NOT_FOUND at launch (which, in wsl-only mode, would just fail to
// launch with no fallback).
try { require.resolve("effect"); } catch (_e) { process.exit(3); }
const fs = require("node:fs");
const path = require("node:path");
const pkgDir = path.dirname(require.resolve("node-pty/package.json"));
// node-pty 1.x is N-API based, so a single Linux pty.node is ABI-stable across
// Node versions — require() succeeding IS the real compatibility test. Compare
// only arch and node-pty version (a stale binary from a different node-pty),
// NOT process.versions.modules: that would reject a perfectly loadable prebuilt
// whenever the user's WSL Node ABI differs from the build's, defeating the
// whole point of shipping one prebuilt for all Node versions.
const expected = {
arch: process.arch,
nodePtyVersion: require("node-pty/package.json").version,
};
const prebuildDir = path.join(pkgDir, "prebuilds", "linux-" + process.arch);
const marker = path.join(prebuildDir, "t3code-wsl-node-pty.json");
const binary = path.join(prebuildDir, "pty.node");
if (!fs.existsSync(marker) || !fs.existsSync(binary)) process.exit(${NODE_PTY_PREBUILD_MISSING_EXIT_CODE});
require("node-pty");
const actual = JSON.parse(fs.readFileSync(marker, "utf8"));
for (const key of Object.keys(expected)) {
if (actual[key] !== expected[key]) process.exit(2);
}
NODE`;
const TOOLCHAIN_CHECK_SCRIPT = [
"for tool in node make g++ python3; do",
' command -v "$tool" >/dev/null 2>&1 || echo "missing:$tool"',
"done",
"if command -v node >/dev/null 2>&1; then",
` ver="$(node -p 'process.versions.node' 2>/dev/null)"`,
' if [ -n "$ver" ]; then printf "nodeVersion:%s\\n" "$ver"; fi',
"fi",
].join("\n");
const NODE_PTY_BUILD_SCRIPT = (linuxServerDir: string) =>
[
"set -e",
`cd ${shellQuote(linuxServerDir)}`,
`pkg_dir=$(node -p "require('node:path').dirname(require.resolve('node-pty/package.json'))")`,
`arch=$(node -p "process.arch")`,
`modules=$(node -p "process.versions.modules")`,
`node_pty_version=$(node -p "require('node-pty/package.json').version")`,
`cd "$pkg_dir"`,
"npx --yes node-gyp rebuild",
`prebuild_dir="prebuilds/linux-$arch"`,
`mkdir -p "$prebuild_dir"`,
`cp build/Release/pty.node "$prebuild_dir/pty.node"`,
`printf '{"arch":"%s","modules":"%s","nodePtyVersion":"%s"}\\n' "$arch" "$modules" "$node_pty_version" > "$prebuild_dir/t3code-wsl-node-pty.json"`,
`node -e 'require("node-pty")'`,
].join("\n");
export interface ToolchainReport {
readonly missingTools: ReadonlyArray<string>;
readonly nodeVersion: string | null;
}
export const parseToolchainReport = (stdout: string): ToolchainReport => {
const lines = stdout
.split("\n")
.map((line) => line.trim())
.filter((line) => line.length > 0);
const missingTools = lines
.filter((line) => line.startsWith("missing:"))
.map((line) => line.slice("missing:".length));
const nodeVersionLine = lines.find((line) => line.startsWith("nodeVersion:"));
const nodeVersion = nodeVersionLine
? nodeVersionLine.slice("nodeVersion:".length).trim() || null
: null;
return { missingTools, nodeVersion };
};
// Pulls the absolute node path the WSL distro resolved after the shared remote
// resolver repaired PATH. Returns null when no node was found, which the caller
// turns into an actionable "install Node" message instead of a confusing
// node-pty error.
export const parseNodePath = (stdout: string): string | null => {
const path = stdout
.split("\n")
.map((line) => line.trim())
.filter((line) => line.startsWith("nodePath:"))
.map((line) => line.slice("nodePath:".length).trim())
.find((value) => value.length > 0);
return path ?? null;
};
// Captures the login-shell PATH after the shared resolver has loaded version
// managers. Preserve the value byte-for-byte apart from a Windows-style CR so
// paths containing spaces or apostrophes can be forwarded as one env argv.
export const parseResolvedPath = (stdout: string): string | null => {
const prefix = "resolvedPath:";
const line = stdout.split("\n").find((candidate) => candidate.startsWith(prefix));
if (line === undefined) return null;
const resolvedPath = line.slice(prefix.length).replace(/\r$/, "");
return resolvedPath.length > 0 ? resolvedPath : null;
};
export const formatMissingToolsReason = (
report: ToolchainReport,
requiredRange: string | null,
): string | null => {
const nodeMissing = report.missingTools.includes("node");
const nodeOutOfRange =
!nodeMissing &&
requiredRange !== null &&
report.nodeVersion !== null &&
!satisfiesSemverRange(report.nodeVersion, requiredRange);
const buildToolsMissing = report.missingTools.filter((tool) => tool !== "node");
if (!nodeMissing && !nodeOutOfRange && buildToolsMissing.length === 0) {
return null;
}
const issues: string[] = [];
const remediations: string[] = [];
if (nodeMissing) {
issues.push("node");
remediations.push(
`Node.js${requiredRange ? ` satisfying \`${requiredRange}\`` : " 18+"} (e.g. via nvm)`,
);
} else if (nodeOutOfRange) {
issues.push(`node ${report.nodeVersion} (requires ${requiredRange})`);
remediations.push(
`a newer Node.js satisfying \`${requiredRange}\` (e.g. \`nvm install 24 && nvm alias default 24\`)`,
);
}
if (buildToolsMissing.length > 0) {
issues.push(...buildToolsMissing);
remediations.push(
"the build toolchain (e.g. `sudo apt install -y build-essential python3` on Ubuntu/Debian)",
);
}
return `WSL distro is missing required tools: ${issues.join(", ")}. Install ${remediations.join(" and ")}, then retry.`;
};
const ensureNodePtyImpl = (
distro: string | null,
windowsRepoRoot: string,
windowsToWslPath: (
distro: string | null,
windowsPath: string,
) => Effect.Effect<Option.Option<string>>,
options: EnsureWslNodePtyOptions = {},
): Effect.Effect<EnsureWslNodePtyResult, never, ChildProcessSpawner.ChildProcessSpawner> =>
Effect.gen(function* () {
const linuxRepoRootOption = yield* windowsToWslPath(distro, windowsRepoRoot);
if (Option.isNone(linuxRepoRootOption)) {
return {
ok: false,
reason: `wslpath conversion failed for ${windowsRepoRoot}`,
fatal: false,
} as const;
}
const linuxRepoRoot = linuxRepoRootOption.value;
// node-pty lives in the apps/server workspace's node_modules; resolve from
// there rather than the monorepo root, where Bun's hoist layout omits it.
const linuxServerDir = `${linuxRepoRoot}/apps/server`;
const probe = yield* runWslShell(
distro,
NODE_PTY_PROBE_SCRIPT(linuxServerDir),
PROBE_TIMEOUT,
options,
);
const nodePath = parseNodePath(probe.stdout);
const resolvedPath = parseResolvedPath(probe.stdout);
const transportFailureReason = formatWslShellTransportFailureReason(probe.transportFailure);
if (transportFailureReason !== null) {
return { ok: false, reason: transportFailureReason, fatal: false } as const;
}
// No node at all, even after the shared resolver repaired PATH. Surface
// the specific, actionable toolchain message rather than a confusing
// node-pty error, and don't try to build.
if (nodePath === null) {
const toolchainCheck = yield* runWslShell(
distro,
TOOLCHAIN_CHECK_SCRIPT,
TOOLCHAIN_TIMEOUT,
options,
);
const toolchainTransportFailure = formatWslShellTransportFailureReason(
toolchainCheck.transportFailure,
);
if (toolchainTransportFailure !== null) {
return {
ok: false,
reason: toolchainTransportFailure,
fatal: false,
retryLimit: TOOLCHAIN_TRANSPORT_RETRY_LIMIT,
} as const;
}
const report = parseToolchainReport(toolchainCheck.stdout);
const reason =
formatMissingToolsReason(report, options.nodeEngineRange?.trim() || null) ??
"Node.js was not found in the WSL distro. Install it (e.g. via nvm) and restart the desktop app.";
return { ok: false, reason, fatal: true } as const;
}
if (resolvedPath === null) {
return {
ok: false,
reason: "WSL login-shell PATH could not be resolved during backend preflight.",
fatal: true,
} as const;
}
// Server dependencies (e.g. "effect") couldn't be resolved on the WSL
// filesystem — a packaging regression, since the server bundle needs its
// node_modules unpacked from the asar. Fatal so wsl-only mode falls back to
// Windows and dual mode surfaces the reason inline, instead of the server
// crash-looping on ERR_MODULE_NOT_FOUND once it actually launches.
if (probe.exitCode === 3) {
return {
ok: false,
reason:
"WSL server dependencies could not be loaded (for example \"effect\"). The server's bundled node_modules is not readable by the WSL distro's Node — this is a packaging problem with this build. Please report it.",
fatal: true,
} as const;
}
if (probe.exitCode === 0) return { ok: true, nodePath, resolvedPath } as const;
if (options.allowBuild !== true) {
const packagedProbeFailure = formatNodePtyProbeFailureReason(probe.exitCode);
if (packagedProbeFailure !== null) {
return { ok: false, reason: packagedProbeFailure, fatal: true } as const;
}
}
// node is present but node-pty's native module didn't load.
const toolchainCheck = yield* runWslShell(
distro,
TOOLCHAIN_CHECK_SCRIPT,
TOOLCHAIN_TIMEOUT,
options,
);
const toolchainTransportFailure = formatWslShellTransportFailureReason(
toolchainCheck.transportFailure,
);
if (toolchainTransportFailure !== null) {
return {
ok: false,
reason: toolchainTransportFailure,
fatal: false,
retryLimit: TOOLCHAIN_TRANSPORT_RETRY_LIMIT,
} as const;
}
const report = parseToolchainReport(toolchainCheck.stdout);
if (options.allowBuild !== true) {
// Packaged builds ship a prebuilt Linux node-pty, so no compiler, node-gyp,
// or network is needed — and we must not nag the user to install build
// tools they don't need. Still surface a missing/too-old Node (both the
// prebuilt and the server require a compatible Node); otherwise reaching
// here means the bundled binary itself couldn't load, which is almost
// always an unsupported CPU architecture or incompatible system libraries.
const nodeOnlyReason = formatMissingToolsReason(
{
missingTools: report.missingTools.filter((tool) => tool === "node"),
nodeVersion: report.nodeVersion,
},
options.nodeEngineRange?.trim() || null,
);
return {
ok: false,
reason:
nodeOnlyReason ??
"The bundled WSL backend binary (node-pty) could not be loaded in this distro. This usually means an unsupported CPU architecture or incompatible system libraries (glibc). Use a glibc-based x64/arm64 WSL distro such as Ubuntu; if you already are, please report this with your distro and the output of `uname -m`.",
fatal: true,
} as const;
}
// Dev only: no prebuilt is bundled in a checkout, so compile node-pty from
// source. Run the toolchain check first so a missing compiler or out-of-range
// Node surfaces a specific, actionable message instead of an opaque node-gyp
// failure. Developers have the toolchain; end users never reach this path.
const missingReason = formatMissingToolsReason(report, options.nodeEngineRange?.trim() || null);
if (missingReason !== null) {
return { ok: false, reason: missingReason, fatal: true } as const;
}
const build = yield* runWslShell(
distro,
NODE_PTY_BUILD_SCRIPT(linuxServerDir),
BUILD_TIMEOUT,
options,
);
const buildTransportFailure = formatWslShellTransportFailureReason(build.transportFailure);
if (buildTransportFailure !== null) {
return {
ok: false,
reason: buildTransportFailure,
fatal: false,
retryLimit: BUILD_TRANSPORT_RETRY_LIMIT,
} as const;
}
if (build.exitCode === 0) return { ok: true, nodePath, resolvedPath } as const;
const trimmedTail = `${build.stdout}${build.stderr}`.trim().slice(-500);
return {
ok: false,
reason: `node-pty Linux build failed (exit ${build.exitCode}): ${trimmedTail || "no stderr captured"}`,
fatal: true,
} as const;
});
export const probeWslDistros: Effect.Effect<
readonly WslDistro[],
DesktopWslDistroListError,
ChildProcessSpawner.ChildProcessSpawner
> = Effect.scoped(
Effect.gen(function* () {
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const command = ChildProcess.make("wsl.exe", ["--list", "--verbose"], {
stdin: "ignore",
stdout: "pipe",
stderr: "ignore",
killSignal: "SIGTERM",
forceKillAfter: PROCESS_TERMINATE_GRACE,
});
const handle = yield* spawner.spawn(command);
const stdoutBytes = yield* Stream.runCollect(handle.stdout);
const exitCode = yield* handle.exitCode;
if ((exitCode as unknown as number) !== 0) {
return yield* new DesktopWslDistroListError({
reason: `wsl.exe --list --verbose exited with code ${String(exitCode)}`,
});
}
return parseWslDistroList(Buffer.from(concatChunks(stdoutBytes)));
}),
).pipe(
Effect.mapError((error) =>
isDesktopWslDistroListError(error)
? error
: new DesktopWslDistroListError({
reason: `Failed to run wsl.exe --list --verbose: ${error.message}`,
}),
),
Effect.timeoutOption(LIST_TIMEOUT),
Effect.flatMap(
Option.match({
onNone: () =>
new DesktopWslDistroListError({
reason: "wsl.exe --list --verbose timed out",
}),
onSome: Effect.succeed,
}),
),
);
const preWarmImpl = (
distro: string | null,
): Effect.Effect<void, never, ChildProcessSpawner.ChildProcessSpawner> =>
Effect.scoped(
Effect.gen(function* () {
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const command = ChildProcess.make("wsl.exe", [...buildDistroArgs(distro), "--", "true"], {
stdin: "ignore",
stdout: "ignore",
stderr: "ignore",
killSignal: "SIGTERM",
forceKillAfter: PROCESS_TERMINATE_GRACE,
});
const handle = yield* spawner.spawn(command);
yield* handle.exitCode;
}),
).pipe(
Effect.timeoutOption(PRE_WARM_TIMEOUT),
Effect.asVoid,
Effect.catch(() => Effect.void),
);
const windowsToWslPathImpl = (
distro: string | null,
windowsPath: string,
): Effect.Effect<Option.Option<string>, never, ChildProcessSpawner.ChildProcessSpawner> => {
// wsl.exe interprets backslashes as escape chars; normalize to forward slashes.
const normalized = windowsPath.replaceAll("\\", "/");
return Effect.scoped(
Effect.gen(function* () {
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const command = ChildProcess.make(
"wsl.exe",
[...buildDistroArgs(distro), "--", "wslpath", "-u", normalized],
{
stdin: "ignore",
stdout: "pipe",
stderr: "ignore",
killSignal: "SIGTERM",
forceKillAfter: PROCESS_TERMINATE_GRACE,
},
);
const handle = yield* spawner.spawn(command);
const stdoutBytes = yield* Stream.runCollect(handle.stdout);
const exitCode = yield* handle.exitCode;
if ((exitCode as unknown as number) !== 0) return Option.none<string>();
const converted = decodeUtf8(concatChunks(stdoutBytes)).trim();
return converted.length > 0 ? Option.some(converted) : Option.none<string>();
}),
).pipe(
Effect.timeoutOption(WSLPATH_TIMEOUT),
Effect.map(Option.flatten),
Effect.orElseSucceed(() => Option.none<string>()),
);
};
const IPV4_PATTERN = /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/;
const getDistroIpImpl = (
distro: string | null,
): Effect.Effect<Option.Option<string>, never, ChildProcessSpawner.ChildProcessSpawner> =>
Effect.scoped(
Effect.gen(function* () {
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
// `hostname -I` prints a space-separated list of all non-loopback
// IPs the distro has bound. The first entry on the WSL2 default
// network is always the eth0 vEthernet address Windows can reach
// directly (no wslhost forwarding required).
const command = ChildProcess.make(
"wsl.exe",
[...buildDistroArgs(distro), "--", "sh", "-c", "hostname -I"],
{
stdin: "ignore",
stdout: "pipe",
stderr: "ignore",
killSignal: "SIGTERM",
forceKillAfter: PROCESS_TERMINATE_GRACE,
},
);
const handle = yield* spawner.spawn(command);
const stdoutBytes = yield* Stream.runCollect(handle.stdout);
const exitCode = yield* handle.exitCode;
if ((exitCode as unknown as number) !== 0) return Option.none<string>();
const raw = decodeUtf8(concatChunks(stdoutBytes)).trim();
const candidate = raw.split(/\s+/).find((part) => IPV4_PATTERN.test(part));
return candidate ? Option.some(candidate) : Option.none<string>();
}),
).pipe(
Effect.timeoutOption(USER_HOME_TIMEOUT),
Effect.map(Option.flatten),
Effect.orElseSucceed(() => Option.none<string>()),
);
const getUserHomeImpl = (
distro: string | null,
): Effect.Effect<Option.Option<string>, never, ChildProcessSpawner.ChildProcessSpawner> =>
Effect.scoped(
Effect.gen(function* () {
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const command = ChildProcess.make(
"wsl.exe",
// printf so there's no trailing newline noise; getent so we get the
// real home from /etc/passwd even if $HOME is unset for some reason.
[
...buildDistroArgs(distro),
"--",
"sh",
"-c",
'printf "%s" "$(getent passwd "$(id -un)" | cut -d: -f6)"',
],
{
stdin: "ignore",
stdout: "pipe",
stderr: "ignore",
killSignal: "SIGTERM",
forceKillAfter: PROCESS_TERMINATE_GRACE,
},
);
const handle = yield* spawner.spawn(command);
const stdoutBytes = yield* Stream.runCollect(handle.stdout);
const exitCode = yield* handle.exitCode;
if ((exitCode as unknown as number) !== 0) return Option.none<string>();
const home = decodeUtf8(concatChunks(stdoutBytes)).trim();
return home.startsWith("/") ? Option.some(home) : Option.none<string>();
}),
).pipe(
Effect.timeoutOption(USER_HOME_TIMEOUT),
Effect.map(Option.flatten),
Effect.orElseSucceed(() => Option.none<string>()),
);
const makeIsAvailable = (
platform: NodeJS.Platform,
windir: string,
): Effect.Effect<boolean, never, FileSystem.FileSystem | Path.Path> =>
Effect.gen(function* () {
if (platform !== "win32") return false;
const path = yield* Path.Path;
const fileSystem = yield* FileSystem.FileSystem;
const wslExePath = path.join(windir, "System32", "wsl.exe");
return yield* fileSystem.exists(wslExePath).pipe(Effect.orElseSucceed(() => false));
});
export interface DesktopWslEnvironmentTestStub {
readonly isAvailable?: boolean;
readonly distros?: ReadonlyArray<WslDistro>;
readonly distroListError?: DesktopWslDistroListError;
readonly windowsToWslPath?: (distro: string | null, windowsPath: string) => Option.Option<string>;
readonly getUserHome?: (distro: string | null) => Option.Option<string>;
readonly getDistroIp?: (distro: string | null) => Option.Option<string>;
readonly ensureNodePty?: (
distro: string | null,
windowsRepoRoot: string,
options?: EnsureWslNodePtyOptions,
) => EnsureWslNodePtyResult;
}
export const layerTest = (stub: DesktopWslEnvironmentTestStub = {}) => {
const probeDistros = stub.distroListError
? Effect.fail(stub.distroListError)
: Effect.succeed(stub.distros ?? []);
return Layer.succeed(
DesktopWslEnvironment,
DesktopWslEnvironment.of({
isAvailable: Effect.succeed(stub.isAvailable ?? false),
listDistros: probeDistros.pipe(Effect.orElseSucceed(() => [])),
probeDistros,
preWarm: () => Effect.void,
windowsToWslPath: (distro, windowsPath) =>
Effect.succeed(stub.windowsToWslPath?.(distro, windowsPath) ?? Option.none()),
getUserHome: (distro) => Effect.succeed(stub.getUserHome?.(distro) ?? Option.none<string>()),
getDistroIp: (distro) => Effect.succeed(stub.getDistroIp?.(distro) ?? Option.none<string>()),
ensureNodePty: (distro, windowsRepoRoot, options) =>
Effect.succeed(
stub.ensureNodePty?.(distro, windowsRepoRoot, options) ?? {
ok: false,
reason: "ensureNodePty stub not configured",
fatal: true,
},
),
}),
);
};
export const layer = Layer.effect(
DesktopWslEnvironment,
Effect.gen(function* () {
const environment = yield* DesktopEnvironment.DesktopEnvironment;
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const fileSystem = yield* FileSystem.FileSystem;
const windir = process.env.WINDIR ?? "C:\\Windows";
const provideSpawner = <A, E>(
effect: Effect.Effect<A, E, ChildProcessSpawner.ChildProcessSpawner>,
): Effect.Effect<A, E> =>
effect.pipe(Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner));
// Probe wsl.exe once at layer init and cache the result, exposing
// `isAvailable` as a resolved value rather than a re-running effect.
// WSL availability is effectively static for the process lifetime — the
// Windows feature isn't added/removed mid-session, and backend mode
// changes already require an app restart — so the cached boolean stays
// accurate. Crucially this keeps `isAvailable` synchronously resolvable:
// it's read inside the sync IPC handler getLocalEnvironmentBootstraps
// (via the primary instance's lazy label -> resolvePrimaryLabel ->
// describePrimary). The underlying probe does a filesystem `exists`
// check, so leaving it as a live effect would make Effect.runSync throw
// there and break the renderer's synchronous bootstrap path.
const wslAvailable = yield* makeIsAvailable(environment.platform, windir).pipe(
Effect.provideService(FileSystem.FileSystem, fileSystem),
Effect.provideService(Path.Path, environment.path),
Effect.withSpan("desktop.wsl.isAvailable"),
);
const isAvailable = Effect.succeed(wslAvailable);
const windowsToWslPath = (distro: string | null, windowsPath: string) =>
provideSpawner(windowsToWslPathImpl(distro, windowsPath)).pipe(
Effect.withSpan("desktop.wsl.windowsToWslPath"),
);
// Cache user-home results per distro key — folder picker can be opened
// many times in a session and the value is stable for the life of the
// distro. Negative results aren't cached so a transient wsl.exe failure
// doesn't permanently disable tilde expansion.
const userHomeCache = new Map<string, string>();
const getUserHome = (distro: string | null) =>
Effect.gen(function* () {
const key = distro ?? "__default__";
const cached = userHomeCache.get(key);
if (cached !== undefined) return Option.some(cached);
const resolved = yield* provideSpawner(getUserHomeImpl(distro));
if (Option.isSome(resolved)) userHomeCache.set(key, resolved.value);
return resolved;
}).pipe(Effect.withSpan("desktop.wsl.getUserHome"));
const getDistroIp = (distro: string | null) =>
provideSpawner(getDistroIpImpl(distro)).pipe(Effect.withSpan("desktop.wsl.getDistroIp"));
const probeDistros = provideSpawner(probeWslDistros).pipe(
Effect.withSpan("desktop.wsl.probeDistros"),
);
return DesktopWslEnvironment.of({
isAvailable,
listDistros: probeDistros.pipe(
Effect.orElseSucceed(() => []),
Effect.withSpan("desktop.wsl.listDistros"),
),
probeDistros,
preWarm: (distro) =>
provideSpawner(preWarmImpl(distro)).pipe(Effect.withSpan("desktop.wsl.preWarm")),
windowsToWslPath,
getUserHome,
getDistroIp,
ensureNodePty: (distro, windowsRepoRoot, options) =>
provideSpawner(ensureNodePtyImpl(distro, windowsRepoRoot, windowsToWslPath, options)).pipe(
Effect.withSpan("desktop.wsl.ensureNodePty"),
),
});
}),
);
-206
View File
@@ -1,206 +0,0 @@
import { describe, it, expect } from "vite-plus/test";
import {
DISTRO_NAME_PATTERN,
extractDistroFromUncPath,
isValidDistroName,
parseWslDistroList,
resolveWslHomeUncPath,
resolveWslPickFolderDefaultPath,
wslUncPathToLinuxPath,
} from "./wslPathParsing.ts";
function makeUtf16LeBuffer(text: string): Buffer {
return Buffer.from("" + text, "utf16le");
}
describe("parseWslDistroList", () => {
it("parses standard output with default distro marked", () => {
const output = makeUtf16LeBuffer(
[
" NAME STATE VERSION",
"* Ubuntu Running 2",
" Debian Stopped 2",
" Ubuntu-22.04 Running 1",
].join("\r\n"),
);
const distros = parseWslDistroList(output);
expect(distros).toEqual([
{ name: "Ubuntu", isDefault: true, version: 2 },
{ name: "Debian", isDefault: false, version: 2 },
{ name: "Ubuntu-22.04", isDefault: false, version: 1 },
]);
});
it("returns empty array for empty buffer", () => {
expect(parseWslDistroList(Buffer.alloc(0))).toEqual([]);
});
it("returns empty array for header-only output", () => {
const output = makeUtf16LeBuffer(" NAME STATE VERSION\r\n");
expect(parseWslDistroList(output)).toEqual([]);
});
it("skips malformed lines", () => {
const output = makeUtf16LeBuffer(
[
" NAME STATE VERSION",
"* Ubuntu Running 2",
" bad line",
"",
" Debian Stopped 2",
].join("\r\n"),
);
const distros = parseWslDistroList(output);
expect(distros).toEqual([
{ name: "Ubuntu", isDefault: true, version: 2 },
{ name: "Debian", isDefault: false, version: 2 },
]);
});
it("handles output without BOM", () => {
const text = [
" NAME STATE VERSION",
"* Ubuntu Running 2",
].join("\r\n");
const output = Buffer.from(text, "utf16le");
const distros = parseWslDistroList(output);
expect(distros).toEqual([{ name: "Ubuntu", isDefault: true, version: 2 }]);
});
it("handles UTF-8 output", () => {
const text = [
" NAME STATE VERSION",
"* Debian Running 2",
].join("\r\n");
const distros = parseWslDistroList(Buffer.from(text, "utf8"));
expect(distros).toEqual([{ name: "Debian", isDefault: true, version: 2 }]);
});
});
describe("extractDistroFromUncPath", () => {
it("extracts the distro from \\\\wsl.localhost UNC paths", () => {
expect(extractDistroFromUncPath("\\\\wsl.localhost\\Ubuntu-22.04\\home\\josh")).toBe(
"Ubuntu-22.04",
);
});
it("extracts the distro from the legacy \\\\wsl$ UNC paths", () => {
expect(extractDistroFromUncPath("\\\\wsl$\\Debian\\home\\josh")).toBe("Debian");
});
it("returns null for non-UNC Windows paths", () => {
expect(extractDistroFromUncPath("C:\\Users\\Josh\\project")).toBeNull();
});
it("returns null when the segment is not a valid distro name", () => {
expect(extractDistroFromUncPath("\\\\wsl.localhost\\bad name!\\home")).toBeNull();
});
});
describe("wslUncPathToLinuxPath", () => {
it("maps WSL UNC paths back to Linux absolute paths", () => {
expect(wslUncPathToLinuxPath("\\\\wsl.localhost\\Ubuntu-22.04\\home\\josh\\repo")).toBe(
"/home/josh/repo",
);
});
it("maps a distro UNC root to Linux root", () => {
expect(wslUncPathToLinuxPath("\\\\wsl$\\Debian")).toBe("/");
expect(wslUncPathToLinuxPath("\\\\wsl.localhost\\Debian\\")).toBe("/");
});
it("rejects invalid distro names and non-WSL paths", () => {
expect(wslUncPathToLinuxPath("\\\\wsl.localhost\\bad!name\\home")).toBeNull();
expect(wslUncPathToLinuxPath("C:\\Users\\Josh\\repo")).toBeNull();
});
});
describe("resolveWslHomeUncPath", () => {
const distros = [
{ name: "Debian", isDefault: true, version: 2 as const },
{ name: "Ubuntu", isDefault: false, version: 2 as const },
];
it("uses the configured distro when one is selected", () => {
expect(resolveWslHomeUncPath({ distro: "Ubuntu" }, distros)).toBe(
"\\\\wsl.localhost\\Ubuntu\\home",
);
});
it("uses the actual default distro when config uses the WSL default", () => {
expect(resolveWslHomeUncPath({ distro: null }, distros)).toBe(
"\\\\wsl.localhost\\Debian\\home",
);
});
it("omits the default path when no default distro is known", () => {
expect(resolveWslHomeUncPath({ distro: null }, [])).toBeNull();
});
});
describe("resolveWslPickFolderDefaultPath", () => {
const config = { distro: null };
const distros = [{ name: "Debian", isDefault: true, version: 2 as const }];
it("uses WSL home when no initial path is provided", () => {
expect(resolveWslPickFolderDefaultPath(undefined, config, distros)).toBe(
"\\\\wsl.localhost\\Debian\\home",
);
});
it("maps Linux initial paths to WSL UNC paths", () => {
expect(
resolveWslPickFolderDefaultPath({ initialPath: "/home/josh/project" }, config, distros),
).toBe("\\\\wsl.localhost\\Debian\\home\\josh\\project");
});
it("expands ~/path against the user's home dir when known", () => {
expect(
resolveWslPickFolderDefaultPath({ initialPath: "~/project" }, config, distros, "/home/josh"),
).toBe("\\\\wsl.localhost\\Debian\\home\\josh\\project");
});
it("resolves bare ~ to the user's home dir when known", () => {
expect(
resolveWslPickFolderDefaultPath({ initialPath: "~" }, config, distros, "/home/josh"),
).toBe("\\\\wsl.localhost\\Debian\\home\\josh");
});
it("falls back to /home parent when the user's home dir isn't known", () => {
expect(resolveWslPickFolderDefaultPath({ initialPath: "~/project" }, config, distros)).toBe(
"\\\\wsl.localhost\\Debian\\home\\project",
);
});
it("preserves existing UNC initial paths", () => {
expect(
resolveWslPickFolderDefaultPath(
{ initialPath: "\\\\wsl.localhost\\Ubuntu\\home\\josh" },
config,
distros,
),
).toBe("\\\\wsl.localhost\\Ubuntu\\home\\josh");
});
});
describe("DISTRO_NAME_PATTERN / isValidDistroName", () => {
it("accepts common distro names", () => {
for (const name of ["Ubuntu", "Ubuntu-22.04", "kali-linux", "Debian", "Ubuntu 22.04"]) {
expect(DISTRO_NAME_PATTERN.test(name)).toBe(true);
expect(isValidDistroName(name)).toBe(true);
}
});
it("rejects names with trailing whitespace, hyphen, or dot", () => {
for (const name of ["Ubuntu ", "Ubuntu-", "Ubuntu."]) {
expect(DISTRO_NAME_PATTERN.test(name)).toBe(false);
}
});
it("rejects names containing control or shell-meta characters", () => {
for (const name of ["bad\nname", "bad\tname", "bad/name", "bad!name", "bad;name"]) {
expect(DISTRO_NAME_PATTERN.test(name)).toBe(false);
}
});
});
-129
View File
@@ -1,129 +0,0 @@
export interface WslDistro {
readonly name: string;
readonly isDefault: boolean;
readonly version: 1 | 2;
}
export interface WslConfig {
readonly distro: string | null;
}
// Literal space — \s would also match \n/\t/\r and corrupt UNC paths like \\wsl.localhost\<distro>\...
// Trailing char must also be \w so hand-edited config like "Ubuntu " / "Ubuntu-" / "Ubuntu." rejects.
export const DISTRO_NAME_PATTERN = /^\w(?:[\w \-.]*\w)?$/;
export function parseWslDistroList(stdout: Buffer): readonly WslDistro[] {
const hasUtf16Bom = stdout.length >= 2 && stdout[0] === 0xff && stdout[1] === 0xfe;
const likelyUtf16Le =
hasUtf16Bom ||
Array.from(stdout.subarray(0, Math.min(stdout.length, 80))).filter(
(byte, index) => index % 2 === 1 && byte === 0,
).length > 10;
let text = stdout.toString(likelyUtf16Le ? "utf16le" : "utf8");
if (text.charCodeAt(0) === 0xfeff) text = text.slice(1);
const lines = text.split(/\r?\n/).filter((line) => line.trim().length > 0);
const distros: WslDistro[] = [];
for (let i = 1; i < lines.length; i++) {
const line = lines[i]!;
const isDefault = line.startsWith("*");
const cleaned = isDefault ? line.slice(1).trim() : line.trim();
const fields = cleaned.split(/\s{2,}/);
if (fields.length < 3) continue;
const name = fields[0]!.trim();
const versionNum = parseInt(fields[2]!, 10);
if (!name || (versionNum !== 1 && versionNum !== 2)) continue;
distros.push({ name, isDefault, version: versionNum as 1 | 2 });
}
return distros;
}
// Recognizes \\wsl.localhost\<distro>\... and the legacy \\wsl$\<distro>\... so
// `wslpath` can be invoked inside the distro that actually owns the path,
// rather than whichever distro is configured for the desktop backend.
export function extractDistroFromUncPath(windowsPath: string): string | null {
const match = /^\\\\(?:wsl\.localhost|wsl\$)\\([^\\]+)/i.exec(windowsPath);
if (!match) return null;
const candidate = match[1]!;
return DISTRO_NAME_PATTERN.test(candidate) ? candidate : null;
}
export function wslUncPathToLinuxPath(windowsPath: string): string | null {
const match = /^\\\\(?:wsl\.localhost|wsl\$)\\([^\\]+)(?:\\(.*))?$/i.exec(windowsPath.trim());
if (!match) return null;
const distro = match[1]!;
if (!DISTRO_NAME_PATTERN.test(distro)) return null;
const rest = match[2] ?? "";
if (rest.length === 0) return "/";
return `/${rest.split("\\").filter(Boolean).join("/")}`;
}
export function resolveWslHomeUncPath(
config: WslConfig,
distros: readonly WslDistro[],
): string | null {
const distroName = config.distro ?? distros.find((distro) => distro.isDefault)?.name ?? null;
return distroName ? `\\\\wsl.localhost\\${distroName}\\home` : null;
}
export function resolveWslPickFolderDefaultPath(
rawOptions: unknown,
config: WslConfig,
distros: readonly WslDistro[],
// Absolute Linux path of the user's home dir inside the chosen distro
// (e.g. "/home/josh"). When known, `~` and `~/...` expand against this so
// we don't open the picker at a non-existent `/home/<rest>`. When null we
// fall back to the `/home` parent — wrong directory but at least it exists.
userHome: string | null = null,
): string | null {
const homePath = resolveWslHomeUncPath(config, distros);
if (typeof rawOptions !== "object" || rawOptions === null) {
return homePath;
}
const { initialPath } = rawOptions as { initialPath?: unknown };
if (typeof initialPath !== "string") {
return homePath;
}
const trimmedPath = initialPath.trim();
if (trimmedPath.length === 0) {
return homePath;
}
if (trimmedPath.startsWith("\\\\")) {
return trimmedPath;
}
const distroName = config.distro ?? distros.find((distro) => distro.isDefault)?.name ?? null;
if (!distroName) {
return homePath;
}
const toUncPath = (linuxPath: string) =>
`\\\\wsl.localhost\\${distroName}${linuxPath.replaceAll("/", "\\")}`;
const normalizedUserHome = userHome && userHome.startsWith("/") ? userHome : null;
if (trimmedPath === "~") {
return normalizedUserHome ? toUncPath(normalizedUserHome) : homePath;
}
if (trimmedPath.startsWith("~/")) {
const remainder = trimmedPath.slice(2);
if (normalizedUserHome) {
return toUncPath(`${normalizedUserHome}/${remainder}`);
}
return homePath ? `${homePath}\\${remainder.replaceAll("/", "\\")}` : null;
}
if (trimmedPath.startsWith("/")) {
return toUncPath(trimmedPath);
}
return homePath;
}
export function isValidDistroName(value: string): boolean {
return DISTRO_NAME_PATTERN.test(value);
}
+1 -1
View File
@@ -10,7 +10,7 @@
"typecheck": "astro check"
},
"dependencies": {
"astro": "^7.0.3"
"astro": "^6.0.4"
},
"devDependencies": {
"@astrojs/check": "^0.9.7",
-1
View File
@@ -1,7 +1,6 @@
included:
- ios/T3Code
- modules/t3-composer-editor/ios
- modules/t3-native-controls/ios
- modules/t3-terminal/ios
- modules/t3-review-diff/ios
+4 -43
View File
@@ -15,38 +15,30 @@ const VARIANT_CONFIG: Record<
readonly appName: string;
readonly scheme: string;
readonly iosIcon: string;
readonly splashIcon: string;
readonly iosBundleIdentifier: string;
readonly androidPackage: string;
readonly relyingParty?: string;
}
> = {
development: {
appName: "T3 Code Dev",
scheme: "t3code-dev",
iosIcon: "./assets/icon-composer-dev.icon",
splashIcon: "./assets/splash-icon-dev.png",
iosBundleIdentifier: "com.t3tools.t3code.dev",
androidPackage: "com.t3tools.t3code.dev",
relyingParty: "clerk.t3.codes",
},
preview: {
appName: "T3 Code Preview",
scheme: "t3code-preview",
iosIcon: "./assets/icon-composer-prod.icon",
splashIcon: "./assets/splash-icon-prod.png",
iosBundleIdentifier: "com.t3tools.t3code.preview",
androidPackage: "com.t3tools.t3code.preview",
relyingParty: "clerk.t3.codes",
},
production: {
appName: "T3 Code",
scheme: "t3code",
iosIcon: "./assets/icon-composer-prod.icon",
splashIcon: "./assets/splash-icon-prod.png",
iosBundleIdentifier: "com.t3tools.t3code",
androidPackage: "com.t3tools.t3code",
relyingParty: "clerk.t3.codes",
},
};
@@ -70,11 +62,7 @@ const config: ExpoConfig = {
scheme: variant.scheme,
version: "0.1.0",
runtimeVersion: {
// Fingerprint (not appVersion) so an OTA only reaches binaries whose native
// project — native deps, config plugins, AND patches/ — matches the update.
// With appVersion, every 0.1.0 build shares a runtime version, so a JS update
// could land on a binary missing the native changes it needs and crash.
policy: process.env.MOBILE_VERSION_POLICY ?? "fingerprint",
policy: process.env.MOBILE_VERSION_POLICY ?? "appVersion",
},
orientation: "portrait",
icon: "./assets/icon.png",
@@ -89,14 +77,6 @@ const config: ExpoConfig = {
icon: variant.iosIcon,
supportsTablet: true,
bundleIdentifier: variant.iosBundleIdentifier,
// Pin code signing to the T3 Tools team so non-interactive `expo run:ios`
// does not fall back to a personal team (which cannot sign app groups,
// Sign in with Apple, or push notification entitlements).
appleTeamId: "ARK85ZXQ4Z",
associatedDomains: [
`applinks:${variant.relyingParty}`,
`webcredentials:${variant.relyingParty}`,
],
infoPlist: {
NSAppTransportSecurity: {
NSAllowsArbitraryLoads: true,
@@ -121,6 +101,7 @@ const config: ExpoConfig = {
favicon: "./assets/favicon.png",
},
plugins: [
"expo-router",
"expo-font",
"expo-secure-store",
["@clerk/expo", { theme: "./clerk-theme.json" }],
@@ -135,12 +116,12 @@ const config: ExpoConfig = {
[
"expo-splash-screen",
{
image: variant.splashIcon,
image: "./assets/splash-icon.png",
resizeMode: "contain",
backgroundColor: "#ffffff",
imageWidth: 220,
dark: {
image: variant.splashIcon,
image: "./assets/splash-icon.png",
backgroundColor: "#0a0a0a",
},
},
@@ -158,22 +139,12 @@ const config: ExpoConfig = {
},
},
],
"./plugins/withIosCocoaPodsUuidCache.cjs",
// Must be listed BEFORE expo-widgets: same-type mods run last-registered-
// first, so registering earlier makes this plugin's mods run AFTER
// expo-widgets' — its dangerous mod wipes ios/ExpoWidgetsTarget/ (which
// would delete the asset catalog) and its xcodeproj mod creates the widget
// target (which must exist before the compile phase can be attached).
"./plugins/withWidgetLogoAsset.cjs",
[
"expo-widgets",
{
bundleIdentifier: `${variant.iosBundleIdentifier}.widgets`,
groupIdentifier: `group.${variant.iosBundleIdentifier}`,
enablePushNotifications: true,
// Agent activity can update many times an hour; without the
// frequent-updates entitlement iOS throttles the update budget sooner.
frequentUpdates: true,
widgets: [
{
name: "AgentActivity",
@@ -184,7 +155,6 @@ const config: ExpoConfig = {
],
},
],
"./plugins/withIosSceneLifecycle.cjs",
"./plugins/withAndroidCleartextTraffic.cjs",
],
extra: {
@@ -196,15 +166,6 @@ const config: ExpoConfig = {
publishableKey: repoEnv.EXPO_PUBLIC_CLERK_PUBLISHABLE_KEY ?? null,
jwtTemplate: repoEnv.EXPO_PUBLIC_CLERK_JWT_TEMPLATE ?? null,
},
// Native Google sign-in credentials. @clerk/expo reads these from `extra`
// under their exact env-var names (not nested), and its config plugin reads
// the iOS URL scheme at prebuild to register it in Info.plist.
// Unset values must be omitted (not null): the public manifest serializes
// null to {}, which is truthy and would defeat Clerk's fallback checks.
EXPO_PUBLIC_CLERK_GOOGLE_WEB_CLIENT_ID: repoEnv.EXPO_PUBLIC_CLERK_GOOGLE_WEB_CLIENT_ID,
EXPO_PUBLIC_CLERK_GOOGLE_IOS_CLIENT_ID: repoEnv.EXPO_PUBLIC_CLERK_GOOGLE_IOS_CLIENT_ID,
EXPO_PUBLIC_CLERK_GOOGLE_ANDROID_CLIENT_ID: repoEnv.EXPO_PUBLIC_CLERK_GOOGLE_ANDROID_CLIENT_ID,
EXPO_PUBLIC_CLERK_GOOGLE_IOS_URL_SCHEME: repoEnv.EXPO_PUBLIC_CLERK_GOOGLE_IOS_URL_SCHEME,
observability: {
tracesUrl: repoEnv.EXPO_PUBLIC_OTLP_TRACES_URL ?? "https://api.axiom.co/v1/traces",
tracesDataset: repoEnv.EXPO_PUBLIC_OTLP_TRACES_DATASET ?? null,
Binary file not shown.

Before

Width:  |  Height:  |  Size: 302 KiB

File renamed without changes.

Before

Width:  |  Height:  |  Size: 2.0 MiB

After

Width:  |  Height:  |  Size: 2.0 MiB

-3
View File
@@ -1,3 +0,0 @@
<svg width="111" height="74" viewBox="7 29 111 74" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M33.4509 93V47.56H15.5309V37H64.3309V47.56H46.4109V93H33.4509ZM86.7253 93.96C82.832 93.96 78.9653 93.4533 75.1253 92.44C71.2853 91.3733 68.032 89.88 65.3653 87.96L70.4053 78.04C72.5386 79.5867 75.0186 80.8133 77.8453 81.72C80.672 82.6267 83.5253 83.08 86.4053 83.08C89.6586 83.08 92.2186 82.44 94.0853 81.16C95.952 79.88 96.8853 78.12 96.8853 75.88C96.8853 73.7467 96.0586 72.0667 94.4053 70.84C92.752 69.6133 90.0853 69 86.4053 69H80.4853V60.44L96.0853 42.76L97.5253 47.4H68.1653V37H107.365V45.4L91.8453 63.08L85.2853 59.32H89.0453C95.9253 59.32 101.125 60.8667 104.645 63.96C108.165 67.0533 109.925 71.0267 109.925 75.88C109.925 79.0267 109.099 81.9867 107.445 84.76C105.792 87.48 103.259 89.6933 99.8453 91.4C96.432 93.1067 92.0586 93.96 86.7253 93.96Z" fill="black"/>
</svg>

Before

Width:  |  Height:  |  Size: 887 B

+1 -8
View File
@@ -6,7 +6,6 @@
},
"build": {
"development": {
"corepack": true,
"env": {
"APP_VARIANT": "development"
},
@@ -15,7 +14,6 @@
"distribution": "internal"
},
"preview": {
"corepack": true,
"env": {
"APP_VARIANT": "preview"
},
@@ -24,7 +22,6 @@
"distribution": "internal"
},
"preview:dev": {
"corepack": true,
"env": {
"APP_VARIANT": "preview",
"MOBILE_VERSION_POLICY": "fingerprint"
@@ -38,7 +35,6 @@
}
},
"production": {
"corepack": true,
"env": {
"APP_VARIANT": "production"
},
@@ -50,10 +46,7 @@
"submit": {
"production": {
"ios": {
"ascAppId": "6787819824"
},
"android": {
"track": "internal"
"ascAppId": "6761315631"
}
}
}
Loaded 100 of 937 files, more files were not shown because too many files have changed in this diff. Show more